使用 PowerShell 重命名 XSL,而不提示保存



我是PowerShell的新手,一直在研究以下脚本来查找XLS和XLSX文件的目录。 之后,它将获取每个文件的创建日期,并重命名文件名,并在末尾附加创建日期。

此脚本适用于 XLSX 文件。 但是,当遇到 XLS 文件时,保存提示:">要将更改保存到 xxx.xls?

如何摆脱此保存提示。 下面是我的代码。 谢谢:

Param(
$path = "C:Excel",  
[array]$include = @("*.xlsx","*.xls")
)
$application = New-Object -ComObject Excel.Application
$application.Visible = $false
$binding = "System.Reflection.BindingFlags" -as [type] 
[ref]$SaveOption = "microsoft.office.interop.Excel.WdSaveOptions" -as [type]
## Get documents
$docs = Get-childitem -path $Path -Recurse -Include $include    
foreach($doc in $docs)
{
try 
{
## Get document properties:
$document = $application.Workbooks.Open($doc.fullname)
$BuiltinProperties = $document.BuiltInDocumentProperties
$pn = [System.__ComObject].invokemember("item",$binding::GetProperty,$null,$BuiltinProperties,"Creation Date") 
$value = [System.__ComObject].invokemember("value",$binding::GetProperty,$null,$pn,$null)
## Clean up
$document.close([ref]$saveOption::wdDoNotSaveChanges)
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($BuiltinProperties) | Out-Null
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($document) | Out-Null
Remove-Variable -Name document, BuiltinProperties
## Rename document:
$date=$value.ToString('yyyyMMdd');
$strippedFileName = $doc.BaseName;
$extension = $doc.Extension;
#write-host $strippedFileName;
$newName = "$strippedFileName" +"_" + "$date"+ "$extension";
write-host $newName;
Rename-Item $doc $newName
}
catch
{ 
write-host "Rename failed."
$_
} 
}
$application.quit()
$application.Workbooks.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($application) | Out-Null

根据这篇旧的知识库文章,您可以通过将工作簿上的Saved属性设置为true来欺骗 excel 不提示您,所以我会尝试:

$document.Saved = $true
$document.close([ref]$saveOption::wdDoNotSaveChanges)

最新更新