Function Powershell函数引发空异常
好的,我已经阅读了有关在powershell中调用函数和传递参数的内容,但可能我还不了解一些东西。我调用了一个函数并传递了几个参数,一切正常。它是在函数中定义的变量,当它不是空的时候,它似乎是空的 功能:Function Powershell函数引发空异常,function,powershell,null,wmi-query,Function,Powershell,Null,Wmi Query,好的,我已经阅读了有关在powershell中调用函数和传递参数的内容,但可能我还不了解一些东西。我调用了一个函数并传递了几个参数,一切正常。它是在函数中定义的变量,当它不是空的时候,它似乎是空的 功能: function get-session { $session = New-PSSession -ComputerName $ip -Credential $cred -Auth CredSSP $subcomps = 'COMP1' foreach ($Computer in $subcom
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
}
脚本:
$ip = '123.45.67.89'
$ComputerName = "HOPCOMP"
$user = '\Admin'
$cred = $ComputerName + $user
$ip
$cred
(get-session -ComputerName $ip -Credential $cred)
当我运行此命令时:
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
当然,如果我在函数中将$Computer改为Get WMIObject line为COMP1,那么一切都很好。但是,foreach循环中写入的$Computer成功写入COMP1
这里缺少什么?函数不知道
$ip
是什么
您需要更改函数以接受参数
$ip
您需要使用调用命令指定-ArgumentLis
t参数。例如:
Invoke-Command -Session $session -ScriptBlock {
param($Computer)
Get-WmiObject -ComputerName $Computer -Query "SELECT * FROM Win32_Group"
} -ArgumentList $Computer
$IP
是全局的,因此该函数是已知的。需要-ArgumentList
,或者在使用Invoke命令对-ArgumentList
执行操作之前,将$MyScriptBlock
填充一行。运行脚本时,会话将打开。你能再解释一下吗?