Search code examples
powershellvariablesherestring

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


I can't seem to figure out how to use a variable in a herestring, and for the variable to be expanded at a later time in a piped command. I have experimented with single ' and double " quotes, and escape ` characters.

I am trying to use the herestring for a list (e.g. like an array) of Exchange groups, and a corresponding list of conditions to apply to those groups. Here is a simplified example which fails to use the $Conditions variable correctly (it does not expand the $_.customattribute2 variable):

# 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
}

Solution

  • TessellatingHeckler's explanation is right. However, if you insist on herestring, it's possible as well. See the following example (created merely for demonstration):

    $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
    }
    

    Output:

    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> 
    

    Caution: some text/code editors could convert tabulators to space sequences!