在scriptblock中使用+ =表示foreach循环中的switch语句

时间:2014-05-17 12:14:19

标签: arrays powershell foreach switch-statement

首先,感谢您花时间阅读本文,感谢您的帮助。

这是我的代码:

<#
        SCCM Request Alert Script
#>
Import-Module ActiveDirectory

$WMIObjects = Get-WmiObject -Namespace 'ROOT\SMS\Site_EUR' -Class SMS_UserApplicationRequest -ComputerName "EUR-SCCM"
$FileStore = "c:\export\SCCMRequestfile.txt"
foreach ($Obj in $WMIObjects)
{
        [String]$RequestValue = $Obj.CurrentState
        $Application = $Obj.Application
        $User = $Obj.User -replace 'MYDOMAIN\\',""
        $ADUser = Get-ADUser -Identity $User
        $PendingRequest = @()
        $CancelledRequest = @()
        $DeniedRequest = @()
        $ApprovedRequest = @()
        $Unknown = @()

        $Args = @{ 'User' = $ADUser.Name; 'Application' = $Obj.Application }

        $PR = New-Object -TypeName PSObject -Property $Args
        $CR = New-Object -TypeName PSObject -Property $Args
        $DR = New-Object -TypeName PSObject -Property $Args
        $AR = New-Object -TypeName PSObject -Property $Args
        $UR = New-Object -TypeName PSObject -Property $Args

        switch ($RequestValue) {
                1 { $PendingRequest += $PR }
                2 { $CancelledRequest += $CR }
                3 { $DeniedRequest += $DR }
                4 { $ApprovedRequest += $AR }
        default { $Unknown += $UK }
        }


}

Write-Host -ForegroundColor 'yellow' "Pending Requests "
$PendingRequest
Write-Host -ForegroundColor 'DarkYellow'  "Cancelled Requests "
$CancelledRequest
Write-Host -ForegroundColor 'DarkRed' "Denied Requests "
$DeniedRequest
Write-Host -ForegroundColor 'Green' "Approved Requests "
$ApprovedRequest
Write-Host -ForegroundColor 'White' "Unknown Approval Type "
$Unknown

此时它只返回foreach循环中的最后一个对象。

我已经使用;

手动测试了一个foreach循环
foreach ($Obj in $Objects) {

$array = @()

$array += $Obj

}

$Array

这会将每个对象放在数组中。

所以我想知道这是关于switch语句的问题还是我还没有像把它作为数组一样做的事情?

任何帮助都会很感激,谢谢。

Nigel Tatschner

1 个答案:

答案 0 :(得分:0)

您在循环的每次迭代中重新初始化数组。移动以下行,使其在 foreach循环之前

$PendingRequest = @();
$CancelledRequest = @();
$DeniedRequest = @();
$ApprovedRequest = @();
$Unknown = @();