【发布时间】:2016-04-11 17:14:51
【问题描述】:
我有一个脚本,用于转换和密码保护许多 Excel 文档。较旧的文档是 Excel 2003 格式,我可以很好地转换/密码保护它们。当我看到更新的文档时,这些文件是 Excel 2010 格式,因此只需要密码保护。我正在尝试找到一种方法来检查 xlsx 文件是否已经受密码保护,因此可以跳过(可能是已经处理过的 2003 文件)。如果我打开文件,因为它有密码,那么即使我将可见属性设置为 false,excel 也会弹出并在继续之前询问该密码。我需要一种自动检查的方法,因为有很多文件要检查。这是我到目前为止的代码:
[cmdletbinding()]
param (
[parameter(mandatory=$true)][string]$Path,
[parameter(mandatory=$false)][switch]$Visible,
[parameter(mandatory=$false)][string]$ToFolder,
[parameter(mandatory=$false)][string]$Password,
[parameter(mandatory=$false)][switch]$Force
)
begin {
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
Write-Verbose 'Opening Excel COM object.'
$Excel = New-Object -ComObject excel.application
if ($Visible -eq $true) {
$Excel.visible = $true
} else {
$Excel.visible = $false
$Excel.DisplayAlerts = $false
$Excel.ScreenUpdating = $false
$Excel.UserControl = $false
$Excel.Interactive = $false
}
$filetype = "*xls"
} process {
if (Test-Path -Path $Path) {
Get-ChildItem -Path $Path -Include '*.xls' -recurse | ForEach-Object {
Write-Verbose "Processing $($_.Basename)"
if ($ToFolder -ne '') {
$FilePath = Join-Path $ToFolder $_.BaseName
$FilePath += ".xlsx"
} else {
$FilePath = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
$FilePath += ".xlsx"
}
if (!(Test-Path $FilePath) -Or $Force) {
Write-Verbose "Opening $($_.Basename)"
$WorkBook = $Excel.workbooks.open($_.fullname)
Write-Verbose "Saving $($_.Basename) to $FilePath with password $Password"
$WorkBook.saveas($FilePath, $xlFixedFormat, $Password)
Write-Verbose "Closing $($_.Basename)"
$WorkBook.close()
} else {
Write-Verbose "$($_.Basename) already converted."
}
}
} else {
return 'No path provided or access has been denied.'
}
} end {
Write-Verbose 'Closing Excel'
$Excel.Quit()
$Excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
}
【问题讨论】:
-
是
$Excel.workbooks.open呼叫停止并要求输入密码? -
@JoachimIsaksson:是的,这就是它停止的地方。
-
好的,这里只是抛出一些想法。如果您将虚拟密码传递给
open,会发生什么?还会提示还是抛出异常? -
@JoachimIsaksson:它会引发异常。所以我想我可以尝试使用无效密码打开它,然后捕获异常。
-
我看不到任何其他明显的方法可以使用 API 进行检查,但我并不完全是专家。
标签: excel powershell