Variable Squeezing in PowerShell


When a variable is assigned with a value, it won’t print it on the console by default, you need to print it separately.

C:\> $varNumber = 10
C:\> $varNumber

And variable squeezing is nothing but while assigning the value to a variable, it will be printed on the console as well, for that you need to wrap the assignment with the parenthesis ()

C:\> ($varNumber = 10)
10

Let’s take another example…

C:\> $varString = ('This is an example of variable squeezing').Split(' ')
 
C:\> $varString
This
is
an
example
of
variable
squeezing
 
C:\> $varString[2..$($varString.Length - 1)] -join ' '

an example of variable squeezing

In the above example, you can use the object properties only after it is assigned, but using the variable squeezing while assigning to the variable itself you can call the properties as well…

C:\> ($varString = ('This is an example of variable squeezing').Split(' '))[2..$($varString.Length - 1)] -join ' '

an example of variable squeezing

One last example

if ($null -ne ($HostInfo = Get-Host)) { $HostInfo.Version }

In the if statement itself you can assign the variable and in the script block you can directly use it.

This way you can cut down a few lines of code in your scripts.


Share it on     |   |   |   | 
  Prev:  

Convert Object Properties Into HashTable

  :Next  

Terraform - Download & Configure on Windows

comments powered by Disqus