【问题标题】:Rename XSL without save prompt using PowerShell使用 PowerShell 在没有保存提示的情况下重命名 XSL
【发布时间】: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


【解决方案1】:

根据this old kb article,您可以通过将工作簿上的Saved 属性设置为true 来欺骗excel 不提示您,所以我会尝试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-12
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多