2

我似乎无法弄清楚如何在 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
}
4

2 回答 2

5

不,不,那是行不通的。关于 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
}
于 2017-11-04T08:09:27.380 回答
4

TessellatingHeckler 的解释是正确的。但是,如果您坚持使用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> 

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

于 2017-11-04T08:36:41.570 回答