2

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?

snoop
  • 379
  • 3
  • 8
  • 21

3 Answers3

3

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
Liam
  • 27,717
  • 28
  • 128
  • 190
Arluin
  • 594
  • 1
  • 8
  • 21
0

The function does not know what $ip is.

You need to change the function to accept a parameter of $ip

Liam
  • 27,717
  • 28
  • 128
  • 190
Jimbo
  • 2,529
  • 19
  • 22
  • It acts like it does. The session opens when you run the script. Could you explain more? – snoop Feb 27 '14 at 20:54
0

The $IP is global and therefore known with the function. The -ArgumentList is needed or populate your $MyScriptBlock a line before acting on it with Invoke-Command.

Liam
  • 27,717
  • 28
  • 128
  • 190
Kirt Carson
  • 756
  • 6
  • 3