PowerShellからエクセルを操作

【改訂新版】 Windows PowerShell ポケットリファレンス

【改訂新版】 Windows PowerShell ポケットリファレンス

エクセルの内容を取得、ファイルへ出力

write "start script"

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$book = $excel.Workbooks.Open("C:\Users\xxxx\ps_test\sample.xlsx")
$sheet = $excel.Worksheets.Item(1)

# 件数取得
$dataCount = 0
#for($i=2; $i -lt 100000 ;$i++){
#    if($sheet.Cells.Item($i,2).Text -eq ""){
#        break;
#    }
#    $dataCount++;
#}
$dataCount = $sheet.UsedRange.Rows.Count

# シートを参照
$lines= @()

for($i=2 ;$i -lt 100000 ;$i++){

    $per = (($i - 2) / $dataCount * 100)
    $per = [int]$per
    write $per
    Write-Progress -Activity "データチェック" -PercentComplete $per -CurrentOperation "$per % 完了"
    Start-Sleep -Milliseconds 10

    $text1 = $sheet.Cells.Item($i,2).Text
    if($text1 -eq ""){
        break;
    } 

    $text2 = $sheet.Cells.Item($i,3).Text
    $text3 = $text1 + $text2
    #write $text3
    $lines += $text3 
}

# ファイル出力(スクリプトのパスへ出力)
$outputDir = Split-Path $MyInvocation.MyCommand.Path -Parent 
$outputPath = Join-Path $outputDir read-result.txt
$outLines = $lines -join "`r`n"
sc -Path $outputPath -Value $outLines -Encoding Utf8

$excel.Quit()
$excel = $null
[GC]::Collect()

write "end script"