Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ???

like image 628
Knuckle-Dragger Avatar asked Sep 01 '25 17:09

Knuckle-Dragger


2 Answers

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

like image 194
MikeAtWake Avatar answered Sep 04 '25 09:09

MikeAtWake


From within the process you can deterine if it's running hidden by testing:

(get-process -Id $PID).StartInfo.WindowStyle
like image 21
mjolinor Avatar answered Sep 04 '25 08:09

mjolinor