Hey Guys, Just thought of writing this quick blog post about an interesting scenario where you can use PowerShell Variable Squeezing. If you don’t know what about variable squeezing – “It is a technique to assign and display the value to\from a variable simultaneously“.
The traditional way is to store a value in a variable and then use the name of the variable in the next line to return the value of the variable in the console like in the following image.
But, if you enclose the variable assignment in parenthesis it will not only assign the value but returns the value to console in a single step.
Let’s suppose we have an array of strings from a command output, like
query.exe user and we can to parse this output into PowerShell objects but we want to get rid of the header string.
To achieve this we define a variable
$array and assign the command output to it in the first line and then in the second line using the
range operatorto select all the strings from index-1 to last-index which will skip the first index ‘0’ with the headers.
* Note that it is required to assign values to
$array variable because we want to the value the
count property to find the last index.
But, if we employ Variable Squeezing here and do the assignment and return of variable values in one step we can easily use the range operator to select the target indices of the array.
($array = query user)[1..($array.count-1)]
Sweet! right? 😀 This might save you a line of code or make you look smart 😉
I have written a blog post to demonstrate a few more approaches to ‘Store and Display PowerShell Variable simultaneously’ if you want to know more on this topic.
~ Author of “PowerShell Guide to Python”