$ServerList1 = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,OU=NCRA,DC=ccx,DC=carecentrix,DC=com" | Select-Object DNSHostName
$ServerList2 = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,OU=FLT2,DC=ccx,DC=carecentrix,DC=com" | Select-Object DNSHostName
$ServerList3 = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,OU=AZPH,DC=ccx,DC=carecentrix,DC=com" | Select-Object DNSHostName
$ServerList4 = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,OU=CLVA1,DC=ccx,DC=carecentrix,DC=com" | Select-Object DNSHostName
$ServerList5 = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,OU=CTHA,DC=ccx,DC=carecentrix,DC=com" | Select-Object DNSHostName
$ServerList6 = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,OU=KSOP,DC=ccx,DC=carecentrix,DC=com" | Select-Object DNSHostName
$ServerList = $ServerList1+$ServerList2+$ServerList3+$ServerList4+$ServerList5+$ServerList6

$ServerReport = @()

$port1 = "8530"
$port2 = "8531"
$wsusserver = "psus002.ccx.carecentrix.com"



foreach ($Server in $ServerList) {
$ServerName = $Server.DNSHostName

$pssession = New-PSSession -ComputerName $ServerName -ErrorAction SilentlyContinue
$CurrentServer = New-Object System.Object
$CurrentServer | Add-Member -MemberType NoteProperty -Name "Name" -Value $ServerName
#Enter-PSSession $pssession

if ($null -ne $pssession){
    write-host "Connected to $ServerName"
    $CurrentServer | Add-Member -MemberType NoteProperty -Name "Status" -Value "Accessible"
    $CurrentServer.Name = $ServerName
    

    #Check HTTP Port
    #Clear Port Variables
    $port8530= @()
    $port8531= @()
    $port8530 = Invoke-Command -Session $pssession -ScriptBlock {invoke-webrequest http://psus002.ccx.carecentrix.com:8530/CLientWebService/Client.asmx -UseBasicParsing} -ErrorAction SilentlyContinue
    if ($port8530.StatusCode -eq "200"){
        Write-host "Port 8530 Accessible"
        $CurrentServer | Add-Member -MemberType NoteProperty -Name "8530" -Value "Open"
        }

    elseif ($null -eq $port8530) {
        $TestNetConnection = New-Object Net.Sockets.TcpClient
        $testnetconnection.connect($wsusserver,$port1)
        
        if ($testnetconnection.Connected){
            $TestNetConnection.Close()
            $CurrentServer | Add-Member -MemberType NoteProperty -Name "8530" -Value "Open"
        }
        else {
            $CurrentServer | Add-Member -MemberType NoteProperty -Name "8530" -Value "Unable to Verify"
            Write-host "Invoke Webrequest not recognized"
        }
        }

    else {
        $CurrentServer | Add-Member -MemberType NoteProperty -Name "8530" -Value "Closed"
        Write-host "Port 8531 Inaccessible"

        }
    # Check HTTPS Port
    $port8531 = Invoke-Command -Session $pssession -ScriptBlock {invoke-webrequest https://psus002.ccx.carecentrix.com:8531/CLientWebService/Client.asmx -UseBasicParsing} -ErrorAction SilentlyContinue
        
    
    if ($port8531.StatusCode -eq "200"){
        $CurrentServer | Add-Member -MemberType NoteProperty -Name "8531" -Value "Open"
        Write-host "Port 8531 Accessible"
        }

    elseif ($null -eq $port8531) {
        $TestNetConnection = New-Object Net.Sockets.TcpClient
        $testnetconnection.connect($wsusserver,$port2)
        
        if ($testnetconnection.Connected){
            $TestNetConnection.Close()
            $CurrentServer | Add-Member -MemberType NoteProperty -Name "8531" -Value "Open"
        }
        else{
            $CurrentServer | Add-Member -MemberType NoteProperty -Name "8531" -Value "Unable to Verify"
            Write-host "Invoke Webrequest not recognized"
        }
        }

    else {
        $CurrentServer | Add-Member -MemberType NoteProperty -Name "8531" -Value "Blocked"
        Write-host "Port 8531 Inaccessible"
        }

    #Check C: Drive Space
    $DriveCheck =Invoke-Command -Session $pssession -ScriptBlock {get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'"}
    $HDFreespace = [Math]::Round($DriveCheck.Freespace / 1GB)
    $HDSize =[Math]::Round($DriveCheck.Size / 1GB)
    $CurrentServer | Add-Member -MemberType NoteProperty -Name "C: Size" -Value $HDSize
    $CurrentServer | Add-Member -MemberType NoteProperty -Name "C: Freespace" -Value $HDFreespace
    if ($HDFreespace -lt 5) {
        $CurrentServer | Add-Member -MemberType NoteProperty -Name "SpaceCheck" -Value "Consider adding Space to C:"
        Write-host "C: Drive does not have enough space"
    }
    else {
        $CurrentServer | Add-Member -MemberType NoteProperty -Name "SpaceCheck" -Value "Server has sufficient space for Windows Updates"
        Write-host "C: has plenty of space"
    }

    $DriveCheck = @()

    #Windows Update Details
    $failedupdates = Invoke-Command -Session $pssession -ScriptBlock {
    $Session = New-Object -ComObject "Microsoft.Update.Session" 
    
    $Searcher = $Session.CreateUpdateSearcher() 
    
    $historyCount = $Searcher.GetTotalHistoryCount() 
    
    $Searcher.QueryHistory(0, $historyCount) | Select-Object @{Name="Computer"; Expression={$Computer}}, Date, 
    
       @{name="Operation"; expression={switch($_.operation){ 
    
           1 {"Installation"}; 2 {"Uninstallation"}; 3 {"Other"}}}}, 
    
       @{name="Status"; expression={switch($_.resultcode){ 
    
           1 {"In Progress"}; 2 {"Succeeded"}; 3 {"Succeeded With Errors"}; 
           
           4 {"Failed"}; 5 {"Aborted"} 
    
    }}},Title| Where-Object {$_.Status -eq "Failed"}
}
$failedupdates |Export-Csv -NoType "E:\Windows Update Failures\UpdateAudit-$ServerName-Failed-WindowsUpdates.csv"
   # Exit-PSSession
    $ServerReport += $CurrentServer
    Get-PSSession | Remove-PSSession
    #Copy-Item -Path \\$ServerName\Users\abamaso-ccxadmin\Desktop\UpdateAudit-$ServerName-Failed-WindowsUpdates.csv -Destination 'C:\Users\abamaso-ccxadmin\Desktop\WIndows Update Failures'
}
#outSide PSSession if
else {
    $CurrentServer | Add-Member -MemberType NoteProperty -Name "Status" -Value "Inaccessible"
    Write-host "$ServerName Inaccessible"
    $ServerReport += $CurrentServer
}
}
#outside for each
$ServerReport | Export-Csv "E:\Windows Update Failures\ServerReport.csv"