Variable squeezing

When you’re developing code interactively how often do you set a variable and then display it to test the result? You can do that in one go using variable squeezing.

Normally you’d do:

PS> $test = 1
PS> $test
1

Set the variable and display the contents as two separate actions.

By enclosing the first statement in parentheses you accomplish both tasks

PS> ($test2 = 2)
2

Great for interactive work but you don’t want in in scripts as you’d be getting output every time you set a variable value!

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

3 Responses to Variable squeezing

  1. Pingback: Figuring out a PowerShell version of Dynamic SQL – No Column Name

  2. postanote says:

    As for..

    “Great for interactive work but you don’t want in in scripts as you’d be getting output every time you set a variable value!”

    Except for when that is what you really want to happen, vs, spinning up progress bars, etc., though progress bars are the more elegant solution, though they don’t show you if a variable is changing inline as you may want to know.

    So, yep, I can agree that the greater portion of the time, maybe avoid this, but all out avoidance, I not yet in that camp.

    • As with all things there are exceptions. The general rule of don’t do this is scripts stands. if you have specific circumstances where you need to do this then the rule is overridden. Only you know what your code needs to do – its the mark of an expert that you know when to override the rules

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