How do I concatenate strings and variables in PowerShell? - powershell

Suppose I have the following snippet:
$assoc = New-Object PSObject -Property #{
Id = 42
Name = "Slim Shady"
Owner = "Eminem"
}
Write-Host $assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner
I'd expect this snippet to show:
42 - Slim Shady - Eminem
But instead it shows:
42 + - + Slim Shady + - + Eminem
Which makes me think the + operator isn't appropriate for concatenating strings and variables.
How should you approach this with PowerShell?

Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.

There is a difference between single and double quotes. (I am using PowerShell 4).
You can do this (as Benjamin said):
$name = 'Slim Shady'
Write-Host 'My name is'$name
-> My name is Slim Shady
Or you can do this:
$name = 'Slim Shady'
Write-Host "My name is $name"
-> My name is Slim Shady
The single quotes are for literal, output the string exactly like this, please.
The double quotes are for when you want some pre-processing done (such as variables, special characters, etc.)
So:
$name = "Marshall Bruce Mathers III"
Write-Host "$name"
-> Marshall Bruce Mathers III
Whereas:
$name = "Marshall Bruce Mathers III"
Write-Host '$name'
-> $name
(I find How-to: Escape characters, Delimiters and Quotes good for reference).

You can also use -join
E.g.
$var = -join("Hello", " ", "world");
Would assign "Hello world" to $var.
So to output, in one line:
Write-Host (-join("Hello", " ", "world"))

One way is:
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
Another one is:
Write-Host ("{0} - {1} - {2}" -f $assoc.Id,$assoc.Name,$assoc.Owner )
Or just (but I don't like it ;) ):
Write-Host $assoc.Id " - " $assoc.Name " - " $assoc.Owner

Try wrapping whatever you want to print out in parentheses:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
Your code is being interpreted as many parameters being passed to Write-Host. Wrapping it up inside parentheses will concatenate the values and then pass the resulting value as a single parameter.

Another option is:
$string = $assoc.ID
$string += " - "
$string += $assoc.Name
$string += " - "
$string += $assoc.Owner
Write-Host $string
The "best" method is probably the one C.B. suggested:
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"

While expression:
"string1" + "string2" + "string3"
will concatenate the string, you need to put a $ in front of the parenthesis to make it evaluate as a single argument when passed to a PowerShell command. Example:
Write-Host $( "string1" + "string2" + "string3" )
As a bonus, if you want it to span multiple lines, then you need to use the awkward backtick syntax at the end of the line (without any spaces or characters to the right of the backtick).
Example:
Write-Host $(`
"The rain in " +`
"Spain falls mainly " +`
"in the plains" )`
-ForegroundColor Yellow
(Actually, I think PowerShell is currently implemented a little bit wrong by requiring unnecessary backticks between parentheses. If Microsoft would just follow Python or Tcl parenthesis rules of allowing you to put as many newlines as you want between the starting and ending parenthesis then they would solve most of the problems that people don't like about PowerShell related to line continuation, and concatenation of strings.
I've found that you can leave the backticks off sometimes on line continuations between parenthesis, but it's really flaky and unpredictable if it will work... It's better to just add the backticks.)

You need to place the expression in parentheses to stop them being treated as different parameters to the cmdlet:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)

(Current PowerShell version 5.1.17134.407)
This also works as of now:
$myVar = "Hello"
echo "${myVar} World"
Note: this only works with double quotes

Here is another way as an alternative:
Write-Host (" {0} - {1} - {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)

I just want to bring another way to do this using .NET String.Format:
$name = "Slim Shady"
Write-Host ([string]::Format("My name is {0}", $name))

These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:
$name = 'Slim Shady'
Write-Host 'My name is'$name
It will output
My name is Slim Shady
Note how a space is put between the words for you

I seem to struggle with this (and many other unintuitive things) every time I use PowerShell after time away from it, so I now opt for:
[string]::Concat("There are ", $count, " items in the list")

Concatenate strings just like in the DOS days. This is a big deal for logging so here you go:
$strDate = Get-Date
$strday = "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output $strday

From What To Do / Not to Do in PowerShell: Part 1:
$id = $assoc.Id
$name = $assoc.Name
$owner = $assoc.owner
"$id - $name - $owner"

Write-Host can concatenate like this too:
Write-Host $assoc.Id" - "$assoc.Name" - "$assoc.Owner
This is the simplest way, IMHO.

If you're concatenating strings to build file paths, use the Join-Path command:
Join-Path C:\temp "MyNewFolder"
It'll automatically add the appropriate trailing / leading slashes for you, which makes things a lot easier.

$assoc = #{
Id = 34
FirstName = "John"
LastName = "Doe"
Owner = "Wife"
}
$assocId = $assoc.Id
$assocFN = $assoc.FirstName
$assocLN = $assoc.LastName
$assocName = $assocFN, $assocLN -Join " "
$assocOwner = $assoc.Owner
$assocJoin = $assocId, $assocName, $assocOwner -join " - "
$assocJoin
#Output = 34 - John Doe - Wife

As noted elsewhere, you can use join.
If you are using commands as inputs (as I was), use the following syntax:
-join($(Command1), "," , $(Command2))
This would result in the two outputs separated by a comma.
See https://stackoverflow.com/a/34720515/11012871 for related comment

Personally I prefer this style:
[string]::Join(' - ', 42, 'Slim Shady', 'Eminem')
or based on any object with even different attribute types:
$assoc = [psCustomObject][ordered]#{
Id = 42
Name = 'Slim Shady'
Owner = 'Eminem'
}
[string]::Join(' - ',$assoc.psObject.Properties.value)
which gives you this result:
42 - Slim Shady - Eminem

Just for the fun. You can also access the values of the PSObject directly like below:
$assoc.psobject.Properties.value -join " - "
But if you do not specify that the object should be ordered, PowerShell will display the values in a random order. So you should add the flag [ordered]:
$assoc = [pscustomobject] [ordered] #{
Id = 42
Name = "Slim Shady"
Owner = "Eminem"
}

