Help us understand the problem. What is going on with this article?

PowerShellでExcelを開始し、終了する

More than 1 year has passed since last update.

開始

Excelがすでに起動している場合はそのプロセスを使用します。
プロセスにExcelが存在しない場合は、新たに起動します。

# プロセス中にExcelが存在するか調べる。
$existsExcel = $false
foreach($process in Get-Process) {
    if ($process.ProcessName -eq "EXCEL") {
        $existsExcel = $true
        Break
    }
}
# Excelプロセスを起動または取得。
$excel = $null
if ($existsExcel) {
    $excel = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application")
} else {
    $excel = New-Object -ComObject Excel.Application
}
$excel.Visible = $true
$excel.Workbooks.Add()

終了

最後にGCを走らせた時点で、プロセスが開放されます。
Quitせずにブックを開きっぱなしにする場合でも、$nullの代入とGCを走らせておきます。
さもないと、Excelの閉じるボタンでアプリケーションを終了した後でも、Excelがプロセスに残り続ける場合があります。

$excel.Quit()
$excel = $null
[System.GC]::Collect() # GC実行
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away