PowerShell Variables

Variables is the most widely used to stored data in powerShell. Here we can use variables to store data like strings, integers, and objects. To declare a variable by simply using ($) sign with the name variable. 

$myString = "This is a string."
$myNumber = 137
$dateObject = Get-Date

Some ways to use variables in strings, like variable subtitution in powerShell, it's when we need to format a string to include values from variables. In powerShell we can do concatenation.

$name = 'Reza Pahlevi'
$myMessage = 'Hello!, My Name is ' + $name
Write-Host $myMessage

That's one variable, what about if there are more.

$firstName = 'Reza'
$lastName = 'Pahlevi'
$message = 'Hello!, my name is ' +$firstName+ ' ' +$lastName+ '.'
write-host $message

Instead of assign the string in variable $message you can experiment with these examples.

$firstName = 'Reza'
$lastName = 'Pahlevi'
Write-Host('Hai!, My name is ' + $firstName + ' ' + $lastName + '.')

# you can do this too
Write-Host('Hai!, My name is {0} {1}.' -f $firstName, $lastName)

# or you can do this instead
Write-Host "Hai!, My name is $firstName $lastName."

Notice that, powerShell treats the string differently with single quote and double quote. In single quote you need to enclose the the string with the brackets.

Sometimes when you are facing a string in variables didn't have a clear boundary, here's what you can do.

$test = 'Bo'
Write-Host "These are my ${test}oks."

# alternate appraoch
Write-Host "These are my $($test)oks."
Write-Host('These are my {0}oks.' -f $test)

In powerShell variables you can you command execution then get object from the command.

# command execution then get object from the command
$date = "Date: $(Get-Date)"
$date

$listing = dir
$listing

So instead of using Write-Host to print out the variables, you simply just invoke the variables name. Try it yourself what happen when you're using Write-Host on $date and $listing variables, from here you will know when you need to use this Write-Host.

In powerShell variables you can do number operation.

# do this instead
$a = 1
$b = 3
$c = 7
Write-Host '$a + $b + $c = ' $($a + $b + $c)

# you can do this too
$d = $a + $b + $c
Write-Host '$a + $b + $c = ' $d

In powerShell, you're allowd to do multiple assignment.

# you can do multiple assignment in one line
$a = $b = $c = "Multiple Assign" # same value
Write-Host $a $b $c

$a, $b, $c = 1, 3, 7 # different value
Write-Host $a $b $c

# assigning with different objects
$a, $b, $c = 137, "Multiple Assigin", $(Get-Date)
$a
$b
$c

Important things you need to know, just like another programming languages has reserved keywords that you can't you use them as variables. In powerShell reserved keywords usually called as Automatic Variables.

Subscribe to receive free email updates:

0 Response to "PowerShell Variables"

Post a Comment