PowerShellでExcelを開く
問題がいくつかある。
1.ファイルをフルパスで指定する必要がある。
2.オブジェクト操作には入力支援が使えない
3.New-Objectに対応するRelease-Objectがない。
エクセルオブジェクトのジャグリングは一度VBAで記述してから
PowerShellに移植するほうが簡単なのかもしれない。
openExcel.ps1
$xlfile = "C:\Users\setsu\powershell\aaa.xlsx"
$xl = New-Object -ComObject Excel.Application
$wb = $xl.Workbooks.Open($xlfile)
$ws = $wb.Worksheets.Item("Alpha")
Write-Host $ws.Cells.Item(1,1).Text
$wb.close()
$xl.quit()
#release-object($xl)
[void][system.runtime.interopservices.marshal]::FinalReleaseComObject($xl)
Release-Objectの代替
Release-Refを定義して使用するか、
function Release-Ref ($ref) {
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) | out-null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
または
[System.Runtime.InteropServices.Marshal]::ReleaseComObject( $ref )
を使用する。
関数はスクリプトの前後に配置して記述してよい。
明示的に呼び出さない限り定義された関数は実行されない。