是否有可用于任何列的外卡?

时间:2015-09-16 09:40:30

标签: powershell

如果我已经有一组带有一组用户的变量$test。 每个用户条目有10列代表电子邮件地址。 如何仅返回包含$test变量中特定条目的值。

用户条目示例:

Alias             : User01
EmailAddresses_1  : X500:/o=bla bla bla b
EmailAddresses_2  : x500:/o=bla1 bla1 bla1 bla1
EmailAddresses_3  : smtp:USR1@testdomain1.com
EmailAddresses_4  : smtp:user01@testdomain1.com
EmailAddresses_5  : smtp:user1@testdomain2.com
EmailAddresses_6  : SMTP:user001@testdomain1.com
EmailAddresses_7  : SIP:usr01@testdomain1.com
EmailAddresses_8  : smtp:u1@testdomain2.com
EmailAddresses_9  :
EmailAddresses_10 :

正如您所看到的,某些列填充了不同的值,而其他列则为空。 如何只返回具有特定值的列,假设我只有要使用的变量。

例如,所有用户条目的值仅以&#34开头; SIP:*"

赞赏一点指路明灯。

1 个答案:

答案 0 :(得分:1)

如果您正在寻找属性名称以Alias开头并且包含特定值的所有用户的EmailAddresses,这可能会帮助您:

$Test = [PSCustomObject]@{
    Alias             = 'User01'
    EmailAddresses_1  = 'X500:/o=bla bla bla b'
    EmailAddresses_2  = 'x500:/o=bla1 bla1 bla1 bla1'
    EmailAddresses_3  = 'smtp:USR1@testdomain1.com'
    EmailAddresses_4  = 'smtp:user01@testdomain1.com'
    EmailAddresses_5  = 'smtp:user1@testdomain2.com'
    EmailAddresses_6  = 'SMTP:user001@testdomain1.com'
    EmailAddresses_7  = 'SIP:usr01@testdomain1.com'
    EmailAddresses_8  = 'smtp:u1@testdomain2.com'
    EmailAddresses_9  = $null
    EmailAddresses_10 = $null
}

$SearchString = 'SIP:'

$Found = Foreach ($T in $Test) {
    $Properties = $Test | Get-Member | Where {($_.MemberType -EQ 'NoteProperty') -and ($_.Name -like 'EmailAddresses*')}
    Foreach ($P in $Properties) {
        if ($T.($P.Name) -like "$SearchString*") {
            $T.Alias
        }
    }
}

$Found | Select -Unique

在评论中澄清之后,这可能更符合您的需求:

$SearchString = 'SIP:'
$Test | Select Alias, 
@{Name='EmailAddres1';Expression={if ($_.EmailAddresses_1 -like "$SearchString*"){$_.EmailAddresses_1}}},
@{Name='EmailAddres2';Expression={if ($_.EmailAddresses_2 -like "$SearchString*"){$_.EmailAddresses_2}}},
@{Name='EmailAddres3';Expression={if ($_.EmailAddresses_3 -like "$SearchString*"){$_.EmailAddresses_3}}},
@{Name='EmailAddres4';Expression={if ($_.EmailAddresses_4 -like "$SearchString*"){$_.EmailAddresses_4}}},
@{Name='EmailAddres5';Expression={if ($_.EmailAddresses_5 -like "$SearchString*"){$_.EmailAddresses_5}}},
@{Name='EmailAddres6';Expression={if ($_.EmailAddresses_6 -like "$SearchString*"){$_.EmailAddresses_6}}},
@{Name='EmailAddres7';Expression={if ($_.EmailAddresses_7 -like "$SearchString*"){$_.EmailAddresses_7}}},
@{Name='EmailAddres8';Expression={if ($_.EmailAddresses_8 -like "$SearchString*"){$_.EmailAddresses_8}}},
@{Name='EmailAddres9';Expression={if ($_.EmailAddresses_9 -like "$SearchString*"){$_.EmailAddresses_9}}},
@{Name='EmailAddres10';Expression={if ($_.EmailAddresses_10 -like "$SearchString*"){$_.EmailAddresses_10}}}