Ranadip_Dutta

Scheduled Task

Oct 23rd, 2016
2,663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .Synopsis
  3.    Write-Log writes a message to a specified log file with the current time stamp.
  4. .DESCRIPTION
  5.    The Write-Log function is designed to add logging capability to other scripts.
  6.    In addition to writing output and/or verbose you can write to a log file for
  7.    later debugging.  
  8.    Changelog:
  9.     * Code simplification and clarification
  10.     * Added documentation.
  11.     * Renamed LogPath parameter to Path to keep it standard.
  12.     * Revised the Force switch to work as it should.
  13.  
  14.    To Do:
  15.     * Add error handling if trying to create a log file in a inaccessible location.
  16.     * Add ability to write $Message to $Verbose or $Error pipelines to eliminate
  17.       duplicates.
  18. .PARAMETER Message
  19.    Message is the content that you wish to add to the log file.  
  20. .PARAMETER Path
  21.    The path to the log file to which you would like to write. By default the function will  
  22.    create the path and file if it does not exist.  
  23. .PARAMETER Level
  24.    Specify the criticality of the log information being written to the log (i.e. Error, Warning, Informational)
  25. .PARAMETER NoClobber
  26.    Use NoClobber if you do not wish to overwrite an existing file.
  27. .EXAMPLE
  28.    Write-Log -Message 'Log message'  
  29.    Writes the message to c:\Logs\PowerShellLog.log.
  30. .EXAMPLE
  31.    Write-Log -Message 'Restarting Server.' -Path c:\Logs\Scriptoutput.log
  32.    Writes the content to the specified log file and creates the path and file specified.  
  33. .EXAMPLE
  34.    Write-Log -Message 'Folder does not exist.' -Path c:\Logs\Script.log -Level Error
  35.    Writes the message to the specified log file as an error message, and writes the message to the error pipeline.  
  36. #>
  37. function Write-Log
  38. {
  39.     [CmdletBinding()]
  40.     Param
  41.     (
  42.         [Parameter(Mandatory=$true,
  43.                    ValueFromPipelineByPropertyName=$true)]
  44.         [ValidateNotNullOrEmpty()]
  45.         [Alias("LogContent")]
  46.         [string]$Message,
  47.  
  48.         [Parameter(Mandatory=$false)]
  49.         [Alias('LogPath')]
  50.         [string]$Path='C:\Logs\PowerShellLog.log',
  51.          
  52.         [Parameter(Mandatory=$false)]
  53.         [ValidateSet("Error","Warn","Info")]
  54.         [string]$Level="Info",
  55.          
  56.         [Parameter(Mandatory=$false)]
  57.         [switch]$NoClobber
  58.     )
  59.  
  60.     Begin
  61.     {
  62.         # Set VerbosePreference to Continue so that verbose messages are displayed.
  63.         $VerbosePreference = 'Continue'
  64.     }
  65.     Process
  66.     {
  67.          
  68.         # If the file already exists and NoClobber was specified, do not write to the log.
  69.         if ((Test-Path $Path) -AND $NoClobber) {
  70.             Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
  71.             Return
  72.             }
  73.  
  74.         # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path.
  75.         elseif (!(Test-Path $Path)) {
  76.             Write-Verbose "Creating $Path."
  77.             $NewLogFile = New-Item $Path -Force -ItemType File
  78.             }
  79.  
  80.         else {
  81.             # Nothing to see here yet.
  82.             }
  83.  
  84.         # Format Date for our Log File
  85.         $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
  86.  
  87.         # Write message to error, warning, or verbose pipeline and specify $LevelText
  88.         switch ($Level) {
  89.             'Error' {
  90.                 Write-Error $Message
  91.                 $LevelText = 'ERROR:'
  92.                 }
  93.             'Warn' {
  94.                 Write-Warning $Message
  95.                 $LevelText = 'WARNING:'
  96.                 }
  97.             'Info' {
  98.                 Write-Verbose $Message
  99.                 $LevelText = 'INFO:'
  100.                 }
  101.             }
  102.          
  103.         # Write log entry to $Path
  104.         "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append
  105.     }
  106.     End
  107.     {
  108.     }
  109. }
  110.  
  111.  
  112.  
  113.  
  114.  
  115. try
  116. {
  117. $ErrorActionPreference='SilentlyContinue'
  118. $Error.Clear()
  119. $Path=$env:windir
  120. Write-Log -Message "################ Script Started #############################" -Level Info
  121. #$input_details= "hardware,10-12-2016-14-20,1;Organization,09-12-2016-15-50,2;"
  122. $input_details= $args[0];
  123. Write-Log -Message "The Input Details are : $input_details" -Level Info
  124. $input_details= $input_details.Remove($input_details.Length -1)
  125. $Inputs = $input_details -split ';'
  126.  
  127.     foreach ($inps in $Inputs)
  128.     {
  129.             Write-Log -Message "###### Operation Inside Loop ######################" -Level Info
  130.                 $array=$inps.split(',')
  131.                 $global:schedule_name=$array[0]
  132.                 $global:Assessment_type=$array[0]
  133.                 $global:Date= $array[1]
  134.                 $global:interval = $array[2]
  135.  
  136.                 $template = 'MM-dd-yyyy-HH-mm'
  137.                 $StartTime = [DateTime]::ParseExact($date, $template, $null)
  138.  
  139.           If(!(& $Path\System32\schtasks.exe /query /TN "SHA_$schedule_name"))
  140.             {
  141.             "Task Not Existed with the name SHA_$schedule_name. Creating the Task."
  142.             Write-Log -Message "Task Not Existed with the name SHA_$schedule_name. Creating the Task." -Level Info
  143.                 $TaskName = "SHA_$schedule_name"
  144.                 $TaskDescr = "Automated Scheduled Task from Powershell"
  145.                 $TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
  146.                 $TaskScript = '"C:\Users\rdutta\Desktop\Scripts\'+"$Assessment_type.ps1"+'"'
  147.                 $TaskArg = "-Executionpolicy unrestricted -file $TaskScript"
  148.                 [DateTime]$TaskStartTime = $StartTime
  149.             Write-Log -Message "Task Name: $TaskName" -Level Info
  150.             Write-Log -Message "TaskDescription : $TaskDescr" -Level Info
  151.             Write-Log -Message "Task Script: $TaskScript" -Level Info
  152.             Write-Log -Message "Task Start Date & Time : $TaskStartTime " -Level Info
  153.            
  154.  
  155.                         $service = new-object -ComObject("Schedule.Service")
  156.                         # connect to the local machine.
  157.  
  158.                         $service.Connect()
  159.                         $rootFolder = $service.GetFolder("\")
  160.                         $TaskDefinition = $service.NewTask(0)
  161.                         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
  162.                         $TaskDefinition.Settings.Enabled = $true
  163.                         $TaskDefinition.Settings.AllowDemandStart = $true
  164.                         $TaskDefinition.Settings.StartWhenAvailable = $true
  165.                         $TaskDefinition.Settings.StopIfGoingOnBatteries=$false
  166.                         $TaskDefinition.Settings.DisallowStartIfOnBatteries=$false
  167.                         $TaskDefinition.Settings.MultipleInstances=2
  168.                         $taskdefinition.Settings.WakeToRun=$true
  169.                         $triggers = $TaskDefinition.Triggers
  170.                         $trigger = $triggers.Create(1) # Creates a "One time" trigger
  171.                         $trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
  172.                         $time_interval=New-TimeSpan -Minutes $interval
  173.                         $time_interval=$time_interval.TotalSeconds
  174.                         $trigger.Repetition.Interval= "PT"+"$time_interval"+"S"
  175.                         $trigger.Enabled = $true
  176.                         $TaskDefinition.Principal.RunLevel =1
  177.                         $Action = $TaskDefinition.Actions.Create(0)
  178.                         $action.Path = "$TaskCommand"
  179.                         $action.Arguments = "$TaskArg"
  180.                         # In Task Definition,
  181.                         #   6 indicates "the task will not execute when it is registered unless a time-based trigger causes it to execute on registration."
  182.                         #   5 indicates "Indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task.In this case, its the SYSTEM"
  183.                         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) | Out-Null
  184.                         "Scheduled Task has been created successfully with the name SHA_$schedule_name"
  185.                         Write-Log -Message "Scheduled Task has been created successfully with the name SHA_$schedule_name" -Level Info
  186.                         Write-Log -Message "#########################################################################################" -Level Info
  187.  
  188.  
  189.                }
  190.  
  191.         elseIf(& $Path\System32\schtasks.exe /query /TN "SHA_$schedule_name")
  192.             {
  193.             "Task Existed with the name SHA_$schedule_name. Updating the Task."
  194.             Write-Log -Message "Task Existed with the name SHA_$schedule_name. Updating the Task." -Level Info
  195.                 $TaskName = "SHA_$schedule_name"
  196.                 $TaskDescr = "Automated Scheduled Task from Powershell"
  197.                 $TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
  198.                 $TaskScript = '"C:\Users\rdutta\Desktop\Scripts\'+"$Assessment_type.ps1"+'"'
  199.                 $TaskArg = "-Executionpolicy unrestricted -file $TaskScript"
  200.                 [DateTime]$TaskStartTime = $StartTime
  201.                 Write-Log -Message "Task Name: $TaskName" -Level Info
  202.                 Write-Log -Message "TaskDescription : $TaskDescr" -Level Info
  203.                 Write-Log -Message "Task Script: $TaskScript" -Level Info
  204.                 Write-Log -Message "Task Start Date & Time : $TaskStartTime " -Level Info
  205.            
  206.  
  207.                         $service = new-object -ComObject("Schedule.Service")
  208.                         # connect to the local machine.
  209.  
  210.                         $service.Connect()
  211.                         $rootFolder = $service.GetFolder("\")
  212.                         $TaskDefinition = $service.NewTask(0)
  213.                         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
  214.                         $TaskDefinition.Settings.Enabled = $true
  215.                         $TaskDefinition.Settings.AllowDemandStart = $true
  216.                         $TaskDefinition.Settings.StartWhenAvailable = $true
  217.                         $TaskDefinition.Settings.StopIfGoingOnBatteries=$false
  218.                         $TaskDefinition.Settings.DisallowStartIfOnBatteries=$false
  219.                         $TaskDefinition.Settings.MultipleInstances=2
  220.                         $taskdefinition.Settings.WakeToRun=$true
  221.                         $triggers = $TaskDefinition.Triggers
  222.                         $trigger = $triggers.Create(1) # Creates a "One time" trigger
  223.                         $trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
  224.                         $time_interval=New-TimeSpan -Minutes $interval
  225.                         $time_interval=$time_interval.TotalSeconds
  226.                         $trigger.Repetition.Interval= "PT"+"$time_interval"+"S"
  227.                         $trigger.Enabled = $true
  228.                         $TaskDefinition.Principal.RunLevel =1
  229.                         $Action = $TaskDefinition.Actions.Create(0)
  230.                         $action.Path = "$TaskCommand"
  231.                         $action.Arguments = "$TaskArg"
  232.                         # In Task Definition,
  233.                         #   6 indicates "the task will not execute when it is registered unless a time-based trigger causes it to execute on registration."
  234.                         #   5 indicates "Indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task.In this case, its the SYSTEM"
  235.                         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) |Out-Null
  236.                         "Scheduled Task with the name SHA_$schedule_name has been updated successfully"
  237.                         Write-Log -Message "Scheduled Task with the name SHA_$schedule_name has been updated successfully" -Level Info
  238.                         Write-Log -Message "#########################################################################################" -Level Info
  239.                        
  240.             }
  241.     }
  242. }
  243. catch
  244. {Write-Log -Message $_.Exception.Message -Level Error}
  245. Finally
  246. {Write-Log -Message $Error -Level Error}
Add Comment
Please, Sign In to add comment