我正在使用下面的powershell
腳本來打開幾個Word文檔,更新它們中的表單域,然後關閉它們。首先,我會注意到,如果這個腳本是從命令行運行的,或者右鍵單擊該文件並選擇Run with Powershell
(基本上是以任何方式手動執行),它都會執行得很好。但是,如果我嘗試將此作爲計劃任務運行,則會發生以下兩種情況之一。按計劃任務運行Powershell腳本
我嘗試了幾種不同的語法形式,但都產生了相同的兩個結果之一。或者A)腳本說它在大約3秒內開始並完成而不做任何事情,或者B)腳本啓動,我可以看到Word在任務管理器中打開,但沒有顯示進度的命令窗口,如正常情況下一樣,Word只是大約2分鐘後掛斷電話。真正讓我選擇B的唯一語法是將powershell
作爲動作,將。\ Script1.ps1作爲參數,並將該文件夾作爲位置的開始。我嘗試了一些這種語法的細微變化,例如使用powershell
的完整路徑等。當我在任務管理器中掛起Word時掛起時,計劃任務表示它已成功完成。有人有主意嗎?該腳本如下:
$filearray = 1..12
$filename="E:\Form0801"
$word=new-object -com Word.Application
$word.Visible=$False #Making this true
#does not show word if run from scheduled task
Write-Host "DO NOT CLOSE THIS WINDOW!"
try
{
foreach ($i in $filearray)
{
if($i -lt 10){$filename="E:\Form080" + $i + ".dot"}
else{$filename="E:\Form08" + $i + ".dot"}
$doc=$word.Documents.Open($filename)
$word.ActiveDocument.Fields.Update()
$doc.SaveAs([REF]$filename)
$doc.Close()
Write-Host "File " $filename " has been updated successfully"
}
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
"A problem occurred while opening one of the files."
$error[0]
}
$word.Quit()
# End Word Application
我的第一個猜測是,這是一些特權問題。您使用哪個用戶來運行計劃任務?該用戶是否有權讀取和寫入文件? – Gisli
用「hello」|嘗試調度一些test.ps1 out-file。\ test.txt並簽出[此腳本專家帖子](http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/12/use-scheduled-tasks-to-run- powershell-commands-on-windows.aspx)和[此服務器故障線程](http://serverfault.com/questions/101671/scheduled-tasks-w-gui-issue) – noam