good-arrow’s blog

https://good-arrow.net/

PowerShell から IE をシークレットモードで起動する

やりたい人、いると思うんです。
ということで書いてみました。

正しく動作させるポイントとしては「待ち時間」処理の部分を入れてやること。
これを含めないと、

[mshtml.HTMLDocumentClass] に 'getElementsById' という名前のメソッドが含まれないため、メソッドの呼び出しに失敗しました

のようなエラーが出ます。

また HTML に ID が割り当たっていない場合は

$btn=$doc.getElementsByTagName("button")[0]

のように配列で取得するしかありません。



サンプルコード

動作内容
1. IEをシークレットモードで開く
2. 検索ボックスに文字を入力する
3. 検索させる
を無限ループさせる。

起動方法 .ps1 ファイルを右クリック → [PowerShell で実行]
停止方法 PowerShell を×で閉じる

[sample.ps1]

while(1){
    #トラップ
    try{
        Start-Process -FilePath "C:\Program Files (x86)\Internet Explorer\iexplore.exe" -ArgumentList ' -private https://www.yahoo.co.jp/'

        start-sleep 3

        $shell = New-Object -ComObject Shell.Application
        $ie_list = @($shell.Windows() | where { $_.Name -match "Internet Explorer" })
        $ie = @($ie_list | where { $_.LocationURL -match "https://www.yahoo.co.jp/" })[-1]

        #待ち時間
        While($ie.Busy){
            start-sleep 1
        }

        $doc=$ie.document
        $dom_srchtxt=$doc.getElementById("srchtxt")
        $dom_srchtxt.value = "powershell ie"
        $dom_srchbtn=$doc.getElementById("srchbtn")
        $dom_srchbtn.click()

        start-sleep 3

    }catch [Exception]{
        $Error
    }finally{

    }

    $ie.Quit()

    start-sleep 2
}