≡ Menu

PowerShell: How to assign the output to a variable and print on console at same time

We want to assign output of a cmdlet/function to a variable so that we can use it in further processing. In scripts it is very inconvenient to debug a issue if the output is going to a variable and not to console. In such cases we can do nothing other than printing the variable value to the console by inserting extra lines of code.

To avoid such inconvenience, powershell has got a way to assign the output to a variable and print to console at the same time. This helped me in quick debugging of my scripts and oneliners.

Ok. Enough explaining about the usage and all and here is how it works.

($service = Get-Service -Name spooler)

Execute the command and you will understand what exactly it is doing. All we need to do it embed the whole command into into brackets like shown above.

Hope this little one helps you. Happy learning.



{ 1 comment… add one }
  • Praveen December 28, 2012, 2:29 pm

    can you please give a small example for same…. I got the use of it buit not getin how i can use it,

Leave a Comment