您可以使用-noexit 运行 Powershell.exe 或试试这个:
"hello world" | out-gridview
Read-Host "press enter to exit"
更新:
Out-GridView 是非阻塞的,所以如果你想测试它是否退出,你必须求助于一些低级别的 Win32 API。以下代码在 ISE 中有效(尚未在控制台主机中对其进行测试)。它也有一个限制——它基本上会寻找与主机进程关联的任何窗口,而不是主机进程的主窗口。到那时,它会返回。事实证明 Out-GridView 不是主窗口的子窗口,并且其标题不一致(GPS | Out-GridView 或 GPS | ogv 或 GPS | <any alias you make up>):
$src = @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace Utils
{
public delegate bool Win32Callback(IntPtr hwnd, IntPtr lParam);
public class WindowHelper
{
private const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
private IntPtr _mainHwnd;
private IntPtr _ogvHwnd;
private IntPtr _poshProcessHandle;
private int _poshPid;
private bool _ogvWindowFound;
public WindowHelper()
{
Process process = Process.GetCurrentProcess();
_mainHwnd = process.MainWindowHandle;
_poshProcessHandle = process.Handle;
_poshPid = process.Id;
}
public void WaitForOutGridViewWindowToClose()
{
do
{
_ogvWindowFound = false;
EnumChildWindows(IntPtr.Zero, EnumChildWindowsHandler,
IntPtr.Zero);
Thread.Sleep(500);
} while (_ogvWindowFound);
}
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(
IntPtr parentHandle, Win32Callback callback, IntPtr lParam);
[DllImport("Oleacc.dll")]
public static extern IntPtr GetProcessHandleFromHwnd(IntPtr hwnd);
[DllImport("Kernel32.dll")]
public static extern int GetProcessId(IntPtr handle);
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DuplicateHandle(
IntPtr hSourceProcessHandle,
IntPtr hSourceHandle,
IntPtr hTargetProcessHandle,
out IntPtr lpTargetHandle,
int dwDesiredAccess,
bool bInheritHandle,
int dwOptions);
[DllImport("Kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("Kernel32.dll")]
public static extern int GetLastError();
private bool EnumChildWindowsHandler(IntPtr hwnd, IntPtr lParam)
{
if (_ogvHwnd == IntPtr.Zero)
{
IntPtr hProcess = GetProcessHandleFromHwnd(hwnd);
IntPtr hProcessDup;
if (!DuplicateHandle(hProcess, hProcess, _poshProcessHandle,
out hProcessDup,
PROCESS_QUERY_LIMITED_INFORMATION,
false, 0))
{
Console.WriteLine("Dup process handle {0:X8} error: {1}",
hProcess.ToInt32(), GetLastError());
return true;
}
int processId = GetProcessId(hProcessDup);
if (processId == 0)
{
Console.WriteLine("GetProcessId error:{0}",
GetLastError());
return true;
}
if (processId == _poshPid)
{
if (hwnd != _mainHwnd)
{
_ogvHwnd = hwnd;
_ogvWindowFound = true;
CloseHandle(hProcessDup);
return false;
}
}
CloseHandle(hProcessDup);
}
else if (hwnd == _ogvHwnd)
{
_ogvWindowFound = true;
return false;
}
return true;
}
}
}
'@
Add-Type -TypeDefinition $src
Get-Process | Out-GridView
$helper = new-object Utils.WindowHelper
$helper.WaitForOutGridViewWindowToClose()
"Done!!!!"