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

141 Views Asked by At

I have a PowerShell script that creates a Scheduled Task. I deploy this script through MEM/Intune and it is currently erroring out. I need to know if there is a way to determine exactly why and/or when (at what step) it fails. What do I need to add to the error logging to get more information populated in the logs? Maybe an if/else statement? Not sure... thanks for any help in advance.

$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
1

There are 1 best solutions below

0
Martinta On

That depends on what you wish to archieve.

Something along the lines of the following will provide you with the last error that powershell logged. But i'm unsure if that's enough for you needs

$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