Unhiding a powershell window that's been run with -WindowStyle Hidden?
Asked Answered
D

2

6

When you run a powershell window in the background, how do you re-connect to it? Or instead, is it's output intended to be viewed via log file at that point?

Deandre answered 13/8, 2012 at 20:45 Comment(0)
C
7

Normally you would just output to a log and examine that for a scheduled task. However, if you can tolerate the console window flashing up briefly, you can pinvoke to the Win32 API to control the visiblity of the console window e.g.:

$src = @'
    [DllImport("Kernel32.dll")]
    public static extern IntPtr GetConsoleWindow();
    [DllImport("User32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'@

Add-Type -Name ConsoleUtils -Namespace Foo -MemberDefinition $src

$hide = 0
$show = 1

$hWnd = [Foo.ConsoleUtils]::GetConsoleWindow()
[Foo.ConsoleUtils]::ShowWindow($hWnd, $hide)

Start-Sleep -Sec 5

[Foo.ConsoleUtils]::ShowWindow($hWnd, $show)

Read-Host "Press any key to exit"

Normally you wouldn't want to show the window but perhaps you define an environment variable and then have the script inspect that environment variable for a certain value and show the window in that case e.g. $env:DebugSchTask -eq 'yes'.

Cerelia answered 13/8, 2012 at 21:59 Comment(3)
Awesome. A nice how-to on calling win32 from powershell.Suppurative
@Keith Hill, I'm trying to use this in a Powershell 4 sched task, run with WindowStyle Hidden, run whether task acct is logged on or not. Your code doesn't throw an error, but it doesn't show the window for me. Could it be that when the task is run without the user logged on, it will be hidden no matter what? Thanks!Supporter
Yup, from technet.microsoft.com/en-us/library/cc722152.aspx - "If this radio button is selected, tasks will not run interactively"Cerelia
H
1

You can always change the window style of the current window by creating a new PowerShell session and using the -WindowStyle switch:

PowerShell -Command {exit} -WindowStyle Hidden # Hide the window

Start-Sleep 1 # Do something while hidden

PowerShell -Command {exit} -WindowStyle Normal # Unhide the window

This also works if you have e.g. a monitoring script, which was started hidden and is only meant to show up once a condition was met.

Haematinic answered 27/3, 2021 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.