You can also get access to C#/.NET methods, and the following also works:
$string1 = "Slim Shady, "
$string2 = "The real slim shady"
$concatString = [System.String]::Concat($string1, $string2)
Output:
Slim Shady, The real slim shady

Related

Having some trouble with Powershell -replace and Environment Variables from Batch File

I finally narrowed down the problem, but need help understanding why.
Invoking Powershell from a batch file, the following works to replace a string within a file:
Powershell -Command "$foobar=[IO.File]::ReadAllText("$Env:File") ;
$foobarred= $foobar -replace '(?<foo>.*Backup.).*.(?<bar>..Backup.)', '${foo}Enabled${bar}' ;
[IO.File]::WriteAllText("$Env:File", $foobarred); "
Now if I try this, the command fails:
Powershell -Command "$foobar=[IO.File]::ReadAllText("$Env:File") ;
$foobarred= $foobar -replace '(?<foo>.*$Env:StrStart.).*.(?<bar>..$Env:StrEnd.)', '${foo}$Env:StrVal${bar}' ;
[IO.File]::WriteAllText("$Env:File", $foobarred); "
If I use a variable passed in from Batch, it fails everytime. If I use PlainText in the command instead for the replacement value, it works just fine. Why does this happen?
My observations would be
you need to [regex]::Escape() arbitrary values when you build regular expressions dynamically.
PowerShell does not do any string interpolation in single-quoted strings, so things like '${foo}$Env:StrVal${bar}' will not work the way you want.
I'd use the following command:
(Get-Content "filename" -Raw) -replace (
'(.*' + [regex]::Escape("start string") + '.).*.(..' + [regex]::Escape("end string") + '.)'
),(
'$1' + "replacement string" + '$2'
) | Set-Content "filename"
called ad-hoc from a batch file as follows (compressed onto one line):
#echo off
setlocal
set "FILENAME=filename"
set "START=start string"
set "END=end string"
set "REPLACEMENT=replacement string"
set "PSCMD=(gc $Env:FILENAME -Raw) -replace ('(.*' + [regex]::Escape($Env:START) + '.).*.(..' + [regex]::Escape($Env:END) + '.)'),('$1' + $Env:REPLACEMENT + '$2') | sc $Env:FILENAME"
powershell -NoLogo -Command "&{%PSCMD%}"
But this is disproportionately hard to maintain.
I'd recommend writing a .ps1 file and passing named arguments, instead of juggling environment variables.
# MyReplace.ps1
param(
[string]$Filename,
[string]$Start,
[string]$End,
[string]$Replacement
)
$ErrorActionPreference = "Stop"
$content = Get-Content $Filename -Raw
$content = $content -replace ('(.*' + [regex]::Escape($Start) + '.).*.(..' + [regex]::Escape($End) + '.)'),('$1' + $Replacement + '$2')
$content | Set-Content $Filename
and in batch
powershell -NoLogo -File MyReplace.ps1 -Filename "filename" -Start "start string" -End "end string" -Replacement "replacement string"
That seems more manageable to me.
At the advice of #Gerhard, adding what I found into the fray as an answer, but did ultimately giving #Tomalak the credit for the better answer overall.
In order to accept variables into both the match pattern and the replace pattern, you have to concatenate the strings (similar to how it is done in Visual Basic).
Reference below:
I have split the command up into multiple lines for readability - if you use this, place it on one line.
Important - when using this, be sure to remove the line-breaks if you use it in a batch file. Also - be wary - I have had some circumstances where even using Set-Content can change the Encoding of the file. I much prefer the secondary solution offered down below.
Powershell -Command "$pattern= '(?<RangeStart>.*' + [regex]::Escape($Env:StrStart) + '.).*.(?<RangeEnd>..' + [regex]::Escape($Env:StrEnd) + '.)' ;
$repl= '${RangeStart}' + $Env:StrVal + '${RangeEnd}' ;
$fil2parse=(Get-Content $Env:FileTOParse) -replace $pattern, $repl | Set-Content $Env:FileTOParse; "
This solution works as well, but I have had much fewer issues with it changing Encoding.
Powershell -Command "$pattern= '(?<RangeStart>.*' + [regex]::Escape($Env:StrStart) + '.).*.(?<RangeEnd>..' + [regex]::Escape($Env:StrEnd) + '.)' ;
$repl= '${RangeStart}' + $Env:StrVal + '${RangeEnd}' ;
$fil2parse=[IO.File]::ReadAllText("$Env:FileTOParse") ;
$filParsed= $fil2parse -replace $pattern, $repl ;
[IO.File]::WriteAllText("$Env:FileTOParse", $filParsed); "

