【问题标题】:join quoted strings with variable in powershell在powershell中加入带变量的引用字符串
【发布时间】:2016-04-06 04:36:23
【问题描述】:

我来自 *nix 脚本背景,我是 powershell 和 Windows 管理员的新手。我正在尝试编写一个脚本来检查 Exchange/IIS smtp 虚拟主机集合上的 SmartHost 值。我试图弄清楚如何将循环变量插入到 ADSI 查询字符串中,但 + 运算符并不能解决问题:

$hosts = @("host1","host2")

foreach ($hostname in $hosts) {
$SMTPSvc = [ADSI]'IIS://' + $hostname + '/smtpsvc/1'
echo $SMTPSvc.SmartHost
}

使用带单引号或双引号的 + 会给我这个错误:

Method invocation failed because [System.DirectoryServices.DirectoryEntry] does not contain a method named 'op_Addition'. At line:3 char:1 + $SMTPSvc = [ADSI]'IIS://' + $hostname + '/smtpsvc/1' + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

将循环主机值插入 ADSI 查询字符串的正确或首选方法是什么?

【问题讨论】:

    标签: powershell string-concatenation single-quotes


    【解决方案1】:

    看起来像是操作顺序问题。查询的第一部分:

    [ADSI]'IIS://'
    

    正在转换为查询字符串,然后您尝试将字符串添加到生成的 [System.DirectoryServices.DirectoryEntry] 对象。由于该类不提供加法运算符,因此它失败了。相反,在构造查询之前先生成整个字符串,方法是将其括在括号中:

    $SMTPSvc = [ADSI]('IIS://' + $hostname + '/smtpsvc/1')
    

    【讨论】:

    • $SMTPSvc = [ADSI]"IIS://$hostname/smtpsvc/1" 在这种情况下也可以使用。
    猜你喜欢
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2012-06-29
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多