この記事のPowerShellスクリプトは下記の環境で動作確認しています。

# UI オートメーションを使うための準備 Add-Type -AssemblyName "UIAutomationClient" Add-Type -AssemblyName "UIAutomationTypes" $AutomationElement = [System.Windows.Automation.AutomationElement] $TreeScope = [System.Windows.Automation.TreeScope] $Condition = [System.Windows.Automation.Condition] $InvokePattern = [System.Windows.Automation.InvokePattern] $SendKeys = [System.Windows.Forms.SendKeys] $Cursor = [System.Windows.Forms.Cursor] # マウスの左クリック操作をおこなうための準備 $SendInputSource =@" using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; public class MouseClick { [StructLayout(LayoutKind.Sequential)] struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public int dwFlags; public int time; public IntPtr dwExtraInfo; [StructLayout(LayoutKind.Sequential)] struct INPUT public int type; public MOUSEINPUT mi; [System.Runtime.InteropServices.DllImport("user32.dll")] extern static uint SendInput(uint cInputs, INPUT[] pInputs, int cbSize); public static void Click() { INPUT[] input = new INPUT[2]; input[0].mi.dwFlags = 0x0002; input[1].mi.dwFlags = 0x0004; SendInput(2, input, Marshal.SizeOf(input[0])); Add-Type -TypeDefinition $SendInputSource -ReferencedAssemblies System.Windows.Forms, System.Drawing $MouseClick = [MouseClick] # 要素を取得する関数 function GetElements { Param($RootWindowName = $null) if ($RootWindowName -eq $null) { try { return $AutomationElement::RootElement.FindAll($TreeScope::Subtree, $Condition::TrueCondition) catch { return $null else { $childrenElements = $AutomationElement::RootElement.FindAll($TreeScope::Children, $Condition::TrueCondition) foreach ($element in $childrenElements) { if ($element.GetCurrentPropertyValue($AutomationElement::NameProperty) -eq $RootWindowName) { return $element.FindAll($TreeScope::Subtree, $Condition::TrueCondition) Write-Host "指定された名前 '${RootWindowName}' のウィンドウが見つかりません。" return $null # 要素を検索する関数 function FindElement { Param($RootWindowName = $null, $PropertyType, $Identifier, $Timeout) $startTime = (Get-Date).Ticks foreach ($element in GetElements -RootWindowName $RootWindowName) { try { if ($element.GetCurrentPropertyValue($AutomationElement::$PropertyType) -eq $Identifier) { return $element catch { continue while (((Get-Date).Ticks - $startTime) -le ($Timeout * 10000)) throw "指定された要素 '${Identifier}' が見つかりません。" # クリック操作をおこなう関数 function ClickElement { Param($RootWindowName = $null, $PropertyType, $Identifier, $Timeout = 5000) $startTime = (Get-Date).Ticks $element = FindElement -RootWindowName $RootWindowName -PropertyType $PropertyType -Identifier $Identifier -Timeout $Timeout $isEnabled = $element.GetCurrentPropertyValue($AutomationElement::IsEnabledProperty) if ($isEnabled -eq "True") { break } while (((Get-Date).Ticks - $startTime) -le ($Timeout * 10000)) if ($isEnabled -ne "True") { throw "指定された要素 '${Identifier}' が有効状態になりません。" if ($element.GetCurrentPropertyValue($AutomationElement::IsInvokePatternAvailableProperty) -eq "True") { $element.GetCurrentPattern($InvokePattern::Pattern).Invoke() else { # IsInvokePatternAvailablePropertyがFalseの時はマウスカーソルを要素に移動して左クリックする $clickablePoint = $element.GetClickablePoint() $Cursor::Position = New-Object System.Drawing.Point($clickablePoint.X, $clickablePoint.Y) $MouseClick::Click() # キーボード操作をおこなう関数 function SendKeys { Param($RootWindowName = $null, $PropertyType, $Idendifier = $null, $Keys, $Timeout = 5000) if ($Idendifier -ne $null) { $element = FindElement -RootWindowName $RootWindowName -PropertyType $PropertyType -Identifier $Idendifier -Timeout $Timeout $element.SetFocus() $SendKeys::SendWait($Keys) # Microsoft EdgeでWebキャプチャの保存操作をおこなう関数 function SaveWebCaptureByMicrosoftEdge { SendKeys -Keys "^(+S)" ClickElement -PropertyType "AutomationIdProperty" -Identifier "view_52561" ClickElement -PropertyType "AutomationIdProperty" -Identifier "save_button_id" Start-Sleep -Seconds 3 SendKeys -Keys "{ESCAPE}" # ↓↓↓↓↓ この行以降にアプリを自動操作するスクリプトを書く ↓↓↓↓↓
################################################################################
# 電卓を自動操作する
################################################################################
# 足し算する値の範囲を設定する
$start = 1
$end = 10
# ボタンをクリックした後の待機ミリ秒を設定する
$waitMilliseconds = 300
# 電卓アプリを開始する
Start-Process calc -Wait
# 電卓アプリを操作する
foreach ($count in $start..$end) {
    # 数値を1桁ずつに分割する
    $array = $count.ToString().ToCharArray()
    # 電卓アプリの数値ボタンをクリックする
    foreach ($number in $array) {
        ClickElement -RootWindowName "電卓" -PropertyType "AutomationIdProperty" -Identifier "num${number}Button"
        Start-Sleep -Milliseconds $waitMilliseconds
    # 現在のカウントで処理を分岐する
    if ($count -ne $end) {
        # 範囲の終わり以外の時は[+]ボタンをクリックする
        ClickElement -RootWindowName "電卓" -PropertyType "AutomationIdProperty" -Identifier "plusButton"
        Start-Sleep -Milliseconds $waitMilliseconds
    else {
        # 範囲の終わりの時は[=]ボタンをクリックする
        ClickElement -RootWindowName "電卓" -PropertyType "AutomationIdProperty" -Identifier "equalButton"
        Start-Sleep -Milliseconds $waitMilliseconds
################################################################################
# Microsoft Edgeを自動操作する
################################################################################
# 検索する値を設定する
$searchWords = @(
    'フェンダー'
    'ギブソン'
    'ポール・リード・スミス'
# ページ読み込み完了待ち秒数を設定する
$pageLoadWaitSeconds = 3
# Microsoft Edgeを開始する
Start-Process msedge -Wait
# Microsoft Bingのトップページを開く
SendKeys -PropertyType "AutomationIdProperty" -Idendifier "view_1020" -Keys "https://www.bing.com/{ENTER}"
Start-Sleep -Seconds $pageLoadWaitSeconds
# 「$searchWords」に記載されている値を検索してWebキャプチャを保存する
$index = 0
foreach ($word in $searchWords) {
    # 2回目以降の検索時は検索ボックスの内容をクリアする
    if ($index -gt 0) {
        ClickElement -PropertyType "AutomationIdProperty" -Identifier "sb_form_q"
        ClickElement -PropertyType "AutomationIdProperty" -Identifier "sw_clx"
        Start-Sleep -Seconds 1
    # 検索ボックスに値を入力して検索する
    SendKeys -PropertyType "AutomationIdProperty" -Identifier "sb_form_q" -Keys "${word}{ENTER}"
    Start-Sleep -Seconds $pageLoadWaitSeconds
     # 1回目の検索時は画像リンクをクリックする
    if ($index -eq 0) {
        ClickElement -PropertyType "NameProperty" -Identifier "さらに表示"
        ClickElement -PropertyType "NameProperty" -Identifier "画像"
        Start-Sleep -Seconds $pageLoadWaitSeconds
    # Webキャプチャを保存する
    SaveWebCaptureByMicrosoftEdge
    $index += 1
# エクスプローラーでダウンロードフォルダーを開く
explorer.exe $env:USERPROFILE\Downloads

「Windows PowerShell ISE」ウィンドウのツールバーのフロッピーディスクアイコンのボタン(スクリプトを保存します)を選択します。(またはメニューバーから [ファイル] > [名前を付けて保存] を選択します。)
「名前を付けて保存」ダイアログが表示されたら、任意の場所・ファイル名で保存します。
では、ツールバーの緑色の「▶︎」(スクリプトを実行)ボタンを選択して、スクリプトを実行しましょう。
お使いの環境によりますが、PowerShellの実行ポリシーが「スクリプトの実行が許可されていない」ポリシーに設定されている場合は、悪意のあるスクリプトの実行を防止するための安全機能が働き「セキュリティ エラー」が発生して、スクリプトの実行が中断されます。

RANKINGアクセスランキング
#TAGS人気のタグ
  • テスト自動化
  •