Windows PowerShell 実践メモ
日記「Windows PowerShell の基本メモ - oknknicの日記」に引き続きPowerShellネタ。
頻用情報源
PowerShell のリファレンス
- powershell_ise のヘルプ
- Windows PowerShell
基本的な作成例
関数定義
# ------------------------ # Xxx-XxxXxx.ps1 # Author, yyyy/MM/dd # # keyword: xxxx, xxxx # # Useage: # # ------------------------ Function Xxx-XxxXxx($arg01, $arg02) { echo "引数01:$arg01 引数02:$arg02" }
関数利用スクリプト
# ------------------------ # xxx.ps1 # ------------------------ # インポート Import-Module .\Xxx-XxxXxx.ps1 # 標準入力 $arg01 = Read-Host "引数01> " $arg02 = Read-Host "引数02> " # 呼び出し $output = Xxx-XxxXxx $arg01 $arg02 # 標準出力 Write-Host $output
実行
./xxx.ps1
頻用コマンドレット
アイテム操作
- New-Item
- Copy-Item
- Remove-Item
- Rename-Item
入出力
- Write-Host
- Read-Host
使用例
# カレントフォルダに新規フォルダを作成し、カレントフォルダの指定拡張子のファイルをコピーし、指定通りリネームする function Copy-And-Rename($dirName, $type, $replaceFrom, $replaceTo){ New-Item $dirName -type directory | out-null foreach($fileName in (ls -name -include "*.${type}")) { Copy-Item $fileName "${dirName}\${fileName}" if($fileName -match ".*${replaceFrom}.*") { Rename-Item ".\${dirName}\${fileName}" -newname (${fileName} -replace $replaceFrom, $replaceTo) } } } Copy-And-Rename "hoge" "txt" "hoge" "hogeです"
単純にリネームするコマンドのシンプルな書き方なら、下記が参考になる。(powershell_ise のヘルプより)
get-childItem *.txt | rename-item -newname { $_.name -replace '\.txt','.log' }
PowerShell で GUI
Windowsのフォーム表示例
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | out-null $WinForm = new-object Windows.Forms.Form $WinForm.showdialog() | out-null