在 PowerShell ISE 中从另一个 PS1 脚本中调用 PowerShell 脚本 PS1
在 PowerShell ISE 中从另一个 PS1 脚本中调用 PowerShell 脚本 PS1
我想在PowerShell ISE中执行一个名为myScript2.ps1的脚本,其中包含另一个名为myScript1.ps1的脚本的调用。
以下代码在PowerShell Administration中从MyScript2.ps1中调用myScript1.ps1可以正常工作,但在PowerShell ISE中无法正常工作:
#Call myScript1 from myScript2 invoke-expression -Command .\myScript1.ps1
在PowerShell ISE中执行MyScript2.ps1时,我得到了以下错误提示:
无法识别“.\\myScript1.ps1”作为命令、函数、脚本文件或可执行程序的名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
admin 更改状态以发布 2023年5月23日
为了找到脚本的位置,使用Split-Path $MyInvocation.MyCommand.Path
(确保在脚本上下文中使用)。
你应该使用这个而不是其他任何东西可以通过这个示例脚本说明。
## ScriptTest.ps1 Write-Host "InvocationName:" $MyInvocation.InvocationName Write-Host "Path:" $MyInvocation.MyCommand.Path
以下是一些结果。
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
在PowerShell 3.0及更高版本中,可以使用自动变量$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