我想调用myScript1的执行。第二个myScript2中的ps1脚本。Powershell ISE中的ps1脚本。

下面是MyScript2中的代码。ps1,从Powershell管理工作很好,但不工作在Powershell ISE:

#Call myScript1 from myScript2
invoke-expression -Command .\myScript1.ps1

当我执行MyScript2时,我得到了以下错误。ps1来自PowerShell ISE:

术语“。\myScript1.”Ps1’不能识别为cmdlet、函数、脚本文件或可操作程序的名称。检查名称的拼写,或者如果包含了路径,请验证路径是否正确,然后重试。


当前回答

我调用myScript1。来自myScript2的ps1。ps1。

假设两个脚本都在相同的位置,首先使用以下命令获取脚本的位置:

$PSScriptRoot

然后,像这样追加你想调用的脚本名称:

& "$PSScriptRoot\myScript1.ps1"

这应该有用。

其他回答

要轻松地执行与调用者相同文件夹(或子文件夹)中的脚本文件,您可以使用以下命令:

# Get full path to the script:
$ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))

# Execute script at location:
&"$ScriptRoute"

我提出我的例子供考虑。这就是我如何在我制作的工具中调用控制器脚本中的一些代码。执行此工作的脚本也需要接受参数,因此本示例将展示如何传递参数。它假设被调用的脚本与控制器脚本(进行调用的脚本)在同一个目录中。

[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Computername,

[Parameter(Mandatory = $true)]
[DateTime]
$StartTime,

[Parameter(Mandatory = $true)]
[DateTime]
$EndTime
)

$ZAEventLogDataSplat = @{
    "Computername" = $Computername
    "StartTime"    = $StartTime
    "EndTime"      = $EndTime
}

& "$PSScriptRoot\Get-ZAEventLogData.ps1" @ZAEventLogDataSplat

上面是一个接受3个参数的控制器脚本。这些在参数块中定义。然后控制器脚本调用名为Get-ZAEventLogData.ps1的脚本。举例来说,这个脚本也接受相同的3个参数。当控制器脚本调用执行该工作的脚本时,它需要调用该脚本并传递参数。上面展示了我如何通过飞溅来做到这一点。

还可以使用以下命令:

$Patch = Join-Path -Path $PSScriptRoot -ChildPath "\patch.ps1"<br>
Invoke-Expression "& `"$Patch`""

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...

一句话解决方案:

& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")