NSClient++ Running Powershell scripts as Jobs


#1

I have written a powershell script which runs a script block as a job - as the job takes a long time to run this allows the script to exit and return to Nagios while the job continues to run in the background (it outputs its findings to a txt file)

Next time the script runs it reports on the txt file from the previous run and then executes the script block job again

This is the script block that runs-

Invoke-Command -ComputerName localhost -ScriptBlock {

#Generate fresh log
New-Item c:\temp\defrag_log.txt -type file -force
#fetch all drives
$drives = gdr -PSProvider 'FileSystem'
foreach ($drive in $drives) {
    
    #ignore removable drives
    if ($drive.Used -gt 0) {
        #build drive letter for query
        $driveletter = $drive.Name + ":"
        #run query and select result
        $query = defrag $driveletter /A | Select-String -Pattern "Total fragmented space"
        #output response to file
        echo "$driveletter $query" >> c:\temp\defrag_log.txt
    }
}
exit

} -AsJob

I have also tried-

start-job -ScriptBlock {

and-

$s = New-PSSession -ComputerName localhost Invoke-Command -session $s -Scriptblock { start-job -ScriptBlock {

When I run the script locally on the box it executes fine, the job runs in the background while the rest of the script correctly exits

But when I run it from the Nagios command the job doesnt function- there are no errors, but the txt file is not created

It does report that it has started the job-

Id Name PSJobTypeName State HasMoreData Location


1 Job1 RemoteJob Running True localhost

I have ran the script from Nagios without using the -asjob (so it runs like a normal script) and it runs fine provided the timeout is set massively high, so the commands do all run

I can only assume that when nrpe completes the original script it kills the session and all of the jobs that go along with it?

Or am I doing something wrong? Or can you think of another way around this? (Yes I have thought about using scheduled tasks)