<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PowerShell &#8211; REONTOSANTA</title>
	<atom:link href="https://knowledge.reontosanta.com/archives/category/powershell/feed" rel="self" type="application/rss+xml" />
	<link>https://knowledge.reontosanta.com</link>
	<description>Collection of personal knowledge</description>
	<lastBuildDate>Mon, 16 Nov 2026 16:23:53 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/knowledge.reontosanta.com/wp-content/uploads/2026/11/cropped-favicon-cat-black-tsum-512.png?fit=32%2C32&#038;ssl=1</url>
	<title>PowerShell &#8211; REONTOSANTA</title>
	<link>https://knowledge.reontosanta.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<atom:link rel='hub' href='https://knowledge.reontosanta.com/?pushpress=hub'/>
<site xmlns="com-wordpress:feed-additions:1">83369280</site>	<item>
		<title>PowerShellでテキストファイル内の文字列置換</title>
		<link>https://knowledge.reontosanta.com/archives/1929</link>
					<comments>https://knowledge.reontosanta.com/archives/1929#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 16:23:50 +0000</pubDate>
				<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://knowledge.reontosanta.com/?p=1929</guid>

					<description><![CDATA[PowerShellでテキストファイル内の文字列を置換する方法を紹介する。基本の置換、同じファイルへの上書き、複数置換、正規表現とリテラル置換の違い、大文字小文字の区別、エンコーディングの注意点を示す。]]></description>
										<content:encoded><![CDATA[<p>PowerShellでテキストファイル内の特定の文字列を置換する方法について。</p>
<p>入力ファイル「input.txt」内に存在する文字列「foo」を全て「bar」に置換して、出力ファイル「output.txt」に出力する。</p>
<p>出力ファイル「output.txt」が既に存在する場合は、上書き保存される。</p>
<p>バッチファイルによる方法では、空行が消えるなどの制限があった。PowerShell では空行を含めてそのまま処理できる。バッチファイル版は以下を参照。<br />
https://knowledge.reontosanta.com/archives/816</p>
<h2>基本の置換</h2>
<p>[Get-Content]でファイルを読み込み、[-replace]演算子で置換して、[Set-Content]で出力する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">(Get-Content input.txt) -replace 'foo', 'bar' | Set-Content output.txt</pre><p></p>
<p>Get-Content はファイルを行ごとの文字列として読み込み、-replace は各行に対して置換を行う。</p>
<h2>同じファイルへ上書きする</h2>
<p>出力先に入力ファイルと同じファイルを指定すると、置換結果でそのまま上書きできる。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">(Get-Content input.txt) -replace 'foo', 'bar' | Set-Content input.txt</pre><p></p>
<p>Get-Content を括弧で囲むことが重要である。括弧により読み込みが完了してから書き込みが始まるため、読み込み途中のファイルへ書き込んでしまうことがない。</p>
<h2>複数の置換を続けて行う</h2>
<p>-replace は続けて書くことで、複数の置換を順に行える。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">(Get-Content input.txt) -replace 'foo', 'bar' -replace 'hoge', 'fuga' | Set-Content output.txt</pre><p></p>
<h2>正規表現とそのままの文字列の置換</h2>
<p>-replace の置換前文字列は正規表現として解釈される。たとえば「.」は任意の1文字に一致するため、意図しない置換が起こる場合がある。</p>
<p>文字列をそのまま置換したい場合は、[regex]::Escape()で置換前文字列をエスケープするか、文字列の Replace メソッドを利用する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># 正規表現として解釈させない場合（Escape）
(Get-Content input.txt) -replace [regex]::Escape('foo.bar'), 'baz' | Set-Content output.txt</pre><p></p><pre class="urvanov-syntax-highlighter-plain-tag"># 文字列変数に対する Replace メソッド
$text = 'foo bar foo'
$text.Replace('foo', 'baz')</pre><p></p>
<p>Replace メソッドは文字列をそのまま検索し、大文字と小文字を区別する。</p>
<h2>大文字と小文字を区別する</h2>
<p>-replace は既定では大文字と小文字を区別しない。区別する場合は [-creplace] 演算子を利用する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">(Get-Content input.txt) -creplace 'Foo', 'bar' | Set-Content output.txt</pre><p></p>
<p>この例では「Foo」だけが置換され、「foo」や「FOO」は置換されない。</p>
<h2>エンコーディングの注意</h2>
<p>日本語を含むファイルを扱う場合は、エンコーディングに注意する。</p>
<p>PowerShell 5.1 では、Set-Content の既定のエンコーディングは ASCII であり、日本語は文字化けする。読み込みと書き出しの両方に [-Encoding Default]（日本語環境では Shift_JIS）を指定すること。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">(Get-Content -Encoding Default input.txt) -replace 'foo', 'bar' | Set-Content -Encoding Default output.txt</pre><p></p>
<p>PowerShell 7 では既定のエンコーディングが UTF-8（BOMなし）に変わっている。扱うファイルの文字コードに合わせて -Encoding を指定すること。</p>
<h2>まとめ</h2>
<p>PowerShell では、Get-Content と -replace と Set-Content の組み合わせで、テキストファイル内の文字列置換を1行で行える。バッチファイルによる方法にあった空行や行頭記号の制限もない。</p>
<p>バッチファイル版の記事はこちら。<br />
https://knowledge.reontosanta.com/archives/816</p>
]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/1929/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1929</post-id>	</item>
		<item>
		<title>PowerShellでExcelを操作する</title>
		<link>https://knowledge.reontosanta.com/archives/1902</link>
					<comments>https://knowledge.reontosanta.com/archives/1902#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Mon, 16 Nov 2026 03:38:14 +0000</pubDate>
				<category><![CDATA[PowerShell]]></category>
		<guid isPermaLink="false">https://knowledge.reontosanta.com/?p=1902</guid>

					<description><![CDATA[PowerShellからCOM経由でExcelを操作する方法を紹介する。起動と終了、ブックの開閉、セルの値の設定・取得・検索、ブックの保存までをサンプルコードで示す。]]></description>
										<content:encoded><![CDATA[<p>PowerShellでExcelを操作することができる。</p>
<p>VBScript は Windows 11 バージョン 24H2 以降で非推奨となり、将来の Windows では削除される予定である。VBScript で行っていた Excel の自動化は、PowerShell からも COM 経由で同様に実現できる。</p>
<p>なお、PowerShell スクリプト（拡張子 .ps1）は実行ポリシーによって実行が制限される場合がある。環境に応じて事前に実行ポリシーを確認すること。</p>
<p>VBScript 版は以下を参照。<br />
https://knowledge.reontosanta.com/archives/838</p>
<h2>Excelの起動と終了</h2>
<p>Excelを起動して、終了するには以下のコードで実現できる。</p>
<p>サンプルを実行するとExcelが起動して、3秒後に終了する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --Excel終了
    $excel.Quit()
    # --Excelオブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>新しいブックを開く</h2>
<p>起動したExcelで新しいブックを開くには、[Application.Workbooks.Add()]を利用する。</p>
<p>サンプルを実行するとExcelが起動して3秒後に新しいブックが開き、さらに3秒後にExcelが終了する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --ブックの追加
    $workbook = $excel.Workbooks.Add()
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --Excel終了
    $excel.Quit()
    # --オブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>既存のブックを開く</h2>
<p>起動したExcelで既存のブックを開くには、[Application.Workbooks.Open()]を利用する。</p>
<p>サンプルを実行するとExcelが起動して3秒後に既存のブック（Test.xlsx）が開き、さらに3秒後にExcelが終了する。</p>
<p>※実行前に[C:]ドライブの直下にファイル名[Test.xlsx]のExcelファイルを用意する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --ブックを開く
    $workbook = $excel.Workbooks.Open("C:\Test.xlsx")
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --Excel終了
    $excel.Quit()
    # --オブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>セルに値を設定</h2>
<p>セルに値を設定する方法は、Range指定とCells指定の2通りが存在する。</p>
<p>サンプルを実行するとExcelが起動して3秒後に新しいブックが開き、A1セルに&#8221;aaa&#8221;、C2セルに&#8221;100&#8243;が入力され、さらに3秒後にExcelが終了する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --Excelの警告を非表示にする
    $excel.DisplayAlerts = $false
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --ブック追加
    $workbook = $excel.Workbooks.Add()
    # --シート選択
    $sheet = $workbook.Worksheets.Item(1)
    # --A1のセルに値を設定
    $sheet.Range("A1").Value = "aaa"
    # --行が2、列が3のセルに値を設定
    $sheet.Cells.Item(2, 3).Value = 100
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --Excel終了
    $excel.Quit()
    # --オブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($sheet) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>セルの値を取得</h2>
<p>セルの値を取得する方法は、Range指定とCells指定の2通りが存在する。</p>
<p>サンプルを実行するとExcelが起動して3秒後に既存のブックが開き、A1セル、C2セルの値がコンソールに表示され、さらに3秒後にExcelが終了する。</p>
<p>※実行前に[C:]ドライブの直下にファイル名[Test.xlsx]のExcelファイルを用意して、A1セル、C2セルに値を設定しておく。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --Excelの警告を非表示にする
    $excel.DisplayAlerts = $false
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --ブックを開く
    $workbook = $excel.Workbooks.Open("C:\Test.xlsx")
    # --シート選択
    $sheet = $workbook.Worksheets.Item(1)
    # --A1のセルの値を取得
    Write-Host "A1セル：$($sheet.Range("A1").Value)"
    # --行が2、列が3のセルの値を取得
    Write-Host "C2セル：$($sheet.Cells.Item(2, 3).Value)"
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --Excel終了
    $excel.Quit()
    # --オブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($sheet) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>セルの値の検索</h2>
<p>[Worksheets.Cells.Find()]を利用することで、値の検索が可能となる。</p>
<p>サンプルを実行するとExcelが起動して3秒後に既存のブックが開き、値（&#8221;100&#8243;）が入力されているセルの行と列がコンソールに表示され、さらに3秒後にExcelが終了する。</p>
<p>※実行前に[C:]ドライブの直下にファイル名[Test.xlsx]のExcelファイルを用意して、C2セルに値（&#8221;100&#8243;）を設定しておく。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --Excelの警告を非表示にする
    $excel.DisplayAlerts = $false
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --ブックを開く
    $workbook = $excel.Workbooks.Open("C:\Test.xlsx")
    # --シート選択
    $sheet = $workbook.Worksheets.Item(1)
    # --セルの値を検索
    $range = $sheet.Cells.Find("100")
    if ($null -eq $range) {
        Write-Host "検索対象が存在しません。"
    }
    else {
        # --セルの位置を表示
        Write-Host "行：$($range.Row)"
        Write-Host "列：$($range.Column)"
        # --検索結果のオブジェクト解放
        [System.Runtime.InteropServices.Marshal]::ReleaseComObject($range) | Out-Null
    }
    # --3秒待つ
    Start-Sleep -Seconds 3
    # --Excel終了
    $excel.Quit()
    # --オブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($sheet) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>ブックを保存する</h2>
<p>編集したブックを保存するには、[Workbook.Save()]で上書き保存、[Workbook.SaveAs()]で名前を付けて保存を行う。</p>
<p>サンプルを実行するとExcelが起動して新しいブックが開き、A1セルに&#8221;aaa&#8221;が入力された状態で、Cドライブの直下にTest.xlsxとして保存され、Excelが終了する。</p>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag"># Excel起動
try {
    $excel = New-Object -ComObject Excel.Application
}
catch {
    # Excel起動失敗（Excelがインストールされていない場合など）
    $excel = $null
}
if ($null -eq $excel) {
    # Excel起動失敗
    Write-Host "Excel起動失敗"
}
else {
    # Excel起動成功
    # --Excel表示（$falseにすると非表示にできる）
    $excel.Visible = $true
    # --Excelの警告を非表示にする
    $excel.DisplayAlerts = $false
    # --ブック追加
    $workbook = $excel.Workbooks.Add()
    # --シート選択
    $sheet = $workbook.Worksheets.Item(1)
    # --A1のセルに値を設定
    $sheet.Range("A1").Value = "aaa"
    # --名前を付けて保存
    $workbook.SaveAs("C:\Test.xlsx")
    # --Excel終了
    $excel.Quit()
    # --オブジェクト解放
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($sheet) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($workbook) | Out-Null
    [System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
}</pre><p></p>
<h2>まとめ</h2>
<p>PowerShell からも VBScript と同様に COM 経由で Excel を操作できる。相違点として、PowerShell では COM オブジェクトの解放（ReleaseComObject）を行わないと Excel のプロセスが残る場合があるため、終了時には解放処理を行うこと。</p>
<p>VBScript 版の記事はこちら。<br />
https://knowledge.reontosanta.com/archives/838</p>
]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/1902/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1902</post-id>	</item>
	</channel>
</rss>
