powershell memo


Hello World

write-output "こんにちは、PowerShell!"

コンソール入出力

Write-Output "文字列1"

# 文字列を連結して出力
$output = "文字列1" + "文字列2"
Write-Output $output

# キーボードからの入力(標準入力からの読み取りではない)
$input = Read-Host "入力1"
Write-Output $input

# Write-Hostで改行無しで画面へ出力(標準出力への書き出しではない)
Write-Host -NoNewline "入力2 -> "
$input = Read-Host
Write-Output $input

# Out.writeで改行無しで画面へ出力
[Console]::Out.write("入力3:")
# In.ReadLineでキーボードからの入力
$input = [Console]::In.readLine()
# Out.writeLineで改行有りで画面へ出力
[Console]::Out.writeLine($input)
[Console]::Error.writeLine($input)

# パスワード入力の例
$input = Read-Host -AsSecureString "パスワード"
$ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($input)
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr);
Write-Output $password

変数

$a = "文字列1"
Write-Output $a
# $a を展開できる
Write-Output "文字列は $a"
# $a を展開できない
Write-Output '文字列は $a'

# 変数の連結
$a = "文字列1"
$b = "文字列2"
$c = '$c=' + $a + $b
Write-Output $c

配列

# 配列の初期化
$array1 = @("項目1", "項目2", "項目3")
Write-Output $array1[0]
Write-Output $array1[1]
Write-Output $array1[2]

# 配列の確保
$array2 = New-Object "object[]" 3
$array2[0] = "項目1"
$array2[1] = "項目2"
$array2[2] = "項目3"
Write-Output $array2[0]
Write-Output $array2[1]
Write-Output $array2[2]

# 連想配列の初期化
$hash_array1 = @{"みかん" = "オレンジ色" ; "イチゴ" = "赤色" ; "レモン" = "黄色"}
Write-Output $hash_array1["イチゴ"]

# 連想配列の確保
$hash_array2 = @{}
$hash_array2.Add("みかん","オレンジ色")
$hash_array2.Add("イチゴ","赤色")
$hash_array2.Add("レモン","黄色")
Write-Output $hash_array2["レモン"]

演算子

$a = "文字列1"
$b = "文字列2"
$c = $a + $b
Write-Output $c

$a = "文字列1"
$b = 3
$c = $a * $b
Write-Output $c

$a = 5
$b = 2
$c = $a + $b
Write-Output $c

$a = 5
$b = 2
$c = $a - $b
Write-Output $c

$a = 5
$b = 2
$c = $a * $b
Write-Output $c

$a = 5
$b = 2
$c = $a / $b
Write-Output $c

$a = 5
$b = 2
$c = $a % $b
Write-Output $c

$c = [Math]::Pow($a, $b)
Write-Output $c

$a++
Write-Output $a

$b--
Write-Output $b

条件分岐

$a = 100

if ($a -eq 10){
	Write-output '$a is 10'
}elseif ($a -eq 100){
	Write-output '$a is 100'
}else{
	Write-output '$a is unknown'
}

if ($a -ne 10){
	Write-output '$a is not 10'
}

if ($a -gt 10){
	Write-output '$a is greater than 10'
}

if ($a -ge 10){
	Write-output '$a is greater equal than 10'
}

if ($a -lt 200){
	Write-output '$a is less than 200'
}

if ($a -le 200){
	Write-output '$a is less equal than 200'
}

if ($a -ge 10 -and $a -le 200){
	Write-output '$a is between 10 and 200'
}

繰り返し(while)

$a = 0
while ($a -lt 5){
	Write-output $a
	$a++
}

繰り返し(for)

# 変数による条件判定
for ($a = 0; $a -lt 5; $a++){
	Write-Output $a
}

# 配列による繰り返し
$array = @(10,20,30)
foreach ($i in $array){
  $sum += $i;
}
Write-Output $sum

# 連想配列による繰り返し
$hash_array = @{"りんご" = "赤色"; "レモン" = "黄色"; "みかん" = "オレンジ色"}
foreach ($i in $hash_array.keys){
	Write-Output $hash_array[$i]
}

foreach ($i in $hash_array.keys | sort-object -descending){
	Write-Output $hash_array[$i]
}

ファイルの入出力

# 文字コード変換
Write-Output "1行目" | Out-File -encoding Default 008_file.txt
# 追加出力
Write-Output "2行目" | Out-File -encoding Default -Append 008_file.txt
Write-Output "3行目" | Out-File -encoding Default -Append 008_file.txt

