【发布时间】:2017-04-20 19:08:15
【问题描述】:
我是 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
【问题讨论】:
-
在
$document.close()之前尝试$document.Saved = $true -
谢谢马蒂亚斯!那行得通。
标签: excel powershell