6
11

More than 5 years have passed since last update.

自分用サンプル

Last updated at Posted at 2018-11-11

サンプル集

基本拾い物のPowershellサンプルを集めただけの記事です。自分用

どういう環境で使うか

・自動化をしたい
・OfficeがなくVBAが使えない
・マウスクリック作業が多いサーバ等々

マウスクリックを実行する

start iexplore.exe

#Set the average time to your system load and open an iexplorer page
Start-Sleep -Seconds 3

[system.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | out-null

# Set the exactly position of cursor in some iexplore hyperlink between the (open parenthesis) below: 
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(1240,489)

function Click-MouseButton
{
    $signature=@' 
      [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
      public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
'@ 

    $SendMouseClick = Add-Type -memberDefinition $signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru 

        $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0);
        $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0);
}

Click-MouseButton

マウスの座標を調べる1

# PowerShellでマウスポインタの座標を取得する

# アセンブリのロード
Add-Type -AssemblyName System.Windows.Forms

# フォームの作成・ボタンの作成
$form = New-Object System.Windows.Forms.Form
$form.Size = "200,200"
$form.StartPosition = "CenterScreen"

$Button = New-Object System.Windows.Forms.Button
$Button.Location = "50,50"
$Button.Size = "100,50"
$Button.Text = "クリック!"

# クリックイベント
$click = {
    for ( $a = 0 ; $a -lt 10 ; $a++ )
    {
        $x = [System.Windows.Forms.Cursor]::Position.X # マウスのX座標
        $y = [System.Windows.Forms.Cursor]::Position.Y # マウスのY座標
        Write-Host "マウスの現在座標は($x,$y)です"
        Start-Sleep(1)
    }
    Write-Host "終わり"
}
$Button.Add_Click($click)

$form.Controls.Add($Button)
$Form.Showdialog()

マウスの座標を調べる2

$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
$params = New-Object System.CodeDom.Compiler.CompilerParameters
$params.GenerateInMemory = $True
$params.TreatWarningsAsErrors = $True
$refs = "System.dll","mscorlib.dll","System.Drawing.dll","System.Windows.Forms.dll"
$params.ReferencedAssemblies.AddRange($refs)

# C Sharp
$txtCode = '
using System;
using System.Drawing;
using System.Windows.Forms;

public class MouseTrace {
    bool cap_stat = false;
    Form f1 = new Form();
    TextBox tb_x = new TextBox();
    TextBox tb_y = new TextBox();
    Button btn1 = new Button();
    Label lbl1 = new Label();
    Color c_on = Color.Green;
    Color c_off = Color.Red;
    System.Timers.Timer tm1 = new System.Timers.Timer(100.0);
    public MouseTrace(){
        Font font1 = new Font("MS ゴシック",16);
        f1.Text = "Mouse Trace";
        tb_x.Font = font1;
        tb_x.Location = new Point(10,10);
        tb_x.Text = "0";
        tb_x.TextAlign = HorizontalAlignment.Center;
        tb_x.Width = 100;
        tb_y.Font = font1;
        tb_y.Location = new Point(tb_x.Right+10,10);
        tb_y.Text = "0";
        tb_y.TextAlign = HorizontalAlignment.Center;
        tb_y.Width = 100;
        btn1.Location = new Point(10,tb_x.Bottom+10);
        btn1.Text = "Mouse Capture";
        btn1.Width = 110;
        btn1.MouseClick += new MouseEventHandler(btn1_MouseClick);
        lbl1.Location = new Point(btn1.Right+10,btn1.Top);
        lbl1.Text = "Off";
        lbl1.ForeColor = c_off;
        lbl1.Font = font1;
        f1.Size = new System.Drawing.Size(tb_y.Right+30,btn1.Bottom+50);
        f1.Controls.Add(tb_x);
        f1.Controls.Add(tb_y);
        f1.Controls.Add(btn1);
        f1.Controls.Add(lbl1);
        tm1.Elapsed += new System.Timers.ElapsedEventHandler(WriteMousePosition);
    }
    public void Show(){
        f1.ShowDialog();
    }
    private void WriteMousePosition(object source, System.Timers.ElapsedEventArgs e){
        // 画面上の絶対座標
        tb_x.Text = Cursor.Position.X.ToString();
        tb_y.Text = Cursor.Position.Y.ToString();
    }
    private void btn1_MouseClick(object sender, MouseEventArgs e){
        if(cap_stat){
            lbl1.ForeColor = c_off;
            lbl1.Text = "Off";
            cap_stat = false;
            tm1.Stop();
        }else{
            lbl1.ForeColor = c_on;
            lbl1.Text = "On";
            cap_stat = true;
            tm1.Start();
        }
    }
}
'

