Author : MD TAREQ HASSAN | Updated : 2021/09/25
String syntax
# The string type represents text as a sequence of char values,
# while each character is UTF-16 encoded 16-bit Unicode code point
# literal string
$sampleText = "This is a string";
# empty string
$emptyStr = "";
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)
$x = 5
# no substitution
Write-Host 'The value of $x is $x.' # The value $x is $x.
# substitution
Write-Host "The value of `$x is $x." # The value $x is 5.
Multiline string
$title = "PowerShell block string"
# verbatim block string
$html = @'
<div>
<h1>$title<h1>
<p>xyz</p>
</div>
'@
Write-Host $html
Write-Host "------------------------------------"
# interpolation possible block string
$html = @"
<div>
<h1>$title<h1>
<p>xyz</p>
</div>
"@
Write-Host $html
Null or empty check
$input = Read-Host "Enter something"
$isEmpty = [string]::IsNullOrEmpty($input)
Write-Host "Input is empty: $isEmpty"
New line
Use” backtick r and backtick n ('
rn'
)
Write-Host "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