1

Could anybody provide any insight on why the below code is not working? I had this working before and cannot see why the New-PSSession cannot validate the ComputerName parameter. Full Error Below code.

$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
        }
    }

Return Output:

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

Thanks in Advance

Royston
  • 433
  • 2
  • 9
  • 25
  • Your error is different than your script. In your error it says `$computers` but your example script says `$computer` when creating a session. Which is it? – TheMadTechnician Aug 22 '17 at 19:36

1 Answers1

0

i have fixed the issue - it was an unnecessary nest of {} within the script block. The below code works:

$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 # 
        }
Royston
  • 433
  • 2
  • 9
  • 25