Run a powershell script in the background once per minute
Asked Answered
D

9

45

I want a powershell script to be run once per minute in the background. No window may appear. How do I do it?

Diplomatic answered 15/1, 2010 at 12:46 Comment(1)
Do you know how to create a scheduled task?Oral
H
41

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.

Hardaway answered 15/1, 2010 at 12:47 Comment(6)
I now, but how do I run the powershell in the background?Diplomatic
@Diplomatic - How much more "background" do you need to get? The Windows task scheduler is how you would run a "background" task, and in this case, the task would be to start PowerShell and run the specified script.Kr
Well, to be fair, the initial answer wouldn't have resulted in a background process if the current user is an administrator and doesn't change the default settings for the task. However, explicitly letting the task run regardless of the logged-on user fixes that. Hm. My test script ran 181 times so far. I should turn that task off again :-)Hardaway
I use following string to create a Windows Task Scheduler: schtasks /CREATE /RU BURE /SC MINUTE /TN files_to_nomad /TR "powershell.exe -NoProfile -WindowStyle Hidden & 'C:\Documents and Settings\BURE\My Documents\ibös\script\files_to_nomad.ps1' 1" But I stil get a window each minute.Diplomatic
@Diplomatic Check the "Run whether user is logged on or not" check box and executable will run in the background.Unicameral
Important: "When the value of File is a file path, File must be the last parameter in the command"Minne
C
27

Schedule your task to be run as System. The command below will schedule a script to be run in the background without showing powershell console window:

schtasks /create /tn myTask /tr "powershell -NoLogo -WindowStyle hidden -file myScript.ps1" /sc minute /mo 1 /ru System

/ru switch lets you change the user context in which the scheduled task will be executed.

Claritaclarity answered 22/6, 2013 at 8:51 Comment(3)
Thanks Xemlock! In my case iyour suggestion was the only solution that generated absolutely no PowerShell window.Cornall
For anyone looking for the UI way to do this.. go to the task properties, change user or group button, search for the object system and click Check Names, it should populate with the object NT AUTHORITY\SYSTEM. This was the only solution that prevented a PS window from showing up on my screen.Premarital
Frantumn comment was the only information here that indeed did the powershell stopping showing for a second when running.Pumpernickel
A
23

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.

Arcane answered 9/1, 2011 at 7:56 Comment(1)
Canceling the created hidden window: see reddit.com/r/PowerShell/comments/6seg7d/…Bjorn
R
11

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()
Roundish answered 28/9, 2018 at 17:38 Comment(0)
T
5

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 ;-).

Tagmemic answered 25/3, 2021 at 21:37 Comment(0)
I
3

On the [General] tab in the Task Scheduler properties for the task, selecting the "Run whether user is logged on or not" radio button prevents the window from appearing on my Windows 7 machine.

Indebtedness answered 6/5, 2014 at 14:58 Comment(0)
H
0

If you want to run script automatically in time interval. (for windows os)

1)  Open Schedule tasks from control panel.
2)  Select Task Scheduler Library from left side window.
3)  select Create Task from right side window.
4)  Enter Name in General tab (any name).
5)  Open Triggers tab -> New
6)  Select interval as needed.Use Advanced settings for repeat task. 
7)  Open Actions tab ->New
8)  Copy/Paste following line in Program/script *

* Here D:\B.ps1 in code is path to my B.ps1 file

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe D:\B.ps1

9)  ok and apply changes
10) Done!  
Holothurian answered 9/5, 2014 at 5:52 Comment(0)
S
-1

These answers are histerical! If you want to run a powershell script as a background job try start-job .\script from the CLI within the folder you house scripts in.

Sieracki answered 1/3, 2012 at 3:49 Comment(0)
T
-2
#   Filecheck.ps1

#   Version 1.0

#   Use this to simply test for the existance of an input file... Servers.txt.

#   I want to then call another script if the input file exists where the

#   servers.txt is neded to the other script.

#


    $workpath=".\Server1\Restart_Test"

#   Created a functon that I could call as part of a loop.


    function Filecheck

    {
    if (test-path $workpath\servers.txt)

        {

        rename-item $workpath\servers.txt servers1.txt

        "Servers.txt exist... invoking an instance of your script agains the list of servers"


        Invoke-Expression .\your_Script.ps1

        }

    Else
        {

            "sleeping"

            Start-Sleep -Seconds 60
        }

     }

    Do
        {
        Filecheck

        $fred=0
        # Needed to set a variabe that I could check in the while loop.

        # Probably a better way but this was my way.

        }

        While( $fred -lt 1 )
Trying answered 31/12, 2015 at 5:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.