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?
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'
.
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.
© 2022 - 2024 — McMap. All rights reserved.