![](https://batch-file.net/wp-content/themes/cocoon-master/images/b-woman.png)
バッチファイルで
・テキストファイルをソート
できます!
![](https://batch-file.net/wp-content/themes/cocoon-master/images/b-woman.png)
バッチファイルから
・Power Shellのコマンドレットを実行
することで実現します!
コード
ここでは例として
・デスクトップ配下のテキストファイル「sample.txt」をソート
します。
![テキストファイル「sample.txt」](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_001.png)
![テキストファイル「sample.txt」の内容(ソートされていない)](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_002.png)
@echo off
rem 対象ファイル
set targetFile=C:\Users\user\Desktop\sample.txt
rem PowerShellのコマンドレットを組み立て(昇順でソート)
set psCommand="(Get-Content %targetFile%) | Sort-Object | Out-File -Encoding default %targetFile%"
rem PowerShellのコマンドレットを組み立て(降順でソート)
rem set psCommand="(Get-Content %targetFile%) | Sort-Object -Descending | Out-File -Encoding default %targetFile%"
rem PowerShellのコマンドレットを実行
powershell -NoProfile -ExecutionPolicy Unrestricted %psCommand%
rem 実行結果を確認
if %errorlevel% == 0 (
echo 正常終了しました。戻り値:%errorlevel%
) else (
echo 異常終了しました。戻り値:%errorlevel%
)
echo.
pause
exit
実行結果
テキストファイルをソートできました。
![実行結果①](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_003.png)
![実行結果②](https://batch-file.net/wp-content/uploads/2022/11/bat_textfile_sort_004.png)
参考①
上記のコードは以下の記事を参考にして作成しました。
参考②
上記で使用した以下の詳細は、公式サイトをご確認ください。
●「Get-Content」コマンドレット
●「Sort-Object」コマンドレット
●「Out-File」コマンドレット