How do I concatenate values in PowerShell?

Viewed 477

I am trying to Resolve some DNS records using PowerShell. All of the Resolve-DnsName methods work below with the exception of the one where I try to append "owa." to the beginning of the domain name. The latest error I get is "cannot validate argument on parameter name". I have tried various combinations with no luck (i.e. owa.$Domain.Name). What is the proper way to concatenate the values to achieve a successful DNS resolution?

$Domain = New-Object System.Object
$Domain | Add-Member -type NoteProperty -name MXRecord -value $MXQuery
$Domain | Add-Member -type NoteProperty -name Name -value "mydomain.com"
$MXQueryRecord = Resolve-DnsName $Domain.Name -type MX -Server 8.8.8.8
$OWAQuery = Resolve-DnsName $("owa.")-$($Domain.Name) -type CNAME -Server 8.8.8.8
$TXTQuery = Resolve-DnsName $Domain.Name -type TXT -Server 8.8.8.8
$NSQuery = Resolve-DnsName $Domain.Name -type NS -Server 8.8.8.8

$Queries =$($MXQuery,$OWAQuery,$TXTQuery,$NSQuery)
2 Answers

Use (...) to pass an expression's value / command's output as a command argument:

Resolve-DnsName ("owa." + $Domain.Name) -type CNAME -Server 8.8.8.8

Note: $(...), the subexpression operator, is only needed if what you're trying to pass comprises multiple statements. @(...), the array-subexpression operator, is only needed if you need to guarantee that the output is treated as an array even if only a single object is output.

(...), $(...), @(...) have the advantage of working with any data type, not just strings.

Alternatively, if what you're passing is a string value (as in this case), you can use string expansion (interpolation), as shown in Drako's answer.


As for what you tried:

$("owa.")-$($Domain.Name)

is parsed as two arguments by PowerShell:

  • Subexpression $("owa."), which evaluates to string literal owa.
  • Expandable string -$($Domain.Name), which evaluates to -<domain-name> (evaluation as an expandable string means that is evaluated the same way it would if you explicitly double-quoted that token ("-$($Domain.Name)")).

It's not always obvious when PowerShell breaks a compound token into multiple arguments; the behavior is summarized here.
To learn about how unquoted tokens are parsed as arguments in general, see this answer.

Note that if you had double-quoted your entire token ("$("owa.")-$($Domain.Name)"), your command would have worked too (but there'd be no need to embed a string literal via $(...)).
To learn more about expandable strings (string interpolation), see this answer.

Try to write it like this

$OWAQuery = Resolve-DnsName "owa.-$($Domain.Name)" -type CNAME -Server 8.8.8.8

(if I correctly understood that it should look as: owa.-somedomainname; because dash seems extra so just remove it if unnecessary)

Related