# ForEach-Objectと$_による処理
$line = 0
Get-Content 008_file.txt |
ForEach-Object {
	$line++
	$out = "$line => $_"
	Write-Output $out
}

# open,close,read,writeによるプログラム的な処理
$objR = New-Object System.IO.StreamReader("008_file.txt", [Text.Encoding]::GetEncoding("Shift_JIS"))
$append_sw = $false
$objW = New-Object System.IO.StreamWriter("008_file2.txt", $append_sw,[Text.Encoding]::UTF8)
while (($rec = $objR.readLine()) -ne $null){
	$objW.writeLine($rec)
}
$objR.close()
$objW.close()

正規表現

# 条件マッチ
$a = "abcde"
if ($a -match "^a.*e"){
	Write-Output "matched!"
}

# 条件非マッチ
if ($a -notmatch "^a.*e"){
	Write-Output "not matched!"
}else{
	Write-Output "matched!"
}

# 文字列置喚
$b = $a -replace "b.*d","BCD"
Write-Output $b

# 文字列置喚(自己置喚有り)
$b = $a -replace '(b).*d','$1CD'
Write-Output $b

# 文字列分割
$a = "文字列1,文字列2,,文字列3"
$array = $a -split ",,*"
foreach ($i in $array){
	Write-Output $i
}

文字列操作

$a = "abcdefg"
Write-Output $a.Length
Write-Output $a.substring(2,3) # -> cde

関数

function tasizan($a, $b){
	Write-Output ($a + $b)
}

$out = tasizan 10 20
Write-Output "10 + 20 = $out"

# ラムダ関数(無名関数)
Get-Content *.ps1 |
&{
	begin{
		$count = $args[0]
		$step = $args[1]
	}
	process{
		write-output "$count $_"
		$count += $step
	}
	end{
	}
} 100 10

日時取得

$out = get-date -uformat "%Y/%m/%d %H:%M:%S(%w)"
Write-Output $out

$day = get-date 
$day.AddDays(1)
$day.AddMonths(-2)
$day.AddYears(3)

引数

for ($i = 0; $i -le $args.length; $i++){
	Write-Output $args[$i]
}

catもどき

$line = 0
Get-Content *.ps1 |
ForEach-Object {
	$line++
	$out = "${line}: $_"
	Write-Output "$out"
}

wc -lもどき

$file = Get-Content 001*ps1
Write-Output $file.Count

(get-content 001*ps1).count

Get-Content 001*ps1 |
Measure-Object |
ForEach-Object{$_.Count}

cutもどき

Get-Content 103_cut.csv |
ForEach{
	$_.split(",")[4] + "," + $_.split(",")[3]
}

Get-Content 103_cut.csv |
ConvertFrom-Csv -Delimiter "," -Header "mode","date","time","size","name"  |
Select-Object name,size |
ConvertTo-Csv -Delimiter ","

grepもどき

Get-Content .\103_cut.csv |
select-string "005_.*ps1"

select-string "005_.*ps1" 103_cut.csv

select-string -NotMatch "005_.*ps1" 103_cut.csv

headもどき

Get-Content 103_cut.csv |
Select-Object -First 3

sedもどき

Get-Content .\103_cut.csv |
foreach{
	$_ -replace ".ps1$",".PS1"
}

抽出

Get-Content 103_cut.csv |
ForEach{
	if ([int]$_.split(",")[3] -gt 100){
		$_.split(",")[4] + "," + $_.split(",")[3]
	}
}

# CSVをオブジェクトに変換して処理
Get-Content 103_cut.csv |
ConvertFrom-Csv -Delimiter "," -Header "mode","date","time","size","name"  |
Where-Object {[int]$_.size -gt 100}|
Select-Object name,size |
ConvertTo-Csv -Delimiter ","

sortもどき

# 文字列としてソート
Get-Content 103_cut.csv |
ConvertFrom-Csv -Delimiter "," -Header "mode","date","time","size","name"  |
Sort-Object size |
ConvertTo-Csv -Delimiter ","

# 数値としてソート
Get-Content 103_cut.csv |
ConvertFrom-Csv -Delimiter "," -Header "mode","date","time","size","name"  |
Sort-Object {[int]$_.size} |
ConvertTo-Csv -Delimiter ","

