如何使用 $_. herestring 中的变量?

How to use a $_. variable in a herestring?

我似乎无法弄清楚如何在 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 的全部好处在于不必将所有内容都变成一个字符串,然后将它拖到月球上然后再拖回来,试图从字符串中取出重要的东西。 {$_.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
}

是对的。但是,如果您坚持使用 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\SO108347.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> 

注意:一些 text/code 编辑器可以将制表符转换为 space 序列!