2017-11-04 4 views
2

herestring에서 변수를 사용하는 방법과 나중에 파이프 된 명령에서 변수를 확장하는 방법을 알아낼 수 없습니다. 나는 '이라는 싱글을 인용하여 " 따옴표를 더블 시도하고 ` 문자를 이스케이프한다.

Exchange 그룹의 목록 (예 : 배열과 같은) 및 해당 그룹에 적용 할 조건 목록에이 문자열을 사용하려고합니다.

# 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

TessellatingHeckler's explanation이 맞습니다. 그러나 당신이 스트링 스트링을 고집한다면 그것은 가능합니다.

[email protected]' 
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> 

주의 : (데모 단순히 생성) 다음의 예를 참조 텍스트/코드 편집기 공간 시퀀스에 도표 작성자를 변환 할 수 있습니다!

+0

고마워, 내가 찾고있는 Invoke-Expression이 그 것이다! –

5

아니,하지 않을 것없이 작동하려면 다음은 올바르게 $Conditions 변수를 사용하지 단순화 된 예는 (가 $_.customattribute2 변수를 확장하지 않습니다)입니다. 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 
} 
+0

해시 테이블은 배열보다 더 적합한 데이터 구조라고 주장합니다. –

+0

@AnsgarWiechers에 동의합니다. 그룹 이름과 조건의 해시 테이블은 실제 사용에 더 잘 맞을 것입니다. Hashtable 버전으로 작성하기 시작했습니다. 그러나 추가 속성 이름과 스크립트 블록과 관련없는'{}'을 사용하는 것이 불분명 할지도 모른다고 결정했습니다. 요점은 분리 된 쌍 목록의 원래 '모양'에 가깝게 만들었습니다. – TessellatingHeckler

+0

아마도 이것이 더 나은 파워 쉘 방식이지만, @JosefZ이 내 특정 질문에 대답했습니다. –