Taking my cue from @stej answer above when I found this question because I was trying to do the same thing, I expanded to produce this code, which will bring the script back into focus whether being run in the ISE, console window, or via cmd prompt (through a batch file).
#bring script back into focus
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
$parent = Get-Process -id ((gwmi win32_process -Filter "processid='$pid'").parentprocessid)
If ($parent.Name -eq "cmd") {# Being run by via cmd prompt (batch file)
$h = (Get-Process cmd).MainWindowHandle
[void] [Tricks]::SetForegroundWindow($h)
}
else{# being run in powershell ISE or console
$h = (Get-Process -id $pid).MainWindowHandle
[void] [Tricks]::SetForegroundWindow($h)
}
Or to re-use more readily, save the following as a .psm1 file in your module directory - from PS v3 onwards, you don't have to import it, calling a function in a module in your module directory imports it.
To import manually, Import-Module .\Getfocus.psm1
(Assuming it's in your current path).
Function Get-Focus{
#bring script back into focus
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
$parent = Get-Process -id ((gwmi win32_process -Filter "processid='$pid'").parentprocessid)
If ($parent.Name -eq "cmd") {# Being run by via cmd prompt (batch file)
$h = (Get-Process cmd).MainWindowHandle
[void] [Tricks]::SetForegroundWindow($h)
}
else{# being run in powershell ISE or console
$h = (Get-Process -id $pid).MainWindowHandle
[void] [Tricks]::SetForegroundWindow($h)
}
}
Export-ModuleMember -Function Get-Focus