' P '

whatever I will forget

PowerShell 書き方備忘録

全てをググりながらなんとかディレクトリ配下のファイル変更、空フォルダ削除を実装したのでメモ

拡張子

test.ps1

出力

write-host $tmp

比較演算子

www.vwnet.jp

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

$curDir = Convert-Path .

ディレクトリの指定

2番目のように書くと2つ上に戻れる。

Set-Location -Path C:\work\xxxx
Set-Location ../../
Set-Location $folderId.Name

カレントディレクトリのファイル情報の取得

  • フォルダ
$folderNames = Get-ChildItem -Directory 
  • ファイル
$fileNames = Get-ChildItem -File

for文

foreach($curFile in $fileNames) {
  # 処理
}

もしくは

$fileNames | foreach { write-host $_ }

$_がforeachの1つずつのobjを指すらしい。

ファイル名取得

上記変数からNameプロパティにアクセスする

$file.Name

文字列系

  • 文字数の確認
$curFile.Name.Length
  • 切り取り
    JavaとかのSubstringではなく、Excelっぽさがあると覚えておく
    引数は切り取り開始indexと切り取りたい文字数
$tmp1 = $curFile.Name.Substring(0, 4)
$tmp2 = $curFile.Name.Substring($tmp1.Length, $curFile.Name.Length-$tmp1.Length)
  • 特定文字列の検索
    他言語と同じ。-1ならNot Found
if($curFile.Name.indexOf("test") -ne -1) {
  # 処理
}
  • 文字列の連結
$st = $a + "_" + $b

ファイル名の変更

Rename-Item $curFile.Name -NewName $newFileName

ファイルの移動

下記のように記述すると1つ上のディレクトリにファイルを移動

Move-Item $newFileName ../

ファイルの削除

Remove-Item $folderId.Name