需要帮助弄清楚为什么Powershell会抛出错误16

时间:2012-12-13 13:23:15

标签: powershell syntax-error

我发布了此脚本the other day,以便在“另存为”时发现更改文件扩展名的好方法。我有问题舔,但截至今天早上,脚本将无法正常运行。这是我得到的错误消息:

Processing : C:\users\xxx\Desktop\ht\Automatic_Post-Call_Survey.htm
Exception calling "SaveAs" with "16" argument(s): "This is not a valid file name.
Try one or more of the following:
* Check the path to make sure it was typed correctly.
* Select a file from the list of files and folders."
At C:\users\xxx\Desktop\hd.ps1:11 char:20
+     $opendoc.saveas <<<< ([ref]"$docpath\$doc.FullName.doc", [ref]$saveFormat);
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

如果“16”是错误代码,则表示无法删除目录...但它看起来并不像我要求那样 - 除非某处有某个默认参数。我非常困惑。任何人都可以尝试其他任何想法吗?

$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"

$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument"); 
$word = new-object -comobject word.application 
$word.Visible = $False        
$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))

function saveas-document   {         
        $opendoc = $word.documents.open($doc.FullName);         
    $opendoc.saveas([ref]"$docpath\$filename", [ref]$saveFormat);         
    $opendoc.close();
}       
ForEach ($doc in $srcfiles)     {
    Write-Host "Processing :" $doc.FullName         
    saveas-document        
    $doc = $null   
}   

$word.quit(); 

1 个答案:

答案 0 :(得分:3)

这应该做你需要的,但不是最好的设计:)

$docpath = "c:\users\xxx\desktop\do"
$htmPath = "c:\users\xxx\desktop\ht"


$srcfiles = Get-ChildItem $htmPath -filter "*.htm*"

$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument"); 

$global:word = new-object -comobject word.application 

$word.Visible = $False        

#$filename = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))

function saveas-document ($docs)  {         
    $opendoc = $word.documents.open($docs);    
    $savepath = $docs -replace [regex]::escape($htmPath),"$docpath"
    $savepath = $savepath -replace '\.html*', '.doc'
    $opendoc.saveas([ref]"$savepath", [ref]$saveFormat);         
    $opendoc.close();
}       
ForEach ($doc in $srcfiles)     {
    Write-Host "Processing :" $doc.FullName         
    saveas-document  -doc  $doc.FullName     
    $doc = $null   
}   

$word.quit();