Call PowerShell script PS1 from another PS1 script inside Powershell ISE

后端 未结 11 1088
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  猫巷女王i
    2020-12-12 15:47

    In order to find the location of a script, use Split-Path $MyInvocation.MyCommand.Path (make sure you use this in the script context).

    The reason you should use that and not anything else can be illustrated with this example script.

    ## ScriptTest.ps1
    Write-Host "InvocationName:" $MyInvocation.InvocationName
    Write-Host "Path:" $MyInvocation.MyCommand.Path
    

    Here are some results.

    PS C:\Users\JasonAr> .\ScriptTest.ps1
    InvocationName: .\ScriptTest.ps1
    Path: C:\Users\JasonAr\ScriptTest.ps1
    
    PS C:\Users\JasonAr> . .\ScriptTest.ps1
    InvocationName: .
    Path: C:\Users\JasonAr\ScriptTest.ps1
    
    PS C:\Users\JasonAr> & ".\ScriptTest.ps1"
    InvocationName: &
    Path: C:\Users\JasonAr\ScriptTest.ps1
    

    In PowerShell 3.0 and later you can use the automatic variable $PSScriptRoot:

    ## ScriptTest.ps1
    Write-Host "Script:" $PSCommandPath
    Write-Host "Path:" $PSScriptRoot
    
    PS C:\Users\jarcher> .\ScriptTest.ps1
    Script: C:\Users\jarcher\ScriptTest.ps1
    Path: C:\Users\jarcher
    

提交回复
热议问题