I want a powershell script to be run once per minute in the background. No window may appear. How do I do it?
I want a powershell script to be run once per minute in the background. No window may appear. How do I do it?
Use the Windows Task Scheduler and run your script like this:
powershell -File myScript.ps1 -WindowStyle Hidden
Furthermore create the script that it runs under a specific user account and not only when that user is logged on. Otherwise you'll see a console window.
Perhaps this scenario will do. We do not start PowerShell executable every minute (this is expensive, BTW). Instead, we start it once by calling an extra script that calls the worker script once a minute (or actually waits a minute after the worker script exits or fails).
Create the starting Invoke-MyScript.ps1:
for(;;) {
try {
# invoke the worker script
C:\ROM\_110106_022745\MyScript.ps1
}
catch {
# do something with $_, log it, more likely
}
# wait for a minute
Start-Sleep 60
}
Run this from Cmd (e.g. from a startup .bat file):
start /min powershell -WindowStyle Hidden -Command C:\ROM\_110106_022745\Invoke-MyScript.ps1
The PowerShell window appears for a moment but it is minimized due to start /min and just in a moment it gets hidden forever. So that actually only the task bar icon appears for a moment, not the window itself. It's not too bad.
To create a background powershell task to run a script that repeats every minute with no visible window at all, run powershell as administrator and then use the Register-ScheduledJob cmdlet to run your script. Here's an example of how to make that happen:
Register-ScheduledJob -Name 'SomeJobName' -FilePath 'path\to\your\ps1' -Trigger (New-JobTrigger -Once -At "9/28/2018 0am" -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration ([TimeSpan]::MaxValue))
If you want to manually force this job to run (perhaps for troubleshooting purposes) you can use the Get-ScheduledJob cmdlet like this:
(Get-ScheduledJob -Name 'SomeJobName').StartJob()
I labor under the constraints of our IT organization, who has disabled execution of scripts. I therefore am limited to on-liners. Here's what I used:
while ($true) {<insert command(s) here>;start-sleep 2}
I'm a noob to PowerShell, so if you have feedback, please be gentle ;-).