トッカンソフトウェア

PowerShell ファイル関連



PowerShellのファイルの入出力をまとめます。 ■サンプル:ファイルを読み込み、ループでまわす
				
#読み込むファイルパス
$readPath = "C:\work\powershell\read.txt"

#ファイルの読み込み
$readAry = (Get-Content $readPath) -as [string[]]

#ファイル中身でループ
foreach($readStr in $readAry){

    #ファイルの内容出力
    echo $readStr;
}

			


■サンプル:配列をファイルに書き込む(UTF-8 BOMあり)
				
#出力するファイルパス
$writePath = "C:\work\powershell\write.txt"

#出力する配列定義
$writeAry = "aaa","bbb","","ccc"

#出力処理(上書き)
$writeAry | Out-File $writePath -encoding UTF8

#出力処理(追記)
"ddd" | Out-File $writePath -encoding UTF8 -Append

			


■サンプル:UTF-8 BOMなしでファイル出力
				
$data = "UTF-8 BOMなしで出力"
$path = "C:\tmp\test.txt"
$UTF8 = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines($path, $data, $UTF8)

			


■サンプル:SJISでファイル出力
				
#出力するファイルパス
$writePath = "C:\work\powershell\write.txt"

#出力する配列定義
$writeAry = "aaa","bbb","","あああ"

$encoding = [Text.Encoding]::GetEncoding(932)

[System.IO.File]::WriteAllLines($writePath, $writeAry, $encoding)


			


■サンプル:UTF-8 ファイル読み込み
				
$path = "C:\tmp\test.txt"
Get-Content -Encoding UTF8 $path

			


■サンプル:エンコードを指定してファイル読み込み

$encoding = [Text.Encoding]::GetEncoding(932)

#読み込むファイルパス
$readPath = "C:\work\powershell\read.txt"

#ファイルの読み込み
$readAry = [System.IO.File]::readAllLines($readPath, $encoding)


■サンプル:ファイルを読み込んで、(編集して)出力する
				
#読み込むファイルパス
$readPath = "C:\work\powershell\read.txt"

#出力するファイルパス
$writePath = "C:\work\powershell\write.txt"

#ファイルの読み込み
$readAry = (Get-Content $readPath) -as [string[]]

#出力する配列定義
$writeAry = @()

#ファイル中身でループ
foreach($readStr in $readAry){

    #ファイルの内容出力(ここで編集する)
    $writeAry += $readStr;
}

#出力処理
$writeAry | Out-File $writePath -encoding UTF8

			


■サンプル:フォルダ作成(削除)、ファイル作成(削除)
				
#フォルダ作成
New-Item c:\new1\new2 -itemType Directory

#フォルダ削除
Remove-Item c:\new1\new2 -Recurse

#ファイル作成
New-Item c:\new1\new2\new3.dat -itemType File -Value "ファイルの内容"

#ファイル削除
Remove-Item c:\new1\new2\*.txt

ファイルが存在する場合、削除
$path = "C:\tmp\appp.log"

#ファイル存在チェック
if(Test-Path $path){

    #ファイル削除
    Remove-Item $path
}

			
フォルダ作成は親フォルダも作ってくれます。

■サンプル:ファイルコピー、ファイル移動
				
#ファイルコピー
Copy-Item C:\tmp\from.txt C:\tmp\to1.txt

#ファイル移動
Move-Item C:\tmp\from.txt C:\tmp\to2.txt

			
-Forceを付けると強制上書きになります。

■サンプル:フォルダコピー
				
Copy-Item -Path C:\workFrom -Recurse -Destination C:\workTo

#指定ファイルのみコピー
Copy-Item -Filter *.txt -Path C:\workFrom -Recurse -Destination C:\workTo

			


■サンプル:空のファイルを作成
				
New-Item -Type File new.txt

			


■サンプル:親フォルダ取得、ファイル名取得
				
#親フォルダ取得( C:\work\powershell が取得される)
Split-Path "C:\work\powershell\write.txt" -Parent
#ファイル取得( write.txt が取得される)
Split-Path "C:\work\powershell\write.txt" -Leaf

			

■サンプル:ps1ファイルのパスを取得、パスの結合
				
#ps1ファイルのパスを取得し、その親フォルダを取得
$path = Split-Path $MyInvocation.MyCommand.Path -Parent

#パスの結合
$fullPath = Join-Path $path "read.txt"

echo $fullPath



			
$MyInvocation.MyCommand.Path ・・・ ps1ファイルパスの取得
Split-Path XXX -Parent ・・・ 親フォルダを取得

■サンプル:カレントディレクトリ取得、パスの結合
				
#カレントディレクトリ取得
$path = Get-Location

#パスの結合
$fullPath = Join-Path $path "read.txt"

echo $fullPath

			


■サンプル:ファイル(フォルダ存在チェック)
				
$path = "C:\tmp\appp.log";

#ファイル存在チェック
if(Test-Path $path){
    echo "ファイルが存在";
}

			
同じ書き方でファイル、フォルダの存在チェックができます。

■サンプル:ファイルに指定文字が含まれているかチェック
				
