0

$AllMailboxesオブジェクトを作成して変数に保持する関数 DoWork があります。次に、その関数内で別の関数 ProcessEmail を実行します。この関数は、参照によって変数を取得$Mailboxし、それにいくつかのフィールドを追加して、更新または更新されたフィールドを持つすべての $Mailbox を保持する新しいものを作成します。$AllMailboxes$AllMailboxes$collection

$collection = @()

function DoWork() { 
    Get-User -ResultSize Unlimited | Where { $_.RecipientType -eq 'UserMailbox' } | ForEach { $Users = @{} } { $Users[$_.SamAccountName] = $_ }
    $AllMailboxes = Get-Mailbox -ResultSize Unlimited | Where { $_.RecipientTypeDetails -eq "UserMailbox" } | ForEach {
    $PrimarySmtpDomain = $_.PrimarySmtpAddress.split("@")

    New-Object psobject | 
        Add-Member -PassThru NoteProperty Alias $_.Alias | 
        Add-Member -PassThru NoteProperty Name $_.Name |        
        Add-Member -PassThru NoteProperty DisplayName $_.DisplayName 
        Add-Member -PassThru NoteProperty .... other values
     foreach ($mailbox in $allmailboxes) {
         $FullEmail = "somestring"
         ProcessEmail ([ref] $Mailbox) ($FullEmail)
     }
     $collection | ft # doesn't display anything


}

function ProcessEmail ([ref] $Mailbox, $FullEmail) {
    $RequireAdd = $true
    $addresses = $Mailbox.EmailAddresses
    foreach ($address in $addresses) {
        if ($address -imatch "sip:") { continue }
        if ($address -ireplace("smtp:","") -ieq $FullEmail) {
            $requireAdd = $false
            break
    }

    $Mailbox | Add-Member -MemberType NoteProperty -Name NewEmailToAdd -Value $FullEmail 
    $Mailbox | Add-Member -MemberType NoteProperty -Name NewEmailRequiresAdding -Value $RequireAdd  
    $Mailbox.NewEmailToAdd # displays correctly
    $Mailbox.NewEmailRequiresAdding #display correctly
    $collection += $Mailbox
}

個別の変数を作成して、ref を使用せずに ref を使用して複数のアプリケーションを試しましたが、何らかの理由で $collection またはProcessEmail関数の外にある他の手段で何かを表示することはできません。私は何かが欠けていると確信しています。

4

3 に答える 3

1

PSReference を使用して、より複雑にしています (value プロパティにアクセスする必要があります)。ここまでは必要ありません。

また、このモックアップに示されているように DoWork からの割り当てとして使用する場合を除いて、グローバル / スクリプト変数を使用する必要はほとんどありません。

function DoWork {
    foreach ($i in (1..100)) {
        $psObject = [PSCustomObject]@{
            Property1 = 1
            Property2 = 2
        }

        ProcessEmail -Mailbox $psObject -FullEmail $FullEmail

        $psObject
    }
}

function ProcessEmail {
    param(
        $Mailbox,
    )

    $Mailbox | Add-Member NewProperty1 "one"
    $Mailbox | Add-Member NewProperty2 "two"
}

$collection = DoWork

クリス

于 2016-08-02T08:43:16.297 に答える
1

スコープが不足しているようです。次のように、少なくともスクリプト スコープに変更します。

$script:collection = @()
$script:collection += $Mailbox
于 2016-08-02T08:03:48.417 に答える