You write a perfect script, well thought out and commented, and it even looks visually pleasing. Proud of yourself, you select the clients you want the script pushed out to from your RMM platform and click run. Then…nothing happens.
An all too common mistake is forgetting that (unless you use some user impersonation trickery) your script running from the RMM platform, through an agent, is almost assuredly running as the “System” account, and perhaps the objects you were attempting to interact with in the user space don’t exist for the account the script was running as.
Using PsExec to run PowerShell as System
One way to test your script under the system account, or even to just test what various cmdlets will return when running as System, is to use PsExec to launch PowerShell as the System account.
Download and extract PsExec
https://docs.microsoft.com/en-us/sysinternals/downloads/psexec
Open Command Prompt as an admin, browse to where you extracted PsExec to and run the following command:
Psexec.exe -i -s C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
In the PowerShell window that pops up run “whoami” and you will see that you are indeed the System account.
Running PowerShell scripts as System through Task Scheduler
Another technique for running PowerShell scripts as the System account (or another account) is to use the Windows Task Scheduler to launch PowerShell as the System account and then pass it the script of your choice.
Let’s make a script that we want to run as the System account called System.ps1 and place it in C:\Scripts\
try {
$Who = whoami.exe
}
catch {
$Who = Write-Output "Error Message: $($_.Exception.Message) Error on line $($_.InvocationInfo.ScriptLineNumber)"
}
finally {
$Who | Out-File -FilePath 'C:\Scripts\SystemWhoami.txt'
}
Open Tack Scheduler or run taskschd.msc
Click on “Create Basic Task”
Give your task a name and click “Next”
Choose when you want the task to run, in this case “One Time”
Pick an appropriate start time
Leave it on the default action, in this case “Start a program”
Add your program that you want to run “powershell.exe”
Then add the following arguments to reference your script you created
-ExecutionPolicy Bypass -FilePath C:\Scripts\System.ps1
Check the box to open the properties dialog when you click “Finish”
Pick configure for Windows 10 from the dropdown
Click on “Change User or Group…”
Type “system” into the box and click “Check Names” or press enter
Save your task and it’s ready to run. You can wait for the time you put in to trigger, or you can right click your task in the list and click “Run”. When the task runs you can check the results by looking at the .txt file in C:\Scripts\ to see that it did run as the System account
nt authority\system