Using Windows PowerShell as an IT Pro – Part 11
In my last post I reviewed the Out-Gridview cmdlet. Now I will look at variables.Windows PowerShell lets you create variables – essentially named objects – to preserve output for later use. The Windows PowerShell variables are actually mapped to underlying classes in the Microsoft® .NET Framework. In the Framework, variables are objects, meaning they can store data and also manipulate it in many ways.
Variables are always specified with the initial character $ and can include a mix of letters, numbers, symbols, or even spaces. However, if spaces are used, the variable needs to be enclosed in braces, such as: ${My Variable} = “Hello”). Variables are created by typing a valid variable name or assigning a value to it. A variable name should help you remember what it contains, using a simple, straight-forward name.
$Loc = Get-Location
Output is not displayed when this command is entered, because the output is sent to $Loc. In Windows PowerShell, displayed output is a side effect of the fact that data which is not otherwise directed always gets sent to the screen. Typing $Loc shows its value, which in this case is the current location.
$Loc
Get-Member is used to display information about the contents of variables. Get-Member enumerates the properties and methods of that object type. Piping $Loc to Get-Member shows that it is a PathInfo object, just like the output from Get-Location.
$Loc | Get-Member
There is also a default variable that can be used for certain situations. The $_ acts a placeholder for the current object. This can be used to access the properties or methods of the current object in a command. For example we can use $_ to help filter the output of the Get-Service cmdlet, displaying only services that have a status of Running.
Get-Service | where {$_.status -eq "Running"}
In my next post we continue to look at variables and types.
No comments:
Post a Comment