Your Invoke-Command https://learn.microsoft.com/powershell/module/microsoft.powershell.core/invoke-command呼叫有一个语法问题, as 圣地亚哥·斯夸松 https://stackoverflow.com/users/15339544/santiago-squarzon指出:
Any 直通论点- 路径被传递到的脚本可以看到的那些-FilePath
- 必须通过指定-ArgumentList
(-Args
) 参数,作为array.
# Simplified example with - of necessity - *positional* arguments only.
# See below.
Invoke-Command -ComputerName NAME -FilePath .\foo.ps1 -Args 'bar', 'another arg'
The 同样适用到使用脚本块的更常见的调用形式({ ... }
),通过(可能位置隐含)-ScriptBlock
范围.
然而,有一个问题:Only 位置性的参数可以这样传递, which:
解决方法:
Use a -ScriptBlock
基于调用,它允许常规参数传递并支持通常的named参数(包括开关):
- 如果像您的情况一样,脚本文件是也可通过远程会话可见的 UNC 路径访问,你可以简单地调用它从远程脚本块内部.
- 注意:您的情况不需要,但您通常可能需要$using:参考 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes#the-using-scope-modifier为了合并来自的值local会话到参数中 - 请参阅下面的示例。
Invoke-Command -ComputerName NAME {
& \\srv\share\install.ps1 -OnboardingScript \\srv\share\WindowsDefenderATPonboardingscript.cmd -Passive
}
-
否则(通常,一个脚本文件对于调用者来说是本地的):
Use a $using:
参考通过content将脚本文件(源代码)发送到远程会话,将其解析为脚本块,然后使用感兴趣的参数执行该脚本块:
$scriptContent = Get-Content -Raw \\srv\share\install.ps1
Invoke-Command -ComputerName NAME {
& ([scriptblock]::Create($using:scriptContent)) -OnboardingScript \\srv\share\WindowsDefenderATPonboardingscript.cmd -Passive
}
小警告:由于执行了原始脚本文件的源代码在记忆中在远程会话中,file- 相关的反射信息将不可用,例如报告脚本文件的完整路径和目录路径的自动变量($PSCommandPath
and $PSScriptRoot
).
也就是说,这同样适用于使用-FilePath
参数,它本质上使用相同的技术,在幕后将源代码而不是文件复制到远程会话。