【PowerShell:リファレンス&使用例】Set-Contentコマンドレット
PowerShellのコマンドレット「Set-Content」
説明
新しいコンテンツを書き込むか、ファイル内の既存のコンテンツを置き換えます。
書式
・構文
Set-Content
[-Path] <string[]>
[-Value] <Object[]>
[-PassThru]
[-Filter <string>]
[-Include <string[]>]
[-Exclude <string[]>]
[-Force]
[-Credential <pscredential>]
[-WhatIf]
[-Confirm]
[-NoNewline]
[-Encoding <Encoding>]
[-AsByteStream]
[-Stream <string>]
[<CommonParameters>]
エイリアス
sc
使用例
使用例①今日の日付(get-dateの出力結果)をテキストファイルに出力します。
PS C:\temp> get-date|Set-Content -Path "c:\temp\today.txt" PS C:\temp> PS C:\temp> more today.txt 2022/12/04 13:45:47 PS C:\temp>
使用例②拡張子を指定してファイルを空にする
ディレクトリ内の拡張子を指定してファイルを全てクリア(空ファイル)にするには以下のようにします。
PS C:\temp> Set-Content -Path "c:\temp\*" -Filter "*.log" -value $null PS C:\temp> PS C:\temp> ls *.log ディレクトリ: C:\temp Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2022/12/04 15:08 0 file01.log -a---- 2022/12/04 15:08 0 file02.log -a---- 2022/12/04 15:08 0 file03.log
Set-Contentはファイルに上書きしますが、ファイルに追加出力したい場合はAdd-Contentを使用します。


