调用命令并使用参数运行 ps1

2024-03-06

我正在尝试使用 invoke-command 运行脚本来安装端点防御程序以及一些相关参数。

如果我使用 invoke-command 运行标准 ps1,它可以正常工作。但是,如果我运行以下命令:

Invoke-Command -ComputerName NAME -FilePath \\srv\share\install.ps1 -OnboardingScript \\srv\share\WindowsDefenderATPonboardingscript.cmd -Passive

我收到“找不到与参数名称“OnboardingScript”匹配的参数”。有人可以帮助我了解如何调用命令并运行带参数的脚本吗?

install.Ps1 文件中已定义参数

https://github.com/microsoft/mdefordownlevelserver/blob/main/Install.ps1 https://github.com/microsoft/mdefordownlevelserver/blob/main/Install.ps1


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:

  • (a) 要求目标脚本支持所有感兴趣的参数的位置参数绑定...

  • (b) ...这明显阻止了通过switch参数(类型[switch]), 例如-Passive在你的通话中。

  • (c) 要求您以正确的顺序传递不变的位置参数。


解决方法:

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参数,它本质上使用相同的技术,在幕后将源代码而不是文件复制到远程会话。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调用命令并使用参数运行 ps1 的相关文章

随机推荐