我想调用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、函数、脚本文件或可操作程序的名称。检查名称的拼写,或者如果包含了路径,请验证路径是否正确,然后重试。
你可能已经找到了答案,但下面是我要做的。
我通常把这一行放在安装脚本的开头:
if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).
然后我可以使用$PSScriptRoot变量作为当前脚本(路径)的位置,就像下面的例子:
if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).
Try {
If (Test-Path 'C:\Program Files (x86)') {
$ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise64_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x64.log`""
Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
$Result= [System.Environment]::ExitCode
} Else {
$ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x86.log`""
Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
$Result= [System.Environment]::ExitCode
}
} ### End Try block
Catch {
$Result = [System.Environment]::Exitcode
[System.Environment]::Exit($Result)
}
[System.Environment]::Exit($Result)
在你的情况下,你可以替换
起动过程……与
Invoke-Expression PSScriptRoot \ ScriptName.ps1美元
您可以在Microsoft网站https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_automatic_variables上阅读有关$MYINVOCATION和$PSScriptRoot自动变量的更多信息
我提出我的例子供考虑。这就是我如何在我制作的工具中调用控制器脚本中的一些代码。执行此工作的脚本也需要接受参数,因此本示例将展示如何传递参数。它假设被调用的脚本与控制器脚本(进行调用的脚本)在同一个目录中。
[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个参数。当控制器脚本调用执行该工作的脚本时,它需要调用该脚本并传递参数。上面展示了我如何通过飞溅来做到这一点。