Using #Splat to send email attachment result and then delete after successful execution [duplicate]

Suppose I have the following snippet:
$assoc = New-Object PSObject -Property #{
Id = 42
Name = "Slim Shady"
Owner = "Eminem"
}
Write-Host $assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner
I'd expect this snippet to show:
42 - Slim Shady - Eminem
But instead it shows:
42 + - + Slim Shady + - + Eminem
Which makes me think the + operator isn't appropriate for concatenating strings and variables.
How should you approach this with PowerShell?
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
See the Windows PowerShell Language Specification Version 3.0, p34, sub-expressions expansion.
There is a difference between single and double quotes. (I am using PowerShell 4).
You can do this (as Benjamin said):
$name = 'Slim Shady'
Write-Host 'My name is'$name
-> My name is Slim Shady
Or you can do this:
$name = 'Slim Shady'
Write-Host "My name is $name"
-> My name is Slim Shady
The single quotes are for literal, output the string exactly like this, please.
The double quotes are for when you want some pre-processing done (such as variables, special characters, etc.)
So:
$name = "Marshall Bruce Mathers III"
Write-Host "$name"
-> Marshall Bruce Mathers III
Whereas:
$name = "Marshall Bruce Mathers III"
Write-Host '$name'
-> $name
(I find How-to: Escape characters, Delimiters and Quotes good for reference).
You can also use -join
E.g.
$var = -join("Hello", " ", "world");
Would assign "Hello world" to $var.
So to output, in one line:
Write-Host (-join("Hello", " ", "world"))
One way is:
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
Another one is:
Write-Host ("{0} - {1} - {2}" -f $assoc.Id,$assoc.Name,$assoc.Owner )
Or just (but I don't like it ;) ):
Write-Host $assoc.Id " - " $assoc.Name " - " $assoc.Owner
Try wrapping whatever you want to print out in parentheses:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
Your code is being interpreted as many parameters being passed to Write-Host. Wrapping it up inside parentheses will concatenate the values and then pass the resulting value as a single parameter.
Another option is:
$string = $assoc.ID
$string += " - "
$string += $assoc.Name
$string += " - "
$string += $assoc.Owner
Write-Host $string
The "best" method is probably the one C.B. suggested:
Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)"
While expression:
"string1" + "string2" + "string3"
will concatenate the string, you need to put a $ in front of the parenthesis to make it evaluate as a single argument when passed to a PowerShell command. Example:
Write-Host $( "string1" + "string2" + "string3" )
As a bonus, if you want it to span multiple lines, then you need to use the awkward backtick syntax at the end of the line (without any spaces or characters to the right of the backtick).
Example:
Write-Host $(`
"The rain in " +`
"Spain falls mainly " +`
"in the plains" )`
-ForegroundColor Yellow
(Actually, I think PowerShell is currently implemented a little bit wrong by requiring unnecessary backticks between parentheses. If Microsoft would just follow Python or Tcl parenthesis rules of allowing you to put as many newlines as you want between the starting and ending parenthesis then they would solve most of the problems that people don't like about PowerShell related to line continuation, and concatenation of strings.
I've found that you can leave the backticks off sometimes on line continuations between parenthesis, but it's really flaky and unpredictable if it will work... It's better to just add the backticks.)
You need to place the expression in parentheses to stop them being treated as different parameters to the cmdlet:
Write-Host ($assoc.Id + " - " + $assoc.Name + " - " + $assoc.Owner)
(Current PowerShell version 5.1.17134.407)
This also works as of now:
$myVar = "Hello"
echo "${myVar} World"
Note: this only works with double quotes
Here is another way as an alternative:
Write-Host (" {0} - {1} - {2}" -f $assoc.Id, $assoc.Name, $assoc.Owner)
I just want to bring another way to do this using .NET String.Format:
$name = "Slim Shady"
Write-Host ([string]::Format("My name is {0}", $name))
These answers all seem very complicated. If you are using this in a PowerShell script you can simply do this:
$name = 'Slim Shady'
Write-Host 'My name is'$name
It will output
My name is Slim Shady
Note how a space is put between the words for you
I seem to struggle with this (and many other unintuitive things) every time I use PowerShell after time away from it, so I now opt for:
[string]::Concat("There are ", $count, " items in the list")
Concatenate strings just like in the DOS days. This is a big deal for logging so here you go:
$strDate = Get-Date
$strday = "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output "$($strDate.Year)$($strDate.Month)$($strDate.Day)"
Write-Output $strday
From What To Do / Not to Do in PowerShell: Part 1:
$id = $assoc.Id
$name = $assoc.Name
$owner = $assoc.owner
"$id - $name - $owner"
Write-Host can concatenate like this too:
Write-Host $assoc.Id" - "$assoc.Name" - "$assoc.Owner
This is the simplest way, IMHO.
If you're concatenating strings to build file paths, use the Join-Path command:
Join-Path C:\temp "MyNewFolder"
It'll automatically add the appropriate trailing / leading slashes for you, which makes things a lot easier.
$assoc = #{
Id = 34
FirstName = "John"
LastName = "Doe"
Owner = "Wife"
}
$assocId = $assoc.Id
$assocFN = $assoc.FirstName
$assocLN = $assoc.LastName
$assocName = $assocFN, $assocLN -Join " "
$assocOwner = $assoc.Owner
$assocJoin = $assocId, $assocName, $assocOwner -join " - "
$assocJoin
#Output = 34 - John Doe - Wife
As noted elsewhere, you can use join.
If you are using commands as inputs (as I was), use the following syntax:
-join($(Command1), "," , $(Command2))
This would result in the two outputs separated by a comma.
See https://stackoverflow.com/a/34720515/11012871 for related comment
Personally I prefer this style:
[string]::Join(' - ', 42, 'Slim Shady', 'Eminem')
or based on any object with even different attribute types:
$assoc = [psCustomObject][ordered]#{
Id = 42
Name = 'Slim Shady'
Owner = 'Eminem'
}
[string]::Join(' - ',$assoc.psObject.Properties.value)
which gives you this result:
42 - Slim Shady - Eminem
Just for the fun. You can also access the values of the PSObject directly like below:
$assoc.psobject.Properties.value -join " - "
But if you do not specify that the object should be ordered, PowerShell will display the values in a random order. So you should add the flag [ordered]:
$assoc = [pscustomobject] [ordered] #{
Id = 42
Name = "Slim Shady"
Owner = "Eminem"
}
You can also get access to C#/.NET methods, and the following also works:
$string1 = "Slim Shady, "
$string2 = "The real slim shady"
$concatString = [System.String]::Concat($string1, $string2)
Output:
Slim Shady, The real slim shady

