I am pretty light on the details of variables, particularly around scope, expansion and built-in variables, but PowerShell does have them. Variables are always prefaced with “$”. Declaration and assignment of variables is as simple as:
$Number = 2
Or
$Files = Get-ChildItem
In the first case, we’re assigning the number 2 to the variable $Number. In the second we’re assigning $Files an array of files in the current folder. Remember that depending on the provider this may not be files. In the case of:
SQL:\MYSQLSERVER\DEFAULT\Databases\MyDatabase\Tableswe’d be assigning an array of SMO table objects in the MyDatabase database.
I’m a little shaky on variable expansion. For example:
$Subfolder = “MySubFolder”
Set-Location C:\MyFolder\$Subfolder
will set your current location to C:\MyFolder\MySubFolder. If you have space in your path you could type:
Set-Location “C:\My Folder\$Subfolder”
and the value of $Subfolder will replace $Subfolder in the path. However, I seem to have had cases where the string replacement doesn’t happen and I simply end up with a string “C:\My Folder\$Subfolder”
When in doubt, you can look to string concatenation as follows:
$Subfolder = “MySubFolder”
$Folder = “C:\MyFolder\” + $Subfolder
Or PowerShell’s equivalent of the .NET string.Format(string, arg1, arg2, …) as follows:
Set-Location (“C:\My Folder\{0}” –F $Subfolder)
Although you don't see it often, you can type variables by declaring them with a specific .NET type as follows:
[int]$MyInteger = 1
This will explicitly type the variable as an integer. There are two special types of variables and literal assignments, arrays and hastables. You can define and assign a literal array as follows:
$MyArray = @(1, 2, 3)
$MyValue = $MyArray[1]
This creates a 3 integer, zero-indexed array and then assign the second value, 2 to the variable $MyValue. A hash table variable, or dictionary, creates a list of name/value pairs as follows:
$MyHashTable = @{"Value1" = 123, "Value2" = 456}
$MySecondValue = $MyHashTable["Value2"]
You can add a new value by simply assigning a value to an unused name as follows:
$MyHasTable["Value3"] = 789
Or remove a value using the .Remove method as follows:
$MyHashTable.Remove("Value2")
Don't forget you can do all of this interactively from the command line and viewing the value of the variable is as simple as typing the variable name at the command line and hitting enter.
As noted at the beginning, I’m still a little light on the details of variables. I believe there are a number of scope rules around access to variables inside modules etc. that I am not familiar with so Google will be your friend with this.
A good article I found on variables is PowerShell Tutorial 7: Accumulate, Recall, and Modify Data.
No comments:
Post a Comment