使用Invoke-Command运行带有参数的Powershell



我正在尝试在远程计算机上运行Power Shell脚本,但它不起作用。 尝试以下两个选项失败。

Invoke-Command  -Session $Session -FilePath "c:ConfigureRemotingForAnsible.ps1 -CertValidityDays 3650 -EnableCredSSP  -Verbose"

方法2:

$script = [scriptblock]::Create("c:ConfigureRemotingForAnsible.ps1 -CertValidityDays 3650 -EnableCredSSP  -Verbose")
$result =Invoke-Command  -Session $Session  -script $script

如何在远程计算机上运行此脚本?

谢谢锶

function Send-RemoteCommand
{
    [CmdletBinding()]
    Param
    (
    [Parameter(Position = 0, Mandatory = $true,ValueFromPipeline=$True,HelpMessage="Computer Name to run command on.")]
    [String]$ComputerName,
    [Parameter(Position = 1, Mandatory = $true,ValueFromPipeline=$false,HelpMessage="Command to be ran on remote computer.")]
    [String]$Command
    )
    Invoke-Command -ComputerName $ComputerName -ScriptBlock {param($Arg) Invoke-Expression -Command $Arg} -ArgumentList "$Command"
}
Send-RemoteCommand -ComputerName "ComputerNameHere" -Command "YourPowerShellCommandsHere"

这是我通常用于向我们域上的用户计算机发送远程命令的功能。写了它,所以我不必记住如何正确执行调用命令语法:)我唯一的想法是,我不确定这是否适用于脚本,但它确实适用于一行。如果你想试一试,由你决定!祝你好运。

从脚本中删除特殊字符后,下面的代码起作用了。

$script = [scriptblock]::Create("c:ConfigureRemotingForAnsible.ps1 -CertValidityDays 3650 -EnableCredSSP  -Verbose")
$result =Invoke-Command  -Session $Session  -script $script

最新更新