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

后端 未结 2 1362
死守一世寂寞
死守一世寂寞 2021-02-06 16:38

After writing deployment scripts from within the ISE, we need our continuous integration (CI) server to be able to run them automatically, i.e. from the command line or via a ba

相关标签:
2条回答
  • 2021-02-06 17:05

    Not an answer, just a note.

    I searched for explanation of -file parameter. Most sources say only "Execute a script file.". At http://technet.microsoft.com/en-us/library/dd315276.aspx I read

    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.
    

    After that I tried to call this:

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

    Note that first two stop after Get-Foo, but the last one doesn't.

    The problem I describe above is related to modules -- if you define Get-Foo inside script.ps1, all the 3 calls I described stop after call to Get-Foo.

    Just try to define it inside the script.ps1 or dotsource the file with Get-Foo and check it. There is a chance it will work :)

    0 讨论(0)
  • 2021-02-06 17:28

    Here is a concrete example of the behaviour I described.

    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"
    } 
    

    Running Script.ps1:

    • From the ISE, or with the -File parameter

      will output "Error occurred" and stop

    • From the command line without the -File parameter

      will output "Failed" followed by "Success" (i.e. not caught)

    0 讨论(0)
提交回复
热议问题