PowerShell:在 cmdlet 之后将字符串与变量连接起来 [英] PowerShell: concatenate strings with variables after cmdlet

查看:54
本文介绍了PowerShell:在 cmdlet 之后将字符串与变量连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己必须在 cmdlet 之后将字符串与变量连接起来.例如,

I often find myself in the situation where I have to concatenate a string with a variable after a cmdlet. For example,

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

如果我尝试运行它,PowerShell 会抛出以下错误:

If I try to run this, PowerShell throws the following error:

New-Item : 找不到接受参数+"的位置参数.

New-Item : A positional parameter cannot be found that accepts argument '+'.

我没有正确连接字符串吗?我不想在我执行此操作的每个 cmdlet 之前声明另一个变量(例如,$logfile = $archive_path + logfile.txt",然后执行 New-项目 $logfile -type 文件).另外,我不会总是连接文件路径.

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 (e.g., $logfile = $archive_path + "logfile.txt", and then do New-Item $logfile -type file). Also, I won't always be concatenating a file path.

推荐答案

您收到该错误是因为 PowerShell 解析器看到 $archive_path+"logfile.txt" 作为三个单独的参数参数,而不是一个字符串.

You get that error because the PowerShell parser sees $archive_path, +, and "logfile.txt" as three separate parameter arguments, instead of as one string.

将字符串连接括在括号中,(),以更改计算顺序:

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.

这篇关于PowerShell:在 cmdlet 之后将字符串与变量连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