Just a tip #9 – 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
10

VariableSqueezing

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

VariableSqueezing1

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

VariableSqueezing2

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

VariableSqueezing3

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.

VariableSqueezing4

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

Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.