希望加快这个PowerShell功能

时间:2016-01-23 02:23:35

标签: loops powershell

我正在运行以下代码从SCOM 2012中提取数据,并使用SCCM 2012中的导出电子表格,正在等待重启的输出服务器以及用于自动计划重新启动的SCCM维护窗口。

代码大约需要5-8分钟才能运行,我想知道是否有任何方法可以加快这个过程。在Begin Loop下运行的代码是瓶颈。

Function Generate-RebootData{
IF(Get-Command Get-SCOMAlert -ErrorAction SilentlyContinue){}ELSE{Import-Module OperationsManager}

"Get Pend reboot servers from prod"
New-SCOMManagementGroupConnection -ComputerName ProdSrv

$AlertData = get-SCOMAlert -Criteria `
"Severity = 1 AND ResolutionState < 254 AND Name = 'Pending Reboot'" |
Select NetbiosComputerName

"Get Pend reboot servers from cert"
#For cert information
New-SCOMManagementGroupConnection -ComputerName CertSrv

$AlertData += Get-SCOMAlert -Criteria `
"Severity = 1 AND ResolutionState < 254 AND Name = 'Pending Reboot'" |
Select NetbiosComputerName

"Remove duplicates"
$AlertDataNoDupe = $AlertData | Sort NetbiosComputerName -Unique

"Create hash table"
$table = @{}
"Populate hash table"
Import-Csv D:\Scripts\servers2.csv | ForEach-Object {
    $table[$_.Computername] = $_.'Collection Name'}

"Create final object"
$result = @{}
"Begin Loop"
$result = $AlertDataNoDupe | ForEach-Object { [PSCustomObject] @{ 

Server=$_.NetbiosComputerName

MaintenanceWindow=IF($table[$_.NetbiosComputerName]){$table[$_.NetbiosComputerName]}

                ELSE{"Not found!"}

PingCheck=IF(Test-Connection -Count 1 $_.NetbiosComputerName -Quiet -EA SilentlyContinue)
        {"Alive"}
        ELSE{"Dead"}

LastReboot=Try{
 $operatingSystem = Get-WmiObject Win32_OperatingSystem -ComputerName `
 $_.NetbiosComputerName -ErrorAction Stop
        [Management.ManagementDateTimeConverter]::ToDateTime(`
 $operatingSystem.LastBootUpTime)}
        Catch{"Access Denied!"}
 } }
}

1 个答案:

答案 0 :(得分:0)

您应首先执行PingCheck,并且只有在成功继续进行Get-WmiObject通话时才会执行 - 如果您刚刚确定,则无需联系机器它已经死了&#34;。

...
$result = $AlertDataNoDupe | ForEach-Object {
    # Create hashtable
    $Properties = @{
        Server = $_.NetbiosComputerName
        MaintenanceWindow = if($table[$_.NetbiosComputerName]){
            = $_.NetbiosComputerName
        } else {
            'Not found!'
        }
    }

    # Perform ping check, keep as boolean
    $Properties['PingCheck'] = Test-Connection -Count 1 $_.NetbiosComputerName -Quiet -EA SilentlyContinue

    $Properties['LastReboot'] = if($Properties['PingCheck'])
    {
        try 
        {
            # Server seems to be online
            $operatingSystem = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_.NetbiosComputerName -ErrorAction Stop
            [Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)
        }
        catch 
        {
            'Access Denied!'
        }
    }
    else
    {
        # If server doesn't respond, declare it offline
        'Computer offline!'
    }

    # create the object
    New-Object -TypeName psobject -Property $Properties
}
相关问题