如何在powershell中扩展变量? [英] How to expand variable in powershell?

查看:43
本文介绍了如何在powershell中扩展变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Get-WmiObject -Class win32_logicaldisk -Filter 'DeviceID="C:"'

做我想做的,

$var="C:"
Get-WmiObject -Class win32_logicaldisk -Filter 'DeviceID="{$var}"'

什么都不做.我尝试更改引号、连接字符串和其他 1000 项内容,但它们不起作用.为什么上面的例子不起作用,什么会起作用?

does nothing. I tried to change the quotes, to concatenate strings, and other 1000 things, but they didn't work. Why the above example doesn't work, and what would work?

推荐答案

当您以 '(单引号)开始字符串文字时,您正在创建一个逐字字符串 - 也就是说,每个字符串中的字符按字面解释,变量引用和表达式不会扩展!

When you start a string literal with ' (single-quotes), you're creating a verbatim string - that is, every character inside the string is interpreted literally and variable references and expressions won't expand!

如果要扩展变量,请使用 ":

Use " if you want the variable to be expanded:

$var = 'C:'
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='$var'"

如果你的变量名有奇怪的字符,或者后面跟着一个单词字符,你可以用大括号{}之后限定变量名$:

If your variable name has weird characters, or is followed by a word character, you can qualify the variable name with curly brackets {} immediately after the $:

$var = 'C:'
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='${var}'"

这篇关于如何在powershell中扩展变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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