Invoke-Command Get-AdOrganizationalUnit

I’ve written a script that will take User input of an OU name and the initial part of the Script will ‘Validate’ the input but checking to see if the OU exists.

I need to run the Get-ADOrganizationUnit cmdlet with the scriptblock of the Invoke-command while the user supplies it with the correct credentials.

I am having problems running it since the $OU variable will need to be passed to the Invoke-Command as a string. I think I am getting hung up on when to use double quotes and when to use curly brackets and how to pass a variable to the ‘filter’ parameter of Get-ADOrganizationalUnit

This is essentially what I am trying to do.

#user Input
$OUName = "NSSS"

$ScriptBlockContent = {Get-ADOrganizationalUnit -Filter "Name -eq $Using:OU"}

Invoke-Command -ComputerName ADServer -ScriptBlock $ScriptBlockContent -Credential domain\user

This of course fails. I have tried removing the curly brackets from the $ScriptContent variable and creating a string. Can’t seem to find my error.

What error message you are getting ?

Invoke-Command : The value of the using variable '$using:OU' cannot be retrieved because it has not been set in the local session.
At line:6 char:1
+ Invoke-Command -ComputerName -ScriptBlock $ScriptBlockCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Command], RuntimeException
+ FullyQualifiedErrorId : UsingVariableIsUndefined,Microsoft.PowerShell.Commands.InvokeCommandCommand

Can you try this?
$OUName = “NSSS”
Invoke-Command -ComputerName ADServer -ScriptBlock {Get-ADOrganizationalUnit -Filter “Name -eq $($args[0])”} -Credential domain\user -ArgumentList $OUName

Error parsing query: ‘Name -eq NSSS’ Error Message: ‘syntax error’ at position: ‘10’.

  • CategoryInfo : ParserError: (:slight_smile: [Get-ADOrganizationalUnit], ADFilterParsingException
  • FullyQualifiedErrorId : ActiveDirectoryCmdlet:<wbr />Microsoft.ActiveDirectory.<wbr />Management.<wbr />ADFilterParsingException,<wbr />Microsoft.ActiveDirectory.<wbr />Managemen
    t.Commands.<wbr />GetADOrganizationalUnit
  • PSComputerName :<

your variable name is OUName, hence you should use $Using:OUName

Try this:

$ouName = 'NSSS'

Invoke-Command -ComputerName ADServer -Credential domain\user -ArgumentList $ouName -ScriptBlock {
    param($ouName = $ouName)

    Get-ADOrganizationalUnit -Filter "Name -eq '$ouName'"


Edit: You do not have use the param() block; just refer to the argument using $($args[0]) as per the previous poster. This was just a ‘fuller’ approach.