PowershellでIE操作する方法を整理。必要な設定や関数等。
# エラー防止のアセンブリ読み込み
[System.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll")
# 保護モード考慮のDOM操作関数
function OverrideMethod ([mshtml.HTMLDocumentClass]$Document) {
$doc = $Document | Add-Member -MemberType ScriptMethod -Name "getElementById" -Value {
param($Id)
[System.__ComObject].InvokeMember(
"getElementById",
[System.Reflection.BindingFlags]::InvokeMethod,
$null,
$this,
$Id
) | ? {$_ -ne [System.DBNull]::Value}
} -Force -PassThru
$doc | Add-Member -MemberType ScriptMethod -Name "getElementsByClassName" -Value {
param($ClassName)
[System.__ComObject].InvokeMember(
"getElementsByClassName",
[System.Reflection.BindingFlags]::InvokeMethod,
$null,
$this,
$ClassName
) | ? {$_ -ne [System.DBNull]::Value}
} -Force
$doc | Add-Member -MemberType ScriptMethod -Name "getElementsByTagName" -Value {
param($TagName)
[System.__ComObject].InvokeMember(
"getElementsByTagName",
[System.Reflection.BindingFlags]::InvokeMethod,
$null,
$this,
$TagName
) | ? {$_ -ne [System.DBNull]::Value}
} -Force
return $doc
}
# IEでjavascript実行する関数
Function ExecJavaScript($ie, $jsCommand, [switch]$global)
{
if (!$global) {
$jsCommand = "document.body.setAttribute('PSResult', (function(){$jsCommand})());"
}
$document = $ie.document
$window = $document.parentWindow
$window.execScript($jsCommand, 'javascript') | Out-Null
if (!$global) {
return $document.body.getAttribute('PSResult')
}
}
# JQueryの有無確認
Function CheckJQueryExists
{
$result = ExecJavaScript $ie 'return window.hasOwnProperty("$");'
return ($result -eq $true)
}
ネタ元
なにか作ってみるよ。: 【解決】PowerShellでInternetExplorerを操作するときにエラーが発生
https://nanitsuku.blogspot.com/2013/10/powershellinternetexplorer.html
PowershellでInternetExplorerを操作する - Qiita
https://qiita.com/flasksrw/items/a1ff5fbbc3b660e01d96
jquery - Powershell:InternetExplorer.Applicationを介したjQueryの使用 - ITツールウェブ
https://cloud6.net/so/jquery/1657650