PowerShell 2.0 - 从ISE运行命令行调用脚本

时间:2010-05-24 03:48:35

标签: command-line powershell scripting psake

在ISE中编写部署脚本之后,我们需要continuous integration(CI)服务器能够自动运行它们,即从命令行或通过批处理文件运行它们。

我注意到以下调用之间存在一些显着差异:

powershell.exe -File Script.ps1
powershell.exe -Command "& '.\Script.ps1'"
powershell.exe .\Script.ps1

一些简单的例子:

  • 使用-File时,错误的处理方式与ISE完全相同。
  • 其他两个调用似乎忽略了$ErrorActionPreference变量,并且在try / catch块中没有捕获Write-Error

使用pSake时:

  • 最后两次通话完美无缺
  • 使用ISE或-File参数将失败,并显示以下错误:

The variable '$script:context' cannot be retrieved because it has not been set


每种语法的含义是什么,以及它们为什么表现不同?理想情况下,我希望找到一种始终有效的语法就像ISE一样。

2 个答案:

答案 0 :(得分:2)

不是答案,只是一张纸条。

我搜索了-file参数的解释。大多数消息来源只说“执行脚本文件”。在http://technet.microsoft.com/en-us/library/dd315276.aspx我读了

Runs the specified script in the local scope ("dot-sourced"), so that the functions
and variables that the script creates are available in the current session. Enter
the script file path and any parameters.

之后我试着称之为:

powershell -command ". c:\temp\aa\script.ps1"
powershell -file c:\temp\aa\script.ps1
powershell -command "& c:\temp\aa\script.ps1"

请注意,前两个在Get-Foo之后停止,但最后一个不停止。

我上面描述的问题与模块有关 - 如果你在script.ps1中定义Get-Foo,我所描述的所有3个调用都会在调用Get-Foo后停止。

尝试在script.ps1中定义它,或者使用Get-Foo对文件进行dotource并检查它。它有可能起作用:)

答案 1 :(得分:0)

以下是我描述的行为的具体示例。

MyModule.psm1

function Get-Foo
{
    Write-Error 'Failed'
}

Script.ps1

$ErrorActionPreference = 'Stop'

$currentFolder = (Split-Path $MyInvocation.MyCommand.Path)
Import-Module $currentFolder\MyModule.psm1

try
{
    Get-Foo 
    Write-Host "Success"
}
catch
{
    "Error occurred"
} 

运行Script.ps1:

  • 来自ISE,或-File参数

      
        

    将输出“发生错误”并停止

      
  • 从没有-File参数的命令行

      
        

    将输出“Failed”,然后输出“Success”(即未捕获)