如果使用PowerShell打开另一个URL,则在IE中打开一组URL

时间:2017-09-09 08:34:39

标签: powershell internet-explorer

在第二次运行此脚本时,如果我第一次关闭Bing,我可以打开Microsoft和Yahoo;如何在不先关闭Bing的情况下打开这些网站?错误:

Method invocation failed because [System.Object[]] doesn't contain a method named 'Navigate2'.
+                 $ie.Navigate2 <<<< ("www.microsoft.com", $navOpenInNewTab);
+ CategoryInfo          : InvalidOperation: (Navigate2:String) [], Runtime Exception
+ FullyQualifiedErrorId : MethodNotFound

为什么Bing和Google打开时会失败,但是当我打开Goog​​le时却没有?

# Set BrowserNavConstants to open URL in new tab
# Full list of BrowserNavConstants: https://msdn.microsoft.com/en-us/library/aa768360.aspx
$navOpenInNewTab = 0x800;
$navOpenInBackgroundTab = 0x1000;

$ie = $null
if (Get-Process iexplore -ea silentlycontinue | Where-Object {$_.MainWindowTitle -ne ""}) {
    $ie = (New-Object -COM "Shell.Application").Windows() | ? { $_.Name -eq "Internet Explorer" }
} else {
    $ie = New-Object -COM "InternetExplorer.Application"
    sleep -milliseconds 50
    $ie.visible = $true
}

$today = (get-date).DayOfWeek
switch ($today) { 
    "Someday" {
        $ie.Navigate("www.bing.com");
        $ie.Navigate2("www.yahoo.com", $navOpenInBackgroundTab); break
    }
    default {
        $google = $false
        # Check if Google open
        foreach ($tab in $ie) {
            if ($tab.LocationURL.Contains("google"))
            { $google = $true; break }
        }
        # If Google open on second run, open Microsoft and Yahoo
        if ($google) {
            $ie.Navigate2("www.microsoft.com", $navOpenInNewTab);
            $ie.Navigate2("www.yahoo.com", $navOpenInBackgroundTab);
        } else {
            # On first run, open Bing and Google 
            $ie.Navigate("www.bing.com");
            $ie.Navigate2("www.google.com", $navOpenInBackgroundTab);
        }
        break
    }
}

# Cleanup
'ie' | ForEach-Object {Remove-Variable $_ -Force}

1 个答案:

答案 0 :(得分:0)

您的问题似乎是,脚本无法在第二次运行时找到(右侧)打开的IE实例。在PowerShell ISE(或PowerShell PowerGUI)中调试脚本,并在$ie=(New-Object -COM "Shell.Application").Windows() | ? {$_.Name -eq "Internet Explorer"}

设置断点

在下面的交互式PowerShell窗口中运行以下命令:(New-Object -COM "Shell.Application").Windows() | Select-Object { $_.Name }

你得到这样的东西作为输出吗?

File Explorer    
Internet Explorer  
Internet Explorer  
Internet Explorer  
Internet Explorer  

当IE窗口具有不同的名称时,尝试根据需要调整代码 以下代码适用于我的机器:我只选择第一个IE实例(否则您打开多个站点时会出现问题)。

    ...
    # If Google open on second run, open Microsoft and Yahoo
    if ($google) {
        sleep -milliseconds 50
        $ie[0].Navigate2("www.microsoft.com", $navOpenInBackgroundTab);
        sleep -milliseconds 50
        $ie[0].Navigate2("www.yahoo.com", $navOpenInBackgroundTab);
    } else { ...