The following script will collect tasks scheduled in Task Scheduler in windows server from all SQL server VMs. The purpose of my script is to know monthly reboot schedule of each server in the organization.
Enjoy Scripting..
Step 1. Create a text file in which all sql server vm names. Save the file in your preferred. In my case the file is located at E:\PowerShell\SQLServerList\ folder
Step 2. run the script in powershell ISE or Schedule it in SQL Agent in your DBA test server instance
$($ServerList = 'E:\PowerShell\SQLServerList\SQLSvrList.txt'
if(!(test-path $ServerList))
{
Write-Error "SQLSvrList.txt is not Found" -ea Stop
}
if(test-path $ServerList)
{
$errorlog = 'E:\PowerShell\GetScheduleTask\Error.txt'
$exportcsv ='E:\PowerShell\GetScheduleTask\ScheduleList.csv'
$servername = Get-Content $ServerList
foreach($server in $servername){
Try{
Clear-Content $exportcsv
$schedule = new-object -com("Schedule.Service")
$schedule.connect($server)
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks |select @{Name="Server";Expression={$server}},Name,LastRunTime,NextRunTime,@{Name="RunAs";Expression={[xml]$xml = $_.xml ; $xml.Task.Principals.principal.userID}}
}Catch
{
Clear-Content $errorlog
"Fail to get information $server +' ' + $RunTime :$_" |Out-File $errorlog -Append
}
}
})|Export-csv $exportcsv -noType
Get-Job | Wait-Job | Out-Null
Remove-Job -State Completed
No comments:
Post a Comment