https://soma-engineering.com/coding/powershell/text-file-handling/2018/07/08/#st-toc-h-8
想定シナリオ:
エクセルからデータを取得し、すべての列をスペースで連結してテキストファイルに書き込む
# テスト用ファイル作成
$excel = new-object -com excel.application
$excel.Visible = $false
$excel.DisplayAlerts = $false
$wb1 = $excel.workbooks.add()
$wb1.worksheets(1).cells(1,1) = "col1"
$wb1.worksheets(1).cells(1,2) = "col2"
$wb1.worksheets(1).cells(1,3) = "col3"
for($i=1;$i -le 10;$i++){
$wb1.worksheets(1).cells($i+1,1) = "A"+$i
$wb1.worksheets(1).cells($i+1,2) = "あ"+$i
$wb1.worksheets(1).cells($i+1,3) = $i
}
$wb1.SaveAs("H:\tmp\a.xlsx")
[void]$wb1.close()
# ファイル出力
$f1 = "H:\tmp\b.txt"
$wb2 = $excel.Workbooks.Open("H:\tmp\a.xlsx")
$ws2 = $wb2.Sheets(1)
$i=2
while ($ws2.cells($i,1).Value() -ne $null) {
$tmp = $ws2.cells($i,1).Value()+" "+$ws2.cells($i,2).Value()+" "+$ws2.cells($i,3).Value()
Write-Output $tmp | Out-File -FilePath $f1 -Append
$i++
}
# 出力ファイル確認
Get-Content -Path $f1
$i=1
foreach ($l in Get-Content -Path $f1) {
Write-Host $i : $l
$i++
}
# Excel の終了 変数の破棄
[void]$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb1)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($wb2)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ws2)