无法在同一PowerShell会话中两次运行相同的脚本

时间:2017-07-18 15:52:31

标签: powershell sas enterprise-guide

我正在编写PowerShell脚本,该脚本将打开一个应用程序,运行一个进程,然后关闭它,然后打开另一个应用程序,运行一个进程并关闭它。 (最终超过两个,但我从小开始。)

我可以运行以下脚本,没有任何问题:

# 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>

但是,如果我在上面的提示中第二次运行它,而没有退出PowerShell,我会收到错误。

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>

如果我从Powershell退出并重新打开Powershell并再次运行它,它可以正常工作。

记录的限制主要包括一次只能打开一个项目;但是,显然$projectObject.Close()工作正常,因为它确实成功运行了两个一个脚本。只有当我离开剧本并再次运行它才会出现问题。

现在,如果我删除$app.Quit(),那么然后允许我在同一会话中再次运行它;但我想要退出应用程序(以确保脚本的任何后续运行不受我刚刚做的任何事情的影响;这是一个编程环境,所以像设置会话宏变量之类的东西这可能会产生不良影响)。我也不完全理解为什么行$app = New-Object ...没有创建应用程序的新实例(以及为什么之前运行的$ app quit是相关的)?

PowerShell中有什么东西我在这里做错了吗?或者这仅仅是我使用的API的一个问题,我必须与SAS(供应商)交谈?

1 个答案:

答案 0 :(得分:1)

在原始PS会话中,为每个项目创建一个新的PS会话:New-PSSession

可以在Microsoft文档网站here上找到更多详细信息和示例。