使用PowerShell在Scriptblock中调用Command到远程会话计算机

时间:2017-08-22 19:31:33

标签: powershell invoke-command

有人可以提供以下代码无效的原因吗?之前我有这个工作,并且无法理解为什么New-PSSession无法验证ComputerName参数。完全错误下面的代码。

$Cred = Get-Credential DOMAIN\User

    # $TargetSession = Get-Content C:\Users\user\Downloads\tablets.txt

    $computers = gc 'C:\Users\user\Downloads\tablets.txt'

    foreach ($computer in $computers) {

            #Creates a new remote PowerShell Session and script block - enter the code you want to execute remotely from this block 
            $Session = New-PSSession $computer -Credential $cred {

                Invoke-Command -Session $Session -ScriptBlock {

                Start-Process “C:\windows\system32\notepad.exe”


            } 

            Remove-PSSession -Session $Session
        }
    }

退货输出:

New-PSSession : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\user\Desktop\invoke-command-script.ps1:21 char:34
+         $Session = New-PSSession $computers -Credential $cred {
+                                  ~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [New-PSSession], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewPSSessionCommand

先谢谢

1 个答案:

答案 0 :(得分:0)

我已经修复了问题 - 它是脚本块中{}的不必要的嵌套。以下代码有效:

$cred = Get-Credential DOMAIN\Admin

    # $TargetSession = Get-Content C:\Users\user\Downloads\tablets.txt

    $computers = Get-Content C:\Users\rh.admin\Downloads\tablets.txt | Where-Object { $_ } 




    foreach ($computer in $computers)

        {
            #Creates a new remote PowerShell Session and script block - enter the code you want to execute remotely from this block 
            $Session = New-PSSession $computer -Credential $cred

                Invoke-Command -Session $Session -ScriptBlock {

                Start-Process “C:\windows\system32\notepad.exe”


            } 

            Remove-PSSession -Session $Session # 
        }