# 複雑なソート
get-content .\junk2.csv
000,111,aaa,1
aaa,bbb,ccc,10
aaa,bbb,eee,2
aaa,bbb,ggg,333
bbb,ccc,iii,3
ccc,ddd,kkk,5000
ccc,ddd,mmm,4
ddd,eee,lll,1000
eee,fff,jjj,5
eee,fff,ggg,444
eee,fff,hhh,6
eee,fff,fff,20
eee,fff,ddd,7
fff,ggg,bbb,10

Get-Content .\junk2.csv |
sort-object -property @{expression={$_.split(",")[0]};descending=$true},@{expression={[int]$_.split(",")[3]}}
fff,ggg,bbb,10
eee,fff,jjj,5
eee,fff,hhh,6
eee,fff,ddd,7
eee,fff,fff,20
eee,fff,ggg,444
ddd,eee,lll,1000
ccc,ddd,mmm,4
ccc,ddd,kkk,5000
bbb,ccc,iii,3
aaa,bbb,eee,2
aaa,bbb,ccc,10
aaa,bbb,ggg,333
000,111,aaa,1

teeもどき

Get-Content 103_cut.csv |
Tee-Object 109_tee.txt

tailもどき

Get-Content 103_cut.csv |
Select-Object -Last 3

uniqもどき

function uniqd (){
	begin{
		$first_sw = "on"
	}
	process{
		if ($first_sw -eq "on"){
			$rec = $_
			$first_sw = "off"
			$dup_sw = "off"
		}else{
			if ($rec -eq $_){
				$dup_sw = "on"
			}else{
				if ($dup_sw -eq "on"){
					write-output $rec
				}
				$rec = $_
				$dup_sw = "off"
			}
		}
	}
	end{
		if ($dup_sw -eq "on"){
			write-output $rec
		}
	}
}

# uniq
Get-Content 111_uniq.txt |
Select-Object -Unique

# uniq -d
Get-Content 111_uniq.txt |
Sort-Object |
uniqd

# uniq -c
Get-Content 111_uniq.txt |
Sort-Object |
&{
	begin{
		$first_sw = "on"
		$count = 0
	}
	process{
		if ($first_sw -eq "on"){
			$rec = $_
			$count++
			$first_sw = "off"
		}else{
			if ($rec -eq $_){
				$count++
			}else{
				write-output "$count $rec"
				$count = 0

				$rec = $_
				$count++
			}
		}
	}
	end{
		write-output "$count $rec"
	}
}

エクセル to CSV変換

$intSheetNum = 1
$strSheetName = "Sheet1"

Get-ChildItem *.xls* |
ForEach-Object {
	$InPath = resolve-path $_.Name
	$OutPath = $InPath -replace ".xls.*", ".csv"
	$objExcel = New-Object -ComObject Excel.Application
	$objExcel.DisplayAlerts = $false

	$objExcel.Workbooks.open($InPath)

#	$objSheet = $objExcel.Worksheets.Item($intSheetNum)
	$objSheet = $objExcel.Worksheets.Item($strSheetName)
	$objSheet.SaveAs($OutPath, 6)
	$objExcel.Workbooks.Close()
	$objExcel.Quit()
}

DISPLAYもどき

function display (){
	$out = $args -join ""
	write-output $out
}

$a = 10
$b = 20

display "$a + $b = " ($a + $b)

コマンドレットの出力をテキストに変換

get-childitem | out-string -stream

コマンドレットの出力をすてる

get-childitem | out-null

テンポラリファイル名取得

[System.IO.Path]::GetTempFileName()

カレントディレクトリ取得

(get-location).tostring()

自動実行ファイルのパス

$profile

カレントディレクトリ直下のディレクトリ容量

get-childitem |
where-object {
	$_.PsIsContainer -eq $true
} |
select-object FullName |
foreach-object {
	$fullname = $_.FullName
	get-childitem $_.FullName -recurse |
	where-object {
		$_.PsIsContainer -eq $False
	} |
	&{
		begin{
			$sum=0
		}
		process{
			$sum += $_.Length
		}
		end{
			write-output "$sum,$fullname"
		}
	}
} |
sort-object -property @{expression={[int]$_.split(",")[0]};descending=$true}

再帰的にファイルをさがす

get-childitem . -include "*.txt" -recurse -force

再帰的に文字列検索する

get-childitem . -include "*.txt" -recurse | select-string "文字列" -encoding default

インストール一覧表示

Get-WmiObject -Class Win32_Product

[更新] [戻る]
m-ito@myh.no-ip.org