简体   繁体   中英

How can I run powershell in the background if I want execution policy Bypass?

I have this batch file which runs the powershell script.

I want to run it the background but if I run with "windowstyle hidden" still visible.

powershell -ExecutionPolicy ByPass -windowstyle hidden -File "C:\\script.ps1"

You can run, eg long running scripts, as a jobs.

To start it you run

$job = Start-Job -ScriptBlock {Get-Process}

this will start the Get-Process cmdlet in the background. The script can be also some custom made script or a longer script, it doesn't need to be a one-liner.

You can check its status by running

$job | Get-Job 

and to receive the output you run

$job | Receive-Job

just note that once the data is received, it's lost. You can only receive it once, after that it's up to you to save it in a variable or later processing.

Finally to remove the job from the queue you run

$job | Remove-Job

I use the following function:

function bg() {
  Start-Process `
   -WorkingDirectory (Get-Location) `
   -NoNewWindow `
   -FilePath "powershell" `
   -ArgumentList "-NoProfile -command `"$args`" " 
}

It starts a new powershell instance which is executed in background and allows the usage of cmdlets. You call it like:

bg "Start-Sleep 2; get-location; write 'done' "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM