hakeの日記

Windows環境でプログラミングの勉強をしています。

PowerShell - Excelの操作

EXCEL用のCOMオブジェクトを作成して、あとはVBAと同じ感覚で操作できるっぽいです。
一点、配列やコレクションの括弧の形状がVBAだと( )ですが、[ ]にしないとメソッドと間違えられてエラーになるので注意。

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true

$book = $excel.Workbooks.Add()
$sht = $excel.Worksheets[1] # 括弧の形状に注意
$sht.Name = "PowerShell"

$sht.Cells(1,1).Value = "Hello World"
$sht.Range("A2").Value = "PowerShell"


$book.Save()
$book.Close()
$excel.Quit()

プロセスの解放

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

または

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($sht)