如何使用 $_.此处字符串中的变量



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

TessellatingHeckler的解释是正确的。但是,如果您坚持在这里字符串,这也是可能的。请参阅以下示例(仅为演示而创建):

$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:PShellSO47108347.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> 

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

相关内容

  • 没有找到相关文章

最新更新