【问题标题】:How to use a $_. variable in a herestring?如何使用 $_.字符串中的变量?
【发布时间】:2018-04-16 22:16:18
【问题描述】:

我似乎无法弄清楚如何在 herestring 中使用变量,以及稍后在管道命令中扩展该变量。我尝试过使用单引号 ' 和双引号 ",并转义 ` 字符。

我正在尝试将 herestring 用于 Exchange 组的列表(例如数组),以及适用于这些组的相应条件列表。这是一个未能正确使用$Conditions 变量的简化示例(它不会扩展$_.customattribute2 变量):

# List of groups and conditions (tab delimitered)
$records = @"
Group1  {$_.customattribute2 -Like '*Sales*'}
Group2  {$_.customattribute2 -Like '*Marketing*' -OR $_.customattribute2 -Eq 'CEO'}
"@

# Loop through each line in $records and find mailboxes that match $conditions
foreach ($record in $records -split "`n") {
    ($DGroup,$Conditions) = $record -split "`t"

    $MailboxList = Get-Mailbox -ResultSize Unlimited
    $MailboxList | where $Conditions
}

【问题讨论】:

    标签: powershell variables herestring


    【解决方案1】:

    不,不,那是行不通的。关于 PowerShell 的全部优点是不必将所有内容都变成字符串,然后将其拖到月球上然后再拖回来,试图从字符串中取出重要的东西。 {$_.x -eq "y"} 是一个脚本块。它本身就是一个东西,你不需要把它放在一个字符串中。

    #Array of arrays. Pairs of groups and conditions
    [Array]$records = @(
    
      ('Group1', {$_.customattribute2 -Like '*Sales*'}),
      ('Group2', {$_.customattribute2 -Like '*Marketing*' -OR $_.customattribute2 -Eq 'CEO'})
    
    )
    
    #Loop through each line in $records and find mailboxes that match $conditions
    foreach ($pair in $records) {
    
            $DGroup, $Condition = $pair
    
            $MailboxList = Get-Mailbox -ResultSize Unlimited
            $MailboxList | where $Condition
    }
    

    【讨论】:

    • 我认为哈希表是比数组更合适的数据结构。
    • 我同意@AnsgarWiechers,组名和条件的哈希表更适合实际使用,我开始将其编写为哈希表版本 - 但决定额外的属性名称并使用@987654323 @ 与 scriptblocks 无关可能会掩盖这一点,因此我将其改为接近分隔对列表的原始“形状”。
    • 虽然这可能是更好的 powershell 方式,但@JosefZ 回答了我的具体问题。
    【解决方案2】:

    TessellatingHeckler's explanation 是对的。但是,如果您坚持使用herestring,那也是可能的。请参阅以下示例(仅为演示而创建):

    $records=@'
    Group1  {$_.Extension -Like "*x*" -and $_.Name -Like "m*"}
    Group2  {$_.Extension -Like "*p*" -and $_.Name -Like "t*"}
    '@
    foreach ($record in $records -split "`n") {
        ($DGroup,$Conditions) = $record -split "`t"
        "`r`n{0}={1}" -f $DGroup,$Conditions
        (Get-ChildItem | 
            Where-Object { . (Invoke-Expression $Conditions) }).Name
    }
    

    输出

    PS D:\PShell> D:\PShell\SO\47108347.ps1
    
    Group1={$_.Extension -Like "*x*" -and $_.Name -Like "m*"}
    myfiles.txt
    
    Group2={$_.Extension -Like "*p*" -and $_.Name -Like "t*"}
    Tabulka stupnic.pdf
    ttc.ps1
    
    PS D:\PShell> 
    

    注意:一些文本/代码编辑器可以将制表符转换为空格序列!

    【讨论】:

    • 谢谢,我要找的是Invoke-Expression
    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 2021-10-27
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多