Powershell function throwing null exception

强颜欢笑 提交于 2019-12-08 02:53:46

问题


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?


回答1:


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



回答2:


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.




回答3:


The function does not know what $ip is.

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



来源:https://stackoverflow.com/questions/22078586/powershell-function-throwing-null-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!