Hide your own window when starting PowerShell
If I were to execute a script file periodically through Powershell.exe in a scheduled task, I would like to hide the window, at which point we might consider using the PowerShell.exe option argument:
Copy Code code as follows:
-windowstyle
Sets the window style to Normal, minimized, maximized, or Hidden.
Copy Code code as follows:
Powershell.exe-windowstyle hidden-file ' your script. PS1 '
Hide a window when PowerShell starts another process
This requirement can also be understood:
Copy Code code as follows:
Start-process Notepad.exe-windowstyle Hidden
The script above will start a hidden Notepad program.
Using PowerShell to hide the windows of other processes
This is a wonderful demand, but users also have their own reasons:
@scl95tx says:
I've implemented a 24-hour PowerShell script that has a lot of data output to the console via the Write-host command (you need to view this data at any time to make sure that the server is working, so I don't think about running the background), if (due to the operation error), click the Console window incorrectly , then the script will stop executing, whether there is a way to hide the console, if I want to see the script running, and then the console out: that is, there is no time to hide and pull up to the console method?
It's a reasonable demand, and then we're going to solve this problem:
Copy Code code as follows:
Add-type @ '
[DllImport ("user32.dll")]
public static extern bool Showwindowasync (IntPtr hWnd, int ncmdshow);
@-name "Win32showwindowasync"-namespace Win32API
Function Set-processwindowstyle
{
Param
[Parameter (
Mandatory= $true,
Valuefrompipeline= $true)]
[System.Diagnostics.Process] $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 ($Process. Mainwindowhandle, $WindowState)
}
After writing the above script, I was filled with joy to test and hide the window successfully:
Copy Code code as follows:
Get-process Notepad | Set-processwindowstyle-windowstyle Hidden
But when I try to pull out a hidden window, the execution returns false.
Copy Code code as follows:
ps> Get-process Notepad | Set-processwindowstyle-windowstyle Show
False
I deeply regret this, when the window is hidden, the process of the handle value Mainwindowhandle into 0, 0 represents what?
MSDN says: If the associated process does not have a main window, the Mainwindowhandle value is zero.
Conclusion: Do not hide the window of the process, otherwise you will never lose the opportunity to manipulate the window.