![](https://powershell.work/wp-content/themes/cocoon-master/images/b-woman.png)
PowerShellで
・テキストファイル内の文字列を置換
できます!
コード
ここでは例として
・デスクトップ配下のテキストファイル「sample.txt」内の
・文字列「(株)」を「株式会社」へ置換
します。
![テキストファイル「sample.txt」](https://powershell.work/wp-content/uploads/2022/09/ps_textfile_replace_001.png)
![テキストファイル「sample.txt」の内容](https://powershell.work/wp-content/uploads/2022/09/ps_textfile_replace_002.png)
# 対象ファイル
$targetFile = "C:\Users\user\Desktop\sample.txt"
# 置換前文字列
$beforeStr = "\(株\)"
# 置換後文字列
$afterStr = "株式会社"
$ws = New-Object -ComObject Wscript.Shell
try
{
(Get-Content $targetFile -ErrorAction Stop) -creplace $beforeStr,$afterStr | Out-File -Encoding default $targetFile
$ws.popup("置換に成功しました。")
}
catch
{
$ws.popup("エラー : " + $PSItem)
}
実行結果
テキストファイル内の文字列を置換できました。
※文字列「(株)」を「株式会社」へ置換できました。
![実行結果①](https://powershell.work/wp-content/uploads/2022/09/ps_textfile_replace_003.png)
![実行結果②](https://powershell.work/wp-content/uploads/2022/09/ps_textfile_replace_004.png)
参考
上記のコードで使用した以下の詳細は、公式サイトをご確認ください。
●「Get-Content」コマンドレット
●Power Shellの演算子「-creplace」
●「Out-File」コマンドレット