簡體   English   中英

如何從 Powershell 腳本的日志中獲取錯誤信息以創建計划任務?

[英]How to get error information from logs on a Powershell script to create a scheduled task?

我有一個創建計划任務的 PowerShell 腳本。 我通過 MEM/Intune 部署了這個腳本,但它目前正在出錯。 我需要知道是否有辦法確定失敗的確切原因和/或時間(在什么步驟)。 我需要將什么添加到錯誤日志記錄中以獲取日志中填充的更多信息? 也許是 if/else 語句? 不確定...提前感謝您的幫助。

$OutputFile = "$env:WINDIR\TEMP\CPCWindowsUpdates.log"
##########ERROR LOGGING#####
Function Set-WriteToLog ($Write1)
{
    Write-Host "$(Get-Date -format yyyy-MM-dd-hh-mm-ss)`t-`t$Write1"
}
#########START OF SCRIPT BODY#############
Start-Transcript -Path $OutputFile

###creates a scheduled task to import Windows update module and run Windows updates once at logon of new user###
$action = (New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {Install-Module -Name PSWindowsUpdate -Force}"'), (New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {Install-WindowsUpdate -AcceptAll -Install}"')

$trigger = New-ScheduledTaskTrigger -AtLogOn 
$trigger.Repetition = (New-ScheduledTaskTrigger -once -at "12am" -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Minutes 3)).repetition

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Update Windows" -Description "performs Windows Updates at first logon"

Stop-Transcript

這取決於您希望實現的目標。

以下內容將為您提供 powershell 記錄的最后一個錯誤。 但我不確定這是否足以滿足您的需求

$OutputFile = "$env:WINDIR\TEMP\CPCWindowsUpdates.log"
##########ERROR LOGGING#####
Function Set-WriteToLog ($Write1)
{
    Write-Host "$(Get-Date -format yyyy-MM-dd-hh-mm-ss)`t-`t$Write1"
}
#########START OF SCRIPT BODY#############
Start-Transcript -Path $OutputFile

###creates a scheduled task to import Windows update module and run Windows updates once at logon of new user###
try {
    $action = (New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {Install-Module -Name PSWindowsUpdate -Force}"'), (New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -command "& {Install-WindowsUpdate -AcceptAll -Install}"')
    $trigger = New-ScheduledTaskTrigger -AtLogOn 
    $trigger.Repetition = (New-ScheduledTaskTrigger -once -at "12am" -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Minutes 3)).repetition
}
catch {
    $data = Get-Error
    Set-WriteToLog $data
}

Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Update Windows" -Description "performs Windows Updates at first logon"

Stop-Transcript

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM