我是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
答案 0 :(得分:2)
根据this old kb article,您可以通过将工作簿上的Saved
属性设置为true
来欺骗excel,而不是提示您,所以我会尝试:
$document.Saved = $true
$document.close([ref]$saveOption::wdDoNotSaveChanges)