Naming and creating variables

Variables in PowerShell are preceded by the dollar symbol ($), for example:

$MyVariable

The name of a variable may contain numbers, letters, and underscores. For example, each of the following is a valid name:

$123 
$x 
$my_variable 
$variable 
$varIABle 
$Path_To_File 

Variables are frequently written in either camel case or upper-camel case (also known as Pascal case). PowerShell doesn't enforce any naming convention, nor does it exhibit a convention in any of the automatic variables. For example:

  • $myVariable is camel case
  • $MyVariable is upper-camel case, or Pascal case

One of the most commonly accepted practices is that variables used as parameters must use Pascal case. Variables used only within a script or a function must use camel case.

I suggest making your variable names meaningful so that when you revisit your script again after a long break, you can identify its purpose. I recommend choosing and maintaining a consistent style in your own code.

It's possible to use more complex variable names using the following notation:

${My Variable} 
${My-Variable} 

From time to time, the preceding notation appears in PowerShell, perhaps most often in dynamically generated code. This convention is otherwise rare and harder to read and therefore not desirable.

The bracing style has at least one important use. The following example shows an attempt to embed the var variable in a string:

$var = 'var'
"$variable" # Will not expand correctly
"${var}iable" # Will expand var

The braces define a boundary for the variable name. It is otherwise unclear whether PowerShell should attempt to expand the string.

The following notation, where a file path is written as the variable name, allows variables to be stored on the filesystem:

${C:WindowsTempvariable.txt} = "New value" 

Inspecting the given file path shows that the variable value has been written there:

PS> Get-Content C:WindowsTempvariable.txt
New value

As with the bracing notation, this is non-standard practice. It may confuse or surprise anyone reading the code.

Variables don't need to be declared prior to use, nor does a variable need to be assigned a specific type, for example:

$itemCount = 7 
$dateFormat = "ddMMyyyy" 
$numbers = @(1, 9, 5, 2) 
$psProcess = Get-Process -Name PowerShell 

It is possible to assign the same value to several variables in one statement. For example, this creates two variables, i and j, both with a value of 0:

$i = $j = 0 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.183.1