$results = $provider.CompileAssemblyFromSource($params, $txtCode)
$results.Errors
$mAssembly = $results.CompiledAssembly
$i = $mAssembly.CreateInstance("MouseTrace")
$i.Show()

PowwershellでUI Automationで電卓計算

#REQUIRES -Version 3.0

# This is a simple sample for access the MS UIAutomation in PowerShell. 
# In this sample:
#  1. Load the MS UIA via System.Reflection.Assembly
#  2. Launch the AUT ( calc.exe )
#  3. Find the AutomationElement via the AUT Process Id
#  4. Find buttons via 'ClassName' and 'Name' property
#  5. Click the '1', '+', '1', '=' buttons. 
# At last, we will get '2' in the result of calc App.

# Load MS UIAutomation assemblies
Write-Host "Loading MS UIA assemblies"
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationClient")
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationTypes")
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationProvider")
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationClientsideProviders")


# Register client side provider
Write-Host "Register client-side provider"
$client = [System.Reflection.Assembly]::LoadWithPartialName("UIAutomationClientsideProviders")
[Windows.Automation.ClientSettings]::RegisterClientSideProviderAssembly($client.GetName())

# Launch the AUT ( calc.exe ) & sleep 10 seconds for wait the process start
Write-Host "Launching the AUT"
$autProc =  Start-Process calc -PassThru
Start-Sleep -s 10

# Find the calc Element via the process Id
Write-Host "Searching the AUT Root element"
$rootElement = [Windows.Automation.AutomationElement]::RootElement
$condAUTProc = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, $autProc.Id)
$autElement = $rootElement.FindFirst([Windows.Automation.TreeScope]::Children, $condAUTProc)

# Find the buttons '1', '+', '='
Write-Host "Searching the button elements"
$condBtn = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty, "Button")

$condName = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, "1")
$condTarget = New-Object Windows.Automation.AndCondition($condBtn, $condName)
$btn1Element = $autElement.FindFirst([Windows.Automation.TreeScope]::Descendants, $condTarget)

$condName = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, "+")
$condTarget = New-Object Windows.Automation.AndCondition($condBtn, $condName)
$btnPlusElement = $autElement.FindFirst([Windows.Automation.TreeScope]::Descendants, $condTarget)

$condName = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, "=")
$condTarget = New-Object Windows.Automation.AndCondition($condBtn, $condName)
$btnEqualElement = $autElement.FindFirst([Windows.Automation.TreeScope]::Descendants, $condTarget)

# Click the buttons
Write-Host "Clicking the buttons"
$btn1Element.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
Start-Sleep -s 1
$btnPlusElement.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
Start-Sleep -s 1
$btn1Element.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
Start-Sleep -s 1
$btnEqualElement.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
Start-Sleep -s 1

Write-Host "Finished. Please check the results on the AUT."

powershellでsendkeys

add-type -AssemblyName System.Windows.Forms

#メモ帳を開く
notepad

#500ミリ秒スリープ
start-sleep -Milliseconds 500
#aiueoと入力
[System.Windows.Forms.SendKeys]::SendWait("aiueo")
6
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
11