0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellでExcelを開く

Posted at

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 )

を使用する。
関数はスクリプトの前後に配置して記述してよい。
明示的に呼び出さない限り定義された関数は実行されない。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?