【Powershell】よく使うコマンド(随時更新)


私がよく使うPowershellのコマンドをまとめました。随時更新していきます。
(きちんと確認していないので、間違っていたらすみません)
ファイル操作

日付フォルダ作成

■例. 170531(水)
$yymmdd = ((get-date).Tostring(‘yyMMdd’) + “(“ + (get-date).Tostring(‘ddd’) + “)” )
New-item –path ${ディレクトリ} –name $yymmdd –itemtype Directory | Out-null

ファイル一覧出力

Get-ChildItem "調査するフォルダ名" -Recurse -Force | Where-Object {-not $_.PsIsContainer} | Select-Object Directory, Name, Length, LastWriteTime | Export-Csv "出力ファイル" -encoding Default
http://yamahei.blogspot.jp/2012/05/powershell.html

ファイル名変更

Rename-Item "変換前" -newname "変換後"
■年が含むファイルを抽出して、年を消す
Get-ChildItem -path ${変換元パス} -Include *年* | foreach-object { Rename-Item $_ -NewName ($_ -replace '年','')}

ファイル削除

■強制
Remove-Item ${対象ファイル} –Force
■確認
Remove-Item ${対象ファイル} –confirm

ファイルコピー

■確認
copy-Item ${対象元ファイル} ${対象先ファイル} –confirm


ファイル移動

■ファイル名を変更(123を456へ)
move-item $motofile $sakifile.replace(‘123’,’456’) –force

ファイル数のカウント

(Get-ChildItem ${対象パス} | Measure-Object).Count

ファイルソート

■名前でソートして最初のものを表示
(Get-ChildItem ${対象パス} | sort-object name)[0].name

■名前でソートして最初のもののサイズをMBで表示
(Get-ChildItem ${対象パス} | sort-object name)[0].length /1MB

PCのスペック確認

CPU

get-wmiobject -class win32_processor

メモリ

get-wmiobject -class win32_physicalmemory

電源オプション確認

powercfg –l

プログラム作成時に使用

スクリプトのパス

$scriptPath = $MyInvocation.MyCommand.Path   #スクリプトのパス
$ParentPath = (Split-Path -Parent $scriptPath) + "\" #格納フォルダ


コンソールにメッセージ出力(背景黄色)

Write-Host $message -ForegroundColor yellow

メッセージを出力して、ログ出力

Write-Output ${メッセージ} | Out-File ${ログのパス} -Append -Encoding Default

実行スクリプトの名前

[System.IO.Path]::GetFileNameWithoutExtension($MyInvocation.MyCommand.Name)


バッチからの呼び出し


powershell -ExecutionPolicy RemoteSigned -command ./program.ps1

■Powershellの権限を変更しないまま、画面を最小にして起動
powershell -ExecutionPolicy RemoteSigned -WindowStyle Minimized -command ./program.ps1 999

■パラメーター(上記の場合 999)
$args[0]

プロセス起動

start-process ${実行ファイル} ${パラメータ} –wait


ファンクション

Function A($1,$2){
}

ファイルから文字取得

(get-content ${ファイル名}) –as [string[]]


変換


四捨五入(小数点第2位)

[math]::round($value,2)


日付を指定フォーマットで取得

Get-Date -Format "yyyy/MM/dd HH:mm:ss"

■当日
(Get-Date).AddDays(0).tostring("yyyyMMdd")

■翌日
(Get-Date).AddDays(1).tostring("yyyyMMdd")


ループ

ファイルの数だけ実行

Foreach(${対象ファイル} in ${対象ファイル全部} = (Get-childitem *.xml -name )){
   #処理
}

For文

For( $i = 0 ; $i –lt 10 ; $i++){
   #処理
}

変数

複数の値を順番に格納

$hensuu = @(1,2,3)

■xmlで取得した値を格納
$hensuu = @($a.select(“aaa/bbb/”) | % {$_.value})

変数の一番最後

$hensuu[-1]


グローバル変数

$Global:hennsu


2次元配列

$array[1][2]



判定

if条件<test-path>

if(test-path ${対象パス} -Include ${条件①},${条件②})

■if条件(合致しない場合)
if(!(test-path ${対象パス} -Include ${条件①},${条件②}))

if条件 イコール

if($check -eq 1)


if条件 複数

if(($check -eq 1) –or ($check –eq 2)){
}


Grepみたいに文字検索して判定

$hantei = (select-string –pattern 文字 –quiet –path ディレクトリ –encoding UTF8)
if($hantei –eq $true){}
elseif(($hantei –eq $false){}


文字判定(変数内に対象の文字があるか)

if($hantei.Contains(“文字”)){
}


入力判定

$nyuryoku = (Read-host "数字を入力してください”)
switch ($nyuryoku){
 “1” { write-host “1” break }
 defalut { write-host “999” break}
}

その他

ファイルの長さをチェック


$sh = New-Object -ComObject Shell.Application
$f = $sh.Namespace(${対象フォルダ})
$fi = $f.ParseName(${対象ファイル})
$saki_nagasa = $f.GetDetailsOf($fi, 27)


xmlファイルの読込


$doc = [xml](Get-content($dir + “\ファイル名”) –encoding UTF8)
$Navi = $doc.CreateNavigator()

$count = $Navi.select(“aaa/bbb”).count
$value = $Navi.select(“aaa/bbb”).value


マクロの実行


$xls = New-Object -ComObject Excel.Application
$xls.Visible = $True
$wb = $xls.workbooks.open("D:\ファイル名.xlsx")

$excelsheet=$wb.Worksheets.Item(1)
$excelcells = $excelsheet.Cells
$excelcells.Item(1,2) = ”A2に設定する値”

$xls.Run("自動実行用マクロ関数名")
$wb.Save()
$xls.Quit()
$wb= $null
$xls = $null
[GC]::Collect()