Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a powershell script as a background task without displaying a window?

Tags:

I'm working on creating a script that will fire off performance counters and store them in a .csv file, rolling over when the file gets too big. Running the script from a powershell prompt or the ISE (I'm running v.2/win server 2008) works just fine, and the files are running correctly.

However, when I try to execute the command using the following cmd prompt line (even trying the /k switch on cmd), the command prompt closes immediately and the file is not getting run.

powershell.exe -windowstyle hidden {iis_test.ps1} 

I've also tried the following, and although I see Powershell doesn't stop (I monitor it via task manager, looking for Powershell.exe to show up), I'm not seeing the file being created.

powershell.exe -noexit -windowstyle hidden {iis_test.ps1} 

Nor am I seeing any errors being caught in any of the likely places (event viewer, the command prompt window itself).

Any ideas? Ultimately, my goal is to have a vb winforms thing call these script files, and naturally I thought figuring out the command prompt command would be helpful. Note that it is very important that this script be portable, and run on any Windows 2008 Server system (so I need to stay away from third party entities that would require further installation).

EDIT: I needed to use the -file argument to specify a file to run.

like image 418
Sean Long Avatar asked Apr 30 '13 15:04

Sean Long


People also ask

How do I run a PowerShell command in the background?

To run commands in the background in the PowerShell, you need to use Background job cmdlets. Background job means running commands/job in the background without occupying the console.

Does PowerShell script run in background?

The Start-Job cmdlet starts a PowerShell background job on the local computer. A PowerShell background job runs a command without interacting with the current session. When you start a background job, a job object returns immediately, even if the job takes an extended time to finish.


2 Answers

try this from a DOS/CMD shell:

powershell.exe -windowstyle hidden -file C:\iis_test.ps1 
like image 183
CB. Avatar answered Sep 23 '22 15:09

CB.


Powershell.exe -windowstyle hidden -file C:\iis_test.ps1 

But when you run this command, a CMD window will appear.
However, you can use VBscript instead

Set objShell = CreateObject("WScript.Shell") objShell.Run "CMD /C START /B " & objShell.ExpandEnvironmentStrings("%SystemRoot%") & "\System32\WindowsPowerShell\v1.0\powershell.exe -file " & "YourScript.ps1", 0, False Set objShell = Nothing 
like image 33
user2914236 Avatar answered Sep 22 '22 15:09

user2914236