How do I concatenate strings and variables in Powe

2019-01-07 01:56发布

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?

17条回答
虎瘦雄心在
2楼-- · 2019-01-07 02:14

(Current PS version 5.1.17134.407)

It's all said and done by now I guess but this also works as of now:

$myVar = "Hello"

echo "${myVar} World"
查看更多
叼着烟拽天下
3楼-- · 2019-01-07 02:15

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)"
查看更多
姐就是有狂的资本
4楼-- · 2019-01-07 02:16

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
查看更多
唯我独甜
5楼-- · 2019-01-07 02:16

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")
查看更多
看我几分像从前
6楼-- · 2019-01-07 02:21

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

查看更多
疯言疯语
7楼-- · 2019-01-07 02:22

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)
查看更多
登录 后发表回答