简体   繁体   中英

Run Powershell with argument using Invoke-Command

I am trying run the power shell script on the remote computer, but its not working. tried below two option its fails.

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

Method 2:

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

$result =Invoke-Command  -Session $Session  -script $script

How can I run this script on remote computer?

Thanks SR

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"

This is the function I normally use to send remote commands to users computers on our domain. Wrote it so I don't have to remember how to do the Invoke-Command syntax correctly :) My only thought is that i'm not sure if this would work with a script, but it does work with one liners. Up to you if you want to give it a go! Good luck.

After removing special character from the script, below code worked.

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

$result =Invoke-Command  -Session $Session  -script $script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM