Cannot run same script twice in same PowerShell session

Viewed 836

I'm writing a PowerShell script that will open an application, run a process, then close it, and then open another application, run a process, and close it. (Ultimately more than two, but I'm starting small.)

I can run the following script, with no issues:

# Project Config
$projectName = "c:\temp\test3.egp"
$projectName2= "c:\temp\test4.egp"

# Start Enterprise Guide
$app = New-Object -ComObject SASEGObjectModel.Application.7.1

#Open the Enterprise Guide Project
$projectObject = $app.Open($projectName, "")

# Save the Enterprise Guide Project
$projectObject.Save()

# Close the Enterprise Guide Project
$projectObject.Close()

# Open the second project
$projectObject = $app.Open($projectName2, "")

# Save the second project
$projectObject.Save()

#Close the second project
$projectObject.Close()

# Quit Enterprise Guide
$app.Quit()

PS C:\temp> ./test.ps1
PS C:\temp>

However, if I run it a second time at that above prompt, without exiting PowerShell, I get errors.

PS C:\temp> ./test.ps1
Exception calling "Open" with "2" argument(s): "Path is not a directory 'C:': The filename, directory name, or volume label syntax is incorrect."
At C:\temp\test.ps1:9 char:27
    + $projectObject = $app.Open <<<< ($projectName, "")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation
... more errors related to $projectObject not having a value, and then a second copy of each of these for the second attempt ... 

PS C:\temp>

It works fine if I exit from Powershell, and reopen Powershell, and run it again.

Restrictions that are documented primarily include only one Project being able to be opened at one time; however, clearly $projectObject.Close() works fine, because it does successfully run two in one script. It's only when I've left the script and run it again that it's a problem.

Now, if I remove $app.Quit(), it then allows me to run it a second time in the same session; but I do want to quit the app (to ensure that any following run of the script isn't impacted by anything I just did; this is a programming environment, so things like setting session macro variables and such could have bad impacts). I also don't entirely understand why the line $app = New-Object ... doesn't create a new instance of the application (and so why the prior run's $app quit is relevant)?

Is there something in PowerShell I am doing wrong here? Or is this solely an issue with the API I'm using that I'll have to talk to SAS (the vendor)?

1 Answers

Inside your original PS session create a new PS session for each project: New-PSSession

More details and examples can be found on the Microsoft docs site here.

Related