From 8c6434854b0a7fe5729a4700d9e3161dc37052dd Mon Sep 17 00:00:00 2001 From: Jason Gilbertson Date: Wed, 26 Jul 2017 00:06:50 -0400 Subject: [PATCH] =?UTF-8?q?bad=20A=20character=20cleanup=20'=C2=A0=C2=A0?= =?UTF-8?q?=C2=A0=20=20=20=20'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + 2k12-rds-tracing/event-log-manager.ps1 | 4 +- .../events-export/event-log-manager.ps1 | 4 +- .../procmon-tracing/event-task-procmon.ps1 | 364 ++++++++--------- 2k12-remote-manager/remote-manager.ps1 | 136 +++---- Umdh-manager.ps1 | 254 ++++++------ Umdh-task-2k8.ps1 | 58 +-- deploy-files-task.ps1 | 250 ++++++------ dump-configurator.ps1 | 169 ++++---- enum-wmi.ps1 | 20 +- event-task-procmon.ps1 | 366 +++++++++--------- eventTask.ps1 | 356 ++++++++--------- file-copy.ps1 | 8 +- file-regex-string-compare.ps1 | 32 +- find-unique-lines.ps1 | 18 +- functions.ps1 | 170 ++++---- perfmon-counter-action.ps1 | 8 +- ps-certreq.ps1 | 158 ++++---- rds-upd-mgr.ps1 | 266 +++++++------ rdv-vdi-query.ps1 | 2 +- remote-manager.ps1 | 136 +++---- set-regPermissions.ps1 | 66 ++-- 22 files changed, 1434 insertions(+), 1413 deletions(-) diff --git a/.gitignore b/.gitignore index 68af8413..1baaeea5 100644 --- a/.gitignore +++ b/.gitignore @@ -247,6 +247,8 @@ ModelManifest.xml # CUSTOM *.txt +*.ini +*.req *.cer *.pfx **/gather diff --git a/2k12-rds-tracing/event-log-manager.ps1 b/2k12-rds-tracing/event-log-manager.ps1 index 2501108a..8a6bdbe0 100644 --- a/2k12-rds-tracing/event-log-manager.ps1 +++ b/2k12-rds-tracing/event-log-manager.ps1 @@ -1109,7 +1109,7 @@ function log-info($data, [switch] $nocolor = $false, [switch] $debugOnly = $fals if($global:logStream -eq $null) { $global:logStream = new-object System.IO.StreamWriter ($logFile,$true) - $global:logTimer.Interval = 5000 #5 seconds  + $global:logTimer.Interval = 5000 #5 seconds Register-ObjectEvent -InputObject $global:logTimer -EventName elapsed -SourceIdentifier logTimer -Action ` { @@ -1122,7 +1122,7 @@ function log-info($data, [switch] $nocolor = $false, [switch] $debugOnly = $fals } # reset timer - $global:logTimer.Interval = 5000 #5 seconds  + $global:logTimer.Interval = 5000 #5 seconds $global:logStream.WriteLine("$([DateTime]::Now.ToString())::$([Diagnostics.Process]::GetCurrentProcess().ID)::$($data)") } catch {} diff --git a/2k12-remote-manager/events-export/event-log-manager.ps1 b/2k12-remote-manager/events-export/event-log-manager.ps1 index ccf236b1..98ed3633 100644 --- a/2k12-remote-manager/events-export/event-log-manager.ps1 +++ b/2k12-remote-manager/events-export/event-log-manager.ps1 @@ -1079,7 +1079,7 @@ function log-info($data, [switch] $nocolor = $false, [switch] $debugOnly = $fals if($global:logStream -eq $null) { $global:logStream = new-object System.IO.StreamWriter ($logFile,$true) - $global:logTimer.Interval = 5000 #5 seconds  + $global:logTimer.Interval = 5000 #5 seconds Register-ObjectEvent -InputObject $global:logTimer -EventName elapsed -SourceIdentifier logTimer -Action ` { @@ -1092,7 +1092,7 @@ function log-info($data, [switch] $nocolor = $false, [switch] $debugOnly = $fals } # reset timer - $global:logTimer.Interval = 5000 #5 seconds  + $global:logTimer.Interval = 5000 #5 seconds $global:logStream.WriteLine("$([DateTime]::Now.ToString())::$([Diagnostics.Process]::GetCurrentProcess().ID)::$($data)") } catch {} diff --git a/2k12-remote-manager/procmon-tracing/event-task-procmon.ps1 b/2k12-remote-manager/procmon-tracing/event-task-procmon.ps1 index a15233d0..91c87dba 100644 --- a/2k12-remote-manager/procmon-tracing/event-task-procmon.ps1 +++ b/2k12-remote-manager/procmon-tracing/event-task-procmon.ps1 @@ -1,20 +1,20 @@ -<#  -.SYNOPSIS  -    powershell script to monitor debug event logs for event match -.DESCRIPTION  -    This script will monitor 'analytic' and 'debug' event logs of format .etl for certain event entries. +<#  +.SYNOPSIS +powershell script to monitor debug event logs for event match +.DESCRIPTION +This script will monitor 'analytic' and 'debug' event logs of format .etl for certain event entries. Optionally on match, the script can send an email or run an action. -.NOTES  -   File Name  : event-task-procmon.ps1  -   Author  : jagilber -   Version : +.NOTES +File Name : event-task-procmon.ps1 +Author : jagilber + Version : 160920 added -force switch to try delete regardless if open History : 150913 - added process wait and file monitor - added wait for process terminate -.EXAMPLE  -    .\event-task-procmon.ps1 -install $true +.EXAMPLE +.\event-task-procmon.ps1 -install $true .\event-task-procmon.ps1 -uninstall $true .\event-task-procmon.ps1 -test $true .PARAMETER install @@ -27,8 +27,8 @@ working script directory .PARAMETER force use to try delete regardless if open -#>  -  +#> + Param( [parameter(HelpMessage="select to force procmon when pml is around 1GB")] [switch] $circular, @@ -43,14 +43,14 @@ Param( [parameter(HelpMessage="Enter working directory")] [string] $workingDir ) -  + $error.Clear() -  + $ErrorActionPreference = "SilentlyContinue" $logFile = "event-task-procmon.log" $sleepItervalSecs = 60 $startTime = [DateTime]::Now -  + # event information $eventLog = "" # "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Admin" $eventId = "" #20491 @@ -91,7 +91,7 @@ $To = "" $From = "" $Subject = "$($env:computername): monitored event received" $Body = "event was received that matches filter" -  + # SMTP Relay Settings $Server = "" $Port = @@ -99,7 +99,7 @@ $passFile = "" $username = "" $useSSL = $false $useCreds = $false -  + # scheduled task info $TaskName = "EventLog Monitor" $TaskDescr = "Monitors eventlog for event" @@ -107,26 +107,26 @@ $TaskCommand = "powershell.exe" $TaskScript = (get-variable myinvocation -scope script).Value.Mycommand.Definition #"$($workingDir)\event-task-procmon.ps1" $TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy bypass -file $TaskScript" $time = (get-date) #- (new-timespan -day 12) -$processIds = @{}  -  +$processIds = @{} + # ---------------------------------------------------------------------------------------------------------------- function main() { try { -  + if($useCreds) { -     set-credentials + set-credentials } -  -  + + if([string]::IsNullOrEmpty($workingDir)) { -     $workingDir = get-workingDirectory + $workingDir = get-workingDirectory } -  -   if($install) + + if($install) { install-task exit @@ -149,19 +149,19 @@ function main() runas-admin $scriptName install-task -     new-eventLog -LogName $eventLog -source "TEST" -      Write-EventLog -LogName $eventLog -Source "TEST" -Message "TEST" -EventId $eventId -EntryType Information -     remove-eventlog -source "TEST" + new-eventLog -LogName $eventLog -source "TEST" + Write-EventLog -LogName $eventLog -Source "TEST" -Message "TEST" -EventId $eventId -EntryType Information + remove-eventlog -source "TEST" monitor-events uninstall-task -    exit + exit } -  else + else { # start tracing run-processes $eventTasksDeploy -     monitor-events + monitor-events monitor-files } @@ -181,20 +181,20 @@ function main() function set-credentials() { $Creds -    # if storing creds for smtp, password will have to be saved one time -    # uncomment following to prompt for credentials -    #$Creds = Get-Credential -  -    if(!$Creds) -    { -     if(!(test-path $passFile)) -     { -         read-host -assecurestring | convertfrom-securestring | out-file $passFile -     } -  -     $password = cat $passFile | convertto-securestring -     $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password -    } +# if storing creds for smtp, password will have to be saved one time +# uncomment following to prompt for credentials +#$Creds = Get-Credential + +if(!$Creds) +{ + if(!(test-path $passFile)) + { + read-host -assecurestring | convertfrom-securestring | out-file $passFile + } + + $password = cat $passFile | convertto-securestring + $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password +} } # ---------------------------------------------------------------------------------------------------------------- @@ -286,8 +286,8 @@ function is-fileLocked([string] $file) # ---------------------------------------------------------------------------------------------------------------- function monitor-events() { -   $matchCount = 0 -    $monitoring = $true + $matchCount = 0 +$monitoring = $true $lastRecordId = 0 $time = $startTime @@ -303,11 +303,11 @@ function monitor-events() # check files to delete oldest check-files -     $events = get-winEvent -Oldest -FilterHashTable @{LogName=$eventLog; StartTime=$time; Id=$eventId} -     log-info "new event count matching filter:$($events.Length) startTime:$($time)" -  -     foreach($event in $events) -     { + $events = get-winEvent -Oldest -FilterHashTable @{LogName=$eventLog; StartTime=$time; Id=$eventId} + log-info "new event count matching filter:$($events.Length) startTime:$($time)" + + foreach($event in $events) + { if([string]::IsNullOrEmpty($event.TimeCreated)) { @@ -315,7 +315,7 @@ function monitor-events() continue } -         $time = $event.TimeCreated + $time = $event.TimeCreated log-info "last event TimeCreated:$($time) recordId: $($event.RecordId) matchCount: $($matchCount)" # bump time by a second so that we do not get duplicate returns @@ -332,24 +332,24 @@ function monitor-events() $lastRecordId = $event.RecordId } -            log-info $event.Message -  -          #  [xml] $xml = $event.ToXml() -  -         -             -            if($test) -         { +log-info $event.Message + +# [xml] $xml = $event.ToXml() + + + +if($test) + { # with a test source, message will not be stored in event object correctly -             $eventLabel = $xml.Event.EventData.Data #$event.Message -             $label = "TEST" + $eventLabel = $xml.Event.EventData.Data #$event.Message + $label = "TEST" $monitoring = $false -            } -  -             log-info "found match:$($event)" +} + + log-info "found match:$($event)" $matchCount++ -            send-mail + send-mail # stop tracing to gather information #run-processes $eventTasksUnDeploy @@ -364,13 +364,13 @@ function monitor-events() # still monitoring so restart tracing # run-processes $eventTasksDeploy } -           -     } -  -     if($monitoring) -     { -        sleep $sleepItervalSecs -     } + + } + + if($monitoring) + { + sleep $sleepItervalSecs + } } } @@ -380,11 +380,11 @@ function install-task() # run as administrator runas-admin $scriptName -    # add to task scheduler as a computer startup script + # add to task scheduler as a computer startup script if(manage-scheduledTask -enable $true -taskInfo $taskInfoDeploy) { $eventLog = Get-WinEvent -ListLog $eventLog -     $eventLog.IsEnabled = $true + $eventLog.IsEnabled = $true $eventLog.SaveChanges() log-info "create scheduled task and enabled debug eventlog" } @@ -407,12 +407,12 @@ function uninstall-task() manage-scheduledTask -enable $false -taskInfo $taskInfoDeploy manage-scheduledTask -enable $true -taskInfo $taskInfoUnDeploy -wait $true -    if(manage-scheduledTask -enable $false -taskInfo $taskInfoUnDeploy -wait $true) +if(manage-scheduledTask -enable $false -taskInfo $taskInfoUnDeploy -wait $true) { -  $eventLog = Get-WinEvent -ListLog $eventLog -  $eventLog.IsEnabled = $false -  $eventLog.SaveChanges() -  log-info "deleted scheduled task and disabled debug eventlog" + $eventLog = Get-WinEvent -ListLog $eventLog + $eventLog.IsEnabled = $false + $eventLog.SaveChanges() + log-info "deleted scheduled task and disabled debug eventlog" } else { @@ -433,20 +433,20 @@ function send-mail() return } -    if($useSSL -and $useCreds) +if($useSSL -and $useCreds) { -     Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -UseSsl -Credential $Creds -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -UseSsl -Credential $Creds -Subject $Subject -Body $Body } elseif($useCreds) { -   Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Credential $Creds -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Credential $Creds -Subject $Subject -Body $Body } else { -    Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Subject $Subject -Body $Body } } -  + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) { @@ -468,7 +468,7 @@ function run-processes($processes, [bool] $wait = $false) } } } -  + # ---------------------------------------------------------------------------------------------------------------- function run-process([string] $processName, [string] $arguments, [bool] $wait = $false) { @@ -483,7 +483,7 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.CreateNoWindow = $true $process.StartInfo.WorkingDirectory = get-location -    if(!$process.Start()) +if(!$process.Start()) { log-info "Error:unable to start process" return 0 @@ -491,35 +491,35 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = if($wait -and !$process.HasExited) { -     $process.WaitForExit($processWaitMs) -     $exitVal = $process.ExitCode -     $stdOut = $process.StandardOutput.ReadToEnd() -     $stdErr = $process.StandardError.ReadToEnd() -     log-info "Process output:$stdOut" -  -     if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") -     { -         log-info "Error:$stdErr `n $Error" -         $Error.Clear() -     } + $process.WaitForExit($processWaitMs) + $exitVal = $process.ExitCode + $stdOut = $process.StandardOutput.ReadToEnd() + $stdErr = $process.StandardError.ReadToEnd() + log-info "Process output:$stdOut" + + if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") + { + log-info "Error:$stdErr `n $Error" + $Error.Clear() + } log-info "Process terminated." return 0 } elseif($wait) { -     log-info "Process ended before capturing output." + log-info "Process ended before capturing output." return 0 } -    #return $exitVal +#return $exitVal return $process.ID } -  + # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [bool] $wait = $false) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets $TaskName = $taskInfo.taskname @@ -528,10 +528,10 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo $TaskDir = $taskInfo.taskdir $TaskArg = $taskInfo.taskarg -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx # for remote machine connect do $service.Connect(serverName,user,domain,password) if([string]::IsNullOrEmpty($machine)) { @@ -539,73 +539,73 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo } else { -     $service.Connect($machine) + $service.Connect($machine) } -  -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" # 2k8r2 is 65539 (0x10003) 1.3 # procmon needs at least 2k8r2 compat #$TaskDefinition.Settings.Compatibility = 3 -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $TaskDir -         -            #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) -  -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $TaskDir + +#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } -  -  if($wait) + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } + + if($wait) { log-info "waiting for task to complete" while($true) { $foundTask = $false -      # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $foundTask = $true -             } -         } + $foundTask = $true + } + } if(!$foundTask) { @@ -626,40 +626,40 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo { return $true } -  + } -  + # ---------------------------------------------------------------------------------------------------------------- function get-workingDirectory() { $retVal = $null -  + if (Test-Path variable:\hostinvocation) { -     $retVal = $hostinvocation.MyCommand.Path + $retVal = $hostinvocation.MyCommand.Path } else { -     $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition + $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition } -  -    if (Test-Path $retVal) + +if (Test-Path $retVal) { -     $retVal = (Split-Path $retVal) + $retVal = (Split-Path $retVal) } else { -     $retVal = (Get-Location).path -     log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -     -    } -  + $retVal = (Get-Location).path + log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -    Set-Location $retVal -  +} + + +Set-Location $retVal + return $retVal } -  + # ---------------------------------------------------------------------------------------------------------------- function runas-admin([string] $arguments) { diff --git a/2k12-remote-manager/remote-manager.ps1 b/2k12-remote-manager/remote-manager.ps1 index a588b1c7..d120c739 100644 --- a/2k12-remote-manager/remote-manager.ps1 +++ b/2k12-remote-manager/remote-manager.ps1 @@ -6,7 +6,7 @@ Set-ExecutionPolicy Bypass -Force powershell script to manage commands remotely across multiple machines default job definitions at bottom of script -   + .NOTES File Name : remote-manager.ps1 Author : jagilber @@ -54,9 +54,9 @@ Param( [string[]] $machines = @($env:COMPUTERNAME), [parameter(HelpMessage="Enter number of minutes from now for event log gathering. Default is 60")] [string[]] $minutes = 60, -  [parameter(HelpMessage="Use to not clean remote working directory on stop")] + [parameter(HelpMessage="Use to not clean remote working directory on stop")] [switch] $noclean, -  [parameter(HelpMessage="Use to start")] + [parameter(HelpMessage="Use to start")] [switch] $start, [parameter(HelpMessage="Use to stop")] [switch] $stop, @@ -64,7 +64,7 @@ Param( [int] $throttle = 10 ) -  + cls Add-Type -assembly "system.io.compression.filesystem" $ErrorActionPreference = "SilentlyContinue" #"Stop" @@ -716,8 +716,8 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [bool] $wait = $false) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets log-info "manage-scheduledTask $($taskInfo.taskname) $($machine)" @@ -727,10 +727,10 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f $TaskDir = $taskInfo.taskdir $TaskArg = $taskInfo.taskarg -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx # for remote machine connect do $service.Connect(serverName,user,domain,password) if([string]::IsNullOrEmpty($machine)) { @@ -738,80 +738,80 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f } else { -     $service.Connect($machine) + $service.Connect($machine) } -  -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" # 2k8r2 is 65539 (0x10003) 1.3 # procmon needs at least 2k8r2 compat #$TaskDefinition.Settings.Compatibility = 3 -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $TaskDir -         -          #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -       $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) -  -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $TaskDir + + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { if($debugScript) { log-info "found task $($TaskName)" } -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } -  -  if($wait) + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } + + if($wait) { log-info "waiting for task to complete" while($true) { $foundTask = $false -      # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { if($debugScript) { log-info "found task $($TaskName)" } -                 $foundTask = $true -             } -         } + $foundTask = $true + } + } if(!$foundTask) { @@ -832,9 +832,9 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f { return $true } -  + } # end manage-scheduledTask -  + } # end functions diff --git a/Umdh-manager.ps1 b/Umdh-manager.ps1 index c39f5545..edeef2bb 100644 --- a/Umdh-manager.ps1 +++ b/Umdh-manager.ps1 @@ -1,5 +1,5 @@   -  + <# .SYNOPSIS powershell script to manage umdh on local or remote machine @@ -25,13 +25,13 @@ .PARAMETER action The action to take. Currently this is either 'deploy' or 'undeploy'. -  + .PARAMETER machine The remote machine to deploy to. if deploying to local machine do not use this argument. #> -  + Param( -  + [parameter(Position=0,Mandatory=$false,HelpMessage="Enter the action to take: [deploy|undeploy]")] [string] $action, [parameter(Position=1,Mandatory=$false,HelpMessage="Enter machine name to deploy to:")] @@ -41,7 +41,7 @@ Param( [parameter(Position=3,Mandatory=$false,HelpMessage='Enter relative destination share path folder containing files. example: admin$\temp')] [string] $destPath ) -  + $scriptName = "umdh-script-start.bat" $logFile = "umdh-manager.log" $processWaitMs = 1000 @@ -59,12 +59,12 @@ $sleepTimeHours = 1 $requiresRestart = $false $procDumpExe = "procdump.exe" $procArguments = "-accepteula -ma" -  + # ---------------------------------------------------------------------------------------------------------------- function main() { runas-admin -  + if(![string]::IsNullOrEmpty($machine)) { @@ -75,7 +75,7 @@ function main() $machine = [Environment]::MachineName $isRemote = $false } -  + if($action -ieq "deploy") { #[Environment]::SetEnvironmentVariable( "_NT_SYMBOL_PATH", "c:\mysymbols;srv*c:\mycache*http://msdl.microsoft.com/download/symbols", [System.EnvironmentVariableTarget]::Machine ) @@ -84,13 +84,13 @@ function main() log-info "unable to find source path $($sourcePath). exiting" return } -  + if(![IO.Directory]::Exists("\\127.0.0.1\$($destPath)")) { log-info "unable to determine destination path \\127.0.0.1\$($destPath). exiting" return } -  + # verify $svcHostService is in its own process if($svcHostService -ne $null) { @@ -108,9 +108,9 @@ function main() } $svc.Start() -  + log-info "$svcHostService has been configured to run in its own process." -  + } else { @@ -120,15 +120,15 @@ function main() # get source files $sourceFiles = [IO.Directory]::GetFiles($sourcePath, "*.*", [System.IO.SearchOption]::TopDirectoryOnly) -  + # copy files foreach($sourceFile in $sourceFiles) { $destFile = [IO.Path]::GetFileName($sourceFile) $destFile = "\\$($machine)\$($destPath)\$($destFile)" -  + log-info "copying file $($sourceFile) to $($destFile)" -  + try { [IO.File]::Copy($sourceFile, $destFile, $true) @@ -140,10 +140,10 @@ function main() } } -  + #create scheduled task manage-scheduledTask -enable $true -machine $machine -  + if($requiresRestart) { $retVal = Read-Host -Prompt "server needs to be restarted. Do you want to do this now? [yes|no]" @@ -157,7 +157,7 @@ function main() Restart-Computer -ComputerName $machine -Force -Impersonation Impersonate } } -  + return } elseif($action -ieq "undeploy") @@ -178,17 +178,17 @@ function main() } $svc.Start() -  + log-info "$svcHostService set back to sharing process (default)." } else { log-info "$svcHostService already set to use share process" } -  } + } manage-scheduledTask -enable $false -machine $machine -  + if($requiresRestart) { $retVal = Read-Host -Prompt "server needs to be restarted. Do you want to do this now? [yes|no]" @@ -201,24 +201,24 @@ function main() log-info "restarting server." Restart-Computer -ComputerName $machine -Force -Impersonation Impersonate } -  } + } return } -  + # no arguments so do task $workingDir = get-workingDirectory $umdhExe = "$($workingDir)\umdh.exe" -  + if(![System.IO.File]::Exists($umdhExe)) { log-info "$($umdhExe) does not exist. copy umdh.exe into same directory as script. exiting" return } -  + $procDumpExe = "$($workingDir)\$($procDumpExe)" -  + if(![System.IO.File]::Exists($procDumpExe)) { log-info "$($procDumpExe) does not exist. copy umdh.exe into same directory as script. exiting" @@ -235,8 +235,8 @@ function main() return } } -  -  + + $dumpSchedule = @{100 = $false; 200 = $false; 300 = $false; 400 = $false } # do work @@ -267,15 +267,15 @@ function main() } } -  + $arguments = "-p:$($processId) -f:$($outputFile)" run-process -processName $umdhExe -arguments $arguments -wait $true -  + # check size of private bytes # dump at 100,200,300,400,quit $process = Get-Process -id $processId $privateMBytes = $process.PrivateMemorySize / 1024 / 1024 -  + if(($privateMBytes -gt 100) -and ($dumpSchedule[100] -eq $false)) { $dumpSchedule[100] = $true @@ -297,8 +297,8 @@ function main() run-process -processName $procDumpExe -arguments "$procArguments $processId" -wait $true return; } -  -  + + if($sleepTimeHours -eq 0) { #test mode sleep 1 second @@ -310,10 +310,10 @@ function main() } } -  + } -  -  + + # ---------------------------------------------------------------------------------------------------------------- function run-process([string] $processName, [string] $arguments, [bool] $wait = $false) { @@ -328,32 +328,32 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.CreateNoWindow = $true #only needed if useshellexecute is true $process.StartInfo.WorkingDirectory = get-location #$workingDirectory -  -    [void]$process.Start() + +[void]$process.Start() if($wait -and !$process.HasExited) { -     $process.WaitForExit($processWaitMs) -     $exitVal = $process.ExitCode -     $stdOut = $process.StandardOutput.ReadToEnd() -     $stdErr = $process.StandardError.ReadToEnd() -     log-info "Process output:$stdOut" -  -     if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") -     { -         log-info "Error:$stdErr `n $Error" -         $Error.Clear() -     } + $process.WaitForExit($processWaitMs) + $exitVal = $process.ExitCode + $stdOut = $process.StandardOutput.ReadToEnd() + $stdErr = $process.StandardError.ReadToEnd() + log-info "Process output:$stdOut" + + if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") + { + log-info "Error:$stdErr `n $Error" + $Error.Clear() + } } elseif($wait) { -     log-info "Process ended before capturing output." + log-info "Process ended before capturing output." } -    #return $exitVal +#return $exitVal return $stdOut } -  -  + + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) { @@ -361,16 +361,16 @@ function log-info($data) Write-Host $data out-file -Append -InputObject $data -FilePath $logFile } -  + # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable, [string] $machine) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx # for remote machine connect do $service.Connect(serverName,user,domain,password) if([string]::IsNullOrEmpty($machine)) { @@ -378,58 +378,58 @@ function manage-scheduledTask([bool] $enable, [string] $machine) } else { -     $service.Connect($machine) + $service.Connect($machine) } -  -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" # 2k8r2 is 65539 (0x10003) 1.3 # procmon needs at least 2k8r2 compat #$TaskDefinition.Settings.Compatibility = 3 -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $TaskDir -         -            #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) -  -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $TaskDir + +#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } -  + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } + if($error.Count -ge 1) { @@ -441,41 +441,41 @@ function manage-scheduledTask([bool] $enable, [string] $machine) { return $true } -  + } -  + # ---------------------------------------------------------------------------------------------------------------- function get-workingDirectory() { [string] $retVal = "" -  + if (Test-Path variable:\hostinvocation) { -     $retVal = $hostinvocation.MyCommand.Path + $retVal = $hostinvocation.MyCommand.Path } else { -     $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition + $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition } -  -    if (Test-Path $retVal) + +if (Test-Path $retVal) { -     $retVal = (Split-Path $retVal) + $retVal = (Split-Path $retVal) } else { -     $retVal = (Get-Location).path -     log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -     -    } -  + $retVal = (Get-Location).path + log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." + +} + -    Set-Location $retVal -  +Set-Location $retVal + return $retVal -  + } -  + # ---------------------------------------------------------------------------------------------------------------- function runas-admin([string] $arguments) { @@ -486,9 +486,9 @@ function runas-admin([string] $arguments) exit } } -  -  + + # ---------------------------------------------------------------------------------------------------------------- main -  + log-info "finished" diff --git a/Umdh-task-2k8.ps1 b/Umdh-task-2k8.ps1 index d0a53a8d..b3d34805 100644 --- a/Umdh-task-2k8.ps1 +++ b/Umdh-task-2k8.ps1 @@ -84,28 +84,28 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.CreateNoWindow = $true #only needed if useshellexecute is true $process.StartInfo.WorkingDirectory = get-location #$workingDirectory -  -    [void]$process.Start() + +[void]$process.Start() if($wait -and !$process.HasExited) { -     $process.WaitForExit($processWaitMs) -     $exitVal = $process.ExitCode -     $stdOut = $process.StandardOutput.ReadToEnd() -     $stdErr = $process.StandardError.ReadToEnd() -     log-info "Process output:$stdOut" -  -     if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") -     { -         log-info "Error:$stdErr `n $Error" -         $Error.Clear() -     } + $process.WaitForExit($processWaitMs) + $exitVal = $process.ExitCode + $stdOut = $process.StandardOutput.ReadToEnd() + $stdErr = $process.StandardError.ReadToEnd() + log-info "Process output:$stdOut" + + if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") + { + log-info "Error:$stdErr `n $Error" + $Error.Clear() + } } elseif($wait) { -     log-info "Process ended before capturing output." + log-info "Process ended before capturing output." } -    #return $exitVal +#return $exitVal return $stdOut } @@ -117,36 +117,36 @@ function log-info($data) #Write-Host $data out-file -Append -InputObject $data -FilePath ([Environment]::ExpandEnvironmentVariables($logFile)) } -  + # ---------------------------------------------------------------------------------------------------------------- function get-workingDirectory() { [string] $retVal = "" -  + if (Test-Path variable:\hostinvocation) { -     $retVal = $hostinvocation.MyCommand.Path + $retVal = $hostinvocation.MyCommand.Path } else { -     $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition + $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition } -  -    if (Test-Path $retVal) + +if (Test-Path $retVal) { -     $retVal = (Split-Path $retVal) + $retVal = (Split-Path $retVal) } else { -     $retVal = (Get-Location).path -     log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -     -    } -  + $retVal = (Get-Location).path + log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." + +} + -    Set-Location $retVal -  +Set-Location $retVal + return $retVal } diff --git a/deploy-files-task.ps1 b/deploy-files-task.ps1 index 938d0add..9afa777e 100644 --- a/deploy-files-task.ps1 +++ b/deploy-files-task.ps1 @@ -1,5 +1,5 @@   -  + <# .SYNOPSIS powershell script to manage umdh on local or remote machine @@ -25,13 +25,13 @@ .PARAMETER action The action to take. Currently this is either 'deploy' or 'undeploy'. -  + .PARAMETER machine The remote machine to deploy to. if deploying to local machine do not use this argument. #> -  + Param( -  + [parameter(Position=0,Mandatory=$false,HelpMessage="Enter the action to take: [deploy|undeploy]")] [string] $action, [parameter(Position=1,Mandatory=$false,HelpMessage="Enter machine names to deploy to:")] @@ -44,7 +44,7 @@ Param( [string] $gatherFilePattern = "*.pml", [parameter(Position=5,Mandatory=$false,HelpMessage='Enter full path to folder where to store gathered files')] [string] $gatherPath = "$(get-location)\gather" - )  + ) $logFile = "deploy-files-task.log" $processWaitMs = 1000 @@ -68,12 +68,12 @@ $taskInfoUnDeploy.Add("taskarg","-WindowStyle Hidden -NonInteractive -Executionp $time = (get-date) #- (new-timespan -day 12) $requiresRestart = $false -  + # ---------------------------------------------------------------------------------------------------------------- function main() { runas-admin -  + if(![string]::IsNullOrEmpty($machines)) { @@ -90,7 +90,7 @@ function main() $machines = $machines.Split(",") } -  + foreach($machine in $machines) { @@ -108,12 +108,12 @@ function main() { undeploy-files -machine $machine } -  } + } + -  } -  -  + + # ---------------------------------------------------------------------------------------------------------------- function run-process([string] $processName, [string] $arguments, [bool] $wait = $false) { @@ -128,32 +128,32 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.CreateNoWindow = $true #only needed if useshellexecute is true $process.StartInfo.WorkingDirectory = get-location #$workingDirectory -  -    [void]$process.Start() + +[void]$process.Start() if($wait -and !$process.HasExited) { -     $process.WaitForExit($processWaitMs) -     $exitVal = $process.ExitCode -     $stdOut = $process.StandardOutput.ReadToEnd() -     $stdErr = $process.StandardError.ReadToEnd() -     log-info "Process output:$stdOut" -  -     if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") -     { -         log-info "Error:$stdErr `n $Error" -         $Error.Clear() -     } + $process.WaitForExit($processWaitMs) + $exitVal = $process.ExitCode + $stdOut = $process.StandardOutput.ReadToEnd() + $stdErr = $process.StandardError.ReadToEnd() + log-info "Process output:$stdOut" + + if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") + { + log-info "Error:$stdErr `n $Error" + $Error.Clear() + } } elseif($wait) { -     log-info "Process ended before capturing output." + log-info "Process ended before capturing output." } -    #return $exitVal +#return $exitVal return $stdOut } -  -  + + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) { @@ -161,12 +161,12 @@ function log-info($data) Write-Host $data out-file -Append -InputObject $data -FilePath $logFile } -  + # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [bool] $wait = $false) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets $TaskName = $taskInfo.taskname @@ -175,10 +175,10 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo $TaskDir = $taskInfo.taskdir $TaskArg = $taskInfo.taskarg -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx # for remote machine connect do $service.Connect(serverName,user,domain,password) if([string]::IsNullOrEmpty($machine)) { @@ -186,73 +186,73 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo } else { -     $service.Connect($machine) + $service.Connect($machine) } -  -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" # 2k8r2 is 65539 (0x10003) 1.3 # procmon needs at least 2k8r2 compat #$TaskDefinition.Settings.Compatibility = 3 -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $TaskDir -         -            #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) -  -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $TaskDir + +#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } -  -  if($wait) + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } + + if($wait) { log-info "waiting for task to complete" while($true) { $foundTask = $false -      # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $foundTask = $true -             } -         } + $foundTask = $true + } + } if(!$foundTask) { @@ -273,41 +273,41 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo { return $true } -  + } -  + # ---------------------------------------------------------------------------------------------------------------- function get-workingDirectory() { [string] $retVal = "" -  + if (Test-Path variable:\hostinvocation) { -     $retVal = $hostinvocation.MyCommand.Path + $retVal = $hostinvocation.MyCommand.Path } else { -     $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition + $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition } -  -    if (Test-Path $retVal) + +if (Test-Path $retVal) { -     $retVal = (Split-Path $retVal) + $retVal = (Split-Path $retVal) } else { -     $retVal = (Get-Location).path -     log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -     -    } -  + $retVal = (Get-Location).path + log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -    Set-Location $retVal -  +} + + +Set-Location $retVal + return $retVal -  + } -  + # ---------------------------------------------------------------------------------------------------------------- function runas-admin([string] $arguments) { @@ -328,27 +328,27 @@ function deploy-files($machine) log-info "unable to find source path $($sourcePath). exiting" return } -  + if(![IO.Directory]::Exists("\\127.0.0.1\$($destPath)")) { log-info "unable to determine destination path \\127.0.0.1\$($destPath). exiting" return } -  + # get source files $sourceFiles = [IO.Directory]::GetFiles($sourcePath, "*.*", [System.IO.SearchOption]::AllDirectories) -  + # copy files foreach($sourceFile in $sourceFiles) { #$destFile = [IO.Path]::GetFileName($sourceFile) $destFile = $sourceFile.Replace("$($sourcePath)\","") $destFile = "\\$($machine)\$($destPath)\$($destFile)" -  + log-info "copying file $($sourceFile) to $($destFile)" -  + try { if(![IO.Directory]::Exists([IO.Path]::GetDirectoryName($destFile))) @@ -365,10 +365,10 @@ function deploy-files($machine) } } -  + #create scheduled task manage-scheduledTask -enable $true -machine $machine -taskInfo $taskInfoDeploy -  + if($requiresRestart) { $retVal = Read-Host -Prompt "server needs to be restarted. Do you want to do this now? [yes|no]" @@ -382,9 +382,9 @@ function deploy-files($machine) Restart-Computer -ComputerName $machine -Force -Impersonation Impersonate } } -  + return -}  +} # ---------------------------------------------------------------------------------------------------------------- function undeploy-files($machine) @@ -401,7 +401,7 @@ function undeploy-files($machine) $directoryInfo = new-object IO.DirectoryInfo ($remotePath) [IO.FileInfo[]] $sourceFiles = ($directoryInfo.EnumerateFiles($gatherFilePattern,[IO.SearchOption]::TopDirectoryOnly)) -  + # copy files foreach($sourceFile in $sourceFiles) { @@ -433,9 +433,9 @@ function undeploy-files($machine) $destFile = "$($destFileBase)-$($sourceFile.CreationTime.ToString("yy-MM-dd-hh-mm-ss"))$($destFileExtension)" $destFile = "$($gatherPath)\$($machine)\$($destFile)" -  + log-info "copying file $($sourceFile.FullName) to $($destFile)" -  + try { if(![IO.Directory]::Exists([IO.Path]::GetDirectoryName($destFile))) @@ -453,7 +453,7 @@ function undeploy-files($machine) } } } -  + if($requiresRestart) { $retVal = Read-Host -Prompt "server needs to be restarted. Do you want to do this now? [yes|no]" @@ -466,7 +466,7 @@ function undeploy-files($machine) log-info "restarting server." Restart-Computer -ComputerName $machine -Force -Impersonation Impersonate } -  } + } return @@ -503,8 +503,8 @@ function is-fileLocked([string] $file) return $true } } -  + # ---------------------------------------------------------------------------------------------------------------- main -  + log-info "finished" diff --git a/dump-configurator.ps1 b/dump-configurator.ps1 index 0626ef9f..4f1ff349 100644 --- a/dump-configurator.ps1 +++ b/dump-configurator.ps1 @@ -14,7 +14,7 @@ .EXAMPLE .\dump-configurator.ps1 -dumpType complete -machines server1,server2 query azure rm for all resource groups with ip name containing 'GWPIP' by default. -  + .PARAMETER dumpType type of dump, mini, kernel, complete, auto @@ -29,14 +29,14 @@ #> param( - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [switch]$dumpType, - [Parameter(Mandatory=$false)] + [Parameter(Mandatory = $false)] [string[]]$machines = ".", - [Parameter(Mandatory=$false)] - [string]$dumpFile= "c:\windows\memory.dmp", - [Parameter(Mandatory=$false)] - [switch]$restart=$false + [Parameter(Mandatory = $false)] + [string]$dumpFile = "c:\windows\memory.dmp", + [Parameter(Mandatory = $false)] + [switch]$restart = $false ) $HKCR = 2147483648 #HKEY_CLASSES_ROOT @@ -101,21 +101,21 @@ function log-info($data) { $dataWritten = $false $data = "$([System.DateTime]::Now):$($data)`n" - if([regex]::IsMatch($data.ToLower(),"error|exception|fail|warning")) + if ([regex]::IsMatch($data.ToLower(), "error|exception|fail|warning")) { write-host $data -foregroundcolor Yellow } - elseif([regex]::IsMatch($data.ToLower(),"running")) + elseif ([regex]::IsMatch($data.ToLower(), "running")) { - write-host $data -foregroundcolor Green + write-host $data -foregroundcolor Green } - elseif([regex]::IsMatch($data.ToLower(),"job completed")) + elseif ([regex]::IsMatch($data.ToLower(), "job completed")) { - write-host $data -foregroundcolor Cyan + write-host $data -foregroundcolor Cyan } - elseif([regex]::IsMatch($data.ToLower(),"starting")) + elseif ([regex]::IsMatch($data.ToLower(), "starting")) { - write-host $data -foregroundcolor Magenta + write-host $data -foregroundcolor Magenta } else { @@ -140,7 +140,7 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) $retVal = new-object Text.StringBuilder - if([string]::IsNullOrEmpty($value)) + if ([string]::IsNullOrEmpty($value)) { [void]$retVal.AppendLine("-----------------------------------------") [void]$retVal.AppendLine("enumerating $($key)") @@ -159,9 +159,9 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) $sNames = $reg.EnumValues($hive, $key).sNames $sTypes = $reg.EnumValues($hive, $key).Types - for($i = 0; $i -lt $sNames.count; $i++) + for ($i = 0; $i -lt $sNames.count; $i++) { - if(![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value) + if (![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value) { continue } @@ -169,9 +169,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) switch ($sTypes[$i]) { # REG_SZ - 1{ + 1 + { $keyValue = $reg.GetStringValue($hive, $key, $sNames[$i]).sValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -182,26 +183,28 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_EXPAND_SZ - 2{ + 2 + { $keyValue = $reg.GetExpandStringValue($hive, $key, $sNames[$i]).sValue - if($enumValue) + if ($enumValue) { return $keyValue } else { - [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") + [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") } } # REG_BINARY - 3{ + 3 + { $keyValue = (($reg.GetBinaryValue($hive, $key, $sNames[$i]).uValue) -join ',') - if($enumValue -and $displayBinaryBlob) + if ($enumValue -and $displayBinaryBlob) { return $keyValue } - elseif($displayBinaryBlob) + elseif ($displayBinaryBlob) { [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") } @@ -213,9 +216,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_DWORD - 4{ + 4 + { $keyValue = $reg.GetDWORDValue($hive, $key, $sNames[$i]).uValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -226,9 +230,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_MULTI_SZ - 7{ + 7 + { $keyValue = (($reg.GetMultiStringValue($hive, $key, $sNames[$i]).sValue) -join ',') - if($enumValue) + if ($enumValue) { return $keyValue } @@ -239,9 +244,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_QWORD - 11{ + 11 + { $keyValue = $reg.GetQWORDValue($hive, $key, $sNames[$i]).uValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -256,12 +262,12 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } } - if([string]::IsNullOrEmpty($value) -and $subKeySearch) + if ([string]::IsNullOrEmpty($value) -and $subKeySearch) { - foreach($subKey in $reg.EnumKey($hive, $key).sNames) + foreach ($subKey in $reg.EnumKey($hive, $key).sNames) { - if([string]::IsNullOrEmpty($subKey)) + if ([string]::IsNullOrEmpty($subKey)) { continue } @@ -302,39 +308,34 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.WindowStyle = [Diagnostics.ProcessWindowstyle]::Normal -  -    [void]$process.Start() -  - if($wait -and !$process.HasExited) + +[void]$process.Start() + + if ($wait -and !$process.HasExited) { -  -     if($process.StandardOutput.Peek() -gt -1) + if ($process.StandardOutput.Peek() -gt -1) { -     $stdOut = $process.StandardOutput.ReadToEnd() + $stdOut = $process.StandardOutput.ReadToEnd() log-info $stdOut -  } -  -  - if($process.StandardError.Peek() -gt -1) + } + + if ($process.StandardError.Peek() -gt -1) { $stdErr = $process.StandardError.ReadToEnd() log-info $stdErr -         $Error.Clear() -     } - + $Error.Clear() + } } - elseif($wait) + elseif ($wait) { -     log-info "Error:Process ended before capturing output." + log-info "Error:Process ended before capturing output." } -  - - $exitVal = $process.ExitCode -  + $exitVal = $process.ExitCode + log-info "Running process exit $($processName) : $($exitVal)" $Error.Clear() -  + return $stdOut } @@ -342,9 +343,9 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = function manage-wmiExecute([string] $command, [string] $workingDir, [string] $machine) { log-info "wmiExecute: $($machine) : $($command) : $($workingDir)" - # $wmi = new-object System.Management.ManagementClass "\\$($machine)\Root\cimv2:Win32_Process" - # $result = $wmi.Create($command) - if($useCreds) + # $wmi = new-object System.Management.ManagementClass "\\$($machine)\Root\cimv2:Win32_Process" + # $result = $wmi.Create($command) + if ($useCreds) { $result = Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList ($command, $workingDir) -Credential $Creds -ComputerName $computer } @@ -353,42 +354,42 @@ function manage-wmiExecute([string] $command, [string] $workingDir, [string] $ma $result = Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList ($command, $workingDir) -ComputerName $computer } - switch($result.ReturnValue) + switch ($result.ReturnValue) { 0 - { - log-info "$($machine) return:success" - } + { + log-info "$($machine) return:success" + } 2 - { - log-info "$($machine) return:access denied" - } + { + log-info "$($machine) return:access denied" + } 3 - { - log-info "$($machine) return:insufficient privilege" - } + { + log-info "$($machine) return:insufficient privilege" + } 8 - { - log-info "$($machine) return:unknown failure" - } + { + log-info "$($machine) return:unknown failure" + } 9 - { - log-info "$($machine) return:path not found" - } + { + log-info "$($machine) return:path not found" + } 21 - { - log-info "$($machine) return:invalid parameter" - } + { + log-info "$($machine) return:invalid parameter" + } default - { - log-info "$($machine) return:unknown $($result.ReturnValue)" - } + { + log-info "$($machine) return:unknown $($result.ReturnValue)" + } } return $result.ReturnValue @@ -401,15 +402,15 @@ function runas-admin() write-verbose "checking for admin" if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { - if(!$noretry) + if (!$noretry) { write-host "restarting script as administrator. exiting..." Write-Host "run-process -processName "powershell.exe" -arguments $($SCRIPT:MyInvocation.MyCommand.Path) -noretry" run-process -processName "powershell.exe" -arguments "$($SCRIPT:MyInvocation.MyCommand.Path) -noretry" - } + } - exit 1 - } + exit 1 + } write-verbose "running as admin" } diff --git a/enum-wmi.ps1 b/enum-wmi.ps1 index 5ca2b9de..3baa3455 100644 --- a/enum-wmi.ps1 +++ b/enum-wmi.ps1 @@ -33,12 +33,12 @@ $ErrorActionPreference = "silentlycontinue" $logFile = "wmi-enumLog.txt" cls -  + #----------------------------------------------------------------------------------------------- function main() { Stop-Transcript -  + $error.Clear() Start-Transcript -Path $logfile @@ -47,7 +47,7 @@ function main() log-info "starting" log-info "*******************************************" log-info "*******************************************" -  + $wmiNamespaces = enumerate-namespaces -wminamespace $nameSpace foreach($wmiNamespace in $wmiNamespaces) { @@ -58,7 +58,7 @@ function main() "*******************************************" "Namespace:$($wmiNamespace)" "*******************************************" -  + $wmiClasses = Get-CimClass -ClassName * -Namespace $wmiNamespace foreach ($wmiClass in $wmiClasses) @@ -110,7 +110,7 @@ function main() } } -  + "*******************************************" log-info "*******************************************" log-info "finished" @@ -120,22 +120,22 @@ function main() } #----------------------------------------------------------------------------------------------- -  + function enumerate-namespaces($wmiNamespace) { $wmiRootNamespaces = new-object Collections.ArrayList [void]$wmiRootNamespaces.Add($wmiNamespace) -  + foreach($name in (Get-WmiObject -Namespace $wmiNamespace -Class __NAMESPACE).Name) { $tempName = "$($wmiNamespace)\$($name)" [void]$wmiRootNamespaces.AddRange(@(enumerate-namespaces -wminamespace $tempName )) } -  + return $wmiRootNamespaces } #----------------------------------------------------------------------------------------------- -  + function log-info($data) { $data = "$([System.DateTime]::Now):$($data)`n" @@ -143,5 +143,5 @@ function log-info($data) #out-file -Append -InputObject $data -FilePath $logFile } #----------------------------------------------------------------------------------------------- -  + main diff --git a/event-task-procmon.ps1 b/event-task-procmon.ps1 index f3aed38b..fcd9ed6d 100644 --- a/event-task-procmon.ps1 +++ b/event-task-procmon.ps1 @@ -1,15 +1,15 @@ -<#  -.SYNOPSIS  -    powershell script to monitor debug event logs for event match -.DESCRIPTION  -    This script will monitor 'analytic' and 'debug' event logs of format .etl for certain event entries. +<#  +.SYNOPSIS +powershell script to monitor debug event logs for event match +.DESCRIPTION +This script will monitor 'analytic' and 'debug' event logs of format .etl for certain event entries. Optionally on match, the script can send an email or run an action. -.NOTES  -   File Name  : event-task-procmon.ps1  -   Author  : jagilber -   Version : 150824 -.EXAMPLE  -    .\event-task-procmon.ps1 -install $true +.NOTES +File Name : event-task-procmon.ps1 +Author : jagilber + Version : 150824 +.EXAMPLE +.\event-task-procmon.ps1 -install $true .\event-task-procmon.ps1 -uninstall $true .\event-task-procmon.ps1 -test $true .PARAMETER install @@ -20,10 +20,10 @@ will test script and sent email if settings are configured. .PARAMETER workingDir working script directory -#>  -  +#> + Param( -  + [parameter(Position=0,Mandatory=$false,HelpMessage="Enter `$true to install event log monitor")] [switch] $install, [parameter(Position=0,Mandatory=$false,HelpMessage="Enter `$true to uninstall event log monitor")] @@ -35,14 +35,14 @@ Param( [parameter(Position=1,Mandatory=$false,HelpMessage="Enter working directory")] [string] $workingDir ) -  + $error.Clear() -  + $ErrorActionPreference = "SilentlyContinue" $logFile = "event-task-procmon.log" $sleepItervalSecs = 60 $startTime = [DateTime]::Now -  + # event information $eventLog = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Admin" $eventId = 20491 @@ -83,7 +83,7 @@ $To = "" $From = "" $Subject = "$($env:computername): monitored event received" $Body = "event was received that matches filter" -  + # SMTP Relay Settings $Server = "" $Port = @@ -91,7 +91,7 @@ $passFile = "" $username = "" $useSSL = $false $useCreds = $false -  + # scheduled task info $TaskName = "EventLog Monitor" $TaskDescr = "Monitors eventlog for event" @@ -99,26 +99,26 @@ $TaskCommand = "powershell.exe" $TaskScript = (get-variable myinvocation -scope script).Value.Mycommand.Definition #"$($workingDir)\event-task-procmon.ps1" $TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy bypass -file $TaskScript" $time = (get-date) #- (new-timespan -day 12) -  -  + + # ---------------------------------------------------------------------------------------------------------------- function main() { try { -  + if($useCreds) { -     set-credentials + set-credentials } -  -  + + if([string]::IsNullOrEmpty($workingDir)) { -     $workingDir = get-workingDirectory + $workingDir = get-workingDirectory } -  -   if($install) + + if($install) { install-task exit @@ -141,19 +141,19 @@ function main() runas-admin $scriptName install-task -     new-eventLog -LogName $eventLog -source "TEST" -      Write-EventLog -LogName $eventLog -Source "TEST" -Message "TEST" -EventId $eventId -EntryType Information -     remove-eventlog -source "TEST" + new-eventLog -LogName $eventLog -source "TEST" + Write-EventLog -LogName $eventLog -Source "TEST" -Message "TEST" -EventId $eventId -EntryType Information + remove-eventlog -source "TEST" monitor-events uninstall-task -    exit + exit } -  else + else { # start tracing run-processes $eventTasksDeploy -     monitor-events + monitor-events monitor-files } @@ -172,20 +172,20 @@ function main() function set-credentials() { $Creds -    # if storing creds for smtp, password will have to be saved one time -    # uncomment following to prompt for credentials -    #$Creds = Get-Credential -  -    if(!$Creds) -    { -     if(!(test-path $passFile)) -     { -         read-host -assecurestring | convertfrom-securestring | out-file $passFile -     } -  -     $password = cat $passFile | convertto-securestring -     $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password -    } +# if storing creds for smtp, password will have to be saved one time +# uncomment following to prompt for credentials +#$Creds = Get-Credential + +if(!$Creds) +{ + if(!(test-path $passFile)) + { + read-host -assecurestring | convertfrom-securestring | out-file $passFile + } + + $password = cat $passFile | convertto-securestring + $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password +} } # ---------------------------------------------------------------------------------------------------------------- @@ -276,8 +276,8 @@ function is-fileLocked([string] $file) # ---------------------------------------------------------------------------------------------------------------- function monitor-events() { -   $matchCount = 0 -    $monitoring = $true + $matchCount = 0 +$monitoring = $true $lastRecordId = 0 $time = $startTime @@ -293,11 +293,11 @@ function monitor-events() # check files to delete oldest check-files -     $events = get-winEvent -Oldest -FilterHashTable @{LogName=$eventLog; StartTime=$time; Id=$eventId} -     log-info "new event count matching filter:$($events.Length) startTime:$($time)" -  -     foreach($event in $events) -     { + $events = get-winEvent -Oldest -FilterHashTable @{LogName=$eventLog; StartTime=$time; Id=$eventId} + log-info "new event count matching filter:$($events.Length) startTime:$($time)" + + foreach($event in $events) + { if([string]::IsNullOrEmpty($event.TimeCreated)) { @@ -305,7 +305,7 @@ function monitor-events() continue } -         $time = $event.TimeCreated + $time = $event.TimeCreated log-info "last event TimeCreated:$($time) recordId: $($event.RecordId) matchCount: $($matchCount)" # bump time by a second so that we do not get duplicate returns @@ -322,24 +322,24 @@ function monitor-events() $lastRecordId = $event.RecordId } -            log-info $event.Message -  -          #  [xml] $xml = $event.ToXml() -  -         -             -            if($test) -         { +log-info $event.Message + +# [xml] $xml = $event.ToXml() + + + +if($test) + { # with a test source, message will not be stored in event object correctly -             $eventLabel = $xml.Event.EventData.Data #$event.Message -             $label = "TEST" + $eventLabel = $xml.Event.EventData.Data #$event.Message + $label = "TEST" $monitoring = $false -            } -  -             log-info "found match:$($event)" +} + + log-info "found match:$($event)" $matchCount++ -            send-mail + send-mail # stop tracing to gather information #run-processes $eventTasksUnDeploy @@ -354,13 +354,13 @@ function monitor-events() # still monitoring so restart tracing # run-processes $eventTasksDeploy } -           -     } -  -     if($monitoring) -     { -        sleep $sleepItervalSecs -     } + + } + + if($monitoring) + { + sleep $sleepItervalSecs + } } } @@ -370,11 +370,11 @@ function install-task() # run as administrator runas-admin $scriptName -    # add to task scheduler as a computer startup script + # add to task scheduler as a computer startup script if(manage-scheduledTask -enable $true -taskInfo $taskInfoDeploy) { $eventLog = Get-WinEvent -ListLog $eventLog -     $eventLog.IsEnabled = $true + $eventLog.IsEnabled = $true $eventLog.SaveChanges() log-info "create scheduled task and enabled debug eventlog" } @@ -397,12 +397,12 @@ function uninstall-task() manage-scheduledTask -enable $false -taskInfo $taskInfoDeploy manage-scheduledTask -enable $true -taskInfo $taskInfoUnDeploy -wait $true -    if(manage-scheduledTask -enable $false -taskInfo $taskInfoUnDeploy -wait $true) +if(manage-scheduledTask -enable $false -taskInfo $taskInfoUnDeploy -wait $true) { -  $eventLog = Get-WinEvent -ListLog $eventLog -  $eventLog.IsEnabled = $false -  $eventLog.SaveChanges() -  log-info "deleted scheduled task and disabled debug eventlog" + $eventLog = Get-WinEvent -ListLog $eventLog + $eventLog.IsEnabled = $false + $eventLog.SaveChanges() + log-info "deleted scheduled task and disabled debug eventlog" } else { @@ -423,20 +423,20 @@ function send-mail() return } -    if($useSSL -and $useCreds) +if($useSSL -and $useCreds) { -     Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -UseSsl -Credential $Creds -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -UseSsl -Credential $Creds -Subject $Subject -Body $Body } elseif($useCreds) { -   Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Credential $Creds -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Credential $Creds -Subject $Subject -Body $Body } else { -    Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Subject $Subject -Body $Body } } -  + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) { @@ -453,7 +453,7 @@ function run-processes($processes) run-process -processName $process.Key -arguments $process.Value -wait $false } } -  + # ---------------------------------------------------------------------------------------------------------------- function run-process([string] $processName, [string] $arguments, [bool] $wait = $false) { @@ -468,35 +468,35 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.CreateNoWindow = $true $process.StartInfo.WorkingDirectory = get-location -    [void]$process.Start() +[void]$process.Start() if($wait -and !$process.HasExited) { -     $process.WaitForExit($processWaitMs) -     $exitVal = $process.ExitCode -     $stdOut = $process.StandardOutput.ReadToEnd() -     $stdErr = $process.StandardError.ReadToEnd() -     log-info "Process output:$stdOut" -  -     if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") -     { -         log-info "Error:$stdErr `n $Error" -         $Error.Clear() -     } + $process.WaitForExit($processWaitMs) + $exitVal = $process.ExitCode + $stdOut = $process.StandardOutput.ReadToEnd() + $stdErr = $process.StandardError.ReadToEnd() + log-info "Process output:$stdOut" + + if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") + { + log-info "Error:$stdErr `n $Error" + $Error.Clear() + } } elseif($wait) { -     log-info "Process ended before capturing output." + log-info "Process ended before capturing output." } -    #return $exitVal +#return $exitVal return $stdOut } -  + # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [bool] $wait = $false) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets $TaskName = $taskInfo.taskname @@ -505,10 +505,10 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo $TaskDir = $taskInfo.taskdir $TaskArg = $taskInfo.taskarg -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx # for remote machine connect do $service.Connect(serverName,user,domain,password) if([string]::IsNullOrEmpty($machine)) { @@ -516,73 +516,73 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo } else { -     $service.Connect($machine) + $service.Connect($machine) } -  -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" # 2k8r2 is 65539 (0x10003) 1.3 # procmon needs at least 2k8r2 compat #$TaskDefinition.Settings.Compatibility = 3 -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $TaskDir -         -            #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) -  -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $TaskDir + +#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } -  -  if($wait) + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } + + if($wait) { log-info "waiting for task to complete" while($true) { $foundTask = $false -      # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $foundTask = $true -             } -         } + $foundTask = $true + } + } if(!$foundTask) { @@ -603,40 +603,40 @@ function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [boo { return $true } -  + } -  + # ---------------------------------------------------------------------------------------------------------------- function get-workingDirectory() { $retVal = $null -  + if (Test-Path variable:\hostinvocation) { -     $retVal = $hostinvocation.MyCommand.Path + $retVal = $hostinvocation.MyCommand.Path } else { -     $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition + $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition } -  -    if (Test-Path $retVal) + +if (Test-Path $retVal) { -     $retVal = (Split-Path $retVal) + $retVal = (Split-Path $retVal) } else { -     $retVal = (Get-Location).path -     log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -     -    } -  + $retVal = (Get-Location).path + log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -    Set-Location $retVal -  +} + + +Set-Location $retVal + return $retVal } -  + # ---------------------------------------------------------------------------------------------------------------- function runas-admin([string] $arguments) { diff --git a/eventTask.ps1 b/eventTask.ps1 index 29b8f593..a5714725 100644 --- a/eventTask.ps1 +++ b/eventTask.ps1 @@ -1,15 +1,15 @@ -<#  -.SYNOPSIS  -    powershell script to monitor debug event logs for event match -.DESCRIPTION  -    This script will monitor 'analytic' and 'debug' event logs of format .etl for certain event entries. +<#  +.SYNOPSIS +powershell script to monitor debug event logs for event match +.DESCRIPTION +This script will monitor 'analytic' and 'debug' event logs of format .etl for certain event entries. Optionally on match, the script can send an email or run an action. -.NOTES  -   File Name  : eventTask.ps1  -   Author  : jagilber -   Version : 141206 -.EXAMPLE  -    .\eventTask.ps1 -install $true +.NOTES +File Name : eventTask.ps1 +Author : jagilber + Version : 141206 +.EXAMPLE +.\eventTask.ps1 -install $true .\eventTask.ps1 -uninstall $true .\eventTask.ps1 -test $true .PARAMETER install @@ -20,10 +20,10 @@ will test script and sent email if settings are configured. .PARAMETER workingDir working script directory -#>  -  +#> + Param( -  + [parameter(Position=0,Mandatory=$false,HelpMessage="Enter `$true to install event log monitor")] [bool] $install = $false, [parameter(Position=0,Mandatory=$false,HelpMessage="Enter `$true to uninstall event log monitor")] @@ -33,14 +33,14 @@ Param( [parameter(Position=1,Mandatory=$false,HelpMessage="Enter working directory")] [string] $workingDir ) -  + $error.Clear() -  + $ErrorActionPreference = "SilentlyContinue" $logFile = "eventTask.log" $sleepItervalSecs = 60 -  -  + + # event information $eventLog = "Microsoft-Windows-PrintService/Debug" $eventId = 119 @@ -62,7 +62,7 @@ $To = "" $From = "" $Subject = "$($env:computername): monitored event received" $Body = "event was received that matches filter" -  + # SMTP Relay Settings $Server = "" $Port = @@ -70,7 +70,7 @@ $passFile = "" $username = "" $useSSL = $false $useCreds = $false -  + # scheduled task info $TaskName = "EventLog Monitor" $TaskDescr = "Monitors eventlog for event" @@ -78,26 +78,26 @@ $TaskCommand = "powershell.exe" $TaskScript = (get-variable myinvocation -scope script).Value.Mycommand.Definition #"$($workingDir)\eventTask.ps1" $TaskArg = "-WindowStyle Hidden -NonInteractive -Executionpolicy unrestricted -file $TaskScript" $time = (get-date) #- (new-timespan -day 12) -  -  + + # ---------------------------------------------------------------------------------------------------------------- function main() { try { -  + if($useCreds) { -     set-credentials + set-credentials } -  -  + + if([string]::IsNullOrEmpty($workingDir)) { -     $workingDir = get-workingDirectory + $workingDir = get-workingDirectory } -  -   if($install) + + if($install) { install-task exit @@ -117,17 +117,17 @@ function main() runas-admin $scriptName install-task -     new-eventLog -LogName $eventLog -source "TEST" -      Write-EventLog -LogName $eventLog -Source "TEST" -Message "TEST" -EventId $eventId -EntryType Information -     remove-eventlog -source "TEST" + new-eventLog -LogName $eventLog -source "TEST" + Write-EventLog -LogName $eventLog -Source "TEST" -Message "TEST" -EventId $eventId -EntryType Information + remove-eventlog -source "TEST" monitor-events uninstall-task -    exit + exit } -  else + else { -     monitor-events + monitor-events } log-info "exiting" @@ -146,27 +146,27 @@ function main() function set-credentials() { $Creds -    # if storing creds for smtp, password will have to be saved one time -    # uncomment following to prompt for credentials -    #$Creds = Get-Credential -  -    if(!$Creds) -    { -     if(!(test-path $passFile)) -     { -         read-host -assecurestring | convertfrom-securestring | out-file $passFile -     } -  -     $password = cat $passFile | convertto-securestring -     $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password -    } +# if storing creds for smtp, password will have to be saved one time +# uncomment following to prompt for credentials +#$Creds = Get-Credential + +if(!$Creds) +{ + if(!(test-path $passFile)) + { + read-host -assecurestring | convertfrom-securestring | out-file $passFile + } + + $password = cat $passFile | convertto-securestring + $creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password +} } # ---------------------------------------------------------------------------------------------------------------- function monitor-events() { -   $matchCount = 0 -    $monitoring = $true + $matchCount = 0 +$monitoring = $true $lastRecordId = 0 @@ -174,11 +174,11 @@ function monitor-events() # monitor specified eventlog while($monitoring) { -     $events = get-winEvent -Oldest -FilterHashTable @{LogName=$eventLog; StartTime=$time; Id=$eventId} -     log-info "new event count matching filter:$($events.Length) startTime:$($time)" -  -     foreach($event in $events) -     { + $events = get-winEvent -Oldest -FilterHashTable @{LogName=$eventLog; StartTime=$time; Id=$eventId} + log-info "new event count matching filter:$($events.Length) startTime:$($time)" + + foreach($event in $events) + { if([string]::IsNullOrEmpty($event.TimeCreated)) { @@ -186,7 +186,7 @@ function monitor-events() continue } -         $time = $event.TimeCreated + $time = $event.TimeCreated log-info "last event TimeCreated:$($time) recordId: $($event.RecordId) matchCount: $($matchCount)" # bump time by a second so that we do not get duplicate returns @@ -203,29 +203,29 @@ function monitor-events() $lastRecordId = $event.RecordId } -            log-info $event.Message -  -         [xml] $xml = $event.ToXml() -  -         $label = $xml.Event.UserData.SpoolerGenericEvent.Label -            $errorCode = $xml.Event.UserData.SpoolerGenericEvent.ErrorCode -         -             -            if($test) -         { +log-info $event.Message + + [xml] $xml = $event.ToXml() + + $label = $xml.Event.UserData.SpoolerGenericEvent.Label +$errorCode = $xml.Event.UserData.SpoolerGenericEvent.ErrorCode + + +if($test) + { # with a test source, message will not be stored in event object correctly -             $eventLabel = $xml.Event.EventData.Data #$event.Message -             $label = "TEST" -             $errorCode = $eventErrorCode + $eventLabel = $xml.Event.EventData.Data #$event.Message + $label = "TEST" + $errorCode = $eventErrorCode $monitoring = $false -            } -  -         if(($label -match $eventLabel) -and $errorCode -match $eventErrorCode) -         { -             log-info "found match:$($event)" +} + + if(($label -match $eventLabel) -and $errorCode -match $eventErrorCode) + { + log-info "found match:$($event)" $matchCount++ -            send-mail + send-mail # stop tracing to gather information run-process -processName $eventTaskProcessUnDeploy -arguments $eventTaskArgumentsUnDeploy -wait $true @@ -238,15 +238,15 @@ function monitor-events() else { # still monitoring so restart tracing - run-process -processName $eventTaskProcessDeploy -arguments $eventTaskArgumentsDeploy -wait $true  + run-process -processName $eventTaskProcessDeploy -arguments $eventTaskArgumentsDeploy -wait $true } -         } -     } -  -     if($monitoring) -     { -        sleep $sleepItervalSecs -     } + } + } + + if($monitoring) + { + sleep $sleepItervalSecs + } } } @@ -256,11 +256,11 @@ function install-task() # run as administrator runas-admin $scriptName -    # add to task scheduler as a computer startup script + # add to task scheduler as a computer startup script if(manage-scheduledTask -enable $true) { $eventLog = Get-WinEvent -ListLog $eventLog -     $eventLog.IsEnabled = $true + $eventLog.IsEnabled = $true $eventLog.SaveChanges() log-info "create scheduled task and enabled debug eventlog" } @@ -280,12 +280,12 @@ function uninstall-task() runas-admin $scriptName # remove from task scheduler -    if(manage-scheduledTask -enable $false) +if(manage-scheduledTask -enable $false) { -  $eventLog = Get-WinEvent -ListLog $eventLog -  $eventLog.IsEnabled = $false -  $eventLog.SaveChanges() -  log-info "deleted scheduled task and disabled debug eventlog" + $eventLog = Get-WinEvent -ListLog $eventLog + $eventLog.IsEnabled = $false + $eventLog.SaveChanges() + log-info "deleted scheduled task and disabled debug eventlog" } else { @@ -306,20 +306,20 @@ function send-mail() return } -    if($useSSL -and $useCreds) +if($useSSL -and $useCreds) { -     Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -UseSsl -Credential $Creds -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -UseSsl -Credential $Creds -Subject $Subject -Body $Body } elseif($useCreds) { -   Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Credential $Creds -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Credential $Creds -Subject $Subject -Body $Body } else { -    Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Subject $Subject -Body $Body + Send-MailMessage -To $To -From $From -SmtpServer $Server -Port $Port -Subject $Subject -Body $Body } } -  + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) { @@ -327,7 +327,7 @@ function log-info($data) Write-Host $data out-file -Append -InputObject $data -FilePath $logFile } -  + # ---------------------------------------------------------------------------------------------------------------- function run-process([string] $processName, [string] $arguments, [bool] $wait = $false) { @@ -342,85 +342,85 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.CreateNoWindow = $true $process.StartInfo.WorkingDirectory = get-location -    [void]$process.Start() +[void]$process.Start() if($wait -and !$process.HasExited) { -     $process.WaitForExit($processWaitMs) -     $exitVal = $process.ExitCode -     $stdOut = $process.StandardOutput.ReadToEnd() -     $stdErr = $process.StandardError.ReadToEnd() -     log-info "Process output:$stdOut" -  -     if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") -     { -         log-info "Error:$stdErr `n $Error" -         $Error.Clear() -     } + $process.WaitForExit($processWaitMs) + $exitVal = $process.ExitCode + $stdOut = $process.StandardOutput.ReadToEnd() + $stdErr = $process.StandardError.ReadToEnd() + log-info "Process output:$stdOut" + + if(![System.String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") + { + log-info "Error:$stdErr `n $Error" + $Error.Clear() + } } elseif($wait) { -     log-info "Process ended before capturing output." + log-info "Process ended before capturing output." } -    #return $exitVal +#return $exitVal return $stdOut } -  + # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx -     $service.Connect() -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $workingDir -         -            #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -         $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) - -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + $service.Connect() + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $workingDir + +#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { log-info "found task" -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } if($error.Count -ge 1) @@ -435,38 +435,38 @@ function manage-scheduledTask([bool] $enable) } } -  + # ---------------------------------------------------------------------------------------------------------------- function get-workingDirectory() { $retVal -  + if (Test-Path variable:\hostinvocation) { -     $retVal = $hostinvocation.MyCommand.Path + $retVal = $hostinvocation.MyCommand.Path } else { -     $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition + $retVal = (get-variable myinvocation -scope script).Value.Mycommand.Definition } -  -    if (Test-Path $retVal) + +if (Test-Path $retVal) { -     $retVal = (Split-Path $retVal) + $retVal = (Split-Path $retVal) } else { -     $retVal = (Get-Location).path -     log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -     -    } -  + $retVal = (Get-Location).path + log-info "get-workingDirectory: Powershell Host $($Host.name) may not be compatible with this function, the current directory $retVal will be used." -    Set-Location $retVal -  +} + + +Set-Location $retVal + return $retVal } -  + # ---------------------------------------------------------------------------------------------------------------- function runas-admin([string] $arguments) { diff --git a/file-copy.ps1 b/file-copy.ps1 index 113ef6a7..a49e365b 100644 --- a/file-copy.ps1 +++ b/file-copy.ps1 @@ -11,13 +11,13 @@ .PARAMETER machineFile file containing list of machines (one per line) to copy files to. Example c:\temp\machines.txt -  + .PARAMETER sourcePath source path of files to copy. Example c:\temp\sourcefiles -  + .PARAMETER destPath dest path share of files to copy. Example admin$\temp -  + .EXAMPLE .\file-copy.ps1 -machineFile machines.txt -sourcePath .\sourcefiles -destPath admin$\temp deploy all configuration files in default 'configs' or 'configs_templates' folder to local machine using defalut etl output folder of %systemroot%\temp @@ -26,7 +26,7 @@ #> Param( -  + [parameter(Position=0,Mandatory=$true,HelpMessage="Enter file containing list of remote machines to copy files to. one machine per line. example: c:\temp\machines.txt")] [string] $machineFile, [parameter(Position=1,Mandatory=$true,HelpMessage="Enter source folder containing files. example: c:\temp\sourcefiles")] diff --git a/file-regex-string-compare.ps1 b/file-regex-string-compare.ps1 index 75158795..6e4a84a3 100644 --- a/file-regex-string-compare.ps1 +++ b/file-regex-string-compare.ps1 @@ -16,11 +16,11 @@ the first text file for compare .PARAMETER fileTwo the second text file for compare -  + #> -  + Param( -  + [parameter(Position=0,Mandatory=$true,HelpMessage="Enter the quoted regex pattern")] [string] $regexpattern, [parameter(Position=1,Mandatory=$true,HelpMessage="Enter path to first file")] @@ -28,7 +28,7 @@ Param( [parameter(Position=2,Mandatory=$true,HelpMessage="Enter path to second file")] [string] $fileTwo ) -  + # modify cls #$regexPattern = "KB[0-9][0-9][0-9][0-9][0-9][0-9][0-9]" @@ -39,12 +39,12 @@ $listTwo = @{} $listCombined = @{} $listOneOnly = @{} $listTwoOnly = @{} -  + # get all matches from first file $regex = new-object System.Text.RegularExpressions.Regex($regexPattern,[System.Text.RegularExpressions.RegexOptions]::Singleline) $matchesOne = $regex.Matches([System.IO.File]::ReadAllText($fileOne)) -  + foreach($match in $matchesOne) { $value = $match.Groups[0].Value @@ -56,11 +56,11 @@ foreach($match in $matchesOne) } } -  + # get all matches from second file $matchesTwo = $regex.Matches([System.IO.File]::ReadAllText($fileTwo)) -  + foreach($match in $matchesTwo) { @@ -73,7 +73,7 @@ foreach($match in $matchesTwo) } } -  + # find all matches in common foreach($item in $listOne.GetEnumerator()) { @@ -89,7 +89,7 @@ foreach($item in $listOne.GetEnumerator()) $listOneOnly.Add($item.key,$item.value) } } -  + foreach($item in $listTwo.GetEnumerator()) { if($listOne.Contains($item.Key)) @@ -104,7 +104,7 @@ foreach($item in $listTwo.GetEnumerator()) $listTwoOnly.Add($item.key,$item.value) } } -  + # list all in common write-host "*************************************************************" write-host "Items in both files:$($listCombined.Count)" @@ -113,8 +113,8 @@ foreach($item in $listCombined.GetEnumerator()) { $item.Key } -  -  + + # list differences from first file write-host "*************************************************************" write-host "Items only in first file:$($listOneOnly.Count) out of $($listOne.Count)" @@ -123,7 +123,7 @@ foreach($item in $listOneOnly.GetEnumerator()) { $item.Key } -  + # list differences from second file write-host "*************************************************************" write-host "Items only in second file:$($listTwoOnly.Count) out of $($listTwo.Count)" @@ -136,12 +136,12 @@ foreach($item in $listTwoOnly.GetEnumerator()) write-host "*************************************************************" write-host "Items in both files:$($listCombined.Count)" write-host "*************************************************************" -  + # list differences from first file write-host "*************************************************************" write-host "Items only in first file:$($listOneOnly.Count) out of $($listOne.Count)" write-host "*************************************************************" -  + # list differences from second file write-host "*************************************************************" write-host "Items only in second file:$($listTwoOnly.Count) out of $($listTwo.Count)" diff --git a/find-unique-lines.ps1 b/find-unique-lines.ps1 index 59c2daba..f4d1c66c 100644 --- a/find-unique-lines.ps1 +++ b/find-unique-lines.ps1 @@ -12,17 +12,17 @@ .PARAMETER file the text file for compare -  + #> -  + Param( -  + [parameter(Position=0,Mandatory=$true,HelpMessage="Enter path to first file")] [string] $file, [parameter(Position=1,Mandatory=$false,HelpMessage="Enter regex")] [string] $regex ) -  + cls $count = 0 $lineList = @{} @@ -50,7 +50,7 @@ function main() } -  $count++ + $count++ if(!$lineList.ContainsKey($line)) { $lineList.Add($line,1) @@ -61,7 +61,7 @@ function main() $linelist.Remove($line) $lineList.Add($line,++$oldvalue) } -  + } } else @@ -82,8 +82,8 @@ function main() log-info "Total lines:$($count)" log-info "finished" - } -  +} + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) @@ -96,4 +96,4 @@ function log-info($data) # ---------------------------------------------------------------------------------------------------------------- main -  + diff --git a/functions.ps1 b/functions.ps1 index c2e51f7c..a974c274 100644 --- a/functions.ps1 +++ b/functions.ps1 @@ -55,18 +55,18 @@ function authenticate-azureRm() } # verify NuGet package - $nuget = get-packageprovider nuget -Force + $nuget = get-packageprovider nuget -Force - if (-not $nuget -or ($nuget.Version -lt [version]::New("2.8.5.22"))) - { - write-host "installing nuget package..." - install-packageprovider -name NuGet -minimumversion ([version]::New("2.8.5.201")) -force - } + if (-not $nuget -or ($nuget.Version -lt [version]::New("2.8.5.22"))) + { + write-host "installing nuget package..." + install-packageprovider -name NuGet -minimumversion ([version]::New("2.8.5.201")) -force + } $allModules = (get-module azure* -ListAvailable).Name - # install AzureRM module - if ($allModules -inotcontains "AzureRM") - { + # install AzureRM module + if ($allModules -inotcontains "AzureRM") + { # each has different azurerm module requirements # installing azurerm slowest but complete method # if wanting to do minimum install, run the following script against script being deployed @@ -100,10 +100,10 @@ function authenticate-azureRm() Import-Module azurerm.resources Import-Module azurerm.compute Import-Module azurerm.network - #write-host "installing AzureRm powershell module..." - #install-module AzureRM -force + #write-host "installing AzureRm powershell module..." + #install-module AzureRM -force - } + } else { Import-Module azurerm @@ -114,7 +114,7 @@ function authenticate-azureRm() { $rg = @(Get-AzureRmTenant) - if($rg) + if ($rg) { write-host "auth passed $($rg.Count)" } @@ -187,44 +187,44 @@ function get-subscriptions() $subs = Get-AzureRmSubscription -WarningAction SilentlyContinue $newSubFormat = (get-module AzureRM.Resources).Version.ToString() -ge "4.0.0" - if($subs.Count -gt 1) + if ($subs.Count -gt 1) { [int]$count = 1 - foreach($sub in $subs) + foreach ($sub in $subs) { - if($newSubFormat) - { + if ($newSubFormat) + { $message = "$($count). $($sub.name) $($sub.id)" $id = $sub.id - } - else - { + } + else + { $message = "$($count). $($sub.SubscriptionName) $($sub.SubscriptionId)" $id = $sub.SubscriptionId - } + } Write-Host $message - [void]$subList.Add($count,$id) + [void]$subList.Add($count, $id) $count++ } [int]$id = Read-Host ("Enter number for subscription to enumerate or {enter} to query all:") $null = Set-AzureRmContext -SubscriptionId $subList[$id].ToString() - if($id -ne 0 -and $id -le $subs.count) + if ($id -ne 0 -and $id -le $subs.count) { return $subList[$id] } } - elseif($subs.Count -eq 1) + elseif ($subs.Count -eq 1) { - if($newSubFormat) + if ($newSubFormat) { - [void]$subList.Add("1",$subs.Id) + [void]$subList.Add("1", $subs.Id) } else { - [void]$subList.Add("1",$subs.SubscriptionId) + [void]$subList.Add("1", $subs.SubscriptionId) } } @@ -239,12 +239,12 @@ function get-sysInternalsUtility ([string] $utilityName) { $destFile = "$(get-location)\$utilityName" - if(![IO.File]::Exists($destFile)) + if (![IO.File]::Exists($destFile)) { $sysUrl = "http://live.sysinternals.com/$($utilityName)" write-host "Sysinternals process $($utilityName) is needed for this option!" -ForegroundColor Yellow - if((read-host "Is it ok to download $($sysUrl) ?[y:n]").ToLower().Contains('y')) + if ((read-host "Is it ok to download $($sysUrl) ?[y:n]").ToLower().Contains('y')) { $webClient = new-object System.Net.WebClient $webclient.UseDefaultCredentials = $true @@ -320,21 +320,21 @@ function log-info($data) { $dataWritten = $false $data = "$([System.DateTime]::Now):$($data)`n" - if([regex]::IsMatch($data.ToLower(),"error|exception|fail|warning")) + if ([regex]::IsMatch($data.ToLower(), "error|exception|fail|warning")) { write-host $data -foregroundcolor Yellow } - elseif([regex]::IsMatch($data.ToLower(),"running")) + elseif ([regex]::IsMatch($data.ToLower(), "running")) { - write-host $data -foregroundcolor Green + write-host $data -foregroundcolor Green } - elseif([regex]::IsMatch($data.ToLower(),"job completed")) + elseif ([regex]::IsMatch($data.ToLower(), "job completed")) { - write-host $data -foregroundcolor Cyan + write-host $data -foregroundcolor Cyan } - elseif([regex]::IsMatch($data.ToLower(),"starting")) + elseif ([regex]::IsMatch($data.ToLower(), "starting")) { - write-host $data -foregroundcolor Magenta + write-host $data -foregroundcolor Magenta } else { @@ -342,7 +342,7 @@ function log-info($data) } $counter = 0 - while(!$dataWritten -and $counter -lt 1000) + while (!$dataWritten -and $counter -lt 1000) { try { @@ -370,7 +370,7 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) { $retVal = new-object Text.StringBuilder - if([string]::IsNullOrEmpty($value)) + if ([string]::IsNullOrEmpty($value)) { [void]$retVal.AppendLine("-----------------------------------------") [void]$retVal.AppendLine("enumerating $($key)") @@ -389,9 +389,9 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) $sNames = $reg.EnumValues($hive, $key).sNames $sTypes = $reg.EnumValues($hive, $key).Types - for($i = 0; $i -lt $sNames.count; $i++) + for ($i = 0; $i -lt $sNames.count; $i++) { - if(![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value) + if (![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value) { continue } @@ -399,9 +399,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) switch ($sTypes[$i]) { # REG_SZ - 1{ + 1 + { $keyValue = $reg.GetStringValue($hive, $key, $sNames[$i]).sValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -412,26 +413,28 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_EXPAND_SZ - 2{ + 2 + { $keyValue = $reg.GetExpandStringValue($hive, $key, $sNames[$i]).sValue - if($enumValue) + if ($enumValue) { return $keyValue } else { - [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") + [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") } } # REG_BINARY - 3{ + 3 + { $keyValue = (($reg.GetBinaryValue($hive, $key, $sNames[$i]).uValue) -join ',') - if($enumValue -or $displayBinaryBlob) + if ($enumValue -or $displayBinaryBlob) { return $keyValue } - elseif($displayBinaryBlob) + elseif ($displayBinaryBlob) { [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") } @@ -443,9 +446,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_DWORD - 4{ + 4 + { $keyValue = $reg.GetDWORDValue($hive, $key, $sNames[$i]).uValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -456,9 +460,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_MULTI_SZ - 7{ + 7 + { $keyValue = (($reg.GetMultiStringValue($hive, $key, $sNames[$i]).sValue) -join ',') - if($enumValue) + if ($enumValue) { return $keyValue } @@ -469,9 +474,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_QWORD - 11{ + 11 + { $keyValue = $reg.GetQWORDValue($hive, $key, $sNames[$i]).uValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -486,12 +492,12 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } } - if([string]::IsNullOrEmpty($value) -and $subKeySearch) + if ([string]::IsNullOrEmpty($value) -and $subKeySearch) { - foreach($subKey in $reg.EnumKey($hive, $key).sNames) + foreach ($subKey in $reg.EnumKey($hive, $key).sNames) { - if([string]::IsNullOrEmpty($subKey)) + if ([string]::IsNullOrEmpty($subKey)) { continue } @@ -500,7 +506,7 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } } - if($enumValue) + if ($enumValue) { # no value return $null @@ -524,8 +530,8 @@ function runas-admin() { if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { - log-info "please restart script as administrator. exiting..." - return $false + log-info "please restart script as administrator. exiting..." + return $false } return $true @@ -539,7 +545,7 @@ function runas-admin() write-verbose "checking for admin" if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { - if(!$noretry) + if (!$noretry) { write-host "restarting script as administrator." Write-Host "run-process -processName powershell.exe -arguments -ExecutionPolicy Bypass -File $($SCRIPT:MyInvocation.MyCommand.Path) -noretry" @@ -547,12 +553,12 @@ function runas-admin() } return $false - } - else - { + } + else + { write-verbose "running as admin" - } + } return $true } @@ -577,39 +583,37 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.WindowStyle = [Diagnostics.ProcessWindowstyle]::Normal -  -    [void]$process.Start() -  - if($wait -and !$process.HasExited) + +[void]$process.Start() + + if ($wait -and !$process.HasExited) { -  -     if($process.StandardOutput.Peek() -gt -1) + if ($process.StandardOutput.Peek() -gt -1) { -     $stdOut = $process.StandardOutput.ReadToEnd() + $stdOut = $process.StandardOutput.ReadToEnd() log-info $stdOut -  } -  -  - if($process.StandardError.Peek() -gt -1) + } + + if ($process.StandardError.Peek() -gt -1) { $stdErr = $process.StandardError.ReadToEnd() log-info $stdErr -         $Error.Clear() -     } + $Error.Clear() + } } - elseif($wait) + elseif ($wait) { -     log-info "Error:Process ended before capturing output." + log-info "Error:Process ended before capturing output." } -  + $exitVal = $process.ExitCode -  + log-info "Running process exit $($processName) : $($exitVal)" $Error.Clear() -  + return $stdOut } diff --git a/perfmon-counter-action.ps1 b/perfmon-counter-action.ps1 index 361ec491..13eda97e 100644 --- a/perfmon-counter-action.ps1 +++ b/perfmon-counter-action.ps1 @@ -116,7 +116,7 @@ function run-process([string] $processName, [string] $arguments, [string] $worki $process.StartInfo.Arguments = $arguments $process.StartInfo.CreateNoWindow = $true $process.StartInfo.WorkingDirectory = $workingDir -  + [void]$process.Start() if($wait -and !$process.HasExited) { @@ -125,7 +125,7 @@ function run-process([string] $processName, [string] $arguments, [string] $worki $stdOut = $process.StandardOutput.ReadToEnd() $stdErr = $process.StandardError.ReadToEnd() log-info "Process output:$stdOut" -  + if(![String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") { log-info "Error:$stdErr `n $Error" @@ -141,7 +141,7 @@ function run-process([string] $processName, [string] $arguments, [string] $worki return $stdOut } -  + # ---------------------------------------------------------------------------------------------------------------- function runas-admin() { @@ -153,5 +153,5 @@ function runas-admin() } } -#-------------------------------------------------------------------------------------------------  +#------------------------------------------------------------------------------------------------- main diff --git a/ps-certreq.ps1 b/ps-certreq.ps1 index d3273f60..c33458fd 100644 --- a/ps-certreq.ps1 +++ b/ps-certreq.ps1 @@ -1,87 +1,89 @@ # From -#   New-CertificateRequest -subject mail1.showcase.kloud.com.au -#   New-CertificateRequest -subject *.contoso.com -#   New-CertificateRequest -subject remote.contoso.com -sans @("broker.contoso.com","broker.contoso.lab") +# New-CertificateRequest -subject mail1.showcase.kloud.com.au +# New-CertificateRequest -subject *.contoso.com +# New-CertificateRequest -subject remote.contoso.com -sans @("broker.contoso.com","broker.contoso.lab") param( -[string]$subject="",#"*.contoso.com", -[array]$sans=@() -)    -    + [string]$subject = "", #"*.contoso.com", + [array]$sans = @() +) + function New-CertificateRequest () { -        param ( -            [Parameter(Mandatory=$true, HelpMessage = "Please enter the subject beginning with CN=")] -            [ValidatePattern("CN=")] -            [string]$subject, -            [Parameter(Mandatory=$false, HelpMessage = "Please enter the SAN domains as a comma separated list")] -            [array]$SANs, -            [Parameter(Mandatory=$false, HelpMessage = "Please enter the Online Certificate Authority")] -            [string]$OnlineCA, -            [Parameter(Mandatory=$false, HelpMessage = "Please enter the Online Certificate Authority")] -            [string]$CATemplate = "WebServer" -        ) -      -        ### Preparation -        $subjectDomain = $subject.split(',')[0].split('=')[1] -        if ($subjectDomain -match "\*.") { -            $subjectDomain = $subjectDomain -replace "\*", "star" -        } -        $CertificateINI = "$subjectDomain.ini" -        $CertificateREQ = "$subjectDomain.req" -        $CertificateRSP = "$subjectDomain.rsp" -        $CertificateCER = "$subjectDomain.cer" -      -        ### INI file generation -        new-item -type file $CertificateINI -force -        add-content $CertificateINI '[Version]' -        add-content $CertificateINI 'Signature="$Windows NT$"' -        add-content $CertificateINI '' -        add-content $CertificateINI '[NewRequest]' -        add-content $CertificateINI ('Subject="' + $subject + '"') -        add-content $CertificateINI 'Exportable=TRUE' -        add-content $CertificateINI 'KeyLength=2048' -        add-content $CertificateINI 'KeySpec=1' -        add-content $CertificateINI 'KeyUsage=0x30' -        add-content $CertificateINI 'MachineKeySet=True' -        add-content $CertificateINI 'ProviderName="Microsoft RSA SChannel Cryptographic Provider"' -        add-content $CertificateINI 'ProviderType=12' -        add-content $CertificateINI 'SMIME=FALSE' + param ( + [Parameter(Mandatory = $true, HelpMessage = "Please enter the subject beginning with CN=")] + [ValidatePattern("CN=")] + [string]$subject, + [Parameter(Mandatory = $false, HelpMessage = "Please enter the SAN domains as a comma separated list")] + [array]$SANs, + [Parameter(Mandatory = $false, HelpMessage = "Please enter the Online Certificate Authority")] + [string]$OnlineCA, + [Parameter(Mandatory = $false, HelpMessage = "Please enter the Online Certificate Authority")] + [string]$CATemplate = "WebServer" + ) + + ### Preparation + $subjectDomain = $subject.split(',')[0].split('=')[1] + if ($subjectDomain -match "\*.") + { + $subjectDomain = $subjectDomain -replace "\*", "star" + } + $CertificateINI = "$subjectDomain.ini" + $CertificateREQ = "$subjectDomain.req" + $CertificateRSP = "$subjectDomain.rsp" + $CertificateCER = "$subjectDomain.cer" + + ### INI file generation + new-item -type file $CertificateINI -force + add-content $CertificateINI '[Version]' + add-content $CertificateINI 'Signature="$Windows NT$"' + add-content $CertificateINI '' + add-content $CertificateINI '[NewRequest]' + add-content $CertificateINI ('Subject="' + $subject + '"') + add-content $CertificateINI 'Exportable=TRUE' + add-content $CertificateINI 'KeyLength=2048' + add-content $CertificateINI 'KeySpec=1' + add-content $CertificateINI 'KeyUsage=0x30' + add-content $CertificateINI 'MachineKeySet=True' + add-content $CertificateINI 'ProviderName="Microsoft RSA SChannel Cryptographic Provider"' + add-content $CertificateINI 'ProviderType=12' + add-content $CertificateINI 'SMIME=FALSE' + + ### Date Ranges + add-content $CertificateINI ('NotBefore="' + (get-date).ToShortDateString() + '"') + ### Expire in 5 years + add-content $CertificateINI ('NotAfter="' + (get-date).AddYears(5).ToShortDateString() + '"') + + add-content $CertificateINI 'RequestType=Cert' + add-content $CertificateINI 'HashAlgorithm=sha256' + add-content $CertificateINI '[EnhancedKeyUsageExtension]' + add-content $CertificateINI 'OID=1.3.6.1.5.5.7.3.1 ; this is for Server Authentication / Token Signing' - ### Date Ranges -         add-content $CertificateINI ('NotBefore="' + (get-date).ToShortDateString() + '"') - ### Expire in 5 years - add-content $CertificateINI ('NotAfter="' + (get-date).AddYears(5).ToShortDateString() + '"') -      -      add-content $CertificateINI 'RequestType=Cert' -      add-content $CertificateINI 'HashAlgorithm=sha256' -      add-content $CertificateINI '[EnhancedKeyUsageExtension]' -      add-content $CertificateINI 'OID=1.3.6.1.5.5.7.3.1 ; this is for Server Authentication / Token Signing' + if ($SANs) + { + add-content $CertificateINI '[Extensions]' + add-content $CertificateINI '2.5.29.17 = "{text}"' -      if ($SANs) - { -            add-content $CertificateINI '[Extensions]' -            add-content $CertificateINI '2.5.29.17 = "{text}"' -      -          foreach ($SAN in $SANs) - { -                add-content $CertificateINI ('_continue_ = "dns=' + $SAN + '&"') -          } -        } -      -        ### Certificate request generation -        if (test-path $CertificateREQ) {del $CertificateREQ} -        certreq -new $CertificateINI $CertificateREQ -      -        ### Online certificate request and import -        if ($OnlineCA) { -            if (test-path $CertificateCER) {del $CertificateCER} -            if (test-path $CertificateRSP) {del $CertificateRSP} -            certreq -submit -attrib "CertificateTemplate:$CATemplate" -config $OnlineCA $CertificateREQ $CertificateCER -      -            certreq -accept $CertificateCER -        } + foreach ($SAN in $SANs) + { + add-content $CertificateINI ('_continue_ = "dns=' + $SAN + '&"') + } + } + + ### Certificate request generation + if (test-path $CertificateREQ) {del $CertificateREQ} + certreq -new $CertificateINI $CertificateREQ + + ### Online certificate request and import + if ($OnlineCA) + { + if (test-path $CertificateCER) {del $CertificateCER} + if (test-path $CertificateRSP) {del $CertificateRSP} + certreq -submit -attrib "CertificateTemplate:$CATemplate" -config $OnlineCA $CertificateREQ $CertificateCER + + certreq -accept $CertificateCER + } } -  + New-CertificateRequest -subject "CN=$($subject)" -SANs $sans -  + diff --git a/rds-upd-mgr.ps1 b/rds-upd-mgr.ps1 index 00e20026..0476955f 100644 --- a/rds-upd-mgr.ps1 +++ b/rds-upd-mgr.ps1 @@ -1,50 +1,50 @@ -<#  -.SYNOPSIS  -    powershell script to enumerate customer RDS environment for UPD information +<# +.SYNOPSIS +powershell script to enumerate customer RDS environment for UPD information -.DESCRIPTION  -    powershell script to enumerate customer RDS environment for UPD information +.DESCRIPTION +powershell script to enumerate customer RDS environment for UPD information -.NOTES  +.NOTES Version: 160520 original History: -   -.EXAMPLE  -    .\rds-upd-mgr.ps1 -user jagilber + +.EXAMPLE +.\rds-upd-mgr.ps1 -user jagilber .\rds-upd-mgr.ps1 -sid S-1-5-21-124525095-708259637-1543119021-1234567 .PARAMETER user users ad account with issue -  + .PARAMETER sid users sid or sid from vhd with issue .PARAMETER machine machine to query or connection broker to query -#>  -  -  +#> + + Param( -  - [parameter(HelpMessage="Enter user name:")] + + [parameter(HelpMessage = "Enter user name:")] [string] $user, - [parameter(HelpMessage="Enter collection:")] + [parameter(HelpMessage = "Enter collection:")] [string] $collection, - [parameter(HelpMessage="Enter connection Broker:")] + [parameter(HelpMessage = "Enter connection Broker:")] [string] $server = $env:COMPUTERNAME, - [parameter(HelpMessage="Enter `$true to prompt / use alternate credentials. Default is `$false")] + [parameter(HelpMessage = "Enter `$true to prompt / use alternate credentials. Default is `$false")] [bool] $useCreds = $false, - [parameter(HelpMessage="Enter `$true to store alternate credentials. Default is `$false")] + [parameter(HelpMessage = "Enter `$true to store alternate credentials. Default is `$false")] [bool] $storeCreds = $false, - [parameter(HelpMessage="Select this switch to check for script update")] + [parameter(HelpMessage = "Select this switch to check for script update")] [switch] $getUpdate - ) +) + -  $ErrorActionPreference = "SilentlyContinue" $Creds = $null # if storing creds, password will have to be saved one time @@ -72,12 +72,12 @@ function main () log-info $MyInvocation.ScriptName # run as administrator - if(!(runas-admin)) + if (!(runas-admin)) { return } - if($getUpdate) + if ($getUpdate) { get-update -updateUrl $updateUrl } @@ -93,14 +93,14 @@ function main () $machines = @(get-machines -server $server) # get list of users for upd's using sid from upd name - foreach($upd in get-upds -shares $global:updShares) + foreach ($upd in get-upds -shares $global:updShares) { - if([string]::IsNullOrEmpty($upd) -or !$upd.Contains("UVHD-")) + if ([string]::IsNullOrEmpty($upd) -or !$upd.Contains("UVHD-")) { continue } - $sid = [IO.Path]::GetFileNameWithoutExtension($upd).Replace("UVHD-","") + $sid = [IO.Path]::GetFileNameWithoutExtension($upd).Replace("UVHD-", "") $userObj = ([wmi]"Win32_SID.SID='$($sid)'") $info = @{} @@ -140,16 +140,16 @@ function main () #---------------------------------------------------------------------------- function check-creds() { - if($useCreds) + if ($useCreds) { - if((test-path $passFile) -and $storeCreds) + if ((test-path $passFile) -and $storeCreds) { $password = cat $passFile | convertto-securestring $Creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password } - elseif($storeCreds) + elseif ($storeCreds) { read-host -assecurestring | convertfrom-securestring | out-file $passFile @@ -170,12 +170,12 @@ function check-creds() function get-machines($server) { $machines = @($server) - if(!(get-service -DisplayName 'Remote Desktop Connection Broker' -ErrorAction SilentlyContinue)) + if (!(get-service -DisplayName 'Remote Desktop Connection Broker' -ErrorAction SilentlyContinue)) { log-info "$($server) is not a connection broker. trying to find broker." $global:brokers = @((read-reg -machine $server -hive $HKLM -key $deploymentReg -value "SessionDirectoryLocation").Split(';')) - if($global:brokers.Count -gt 0 -and ![string]::IsNullOrEmpty($global:brokers[0])) + if ($global:brokers.Count -gt 0 -and ![string]::IsNullOrEmpty($global:brokers[0])) { $global:broker = $global:brokers[0] } @@ -188,7 +188,7 @@ function get-machines($server) # look for upd share in reg in case it rds. only cb can query for upd via ps $global:updShares = @(read-reg -machine $server -hive $HKLM -key $deploymentReg -value "UvhdShareUrl") - if($global:updShares.Count -lt 1) + if ($global:updShares.Count -lt 1) { log-info "server is part of rds deployment, but does not have upd configured. exiting" exit @@ -201,19 +201,19 @@ function get-machines($server) $global:brokers = get-rdserver -ConnectionBroker $global:broker -Role RDS-CONNECTION-BROKER $global:broker = $server - foreach($farmSettings in ((Get-WmiObject -Namespace root\cimv2\terminalservices -Class Win32_RDCentralPublishedFarm).VmFarmSettings)) + foreach ($farmSettings in ((Get-WmiObject -Namespace root\cimv2\terminalservices -Class Win32_RDCentralPublishedFarm).VmFarmSettings)) { - if([string]::IsNullOrEmpty($farmSettings)) + if ([string]::IsNullOrEmpty($farmSettings)) { continue } #$config = (Get-RDSessionCollectionConfiguration -CollectionName $collection) $pattern = 'name="UvhdProfRoamingEnabled" value="True"' - if([regex]::IsMatch($farmSettings, $pattern, [Text.RegularExpressions.RegexOptions]::IgnoreCase)) + if ([regex]::IsMatch($farmSettings, $pattern, [Text.RegularExpressions.RegexOptions]::IgnoreCase)) { $pattern = 'name="UvhdShareUrl" value="(.+?)"' - $match = [regex]::Match($farmSettings,$pattern, [Text.RegularExpressions.RegexOptions]::IgnoreCase) + $match = [regex]::Match($farmSettings, $pattern, [Text.RegularExpressions.RegexOptions]::IgnoreCase) $global:updShares.Add($match.Groups[1].Value) } } @@ -222,7 +222,7 @@ function get-machines($server) #make sure it is active broker $ha = Get-RDConnectionBrokerHighAvailability -ConnectionBroker $global:broker - if($ha -ne $null) + if ($ha -ne $null) { log-info $ha $global:broker = $ha.ActiveManagementServer @@ -234,23 +234,23 @@ function get-machines($server) # get rdsh machines $machines = (Get-RDServer -ConnectionBroker $global:broker -Role RDS-RD-SERVER).Server - if($machines -ne $null) + if ($machines -ne $null) { - foreach($machine in $machines) + foreach ($machine in $machines) { log-info $machine } -# $result = Read-Host "do you want to collect data from entire deployment? [y:n]" -# if([regex]::IsMatch($result, "y",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) -# { -# log-info "adding rds collection machines" -# return $machines -# } -# else -# { -# return $server -# } + # $result = Read-Host "do you want to collect data from entire deployment? [y:n]" + # if([regex]::IsMatch($result, "y",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) + # { + # log-info "adding rds collection machines" + # return $machines + # } + # else + # { + # return $server + # } } } catch @@ -266,7 +266,7 @@ function get-machines($server) function get-upds([string[]] $shares) { $list = new-object System.Collections.ArrayList - foreach($share in $shares) + foreach ($share in $shares) { try { @@ -280,7 +280,7 @@ function get-upds([string[]] $shares) } } - return ,$list + return , $list } #---------------------------------------------------------------------------- @@ -296,13 +296,13 @@ function is-fileLocked([string] $file) try { - $fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) - if ($fileStream) - { + $fileStream = $fileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) + if ($fileStream) + { $fileStream.Close() - } + } - log-info "File is NOT locked:$($file)" + log-info "File is NOT locked:$($file)" return $false } catch @@ -316,11 +316,11 @@ function is-fileLocked([string] $file) #---------------------------------------------------------------------------- function log-info($data) { - if($data.ToString().ToLower().StartsWith("error")) + if ($data.ToString().ToLower().StartsWith("error")) { $ForegroundColor = "Yellow" } - elseif($data.ToString().ToLower().StartsWith("fail")) + elseif ($data.ToString().ToLower().StartsWith("fail")) { $ForegroundColor = "Red" } @@ -328,12 +328,12 @@ function log-info($data) { $ForegroundColor = "Green" } -  + write-host $data -ForegroundColor $ForegroundColor try { - if(![string]::IsNullOrEmpty($logFile)) + if (![string]::IsNullOrEmpty($logFile)) { out-file -Append -FilePath $logFile -InputObject "$([DateTime]::Now):$($data)" -Encoding ascii } @@ -359,39 +359,39 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.Arguments = $arguments $process.StartInfo.CreateNoWindow = $wait $process.StartInfo.WorkingDirectory = get-location -  -    [void]$process.Start() -  - if($wait -and !$process.HasExited) + +[void]$process.Start() + + if ($wait -and !$process.HasExited) { -  -     if($process.StandardOutput.Peek() -gt -1) + + if ($process.StandardOutput.Peek() -gt -1) { -     $stdOut = $process.StandardOutput.ReadToEnd() + $stdOut = $process.StandardOutput.ReadToEnd() log-info $stdOut -  } -  -  - if($process.StandardError.Peek() -gt -1) + } + + + if ($process.StandardError.Peek() -gt -1) { $stdErr = $process.StandardError.ReadToEnd() log-info $stdErr -         $Error.Clear() -     } + $Error.Clear() + } } - elseif($wait) + elseif ($wait) { -     log-info "Error:Process ended before capturing output." + log-info "Error:Process ended before capturing output." } -  + $exitVal = $process.ExitCode -  + log-info "Running process exit $($processName) : $($exitVal)" $Error.Clear() -  + return $stdOut } @@ -399,9 +399,9 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = function manage-wmiExecute([string] $command, [string] $machine) { log-info "wmiExecute: $($machine) : $($command) : $($workingDir)" - # $wmi = new-object System.Management.ManagementClass "\\$($machine)\Root\cimv2:Win32_Process" - # $result = $wmi.Create($command) - if($useCreds) + # $wmi = new-object System.Management.ManagementClass "\\$($machine)\Root\cimv2:Win32_Process" + # $result = $wmi.Create($command) + if ($useCreds) { $result = Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList ($command, $workingDir) -Credential $Creds -ComputerName $computer } @@ -410,36 +410,42 @@ function manage-wmiExecute([string] $command, [string] $machine) $result = Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList ($command, $workingDir) -ComputerName $computer } - switch($result.ReturnValue) + switch ($result.ReturnValue) { - 0 { - log-info "$($machine) return:success" - } + 0 + { + log-info "$($machine) return:success" + } - 2 { - log-info "$($machine) return:access denied" - } + 2 + { + log-info "$($machine) return:access denied" + } - 3 { - log-info "$($machine) return:insufficient privilege" - } + 3 + { + log-info "$($machine) return:insufficient privilege" + } - 8 { - log-info "$($machine) return:unknown failure" - } + 8 + { + log-info "$($machine) return:unknown failure" + } - 9 { - log-info "$($machine) return:path not found" - } + 9 + { + log-info "$($machine) return:path not found" + } - 21 { - log-info "$($machine) return:invalid parameter" - } + 21 + { + log-info "$($machine) return:invalid parameter" + } default - { - log-info "$($machine) return:unknown $($result.ReturnValue)" - } + { + log-info "$($machine) return:unknown $($result.ReturnValue)" + } } return $result.ReturnValue @@ -451,7 +457,7 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) { $retVal = new-object Text.StringBuilder - if([string]::IsNullOrEmpty($value)) + if ([string]::IsNullOrEmpty($value)) { [void]$retVal.AppendLine("-----------------------------------------") [void]$retVal.AppendLine("enumerating $($key)") @@ -470,9 +476,9 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) $sNames = $reg.EnumValues($hive, $key).sNames $sTypes = $reg.EnumValues($hive, $key).Types - for($i = 0; $i -lt $sNames.count; $i++) + for ($i = 0; $i -lt $sNames.count; $i++) { - if(![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value) + if (![string]::IsNullOrEmpty($value) -and $sNames[$i] -inotlike $value) { continue } @@ -480,9 +486,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) switch ($sTypes[$i]) { # REG_SZ - 1{ + 1 + { $keyValue = $reg.GetStringValue($hive, $key, $sNames[$i]).sValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -493,26 +500,28 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_EXPAND_SZ - 2{ + 2 + { $keyValue = $reg.GetExpandStringValue($hive, $key, $sNames[$i]).sValue - if($enumValue) + if ($enumValue) { return $keyValue } else { - [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") + [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") } } # REG_BINARY - 3{ + 3 + { $keyValue = (($reg.GetBinaryValue($hive, $key, $sNames[$i]).uValue) -join ',') - if($enumValue -and $displayBinaryBlob) + if ($enumValue -and $displayBinaryBlob) { return $keyValue } - elseif($displayBinaryBlob) + elseif ($displayBinaryBlob) { [void]$retval.AppendLine("$($sNames[$i]):$($keyValue)") } @@ -524,9 +533,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_DWORD - 4{ + 4 + { $keyValue = $reg.GetDWORDValue($hive, $key, $sNames[$i]).uValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -537,9 +547,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_MULTI_SZ - 7{ + 7 + { $keyValue = (($reg.GetMultiStringValue($hive, $key, $sNames[$i]).sValue) -join ',') - if($enumValue) + if ($enumValue) { return $keyValue } @@ -550,9 +561,10 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } # REG_QWORD - 11{ + 11 + { $keyValue = $reg.GetQWORDValue($hive, $key, $sNames[$i]).uValue - if($enumValue) + if ($enumValue) { return $keyValue } @@ -567,12 +579,12 @@ function read-reg($machine, $hive, $key, $value, $subKeySearch = $true) } } - if([string]::IsNullOrEmpty($value) -and $subKeySearch) + if ([string]::IsNullOrEmpty($value) -and $subKeySearch) { - foreach($subKey in $reg.EnumKey($hive, $key).sNames) + foreach ($subKey in $reg.EnumKey($hive, $key).sNames) { - if([string]::IsNullOrEmpty($subKey)) + if ([string]::IsNullOrEmpty($subKey)) { continue } @@ -604,7 +616,7 @@ function get-update($updateUrl) $gitClean = [regex]::Replace($git, '\W+', "") $fileClean = [regex]::Replace(([IO.File]::ReadAllBytes($MyInvocation.ScriptName)), '\W+', "") - if(([string]::Compare($gitClean, $fileClean) -ne 0)) + if (([string]::Compare($gitClean, $fileClean) -ne 0)) { log-info "updating new script" [IO.File]::WriteAllText($MyInvocation.ScriptName, $git) @@ -632,8 +644,8 @@ function runas-admin() { if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { - log-info "please restart script as administrator. exiting..." - return $false + log-info "please restart script as administrator. exiting..." + return $false } return $true diff --git a/rdv-vdi-query.ps1 b/rdv-vdi-query.ps1 index 8969ae66..59e1fbd8 100644 --- a/rdv-vdi-query.ps1 +++ b/rdv-vdi-query.ps1 @@ -30,7 +30,7 @@ .EXAMPLE .\rdv-vdi-query.ps1 -update check github for updated script file. -  + .PARAMETER activeBroker optional parameter to specify active connection broker diff --git a/remote-manager.ps1 b/remote-manager.ps1 index a588b1c7..d120c739 100644 --- a/remote-manager.ps1 +++ b/remote-manager.ps1 @@ -6,7 +6,7 @@ Set-ExecutionPolicy Bypass -Force powershell script to manage commands remotely across multiple machines default job definitions at bottom of script -   + .NOTES File Name : remote-manager.ps1 Author : jagilber @@ -54,9 +54,9 @@ Param( [string[]] $machines = @($env:COMPUTERNAME), [parameter(HelpMessage="Enter number of minutes from now for event log gathering. Default is 60")] [string[]] $minutes = 60, -  [parameter(HelpMessage="Use to not clean remote working directory on stop")] + [parameter(HelpMessage="Use to not clean remote working directory on stop")] [switch] $noclean, -  [parameter(HelpMessage="Use to start")] + [parameter(HelpMessage="Use to start")] [switch] $start, [parameter(HelpMessage="Use to stop")] [switch] $stop, @@ -64,7 +64,7 @@ Param( [int] $throttle = 10 ) -  + cls Add-Type -assembly "system.io.compression.filesystem" $ErrorActionPreference = "SilentlyContinue" #"Stop" @@ -716,8 +716,8 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f # ---------------------------------------------------------------------------------------------------------------- function manage-scheduledTask([bool] $enable, [string] $machine, $taskInfo, [bool] $wait = $false) { -     # win 2k8r2 and below have to use com object -     # 2012 can use cmdlets + # win 2k8r2 and below have to use com object + # 2012 can use cmdlets log-info "manage-scheduledTask $($taskInfo.taskname) $($machine)" @@ -727,10 +727,10 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f $TaskDir = $taskInfo.taskdir $TaskArg = $taskInfo.taskarg -  $error.Clear() -     $service = new-object -ComObject("Schedule.Service") -     # connect to the local machine.  -     # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx + $error.Clear() + $service = new-object -ComObject("Schedule.Service") + # connect to the local machine. + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx # for remote machine connect do $service.Connect(serverName,user,domain,password) if([string]::IsNullOrEmpty($machine)) { @@ -738,80 +738,80 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f } else { -     $service.Connect($machine) + $service.Connect($machine) } -  -     $rootFolder = $service.GetFolder("\") -  -     if($enable) -     { -         $TaskDefinition = $service.NewTask(0)  -         $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" + + $rootFolder = $service.GetFolder("\") + + if($enable) + { + $TaskDefinition = $service.NewTask(0) + $TaskDefinition.RegistrationInfo.Description = "$TaskDescr" # 2k8r2 is 65539 (0x10003) 1.3 # procmon needs at least 2k8r2 compat #$TaskDefinition.Settings.Compatibility = 3 -         $TaskDefinition.Settings.Enabled = $true -         $TaskDefinition.Settings.AllowDemandStart = $true -  -         $triggers = $TaskDefinition.Triggers -         #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx -         $trigger = $triggers.Create(8) # Creates a "boot time" trigger -         #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") -         $trigger.Enabled = $true -  -         # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx -         $Action = $TaskDefinition.Actions.Create(0) -         $action.Path = "$TaskCommand" -         $action.Arguments = "$TaskArg" -         $action.WorkingDirectory = $TaskDir -         -          #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx -       $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) -  -         #start task -         $task = $rootFolder.GetTask($TaskName) -  -         $task.Run($null) -  -     } -     else -     { -         # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + $TaskDefinition.Settings.Enabled = $true + $TaskDefinition.Settings.AllowDemandStart = $true + + $triggers = $TaskDefinition.Triggers + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx + $trigger = $triggers.Create(8) # Creates a "boot time" trigger + #$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss") + $trigger.Enabled = $true + + # http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx + $Action = $TaskDefinition.Actions.Create(0) + $action.Path = "$TaskCommand" + $action.Arguments = "$TaskArg" + $action.WorkingDirectory = $TaskDir + + #http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx + $rootFolder.RegisterTaskDefinition("$TaskName",$TaskDefinition,6,"System",$null,5) + + #start task + $task = $rootFolder.GetTask($TaskName) + + $task.Run($null) + + } + else + { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { if($debugScript) { log-info "found task $($TaskName)" } -                 $task.Stop() -             } -         } -  -         # delete task -         $rootFolder.DeleteTask($TaskName,$null) -     } -  -  if($wait) + $task.Stop() + } + } + + # delete task + $rootFolder.DeleteTask($TaskName,$null) + } + + if($wait) { log-info "waiting for task to complete" while($true) { $foundTask = $false -      # stop task if its running -         foreach($task in $service.GetRunningTasks(1)) -         { -             if($task.Name -ieq $TaskName) -             { + # stop task if its running + foreach($task in $service.GetRunningTasks(1)) + { + if($task.Name -ieq $TaskName) + { if($debugScript) { log-info "found task $($TaskName)" } -                 $foundTask = $true -             } -         } + $foundTask = $true + } + } if(!$foundTask) { @@ -832,9 +832,9 @@ function manage-scheduledTaskJob([string] $machine, $taskInfo, [bool] $wait = $f { return $true } -  + } # end manage-scheduledTask -  + } # end functions diff --git a/set-regPermissions.ps1 b/set-regPermissions.ps1 index 0b8ce7db..2a992a08 100644 --- a/set-regPermissions.ps1 +++ b/set-regPermissions.ps1 @@ -11,7 +11,7 @@ Author : jagilber Version : 150109 History : -  + .EXAMPLE .\set-regPermissions.ps1 @@ -30,43 +30,43 @@ $error.Clear() $ErrorActionPreference = "Continue" $logFile = "set-regPermissions.log" -  + $objUser = New-Object System.Security.Principal.NTAccount("everyone") $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None $RegistryRights = [System.Security.AccessControl.RegistryRights]::SetValue -  + $AccessControl = [System.Security.AccessControl.AccessControlType]::Allow -  + $AuditFlag = [System.Security.AccessControl.AuditFlags]::Success # end of variables -  + # ---------------------------------------------------------------------------------------------------------------- function main() { cls $error.Clear() -  + log-info "starting" -  + #enable auditing run-process -processName "Auditpol.exe" -arguments "/set /category:`"Object Access`" /failure:enable /success:enable" -wait $true #set-accessAcl -  + set-auditAcl -  + log-info "finished" } -  + # ---------------------------------------------------------------------------------------------------------------- function set-accessAcl() { $acl = Get-Acl $regKey -  + log-info "current acl:" log-aclInfo $acl -  + foreach($obj in $acl.Access) { $accessLine += "$($obj.IdentityReference) $($obj.AccessControlType) $($obj.RegistryRights)`n`t" @@ -78,23 +78,23 @@ function set-accessAcl() return } } -  + log-info "creating new access rule" $accessRule = New-Object System.Security.AccessControl.RegistryAccessRule ($objUser, $RegistryRights, $AccessControl) $acl.SetAccessRule($accessRule) $newAcl = Get-Acl $regKey -  + log-info "new acl:" log-aclInfo $newAcl } -  + # ---------------------------------------------------------------------------------------------------------------- function set-auditAcl() { $acl = Get-Acl $regKey -Audit -  + log-info "current acl:" log-aclInfo $acl @@ -108,9 +108,9 @@ function set-auditAcl() return } } -  -  -  + + + log-info "creating new audit rule" $auditRule = New-Object System.Security.AccessControl.RegistryAuditRule ($objUser, $RegistryRights, $InheritanceFlag, $PropagationFlag, $AuditFlag) $acl.SetAuditRule($auditRule) @@ -118,37 +118,37 @@ function set-auditAcl() Set-Acl -Path $regKey -AclObject $acl $newAcl = Get-Acl $regKey -Audit -  + log-info "new acl:" log-aclInfo $newAcl } -  + # ---------------------------------------------------------------------------------------------------------------- function log-aclInfo($acl) { log-info "Path: $($acl.Path)" log-info "Owner: $($acl.Owner)" log-info "Group: $($acl.Group)" -  + log-info "Access:" foreach($obj in $acl.Access) { $accessLine += "$($obj.IdentityReference) $($obj.AccessControlType) $($obj.RegistryRights)`n`t" } -  + log-info $accessLine -  + log-info "Audit:" foreach($obj in $acl.Audit) { $auditLine += "$($obj.IdentityReference) $($obj.AuditFlags) $($obj.RegistryRights)`n`t" } -  + log-info $auditLine -  + log-info "Sddl: $($acl.Sddl)" } -  + # ---------------------------------------------------------------------------------------------------------------- function run-process([string] $processName, [string] $arguments, [bool] $wait = $false) { @@ -162,7 +162,7 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $process.StartInfo.Arguments = $arguments $process.StartInfo.CreateNoWindow = $true -  + [void]$process.Start() if($wait -and !$process.HasExited) { @@ -171,7 +171,7 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = $stdOut = $process.StandardOutput.ReadToEnd() $stdErr = $process.StandardError.ReadToEnd() log-info "Process output:$stdOut" -  + if(![String]::IsNullOrEmpty($stdErr) -and $stdErr -notlike "0") { log-info "Error:$stdErr `n $Error" @@ -186,7 +186,7 @@ function run-process([string] $processName, [string] $arguments, [bool] $wait = #return $exitVal return $stdOut } -  + # ---------------------------------------------------------------------------------------------------------------- function log-info($data) { @@ -194,7 +194,7 @@ function log-info($data) Write-Host $data out-file -Append -InputObject $data -FilePath $logFile } -  + # ---------------------------------------------------------------------------------------------------------------- -  -main  + +main