Hi ,I have the following code which checks for scheduled tasks on a list of computers and returns those which were not created by Microsoft and run as administrator.
I'm trying to write any errors to $ErrorLog. It works if the server is not contactable or if access is denied as it writes the error to $ErrorLog and carries on with the next computer.
I have some machines that are returning an error (nError:ERROR: The task XML contains a value which is incorrectly formatted or out of range) on one of these machines (at least) there are scheduled tasks which are in a valid format but these then end up printed to the screen rather than the task details being output to a file. I tried moving the 'Try/catch' to inside the 'foreach ($task in $tasks)' but the first error caused the script to end completely.
Any help greatly appreciated as this is causing just a little frustration! please do the 'idiot' guide approach if replying as I'm new to this.
Thanks.
Pete.
Function gettasks
{
."c:\scripts\Set-AlternatingRows.PS1"
$ComputerList = Get-Content ("c:\scripts\scan2.txt")
$OutPut = "c:\scripts\schedtasklist.txt"
$Date = Get-Date
$ErrorLog = "C:\Scripts\SchedTaskErrors.txt"
$HTMLReport = "C:\Scripts\ScheduledTaskAsAdmin.htm"
"HostName,Task,Next Run Time,Run As" | Out-File $Output
"Scheduled Tasks Errors $Date" | Out-File $ErrorLog
Foreach ($Computer In $ComputerList)
{
TRY
{
$ErrorActionPreference = "stop";
$Computer
$Tasks = schtasks.exe /query /s $Computer /V /FO CSV | ConvertFrom-Csv | Where { ($_.Author -ne "Microsoft Corporation") -and ($_."Run As User" -Like "*administrator")}
ForEach ($Task in $Tasks)
{
# $ErrorActionPreference = "Continue";
$HostName = $Task."HostName"
$TaskName = $Task."TaskName"
$NextRunTime = $Task."Next Run Time"
$RunAsUser = $Task."Run As User"
"$Hostname, $TaskName, $NextRunTime, $RunAsUser" | Out-File $OutPut -append
}
}
CATCH
{
# "Error on $Tasks 'nError:$($_.Exception.Message)" | Out-File $ErrorLog -Append
# "Error on $Task 'nError:$($_.Exception.Message)" | Out-File $ErrorLog -Append
"Error on $Computer 'nError:$($_)" | Out-File $ErrorLog -Append # .Exception.Message)" | Out-File $ErrorLog -Append
# "Error on $HostName 'nError:$($_.Exception.Message)" | Out-File $ErrorLog -Append
}
}
$Report = Get-Content $OutPut | ConvertFrom-Csv
$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
.odd { background-color:#ffffff; }
.even { background-color:#dddddd; }
</style>
<title> "Scheduled Tasks" </title>
"@
$Pre="Scheduled tasks running as administrator $Date"
# $Report | Select 'HostName','Task','Next Run Time','Run As' | ConvertTo-HTML -Head $Header -PreContent $Pre | Set-AlternatingRows -CSSEvenClass even -CSSOddClass odd | out-file $HTMLReport
}
gettasks