はじめに
勉強用の備忘録です。
随時更新していきます。
文法項目をさっと流し読みしたい時に参考になるかもしれません。
$PSVersionTable -> PSVersion 5.1にて動作確認。
変数
# コメント
$a = "Hello"
$b = "World!"
$c = $a + ", " + $b
Write-Host $c
文字列演算子
# 文字列置換
"powerShell" -replace "power", "Power"
# 正規表現マッチ
"PowerShell" -match "S...l"
# ワイルドカードマッチ
"PowerShell" -like "Power*"
比較演算子
# 等しい
1 -eq 1
# 等しくない
1 -ne 10
# より大きい
2 -gt 1
# 以上
2 -ge 1
# より小さい
1 -lt 2
# 以下
1 -le 2
包含
# 左側に右側が含まれる
"PowerShell", "Python" -Contains "PowerShell"
# 右側に左側が含まれる
"PowerShell" -in "PowerShell", "Ruby"
論理演算子
# 論理積
$true -and $true
# 論理和
$true -or $false
# 否定
-not $false
!$false
要素のループ処理
Get-ChildItem C:\ | ForEach-Object {$_.GetType()}
Get-ChildItem C:\ | % {$_.GetType()}
条件による絞り込み
Get-ChildItem c:\ | Where-Object {$_.PSIscontainer}
Get-ChildItem c:\ | ? {$_.PSIscontainer}
Get-ChildItem C:\ -Directory
文字列をコマンドとして実行
$command = "ping localhost"
Invoke-Expression $command
配列
$lang = @("PowerShell", "Python", "Ruby")
$lang[0]
# スライス
$lang[1..2]
# 長さ
$lang.Length
# インデックス
$lang.IndexOf("Python")
# 要素の追加
$lang += "Perl"
# 配列から要素を取り除くのは面倒
$newLang = $lang | ? {$_ -ne "Perl"}
配列はRemoveでは削除できないのでArrayListを使う
[System.Collections.ArrayList]$lang = "PowerShell", "Python", "Ruby", "Perl"
$lang.Remove("Perl")
連想配列(Hash)
$abbr =@{ps="PowerShell"; py="Python"; rb="Ruby"}
$abbr["ps"]
$abbr.Keys
$abbr.Values
$abbr.Add("pl", "Perl")
$abbr.Remove("pl")
定数
Set-Variable -Name pi -Value 3.14 -Option Constant
入力
$value = Read-Host "文字の入力"
If文
[int]$i = Read-Host "input number:"
If($i -eq 0) {
Write-Host "zero."
} ElseIf($i % 2) {
Write-Host "odd number."
} Else {
Write-Host "even number."
}
Swich文
$lang = Read-Host "好きな言語は?"
Switch ($lang) {
"PowerShell" {Write-Host "パワーシェル"}
"Python" {Write-Host "パイソン"}
"Ruby" {Write-Host "ルビー"}
default {Write-Host "知らない言語です"}
}
ForEach文
$lang = @("PowerShell", "Python", "Ruby")
ForEach ($l in $lang) {
Write-Host $l
}
For文
For ($i=1; $i -le 10; $i++) {
Write-Host $i
}
While文
$i = 5
While ($i -ne 11) {
Write-Host $i
$i++
}
$j = 0
While ($true) {
if($j -eq 3) {
break
}
Write-Host $j
$j++
}
スクリプトブロックの実行
$exec = {"プロセス情報を表示"; Get-Process | ? ProcessName -ne "svchost"}
&$exec
関数
Function AddArg {
$sum = 0
foreach ($arg in $args) {
$sum += $arg
}
return $sum
}
AddArg 10 90