从 Powershell ISE 中的另一个 PS1 脚本调用 PowerShell 脚本 PS1 [英] Call PowerShell script PS1 from another PS1 script inside Powershell ISE
问题描述
我想在 Powershell ISE 内的第二个 myScript2.ps1 脚本中调用执行 myScript1.ps1 脚本.
MyScript2.ps1 中的以下代码在 Powershell Administration 中工作正常,但在 PowerShell ISE 中不起作用:
#从 myScript2 调用 myScript1调用表达式 -Command .\myScript1.ps1
当我从 PowerShell ISE 执行 MyScript2.ps1 时出现以下错误:
<块引用>术语.\myScript1.ps1"未被识别为 cmdlet、函数、脚本文件或可运行程序的名称.检查名称的拼写,如果包含路径,请验证路径是否正确,然后重试.
为了找到脚本的位置,使用 Split-Path $MyInvocation.MyCommand.Path
(确保你使用这个在脚本上下文中).
这个示例脚本可以说明您应该使用它而不是其他任何东西的原因.
## ScriptTest.ps1写主机调用名称:"$MyInvocation.InvocationName写主机路径:"$MyInvocation.MyCommand.Path
这是一些结果.
<前>PS C:\Users\JasonAr> .\ScriptTest.ps1调用名称:.\ScriptTest.ps1路径:C:\Users\JasonAr\ScriptTest.ps1PS C:\Users\JasonAr> ..\ScriptTest.ps1调用名称:.路径:C:\Users\JasonAr\ScriptTest.ps1PS C:\Users\JasonAr> & ".\ScriptTest.ps1"调用名称:&路径:C:\Users\JasonAr\ScriptTest.ps1在 PowerShell 3.0 及更高版本中,您可以使用自动变量 $PSScriptRoot
:
## ScriptTest.ps1写主机脚本:"$PSCommandPath写主机路径:"$PSScriptRoot
<前>PS C:\Users\jarcher> .\ScriptTest.ps1脚本:C:\Users\jarcher\ScriptTest.ps1路径:C:\Users\jarcher
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 Powershell Administration, but doesn't work inside PowerShell ISE:
#Call myScript1 from myScript2
invoke-expression -Command .\myScript1.ps1
I obtain the following error when I execute MyScript2.ps1 from PowerShell ISE:
The term '.\myScript1.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
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
这篇关于从 Powershell ISE 中的另一个 PS1 脚本调用 PowerShell 脚本 PS1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!