Powershell function throwing null exception

snoop picture snoop · Feb 27, 2014 · Viewed 17.3k times · Source

Okay, so I've read up on calling functions and passing parameters in powershell but maybe I'm not understanding something. I am calling a function and passing a couple parameters and everything works fine. It is variable defined within the function that seems to be null when it isn't.

Function:

function get-session {
$session = New-PSSession -ComputerName $ip -Credential $cred -Auth CredSSP
$subcomps = 'COMP1'
foreach ($Computer in $subcomps)
{
$Computer
Invoke-Command -Session $session -ScriptBlock { Get-WmiObject -ComputerName $Computer -Query "SELECT * FROM Win32_Group" }
}
Remove-PSSession -ComputerName $ip
}

Script:

$ip = '123.45.67.89'
$ComputerName = "HOPCOMP"
$user = '\Admin'
$cred = $ComputerName + $user
$ip
$cred
(get-session -ComputerName $ip -Credential $cred)

When I run this:

Cannot validate argument on parameter 'ComputerName'. The argument is null or empty.
Supply an argument that is not null or empty and then try the command again.
+ CategoryInfo          : InvalidData: (:) [Get-WmiObject], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Of course, if I change $Computer in in the function Get-WMIObject line to COMP1 everything works great. But, the $Computer write out in the foreach loop writes COMP1 successfully.

What am I missing here?

Answer

Arluin picture Arluin · Feb 27, 2014

You need to specify the -ArgumentList parameter with your Invoke-Command. For example:

Invoke-Command -Session $session -ScriptBlock { 
       param($Computer) 
       Get-WmiObject -ComputerName $Computer -Query "SELECT * FROM Win32_Group" 
  } -ArgumentList $Computer