Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - Determine if script is running hidden

I am trying to programmatically determine if a .ps1 script is running visibly or not. If it is running visibly, it should restart itself hidden. If it is already hidden, take no action.

The problem I have is a loop where it continually restarts itself because hidden status cannot be determined.

I've been looking at both get-process cmdlet and GWMI Win32_process and see nothing like a .visible property to check status.

    If ($me -eq visible ???)
{
$Invisible = New-Object System.Diagnostics.ProcessStartInfo
$Invisible.FileName = "PowerShell.exe"
$Invisible.windowStyle ="Hidden"
$Invisible.arguments = "$myInvocation.MyCommand.Definition"
$Invisible.Verb = 'runas'
[System.Diagnostics.Process]::Start($Invisible)
}

Any idea what field I can If -eq against ???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using the user32 function 'IsWindowVisible'

If (-not ([System.Management.Automation.PSTypeName]'My_User32').Type) {
Add-Type -Language CSharp -TypeDefinition @"
    using System.Runtime.InteropServices;
    public class My_User32
    { 
        [DllImport("user32.dll")]
        public static extern bool IsWindowVisible(int hwnd);
    }
"@
}

$proc = Start-Process powershell.exe -WindowStyle Hidden -ArgumentList $myInvocation.MyCommand.Definition -Verb runas -PassThru
If ([My_User32]::IsWindowVisible($proc.MainWindowHandle)) {
    #Window is visible
}
Else {
    #Window is not visible
}

Note that the return value for 'isWindowVisible' isn't strictly a boolean. It returns the WS_VISIBLE style bit of a window. Because the value for hidden is zero and the value for visible is nonzero, it will work as a boolean. But if you want to be safe, you can rewrite the If statement to check for -ne 0 to determine if visible.

Also note the use of $proc.MainWindowHandle. You can't use $proc.Handle, as that is not the handle of the parent window.

For more information on the 'IsWindowVisible' function, see Microsoft documentation at:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms633530%28v=vs.85%29.aspx

For more information on window styles, see Microsoft documentation at:
http://msdn.microsoft.com/en-us/library/czada357.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...