Hide your window when starting PowerShell
If I execute a script file regularly in the scheduled task, I want to hide this window, and at this time we can consider the option parameters to use:
-WindowStyle
Set the window style to Normal, Minimized, Maximized, or Hidden.
-WindowStyle Hidden -file 'Your script.ps1'
Hide window when PowerShell starts other processes
This requirement can also be understood:
Start-Process -WindowStyle Hidden
The script above will start a hidden notepad program.
Use PowerShell to hide windows of other processes
This is a weird need, but users also have their own reasons:
@scl95tx says:
I have implemented a 24-hour uninterrupted Powershell script. A lot of data is output to the console through the write-host command (you need to view these data at any time to ensure that the server is running normally, so I don't consider it when running in the background). If (due to an operation error), the script will stop executing. Is there a way to hide the console? If I want to check the operation of the script, then call the console out: that is, is there a way to hide and call out the console at any time?
This requirement is reasonable, let's solve this problem next:
Add-Type @'
[DllImport("")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
'@ -name “Win32ShowWindowAsync” -namespace Win32API
Function Set-ProcessWindowStyle
{
param(
[Parameter(
Mandatory=$true,
ValueFromPipeline=$true)]
[]$Process,
[ValidateSet("Show", "Minimized","Maximized","Hidden")]
[string]$WindowStyle="Show"
)
$WinStateInt = 1
switch($WindowState)
{
"Hidden" {$WinStateInt = 0}
"Show" {$WinStateInt = 1}
"Maximize" {$WinStateInt = 3}
"Minimize" {$WinStateInt = 6}
}
[Win32API.Win32ShowWindowAsync]::ShowWindowAsync($,$WindowState)
}
After writing the above script, I tested it with joy and hid the window successfully:
Get-Process notepad | Set-ProcessWindowStyle -WindowStyle Hidden
But when I try to call up the hidden window, execution returns false.
PS> Get-Process notepad | Set-ProcessWindowStyle -WindowStyle Show
False
I deeply regret this. When the window is hidden, the process's handle value MainWindowHandle becomes 0. What does 0 mean?
MSDN says: If the associated process does not have a main window, the MainWindowHandle value is zero.
Conclusion: Don't hide the window of the process, otherwise you will lose the opportunity to operate the window forever.