Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

The power of PowerShell: Essential tips Windows admins will love

Adam Bertram | Nov. 6, 2015
Make the most of Microsoft’s command line by mastering the nuances of the PowerShell language.

The $getContentParameters variable defined in the first line is a hashtable. You can see this by the @{}. Inside, each key represents the parameter, and each value represents the parameter argument or value. One item to note in this example is the Force parameter. You'll notice when Force was used on one line it wasn't technically equal to anything. This is because it is a type of switch. A switch parameter has no value and is simply used as a flag. Since hashtables require a value for each key, you must make any switch parameter used equal to a Boolean $true value.

Once you've defined the hashtable you then pass the entire variable to the command using the ampersand to represent a splatting variable. Get-Content will then process the commands exactly as if you'd passed them the traditional way with dashes.

This is a much cleaner way to pass arguments to commands, and I encourage its use whenever multiple parameters are in play.

Calculated properties

One of the biggest advantages of using PowerShell is that everything is an object. Objects have properties, but sometimes you may not want to get only the default property names on an object. Maybe you'd like to add another property, add text to an existing string property, or perform arithmetic on an integer property. You could send that property to a variable and make your necessary changes, but that requires another line and, depending on the complexity, can become unreadable real quick.

For example, let's say I want to test the network connectivity of a computer and get some common properties. To do this, I'll use the Test-NetConnection cmdlet.

Test-Connection -ComputerName localhost -Count 1 |
   Select-Object IPv4Address,ResponseTime,TimeToLive

Test-Connection -ComputerName localhost -Count 1 |  Select-Object IPv4Address,ResponseTime,TimeToLiv
Click on image to enlarge.

This is great, but maybe I want to put this into a CSV report. As part of the CSV report, I'm reading server names from a text file. I'd like to include the server name as well as the properties I've shown above. I start out by reading the text file, but I don't have the server names that were in the text file.

CSV Report
Click on image to enlarge.

I need to add another property to this to correlate the IP with the server name. This is a job for calculated properties. Since this requires additional code, I will now move into a script rather than show you examples directly from the console.

Adding ServerName
Click on image to enlarge.


Previous Page  1  2  3  4  5  Next Page 

Sign up for Computerworld eNewsletters.