String concatenation with newline not working as expected

I want to add a line break without adding a whole 'nother line to do so, here be my code:
"-- MANIFEST COUNT -- " >> "C:\psTest\test1.txt"
$manCount = (Get-ChildItem -filter "*manifest.csv").Count
$manCount + " `n" >> "C:\psTest\test1.txt"
I thought that + " `n" would tack a line break onto the count, but it's not doing anything. I tried also + "`r`n" (I found this suggestion elsewhere on SO) but to no avail.
Let me complement your own solution with an explanation:
Because $manCount, the LHS, is of type [int],
$manCount + " `n"
is effectively the same as:
$manCount + [int] " `n".Trim()
or:
$manCount + [int] ""
which is effectively the same as:
$manCount + 0
and therefore a no-op.
In PowerShell, the type of the LHS of an expression typically[1]
determines what type the RHS will be coerced to, if necessary.
Therefore, by casting $manCount to [string], + then performs string concatenation, as you intended.
As Matt points out in a comment on your answer, you can also use string interpolation:
"$manCount `n"
[1]There are exceptions; e.g., '3' - '1' yields [int] 2; i.e., PowerShell treats both operands as numbers, because operator - has no meaning in a string context.
The integer needed to be cast as a string in order for the concatenation to take:
"-- MANIFEST COUNT -- " >> "C:\psTest\test1.txt"
$manCount = (Get-ChildItem -filter "*manifest.csv").Count
[string]$manCount + "`r`n" >> "C:\psTest\test1.txt"

