簡體   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