Can't run the same script twice in the same PowerShell session
I am writing a PowerShell script that will open an application, start a process, then close it, then open another application, start a process, and close it. (Ultimately more than two, but I start small.)
I can run the following script, no problem:
# 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 in this above query 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 great if I quit Powershell and reopen Powershell and run it again.
The limitations that are documented primarily include only one Project that can be opened at a time; however, it is clear what $projectObject.Close()
works great because it successfully runs two in one script. It is only when I leave the script and run it again that this is the problem.
Now if I delete $app.Quit()
then it allows me to run it a second time in the same session; but I want to exit the application (to ensure that any next script run does not affect anything, what I just did is a programming environment, so things like setting session macro macros, etc. can have bad implications), I also don't quite understand why the line $app = New-Object ...
doesn't create a new instance of the app (and so why does the question with a previous run of $ app matter)?
Is there something in PowerShell I am doing wrong here? Or is this the only problem with the API I am using, will I have to talk to SAS (vendor)?
source to share