Can variable's be used when running new-adorganizationalunit

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.

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

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.

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?

very helpful!
thanks for the in depth description.