Can variable's be used when running new-adorganizationalunit

This topic contains 4 replies, has 2 voices, and was last updated by  src053 4 years, 4 months ago.

  • Author
    Posts
  • #7028

    src053
    Participant

    All,
    Is it legal to populate a variable with with a new-adorganizationalunit command?
    example would be like this

    $OULocation=New-ADOrganizationalUnit -Name something -Path somepath -Instance sometemplateou

    then use the $OULocation through out the rest of the script.
    I ask because when I try to do this the $OULocation variable is always empty.
    Thanks!

  • #7029

    Poshoholic
    Participant

    Yes, it's legal. Add -PassThru to the list of parameters you use when you invoke New-ADOrganizationalUnit and you'll be all set!

  • #7031

    src053
    Participant

    Yahtzee! That did the trick.

    Now time for the deeper question Why would we need to use the -passthru parameter to populate a variable? Intuitively I would think the Variable (since it precedes the cmdlet) would be defined prior to moving on to the pipeline.
    Thanks!

  • #7041

    Poshoholic
    Participant

    Some cmdlets return objects by default, some return nothing, and others optionally return objects. New-ADOrganizationalUnit falls into the latter category. When you invoke it without -PassThru and you attempt to assign its results to a variable, PowerShell does create the variable and it does perform an assignment, but it isn't the assignment you were expecting. The variable created, but it is assigned to null in this case. To validate that the variable exists following that call, you can use Get-Variable which will raise an error if a variable does not exist. When you changed your logic to use -PassThru, you instructed New-ADOrganizationalUnit to return the object it created, which PowerShell then assigned to your variable.

    Does that help?

  • #7051

    src053
    Participant

    very helpful!
    thanks for the in depth description.

You must be logged in to reply to this topic.