August 30, 2015

PowerShell - Strings

We can define a literal string surrounded with single quotes and that does not interpret variable expansion or escape characters.
$myString = 'Hello World'

Also we have strings with double quotes called as expanding strings, here PowerShelll expands variable names (such as $myVar) and escape sequences (such as `n) with their values.
$myString = "Hello World"

We have to place two of that string’s quote characters together to add the quote character itself

$myString = "This string includes ""double quotes"" because it combined quote characters."
$myString = 'This string includes ''single quotes'' because it combined quote characters.'

Lets create a variable that holds text with newlines or other explicit formatting.
$myString = @"
This is the first line.
            Now expand it to second line.
    Still continues with string text including new lines and tabs.

PowerShell uses a backtick (`) character as escape sequences. In this example `n will start a new line.
$myString = "My heading text`n----------------"

Strings dynamically accepts another variable's value.
$myVar = "PowerShell"
$myString = "We are working with $myVar"
We are working with PowerShell

If you want to prevent PowerShell from interpreting special characters or variable names inside a string. A nonexpanding string uses the single quote character around its text. Now it will not place the variable's content but place the same as we typed.
$myVar = "PowerShell"
$myString = 'I have just defined a variable named $myVar'

You can repeat a string multiple times. Lets say, we want to append "0" to some other value. So for this just put the character inside quotes and multiply it with the number of times you want to repeat. For example, here I want to append ten 0s on the left side with my value "1".
$('0' * 10) + "1"

Like we have string.Format() method in C#, we can format our strings in the same way also. We have to use -f after at the end of string quotes, then put the variables we want to set in placeholders. For example:
$var1= "Strings"
$var2= "PowerShell"
$myString = "We are working with {0} in {1}" -f $var1,$var2

Note that, same like C#, first variable in the sequence will be placed in the first placeholder, second variable in second index and so on.

No comments:

Post a Comment