![](/img/trans.png)
[英]How to redirect powershell output within batch file ( when run from Task Scheduler)?
[英]How can I redirect PowerShell output when run from Task Scheduler?
從任務計划程序運行簡單的 PowerShell 腳本時,我想將輸出重定向到一個文件。
關於這個話題這里有一個很長的話題,但尚不清楚他們最終是否找到了最合適的解決方案。 我想知道 Stack Overflow 上是否有人也解決了這個問題,他們是如何解決的?
我使用成績單功能來幫助解決這個問題。 只需將它包含在您的代碼中,它就會將所有(將是)屏幕內容輸出到一個日志文件中。
Start-Transcript -path $LogFile -append
<Body of the script>
Stop-Transcript
這是對我有用的命令。 我不喜歡在腳本中重定向輸出的想法,因為這會使手動運行變得困難。
powershell -windowstyle minimized -c "powershell -c .\myscript.ps1 -verbose >> \\server\myscript.log 2>&1"
以下適用於 Windows 7:
powershell -command c:\temp\pscript.ps1 2>&1 > c:/temp/apickles.log
在 Windows 7 任務計划程序 GUI 中:
program = "Powershell"
arguments = "-command c:\temp\pscript.ps1 2>&1 > c:/temp/apickles.log"
請注意,“-file”不起作用,因為文件名后的所有參數都被解釋為文件的參數。 請注意,“2>&1”也將錯誤輸出重定向到日志文件。 PowerShell 的更高版本以稍微不同的方式執行此操作。
以前所有答案的組合確實幫助了我......
我的問題是我需要在WinRM上執行一個 PowerShell 腳本作為 Packer 供應器的一部分,並且由於權限問題它一直失敗。 解決這個問題的方法是作為計划任務執行,但我需要將參數傳遞給腳本並獲取輸出以確認一切都已通過。
這個片段對我來說效果很好:
# Generate a unique ID for this execution
$guid = [guid]::NewGuid()
$logFile = "C:\Windows\Temp\$guid.log"
$argument = "-NoProfile -ExecutionPolicy unrestricted -Command ""& {""$ScriptPath"" $ScriptArgs} 2>&1 > $logFile"""
$a = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $argument
Register-ScheduledTask -TaskName $TaskName -RunLevel Highest -User $username -Password $password -Action $a | Start-ScheduledTask
do {
Start-Sleep -Seconds 30
$task = Get-ScheduledTask -TaskName $TaskName
} while ($task.State -eq 4)
完整的腳本可以在這里找到:
https://gist.github.com/dev-rowbot/fa8b8dadf1b3731067a93065db3e1bba
為了直接登錄到文件,使用Start-Transcript可能會更容易:
# Get script name
$ScriptFullPath = $MyInvocation.MyCommand.Path
# Start logging stdout and stderr to file
Start-Transcript -Path "$ScriptFullPath.log" -Append
[Some PowerShell commands]
# Stop logging to file
Stop-Transcript
日志文件將與腳本位於同一目錄中。
我會做:
創建一個函數來調用您的腳本並重定向此函數的輸出,如下所示:
function test{
# Your simple script commands
ls c:\temp -Filter *.JPG
ls z:\ # Non-existent directory
}
test *> c:\temp\log.txt
這是日志文件:
Répertoire : C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 07/06/2008 11:06 176275 HPIM1427.JPG
-a--- 07/06/2008 11:06 69091 HPIM1428.JPG
-a--- 07/06/2008 11:06 174661 HPIM1429.JPG
ls : Lecteur introuvable. Il n'existe aucun lecteur nommé « z ».
Au caractère C:\temp\test.ps1:14 : 1
+ ls z:\ #non existent dir
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (z:String) [Get-ChildItem], Driv
eNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetC
hildItemCommand
您可以使用新的 V3 重定向運算符控制要輸出的內容:
Do-Something 3> warning.txt # Writes warning output to warning.txt
Do-Something 4>> verbose.txt # Appends verbose.txt with the verbose output
Do-Something 5>&1 # Writes debug output to the output stream
Do-Something *> out.txt # Redirects all streams (output, error, warning, verbose, and debug) to out.txt
我在 Windows Server 2016 上測試了以下內容,只調用了一次powershell
。 這樣你就可以擁有帶空格的文件夾名稱:
Powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle minimized "scriptName.ps1 *>> '\\servername\sharename\folder name with space\logfilename.log'"
PowerShell 3 及更高版本允許重定向單個流(輸出、詳細和錯誤)。 然而,Task Scheduler 不理解它們。 執行重定向的是 PowerShell。
@cmcginty 的解決方案半途而廢,因為 PowerShell 正在調用 PowerShell。 它僅支持標准流(錯誤和輸出)。 如果你想使用你需要使用的所有流:
程序或腳本: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
參數: -windowstyle minimized –NonInteractive –NoProfile -c "powershell -c path_to_ps1.ps1 4>>verbose.log 5>>debug.log"
開始於: path_to_ps1
我寫這個答案的靈感來自 Anders 的評論問題(你如何添加時間戳?),以及兩次調用 PowerShell 的多個回復,我認為這不是必需的。 任務調度程序顯然是“powershell.exe”,對於參數我會簡單地建議:
-noninteractive -c "scriptpath.ps1 *>>logpath.txt"
要每天保留一個文件,則:
-noninteractive -c "scriptpath.ps1 *>>logpath-$((get-date).ToString('yyyy-MM-dd')).txt"
如果你確實想要一個帶有時間戳的日志文件,你可以刪除第二個“>”(兩個表示附加到任何現有文件)並擴展時間格式:
-noninteractive -c "scriptpath.ps1 *>logpath-$((get-date).ToString('yyyy-MM-dd_HH-mm-ss-fff')).txt"
下面將詳細輸出發送到屏幕並將其記錄到文件中。
something you're doing -Verbose 4>&1 | Tee-Object "C:\logs\verb.log" -Append
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.