evetsleep

Get-ScheduledTasks

Oct 18th, 2013
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Get-ScheduledTasks
  2. {
  3.     [CmdletBinding()]
  4.     Param
  5.     (
  6.         [Parameter(Mandatory=$true,
  7.                     Position=0)]
  8.         [ValidateNotNullOrEmpty()]
  9.         [String[]]$ComputerName,
  10.  
  11.         [Parameter(Mandatory=$false,
  12.                     Position=1)]
  13.         [ValidateNotNullOrEmpty()]
  14.         [switch]$HTML
  15.     )
  16.  
  17.     #Define the script block we'll run on each machine.
  18.     Write-Verbose "Defining script block for each machine"
  19.     $script = {
  20.         $cName = $env:computerName
  21.  
  22.         #Create schedule COM object and connect to it.
  23.         $taskObj = new-object -com Schedule.Service
  24.         $taskObj.connect($cName)
  25.    
  26.         #Get the assigned tasks and store them in a custom object
  27.         $taskRoot = $taskObj.getfolder("\")
  28.         $tasks = $taskRoot.GetTasks(0)
  29.         $taskData = $tasks | select Name,
  30.             Enabled,
  31.             @{Name="RunAs";Expression={[xml]$xml = $_.xml ; $xml.Task.Principals.principal.userID}},
  32.             @{Name="Author";Expression={[xml]$xml = $_.xml ; $xml.Task.RegistrationInfo.Author}}
  33.    
  34.         #Return any detected tasks.
  35.         return $taskData
  36.         }
  37.  
  38.    
  39.     try
  40.     {
  41.         #Run the script block against all the servers returned (32 at a time)
  42.         Write-Verbose "Invoking script block on each machine"
  43.         $data = Invoke-Command -ComputerName $ComputerName -ScriptBlock $script -ErrorAction Stop
  44.     }
  45.     catch
  46.     {
  47.         Throw $("There was an error invoking command: {0}" -f $_.exception.message)
  48.     }
  49.    
  50.     if($HTML)
  51.     {  
  52.         #Define the HTML header for the report.
  53.         $style = @'
  54. <style>
  55. body { background-color:#EEEEEE; }
  56. body,table,td,th { font-family:Tahoma; color:Black; Font-Size:10pt }
  57. th { font-weight:bold; background-color:#AAAAAA; }
  58. td { background-color:white; }
  59. </style>
  60. '@
  61.  
  62.         #Output the server report, sort it, and convert it to HTML and then store it as a string.
  63.         Write-Verbose "Building e-mail report"
  64.         $htmlbody = $data | where {$_.runas -cnotmatch '^S-|^System$'} |
  65.         sort PSComputerName | ConvertTo-Html PSComputerName,Name,Enabled,RunAs,Author -Head $style -PostContent "<br>" | Out-String
  66.  
  67.         $htmlBody | Out-File .\TaskReport.html -Force
  68.         Invoke-Expression .\TaskReport.html
  69.    
  70.     }
  71.     else
  72.     {
  73.         Write-Output $data
  74.     }
  75. } #END Get-ScheduledTasks
Advertisement
Add Comment
Please, Sign In to add comment