How to run a powershell script in the background

How to run a powershell script in the background

This article is meant to give a quick and simple example on how to run a powershell script in the background (hide the console) without using a 3rd party script (VBS scripts is what you see a lot on the internet).
Now, consider that the method I will show you will still show the Powershell console for a few instants before disappearing.

For instance, on a computer I own, I have a script that starts every hour and runs only when the user is logged on. The powershell console will appear in front of everything else, making a bit annoying, especially if you’re watching a movie or working on something.

So, in order to run the script in the backgroup, add the following code at the beginning of the script:

Add-Type -Name win -MemberDefinition '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' -Namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle,0)

You may even keep the console opened and decide to hide it in the middle of the script, for instance:

Write-host "Hello, I am not hidden."
Sleep -Seconds 2

#Hiding PS console
Add-Type -Name win -MemberDefinition '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);' -Namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle,0)

write-host "This should not be visible."
Sleep -Seconds 2

IT Droplets

IT Droplets