使用PowerShell重命名XSL而不保存提示
我是PowerShell的新手,并且一直在研究以下脚本来查看XLS和XLSX文件的目录。 之后,它会得到每个文件的创builddate,并将创builddate的文件名重命名为结尾。
此脚本适用于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
根据这个老的kb的文章 ,你可以把excel诱骗到不提示你通过将工作簿上的Saved
属性设置为true
,所以我会尝试:
$document.Saved = $true $document.close([ref]$saveOption::wdDoNotSaveChanges)