Powershell Strings

From DataSelf Knowledge Base
Jump to navigation Jump to search

String Concatentation

$userprofile = "C:\users\" + $user + "\"
$userprofile = [String]::Join("C:\users\", $user, "\")
$userprofile = [String]::Concat("C:\users\", $user, "\")
$x = "C:\users\" # not tested
$x += $user + "\"

String Concatenation in Function Calls

<funcName> $("C:\users\" + $user + "\")


String Dereferencing

>write-host $MyInvocation.MyCommand.Path
C:\Users\Main\DSAAD_Development\DSAAutoDist_Version1.2\Untitled1.ps1
>write-host "a - $MyInvocation.MyCommand.Path"
a - System.Management.Automation.InvocationInfo.MyCommand.Path
>write-host "b - $($MyInvocation.MyCommand.Path)"
write-host "b - $($MyInvocation.MyCommand.Path)"

Testing for Null or Empty Strings

Nulls and empty strings in PowerShell can get complicated.

This is going to sound stupid but there are four different types of null in PowerShell ...
Recommended test is:
if ($x  -is [String] -and $x -ne [String]::Empty) {