You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中如何为-Description参数添加变量?

PowerShell中如何为-Description参数添加变量?

嘿,我来帮你搞定这个问题~

你遇到的问题其实是PowerShell里字符串参数的写法问题,直接用加号拼接的话,PowerShell会把"grants rights to"单独当成-Description的参数值,后面的+ $location会被识别成多余的参数,自然就不生效啦。

给你几种正确的写法:

  1. 双引号直接嵌入变量(最简便)
    PowerShell会自动解析双引号内的变量,所以直接把变量放到双引号里就行:
-Description "grants rights to $location"
  1. 括号包裹拼接表达式
    如果习惯用加号拼接,记得把整个拼接结果用括号括起来,让PowerShell把它当成一个完整的参数值:
-Description ("grants rights to " + $location)
  1. 字符串格式化语法
    这种写法可读性也不错,适合复杂的字符串组合:
-Description ("grants rights to {0}" -f $location)

举个完整的示例,比如你创建AD组的命令可以改成这样:

# 获取用户输入的位置信息
$location = Read-Host "请输入组对应的位置信息"

# 创建AD组并设置描述
New-ADGroup -Name "ExampleGroup" `
            -SamAccountName "ExampleGroup" `
            -GroupCategory Security `
            -GroupScope Global `
            -Description "grants rights to $location" `
            -Path "OU=YourTargetOU,DC=yourdomain,DC=com"

这样就能把用户输入的位置信息正确加到组描述里啦~

备注:内容来源于stack exchange,提问作者Phil Hebden

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 02:39:49