PowerShellから各種ブラウザで開いているURLを取得する (Windows10+Microsoft Edge編)
概要
AuntomationのConditionで絞って特定の属性を持つノードをInspectorでとってくる(前の記事参照)。
悲しいことにMSEdgeはActiveになっていないタブのURLは取れない。ので、アドレスバーからとる。タブにフォーカスを順に当ててけばできると思うけど、ここでは秘密裏にユーザ操作に影響を与えず取得することを目的とするため、そういうことはせず、一個とるだけで我慢する。
目標はURL入ってるこれ。ControlTypeでも取れると思うが、Nameの「アドレスと検索バー」からとる。当然、言語が違えば表現が変わるので注意。

コード
$edge_csharp = @"
using System;
using System.Windows.Automation;
using System.Diagnostics;
namespace UIAutomationEdge {
public class Program {
public static string GetURL(Process process) {
AutomationElementCollection roots = AutomationElement.RootElement.FindAll(TreeScope.Element | TreeScope.Children, new AndCondition(new PropertyCondition(AutomationElement.ProcessIdProperty, process.Id), new PropertyCondition(AutomationElement.ClassNameProperty, "Chrome_WidgetWin_1")));
foreach (AutomationElement rootElement in roots){
AutomationElement address = rootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "アドレスと検索バー"));
if (address == null) {continue;}
ValuePattern v = (ValuePattern)address.GetCurrentPattern(ValuePattern.Pattern);
if (v.Current.Value != null && v.Current.Value != "") {
Console.WriteLine("URL:" + v.Current.Value);
return v.Current.Value;
}
}
return "";
}
}
}
"@
Add-Type -TypeDefinition $edge_csharp -ReferencedAssemblies("UIAutomationClient", "UIAutomationTypes");
$msedges = (Get-Process -name msedge)
foreach ($msedge in $msedges) {
$url = [UIAutomationEdge.Program]::GetURL($msedge);
if ($url) {
$url
}
}
