Submitted By: Kent Finkle

Checks to see if the workbook Inventory.xls is open. If it is not, the script then opens that workbook.

PowerShell
Edit|Remove
comments = @'
Script name: Open-Workbook.ps1
Created on: Thursday, July 05, 2007
Author: Kent Finkle
Purpose: How can I use Windows Powershell to
Tell if an Excel Workbook is Open and, If It Isn’t, Open It?
'@
#-----------------------------------------------------
function Release-Ref ($ref) {
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers() 
}
#-----------------------------------------------------
$objShell = New-Object -comobject "Wscript.Shell"
$objWord = New-Object -comobject Word.Application
$colTasks = $objWord.Tasks
$i = 0
foreach ($objTask in $colTasks) { 
    $strName = $objTask.Name.ToLower()
    If ($strName.contains("inventory.xls")) {
        $i = 1
    }
}
$Cmd = [char]34 + "C:\Program Files\Microsoft Office\OFFICE11\EXCEL.EXE" + [char]34 `
    + " C:\Scripts\Inventory.xls"
If ($i -eq 0) {
    $a = $objShell.Run($Cmd, 3)
}
$a = $objWord.Quit()