I often see that in powershell that when someone is doing something, e.g. creating a new AD user, they do it in a variable, like:
$NewUser = New-ADUser
It might be a bad example to use New-ADUser, but it is just an example
Why should it benefit to run it in a variable rather that just run it?
To my testing with New-ADUser at least, I always get an empty variable.
The general reason is, “the command is creating a new object and I want to do something with it after it’s created.” Saving it in a variable enables that. Other times, it might be “the command produces output and I don’t want to see it, so I’m going to stuff it into a variable and just ignore it.”
But not every command produces an object when it creates or modifies something. Sometimes, you have to specify -PassThru to “capture” the created object. Other times, you may have to create the object and they query it (Get-xxxxx) to access the new object. Depends entirely on the command.
An specific reason why you want to create a new object can be performance.
Let’s give you an example when working with Exchange:
You need to update a property on 1000 mailboxes. To do this, you need to execute an action 1000 times. So you decide to put this action inside a ForEach-Object loop. Instead of executing 1000 times “Get-Mailbox” for every mailbox in this ForEach-Object loop, you run Get-Mailbox 1 time outside of the ForEach-Object loop, and put the results in a variable.
This variable is then located locally in the memory on your machine, and much more faster to work with; and the objects in the variable can be used in the ForEach-Object loop.
To add more scenarios, sometimes it’s not a list of objects (like with multiple users), but rather a single object that has multiple important properties which can be stored more securely and called more easily, for example we can store credentials in a secure object to be called for multiple functions within a script:
$Creds = Get-Credential
No I can simply call $creds over and over again no matter how many other cmdlets may ask for credentials and bypass prompting users multiple times.
Thank you Don Jones, that whas exactly what I was after.
Thanks, Richard Diphoorn and Justin King for contributing, but do know what variables in general is good for, it was related to PS cmdlets that did not start with get-*.