if ((Get-Content "C:\work\memo.txt" | %{$_ -match "test"}) -contains $true) {
    Write-Output "TRUE"
}

			

■サンプル:ファイル一覧
				
#フォルダ指定
$path = "C:\work\powershell"

#ファイル一覧を取得
$fileList = Get-ChildItem -Path $path -Recurse  -Filter *.txt -Exclude t*

#ファイル毎にループする
foreach($fileWk in $fileList)
{
    #フルパス
    echo $fileWk.FullName
    #ファイル名
    echo $fileWk.Name
    #更新日
    echo $fileWk.LastWriteTime.ToString('yyyy/MM/dd HH:mm:ss')
}

			

■サンプル:空フォルダを削除

#フォルダ指定
$path = "C:\work\powershell"

for ( $i = 0; $i -lt 10; $i++ )
{
    #フォルダ一覧を取得
    $dirs = Get-ChildItem -Path $path -Recurse -Directory 

    $isBreak = $true

    #フォルダ毎にループする
    foreach($dir in $dirs)
    {
        if((Get-ChildItem -Path  $dir.FullName).Count -eq 0){
    
            Remove-Item -Path  $dir.FullName 
            $isBreak = $false
        } 
    }

    if($isBreak){
        break
    }
}


■サンプル:ファイルの属性取得
				
$path = "C:\work\powershell\read.txt"

#ファイルの属性を取得
$info = Get-ItemProperty $path 

#フルパス
echo $info.FullName
#ファイル名
echo $info.Name
#拡張子
echo $info.Extension
#サイズ
echo $info.Length
#更新日
echo $info.LastWriteTime.ToString('yyyy/MM/dd HH:mm:ss')

			


■サンプル:ファイル検索
				
#7日前より後に更新された10MB以下のテキストファイル一覧
Get-ChildItem -Path "C:\tmp" -Recurse -Filter *.txt | Where-Object {$_.LastWriteTime -ge (Get-Date).AddDays(-7) -and ($_.Length -le 10mb)}

			
オプション 説明
-Path パスを指定
-Filter フィルター。
-Include フィルター。複数指定可能。
パスに*か-Recurseを指定した場合のみ使える

例:-Path "C:\tmp\*" -Include *.csv,*.txt
-Exclude 除外。複数指定可能。

ファイルは指定できるが、フォルダは指定できない。
フォルダを除外する場合は、以下のようにWhere-Objectを指定する。

例:Get-ChildItem -Path "C:\tmp" -Recurse | Where-Object FullName -NotLike "*aaa*"
-Recurse サブフォルダがあれば再帰的に処理
-File ファイル
-Directory ディレクトリ

Where-Object で細かく条件を指定することができる。


■サンプル:Grep
				
# フォルダ内のファイルやファイルを指定してGrep
# Select-String "検索単語" ファイル
Select-String "div" C:\work\*.html

# 指定フォルダ内の全ファイルに対してGrep
# Get-ChildItem フォルダ -Filter ファイル -Recurse | Select-String "検索単語"
Get-ChildItem C:\work -Filter *.html -Recurse | Select-String "div"

# Select-String で複数指定(or)する場合、カンマで区切ります
Get-ChildItem C:\work -Filter *.html -Recurse | Select-String "div","br"

# Select-String で複数指定(and)する場合、パイプラインで結合します
Get-ChildItem C:\work -Filter *.txt -Recurse | Select-String "123" | Select-String -NotMatch "abc"

# Grepして結果のファイル名のみを出力
Get-ChildItem C:\work -Filter *.html -Recurse | Select-String "div" | Select-Object path | Split-Path -Leaf | Select-Object -Unique


			

■サンプル:zip圧縮、解凍
				
# ファイル指定で圧縮
Compress-Archive -Path C:\work\tmp\a.txt -DestinationPath C:\work\b.zip

# ワイルドカード指定で圧縮
Compress-Archive -Path C:\work\tmp\*.txt -DestinationPath C:\work\b.zip

# フォルダ指定で圧縮
Compress-Archive -Path C:\work\tmp -DestinationPath C:\work\b.zip

# 解凍
Expand-Archive -Path C:\work\b.zip -DestinationPath C:\work\c

			
-Path で元ファイル(フォルダ)指定、-DestinationPathで先ファイル(フォルダ)指定。強制的に上書く場合、-Force を付けます。

■サンプル:外部ファイル実行

#外部ファイルを実行
Start-Process "C:\tmp\appp.log"

#コマンドラインオプション指定
Start-Process -FilePath "C:\Program Files (x86)\sakura\sakura.exe" -ArgumentList "-Y=10","C:\tmp\appp.log"

#終了を待つ
Start-Process "C:\tmp\appp.log" -Wait

#ウィンドウを最大化
Start-Process "C:\tmp\appp.log" -WindowStyle Maximized

-WindowStyleは以下の指定ができます。
オプション 説明
Maximized 最大化
Minimized 最小化
Hidden バックグランドで実行


■サンプル:実行スクリプトファイルのパスの取得

#実行スクリプトファイルのパス
$PSCommandPath

#実行スクリプトファイルがおいてあるフォルダ
$PSScriptRoot



ページのトップへ戻る