0

I am attempting to query a domain controller using Get-ADComputer for Active Directory information about a specific computer. This computer is specified by a variable in a local script. However, I can't pass a local variable to the scriptblock for Invoke-Command -ArgumentList then into the -Filter{} block in Get-ADComputer. Below is what I thought would work:

$computername = "nicolas"
Invoke-Command -ComputerName DomainController -ScriptBlock {
  Get-ADComputer -Filter {name -like "$args[0]"}
} -ArgumentList $computername

However, the $args[0] variable does not pass through to the internal filter; it passes to the initial scriptblock, but no farther. It is defined inside of the first scriptblock (I can correctly return its value), but is not defined inside of the -Filter{} scriptblock. How can I pass this variable from my local script, to the remote scriptblock, and into the -Filter{}?

I've attempted $args[], $USING:computername, but neither seem to let me pass it all the way through.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Mr.Budris
  • 552
  • 5
  • 21
  • This is not actually a duplicate question. – FoxDeploy Dec 02 '15 at 21:29
  • Have you tried this syntax? Invoke-Command -ComputerName DomainController -ScriptBlock { Get-ADComputer -Filter {name -like "$using:ComputerName"} } – FoxDeploy Dec 02 '15 at 21:31
  • @FoxDeploy I have in fact tried that syntax, with no luck. I'm currently reviewing the suggested question that I may be duplicating for answers. – Mr.Budris Dec 02 '15 at 21:37
  • try running something like this, to see that your param is getting piped through Invoke-Command -ComputerName DomainController -ScriptBlock { Write-Host "I am passing through this param $using:ComputerName"} } If you see the sentence show up in a way that makes sense, you know you're onto something! – FoxDeploy Dec 02 '15 at 21:41
  • @Ansgar Wiechers Thanks for the link; I did not know that it's not possible to "pass expressions as the second operand"; my actual situation was somewhat more complex than the question, but using that information I was able to cast the variable as a string and pass it through. Thanks. – Mr.Budris Dec 02 '15 at 22:00
  • @FoxDeploy The problem is caused by the misleading syntax Microsoft chose for the argument of the `-Filter` parameter. Despite what it looks like the argument is actually treated as a string, not a scriptblock. – Ansgar Wiechers Dec 02 '15 at 22:06

0 Answers0