Call PowerShell script PS1 from another PS1 script inside Powershell ISE

后端 未结 11 1058
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 15:27

I want call execution for a myScript1.ps1 script inside a second myScript2.ps1 script inside Powershell ISE.

The following code inside MyScript2.ps1, works fine from

相关标签:
11条回答
  • 2020-12-12 15:56

    The current path of MyScript1.ps1 is not the same as myScript2.ps1. You can get the folder path of MyScript2.ps1 and concatenate it to MyScript1.ps1 and then execute it. Both scripts must be in the same location.

    ## MyScript2.ps1 ##
    $ScriptPath = Split-Path $MyInvocation.InvocationName
    & "$ScriptPath\MyScript1.ps1"
    
    0 讨论(0)
  • 2020-12-12 15:59

    One line solution:

    & ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")
    
    0 讨论(0)
  • 2020-12-12 16:03

    To execute easily a script file in the same folder (or subfolder of) as the caller you can use this:

    # Get full path to the script:
    $ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))
    
    # Execute script at location:
    &"$ScriptRoute"
    
    0 讨论(0)
  • 2020-12-12 16:07

    This is just additional info to answers in order to pass argument into the another file

    Where you expect argument

    PrintName.ps1

    Param(
        [Parameter( Mandatory = $true)]
        $printName = "Joe"    
    )
    
    
    Write-Host $printName
    

    How to call the file

    Param(
        [Parameter( Mandatory = $false)]
        $name = "Joe"    
    )
    
    
    & ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name
    

    If you do not do not provide any input it will default to "Joe" and this will be passed as argument into printName argument in PrintName.ps1 file which will in turn print out the "Joe" string

    0 讨论(0)
  • 2020-12-12 16:08

    I had a problem with this. I didn't use any clever $MyInvocation stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax. My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts. When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...

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