Friday Fun: A PowerShell Alarm Clock

Today’s Friday Fun is a continuation of my exploration of ways to use Start-Job. A few weeks ago I wrote about using Start-Job to create “scheduled” tasks. I realized I could take this further and turn this into a sort of alarm clock. The goal is to execute at command at a given time, but I wanted to make it easy to specify the time. What I have so far is a function called New-Alarm. I have some other ideas and hope to expand this into a module, but for now I thought I’d toss this out to you and get some feedback.


Function New-Alarm {

[cmdletbinding(SupportsShouldProcess=$True,DefaultParameterSetName="Time")]

Param (
[Parameter(Position=0,ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[string]$Command="Notepad",
[Parameter(Position=1,ValueFromPipelineByPropertyName=$True,ParameterSetName="Time")]
[ValidateNotNullorEmpty()]
[Alias("time")]
[datetime]$Alarm=(Get-Date).AddMinutes(5),
[Parameter(ValueFromPipelineByPropertyName=$True,ParameterSetName="Seconds")]
[int]$Seconds,
[Parameter(ValueFromPipelineByPropertyName=$True,ParameterSetName="Minutes")]
[int]$Minutes,
[Parameter(ValueFromPipelineByPropertyName=$True,ParameterSetName="Hours")]
[int]$Hours,
[Parameter(ValueFromPipelineByPropertyName=$True)]
[Alias("init","is")]
[string]$InitializationScript
)

Process {

if ($seconds) {$Alarm=(Get-Date).AddSeconds($seconds)}
if ($minutes) {$Alarm=(Get-Date).AddMinutes($minutes)}
if ($Hours) {$Alarm=(Get-Date).AddHours($hours)}

Write-Verbose ("{0} Creating an alarm for {1} to execute {2}" -f (Get-Date),$Alarm,$Command)

#define a scriptblock that takes parameters. Parameters are validated in the
#function so we don't need to do it here.
$sbText=@"
Param ([string]`$Command,[datetime]`$Alarm,[string]`$Init)

#define a boolean flag
`$Done=`$False

#loop until the time is greater or equal to the alarm time
#sleeping every 10 seconds
do {
if ((get-date) -ge `$Alarm) {
#run the command
`$ActualTime=Get-Date
Invoke-Expression `$Command
#set the flag to True
`$Done=`$True
}
else {
sleep -Seconds 10
}
} while (-Not `$Done)

#write an alarm summary object which can be retrieved with Receive-Job
New-Object -TypeName PSObject -Property @{
ScheduledTime=`$Alarm
ActualTime=`$ActualTime
Command=`$Command
Initialization=`$Init
}
"@

#append metadata to the scriptblock text so they can be parsed out with Get-Alarm
#to discover information for currently running alarm jobs

$meta=@"

#Alarm Command::$Command
#Alarm Time::$Alarm
#Alarm Init::$InitializationScript
#Alarm Created::$(Get-Date)

"@

#add meta data to scriptblock text
$sbText+=$meta

Write-Debug "Scriptblock text:"
Write-Debug $sbText
Write-Debug "Creating the scriptblock"

#create a scriptblock to use with Start-Job
$sb=$ExecutionContext.InvokeCommand.NewScriptBlock($sbText)

Try {
If ($InitializationScript) {
#turn $initializationscript into a script block
$initsb=$ExecutionContext.InvokeCommand.NewScriptBlock($initializationscript)
Write-Verbose ("{0} Using an initialization script: {1}" -f (Get-Date),$InitializationScript)
}
else {
#no initialization command so create an empty scriptblock
$initsb={}
}

#WhatIf
if ($pscmdlet.ShouldProcess("$command at $Alarm")) {
#create a background job
Start-job -ScriptBlock $sb -ArgumentList @($Command,$Alarm,$InitializationScript) -ErrorAction "Stop" -InitializationScript $Initsb
Write-Verbose ("{0} Alarm Created" -f (Get-Date))
}
}

Catch {
$msg="{0} Exception creating the alarm job. {1}" -f (Get-Date),$_.Exception.Message
Write-Warning $msg
}
} #Process

} #end function

The function includes full help.

To use the function you specify a command string to execute at a given time. The default’s are to run Notepad in 5 minutes. You can either specify an exact time.


PS C:\> new-alarm "get-process | out-file c:\work\noonprocs.txt" -alarm "12:00PM"

Or X number of seconds, minutes or hours.


PS C:\> $s='$f=[system.io.path]::GetTempFilename(); "Hey! Are you paying attention??" > $f;start-process notepad $f -wait;del $f'
PS C:\> new-alarm $s -minutes 15 -verbose

The first command defines a command string, $s. This creates a temporary file, writes some text to it, displays it with Notepad and then deletes it. The second command creates a new alarm that will invoke the expression in 15 minutes.

For now, the command is passed as text. This is so that I can create an internal scriptblock. I use a Do loop to compare the current time to the alarm time. When the time is right, the command string is executed using Invoke-Expression.


$sbText=@"
Param ([string]`$Command,[datetime]`$Alarm,[string]`$Init)

#define a boolean flag
`$Done=`$False

#loop until the time is greater or equal to the alarm time
#sleeping every 10 seconds
do {
if ((get-date) -ge `$Alarm) {
#run the command
`$ActualTime=Get-Date
Invoke-Expression `$Command
#set the flag to True
`$Done=`$True
}
else {
sleep -Seconds 10
}
} while (-Not `$Done)

#write an alarm summary object which can be retrieved with Receive-Job
New-Object -TypeName PSObject -Property @{
ScheduledTime=`$Alarm
ActualTime=`$ActualTime
Command=`$Command
Initialization=`$Init
}
"@

I also add some metadata to the script block which gets written as the job’s result.


#append metadata to the scriptblock text so they can be parsed out with Get-Alarm
#to discover information for currently running alarm jobs

$meta=@"

#Alarm Command::$Command
#Alarm Time::$Alarm
#Alarm Init::$InitializationScript
#Alarm Created::$(Get-Date)

"@

#add meta data to scriptblock text
$sbText+=$meta

Write-Debug "Scriptblock text:"
Write-Debug $sbText
Write-Debug "Creating the scriptblock"

#create a scriptblock to use with Start-Job
$sb=$ExecutionContext.InvokeCommand.NewScriptBlock($sbText)

Finally, the alarm function allows for an initialization command, like you might use with Start-Job. This permits you to run commands such as importing modules or dot sourcing scripts. I have a function that displays a VB style message box. Here’s how I might use it as an alarm job.


PS C:\> new-alarm "get-messagebox 'It is time for that thing' -title 'Alert!'" -init ". c:\scripts\get-messagebox.ps1" -min 5

In 5 minutes the alarm will go off and I’ll get this.

Remember, the function is creating new jobs with the Start-Job cmdlet. Which means I can get job results.


PS C:\> receive-job 7 -keep

Initialization : . c:\scripts\get-messagebox.ps1
ActualTime : 1/20/2012 8:47:07 AM
ScheduledTime : 1/20/2012 8:47:06 AM
Command : get-messagebox 'It is time for that thing' -title 'Alert!'
RunspaceId : d3461b78-11ce-4c84-a8ab-9e3fcd482637

What do you think? As I said, I have a few more ideas and there are certainly a few tweaks I can make even to this code. I’ve added my Get-MessageBox function in case you want to toy with that. Download AlarmScripts.zip and let me know what you think.

Using Start-Job as a Scheduled Task

Here’s a technique you might want to use for ad hoc troubleshooting or reporting. Even though it is possible to set up scheduled tasks to run PowerShell commands or scripts, it is cumbersome and time consuming. PowerShell v3 offers a great alternative, but I’ll cover that another day. Suppose I want to do something every 15 minutes such as check the status of a service. Instead of going through the effort of creating a scheduled task, I’ll create a PowerShell job.

If I setup a job, it will run in my PowerShell session for as long as it needs to run or until I close my PowerShell session. Thus the trick is to keep the job running which easy to accomplish with a simple While loop.


While ($True) {
#do something
}

This will loop indefinitely because True is always True. In an interactive session, I can break out of this using Ctrl+C or insert code to break out if some condition is met. If I use this loop in my Start-Job command, the command will run indefinitely until the job terminates. I can always kill the job with the Stop-Job cmdlet. Although I suppose you should be careful with the code you put in the While loop as part of job because if you use Stop-Job, there’s no way of knowing what code might be executing at the time. But for my use of this technique I’m keeping it simple and quick.

The other part is the timing interval. This is easily accomplished using the Start-Sleep cmdlet and specifying a value in milliseconds, or more typically, seconds. Depending on your task you could also take advantage of eventing, but that too is a bit complicated to setup and tear down. So, now the main part of my While loop looks like this:


While ($True) {
#do something
Start-Sleep -seconds 900
}

My code will run every 900 seconds (15 minutes). Here’s a longer example that I put in a script.


$file="c:\work\mylog.txt"
#the number of seconds to pause between checks
$seconds=600
#the service to check
$service="Spooler"
#the computer to check
$computer=$env:computername

while ($True) {
$s=get-service $service -ComputerName $computer
$t="{0} Service {1} on {3} has a status of {2}" -f (Get-Date), $s.name,$s.status,$computer
$t | Out-File -FilePath $file -Append
Start-Sleep -seconds $seconds
}

I could have put all of that into a script block and created the job, or I could use the script.


PS C:\> start-job -FilePath C:\scripts\PollService.ps1

The job will write the service status information to a local text file every 10 minutes. When I’m done I can simply my PowerShell session or run Stop-Job. Here’s where it can really get interesting: how about running this “scheduled task” ON a remote computer? There are two approaches. It depends on where you want the job to live. I could keep the job on my computer:


PS C:\> invoke-command -FilePath C:\scripts\PollService.ps1 -ComputerName quark -asjob
PS C:\> get-job 3 | format-list

HasMoreData : True
StatusMessage :
Location : quark
Command : #requires -version 2.0

$file="c:\work\mylog.txt"
#the number of seconds to pause between checks
$seconds=600
#the service to check
$service="Spooler"
$computer=$env:computername

while ($True) {
$s=get-service $service -ComputerName $computer
$t="{0} Service {1} on {3} has a status of {2}" -f (Get-Date),
$s.name,$s.status,$computer
$t | Out-File -FilePath $file -Append
Start-Sleep -seconds $seconds
}
JobStateInfo : Running
Finished : System.Threading.ManualResetEvent
InstanceId : 03a48cd0-f21a-4b7d-9a78-f148ec784ff8
Id : 3
Name : Job3
ChildJobs : {Job4}
Output : {}
Error : {}
Progress : {}
Verbose : {}
Debug : {}
Warning : {}
State : Running

The job object is on my (local) computer, even though the task is running on the remote computer. The other approach is to put the job ON the remote computer. This is a little trickier since I have to get the code I want to run ON the remote computer. I could copy the script over. Or I might try something like this:

First I want to convert my script into a scriptblock by stripping out the comments and inserting a semi colon at the end of each line. Then I can create a scriptblock from this text on the remote computer.


PS C:\> $text=get-content C:\scripts\PollService.ps1 | where {$_ -notmatch "^#" -AND $_} | foreach {"$_;"}

I can pass this text as a parameter with invoke-command to setup a job on the remote computer. I recommend using a PSSession in case you want to go back later and stop the job.


PS C:\> $quark=new-pssession -comp quark
PS C:\> invoke-command -scriptblock {param ($txt) $sb=$executioncontext.invokecommand.newscriptblock($txt) ; Start-job -scriptblock $sb } -session $quark -ArgumentList ($text | out-string)

The job is created on the remote session and runs indefinitely.


PS C:\> invoke-command {get-job -State Running} -Session $quark

WARNING: 2 columns do not fit into the display and were removed.

Id Name State HasMoreData Location
-- ---- ----- ----------- --------
17 Job17 Running True localhost
PS C:\> invoke-command {get-content C:\work\mylog.txt} -Session $quark
1/5/2012 9:37:41 AM Service Spooler on QUARK has a status of Running
1/5/2012 9:38:46 AM Service Spooler on QUARK has a status of Running
1/5/2012 10:44:54 AM Service Spooler on QUARK has a status of Running

As I mentioned there are probably several ways you could do this. When I am finished I can either terminate the PSSession or stop the remote job.


PS C:\> invoke-command {stop-job -State Running -PassThru} -Session $quark

WARNING: 2 columns do not fit into the display and were removed.

Id Name State HasMoreData Location
-- ---- ----- ----------- --------
17 Job17 Stopped False localhost

So the next time you need some scheduled PowerShell, at least on a temporary basis, take a look at Start-Job.

Background Performance Counters

Windows Powershell makes it relatively easy to collect performance counter information via the Get-Counter cmdlet. Because I’m assuming you want to collect more than a few seconds of performance information, you’ll need to take advantage of PowerShell background jobs if you want your prompt back. Of course, you can always open a second session, but I like the background job approach. Here’s how I’ve been experimenting with this. Continue reading

Ping IP Range

Last week I came across a post on using PowerShell, or more specifically a .NET Framework class, to ping a range of computers in an IP subnet. The original post by Thomas Maurer is here. I added a comment. And after looking at this again I decided to take the ball and run with it a bit further. I’m a big proponent of PowerShell tools that are object oriented and that can add real value to the pipeline. To that end I wrote Test-Subnet. Continue reading