PowerShell Tips(グローバルIP取得・短縮URL展開・ウィンドウ移動)

グローバルIPを取得する
と、言ってもほぼGoogleの機能なんですけどね。Googleの言語設定を英語にして"what is my ip"と検索すると、自分のグローバルIPが表示されるので、それをパースして表示しているだけ。ダイナミックDNSを使って自宅サーバーを立てている時に、IPの更新処理をする時なんかに役立つかも。
$response = Invoke-WebRequest "https://www.google.co.jp/search?hl=en&safe=off&q=what+is+my+ip"
$elements = $response.ParsedHtml.getElementsByClassName("_h4c _rGd vk_h")
echo $elements[0].innerText
短縮URLを展開する
PHPとかJavaScriptとか、動作させるのにそれなりに準備が必要になってくるので、コマンドラインでサクッと短縮URLを展開するサンプル。以下のコードをurlexpand.ps1などで保存しておく。
urlexpand.ps1$request = [System.Net.WebRequest]::Create($args[0])
$response = $request.GetResponse()
echo $response.ResponseUri.OriginalString
$response.Close()
$response.Dispose()
使い方はコマンドプロンプトで短縮URLを引数にして起動する。エラーチェックは何も入れてないので悪しからず。
C:\>powershell urlexpand.ps1 http://goo.gl/xxxxx
ウィンドウの位置を移動する
VBScriptでは単体で出来なかったWin32 APIの呼び出しが出来るのは便利だけど、慣れないせいもあって非常に見辛いというか書式が理解しにくい。何でも全部VBScriptで書く必要もないし、全部PowerShellで書く必要もないので、適材適所ではあるけど。
Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class Win32 {
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  }
"@

$hWnd = (Get-Process | Where-Object {$_.MainWindowTitle -like "*chrome*"}).MainWindowHandle
[Win32]::MoveWindow($hWnd, 0, 0, 800, 800, $true)
    この記事で書かれている製品やソフトについて
  • Windows10 Pro 64ビット
  • PowerShell 5.1.14393.206