繁体   English   中英

PowerShell 2.0-与ISE相比,命令行调用运行脚本

[英]PowerShell 2.0 - Running scripts for the command line call vs. from the ISE

从ISE中编写部署脚本后,我们需要我们的持续集成 (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。

没有答案,只有一个音符。

我搜索了-file参数的解释。 大多数资料只说“执行脚本文件”。 http://technet.microsoft.com/zh-cn/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对文件进行Get-Foo并进行检查。 有机会起作用:)

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

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参数

    将输出“失败”,然后输出“成功”(即未捕获)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM