Powershell – Batch files, Powershell Scripts, PSExec and System user

batch-filegeneospowershellprivilegespsexec

I'm trying to put in place some monitoring for Windows Task Scheduler, I have a Powershell script that runs the following:

$serverName = hostname
$schedule = new-object -com("Schedule.Service")
$schedule.connect($serverName)
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks |select name, lasttaskresult, lastruntime

This returns a list of scheduled tasks on the server it is run on, the last task result and last run time. The purpose for this is to return a dataset to our monitoring solution (Geneos) which we can use for alerting.

We have a large Win2008 estate, so I want the script centralised allowing any of the Geneos probes to call it and return a dataset for their host. To do this I wrapped the powershell in a .bat file which does the following:

\\fileserverhk\psexec.exe -accepteula -u admin -p "pwd" powershell.exe cpi \\fileserverhk\scripts\TaskSchedulerMonitor.ps1 -Destination C:\Monitor\TaskSchedulerMonitor.ps1
\\fileserverhk\psexec.exe -accepteula -u admin -p "pwd" powershell.exe -ExecutionPolicy Bypass -File C:\Monitor\TaskSchedulerMonitor.ps1

The First step copies the .ps1 file locally to get around Powershell not trusting UNC paths and the second part runs the script.

If I run the .bat file manually from a test server it executes fine (this is logged in under an admin account). However, when I fire the .bat file via Geneos (which runs under the SYSTEM account) I get:

Access is denied.
PsExec could not start powershell.exe:

So basically my question is, how do I get PsExec to switch user when it is run under the SYSTEM account? Even though PsExec has the credentials set for another account, there is obviously something preventing it from changing when run under system.

I read to try running it with the -h switch but I get the below error:

The handle is invalid.
Connecting to local system...


Starting PsExec service on local system...

Connecting with PsExec service on <server>...

Starting powershell.exe on <server>...

Error communicating with PsExec service on <server>:

In addition to the above error, I end up with the PSExec and powershell processes hung on the remote machine. The interesting part is I can see the PSExec and PSEXEC.SVC running under SYSTEM and the powershell running under admin, so it's almost there, but something isn't quite right there.

Best Answer

We managed to get there using a powershell wrapper on the Windows schtasks command (link here). Schtasks can be run under the SYSTEM account and will return all the necessary task information, so we no longer needed to faff about with permissions, and no more clear text passwords on the environment (bonus).

We wrapped:

schtasks.exe Query /FO CSV

in a powershell script, and used PS to format the output into the csv style expected by Geneos.

Related Topic