You cannot call a method on a null-valued expression?

I'm trying to take the input "name" and find the whitespace so that I can find the first and last letter of the first and last name entered. But it's telling me "You cannot call a method on a null-valued expression." Help?
$name = Read-Host "Please enter the zip of person $count"
$length = $name.Length
$name = $name.split(" ")
write-host $name[0]
You made a significant change to your post. It used to be:
$name = Read-Host "Please enter the name of person $count"
$length = $name.Length
$pos = $name.IndexOf('\s')
print $pos
Lets ignore the $length line since you do not use it. It looks like you are trying to split on the first white space using regular expressions. You are using .IndexOf() which if you examine the overloads will see it expects strings or a char. Not earth shattering but the point is it is looking for string literals and does not support regular expressions. Consider the following statements
PS C:\Users\Cameron> "John Smith".IndexOf('\s')
-1
PS C:\Users\Cameron> "John\sSmith".IndexOf('\s')
4
The first returned -1 since the string \s was not found. Then we put that string between John and Smith and we now get a positive return since the string literal was matched.
What you were possibly trying to do was use the -split which I base on your original question and the edit. -split supports regular expressions.
PS C:\Users\Cameron> $name = "John Smith"
PS C:\Users\Cameron> ($name -split '\s+')[0]
John
What the second line of code did was split the string $name on the group of white-space. We returned the first element which would be 'John'. The second, not shown since it should be obvious is 'Smith'. Neither elements have trailing or leading white-space ( based only on this example. Mileage will vary on other strings.)
Also, the command print is and alias for Out-Printer. Doubt you meant that command and were most likely looking for, like Dane Boulton suggested, Write-Host or Write-Output. Note: Look them up to understand an important difference. Former writes to console where the ladder writes to the output stream.
Lastly good guess would be that the error was caused by $name being null at the time $name.IndexOf('\s') was called. Easy to simulate as well.
PS C:\Users\Cameron> $something = $null
PS C:\Users\Cameron> $something.Method()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $something.Method()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
im not sure which is causing you to get the null value error. But to get the first and last name just use this:
$name = "John Smith"
$name = $name.split(" ")
$name[0] #outputs John
$name[1] #outputs Smith
Also you want write-host or write-output not print

Powershell Using Backtick for new lines - weirdness

What exaxctly is happening in example 1? How is this parsed?
# doesnt split on ,
[String]::Join(",",("aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa," + `
"aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa".Split(',') `
| foreach { ('"' + $_ + '"') }))
# adding ( ) does work
[String]::Join(",",(("aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa," + `
"aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aaaaa").Split(',') `
| foreach { ('"' + $_ + '"') }))
In you first example you may remove the backtick, because Powershell knows that the string will continue (there is a + sign).
What posh does
takes string "aaaa,aaaa..." (1) from first
evaluates the expression with split - it returns array of strings (from "aaaa,...aaaa".Split(','))
converts the array of strings to string, which returns again string "aaaa,...aaaa"
adds results from 1. and 3.
Note: when posh converts array to string, it uses $ofs variable. You will see it better in action when you will try this code:
$ofs = "|"
[String]::Join(",", ("aaaaa,aaaaa" + "bbbb,bbbb,bbbb".Split(',') | foreach { ('"' + $_ + '"') }))
Your first example only has the Split method applied to the second string of a's. The parentheses are necessary for order of operations. The Split method is performed before the concatenation in your first example.