我需要与以前在PowerShell中创建的IE窗口进行交互,而无需使用全局变量。
If(WindowAlreadyCreatedByPowerShell){
$IE = WindowAlreadyCreatedByPowerShell
}Else{
$IE = New-Object -com internetexplorer.application;
$IE.visible = $true;
$IE.navigate($url);
}
注意:使用((New-Object -ComObject Shell.Application).Windows).Invoke() | ?{$_.Name -eq "Internet Explorer"}
不会返回
答案 0 :(得分:1)
因此,您需要在父范围中存储内容-如果您不想存储IE对象,存储打开的URL,或者甚至不希望存储窗口句柄({{ 1}}属性,应该是唯一的)。否则,您将无法获得获取所需窗口的可靠方法,尤其是如果您的会话也正在打开其他 IE窗口时。
HWND
如果您两次运行该命令,但是第二次未将# Variable for the created IE window handle
$expectedHWND = $null
# This will enumerate all ShellWindows opened as a COM object in your session
$allShellWindows = ( New-Object -ComObject Shell.Application ).Windows()
# Get the IE object matching the HWND you stored off when you first opened IE
# If you opened other windows in the session, the HWND should be unique so you
# can get the correct window you are expecting
$existingIE = $allShellWindows | Where-Object {
$_.HWND -eq $expectedHWND
}
# Your code, slightly modified
if( $existingIE ){
# You should be able to operate on $existingIE here instead of reassigning it to $IE
Write-Output "Found existing IE session: HWND - $($existingIE.HWND), URL - $($existingIE.LocationURL)"
} else {
$IE = New-Object -com internetexplorer.application;
$IE.visible = $true;
$IE.navigate($url);
$expectedHWND = $IE.HWND
}
设置为$expectedHWND
,它将找到您的IE窗口。请注意,这是避免在父范围中存储变量的大量工作,但在技术上是可行的。
您可能需要为您的特定应用整理以上示例,但可以很好地说明如何为先前打开的IE窗口获取可操作的对象。