简体   繁体   English

PowerShell:在 cmdlet 之后将字符串与变量连接起来

[英]PowerShell: concatenate strings with variables after cmdlet

I often find myself in the situation where I have to concatenate a string with a variable after a cmdlet.我经常发现自己必须在 cmdlet 之后将字符串与变量连接起来。 For example,例如,

New-Item $archive_path + "logfile.txt" -type file

If I try to run this, PowerShell throws the following error:如果我尝试运行它,PowerShell 会抛出以下错误:

New-Item : A positional parameter cannot be found that accepts argument '+'.新项目:找不到接受参数“+”的位置参数。

Am I not concatenating the string correctly?我没有正确连接字符串吗? I'd like to not have to declare another variable before each cmdlet that I do this in (eg, $logfile = $archive_path + "logfile.txt" , and then do New-Item $logfile -type file ).我不想在我执行此操作的每个 cmdlet 之前声明另一个变量(例如, $logfile = $archive_path + "logfile.txt" ,然后执行New-Item $logfile -type file )。 Also, I won't always be concatenating a file path.另外,我不会总是连接文件路径。

You get that error because the PowerShell parser sees $archive_path , + , and "logfile.txt" as three separate parameter arguments, instead of as one string.您会收到该错误,因为 PowerShell 解析器将$archive_path+"logfile.txt"视为三个单独的参数参数,而不是一个字符串。

Enclose the string concatenation in parentheses, () , to change the order of evaluation:将字符串连接括在括号()中以更改计算顺序:

New-Item ($archive_path + "logfile.txt") -Type file

Or enclose the variable in a subexpression:或将变量括在子表达式中:

New-Item "$($archive_path)logfile.txt" -Type file

You can read about argument mode parsing with Get-Help about_Parsing .您可以使用Get-Help about_Parsing阅读有关参数模式解析的Get-Help about_Parsing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM