Author : HASSAN MD TAREQ | Updated : 2021/09/25
String Interpolation
$hello = "Hello"
$singleLine = $singleLine = "$($hello) PowerShell!" # or "$hello PowerShell!"
#
# MultiLine:
# first line '@"'
# Content in between (content will remain as it is written)
# last line '"@'
#
$multiLine = @"
$($hello) PowerShell!
I am hovermind
@"
Verbatim String
A string enclosed in single-quotation marks is a verbatim string. The string is passed to the command exactly as you type it. No substitution is performed.
$i = 5
echo 'The value of $i is $i.' # Output: The value $i is $i.
Escape
To prevent the substitution of a variable value in a double-quoted string, use the backtick character (```), which is the PowerShell escape character.
$i = 5
echo "The value of `$i is $i." # Output: The value $i is 5.
Null or Empty
#
# [string]::IsNullOrEmpty($xyz)
#
$notExists = (([string]::IsNullOrEmpty($xyz)) -eq $true)
New Line
Use” backtick r and backtick n ('
rn'
)
echo "Please enter Login Credential `r`n(Login User Id & Password)"
Secure String
From Plain Text to Secured String
#
# Plain Text to Secured String
#
$securedString = ConvertTo-SecureString $plainText
$securedString = Read-Host "Enter your password" -AsSecureString
From Secured String to Plain Text
#
# From Secured String to Plain Text
#
$plainText = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securedString))
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
$ClearTextPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Write-Host $ClearTextPassword
# User defined function
function ConvertTo-String {
param(
[Parameter(Mandatory)]
[Security.SecureString] $SecureString
)
try {
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
[Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
}
finally {
if ( $bstr -ne [IntPtr]::Zero ) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
}
}
}
Quoting rules: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules