2014-02-27 1 views
1

좋아요, 그렇기 때문에 함수를 호출하고 powershell에서 매개 변수를 전달하는 것에 대해 읽었지만 어쩌면 뭔가를 이해하지 못하고 있습니다. 함수를 호출하고 몇 개의 매개 변수를 전달하면 모든 것이 잘 작동합니다. 함수 내에 정의 된 변수이며 그렇지 않을 때 null 인 것으로 보입니다.Powershell 함수가 null 예외를 throw합니다

기능 :

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 

, 나는 기능에에 $ 컴퓨터를 변경하면은 Get-WMIObject에서 라인을 COMP1 모든 것이 잘 작동합니다. 그러나 foreach 루프에서 $ Computer 쓰기는 COMP1을 성공적으로 기록합니다.

무엇이 여기에 있습니까?

답변

2

의 매개 변수를 받아들이는 기능을 변경해야합니다. 예를 들면 다음과 같습니다.

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

우수, 감사합니다! – snoop

0

이 함수는 $ ip가 무엇인지 알지 못합니다.

당신은 당신은 당신의 호출-명령과 함께 -ArgumentList 매개 변수를 지정해야합니다 $의 IP

+0

그 것처럼 작동합니다. 스크립트를 실행할 때 세션이 열립니다. 더 설명해 주시겠습니까? – snoop

0

$ IP는 전역이므로 기능과 함께 알려져 있습니다. Invoke-Command로 작업하기 전에 -ArgumentList가 필요하거나 $ MyScriptBlock을 한 줄씩 채 웁니다.

관련 문제