RTPA.ps1 (zpäť na zoznam) Skript na zisťovanie približne 50 nastavení servra ako požiadavka na server aby bol akceptovaný do produkčného prostredia.
			$error.Clear()
$ErrorActionPreference = "SilentlyContinue"
$RTPA_folder = "C:\Install\RTPA_check"
$hostname = hostname
$datacenter = $hostname.substring(0,3)
$myFQDN = [System.Net.Dns]::GetHostByName((hostname)).HostName
$date = Get-Date -Format "yyyy-MM-dd"
$time = Get-Date -Format "_HH.mm"
$date_folder = $RTPA_folder+"\"+$date
$osit_folder = "C:\osit\etc"
$header = "hostname;type;check;result;comment`n`r"
$OSversion = [environment]::OSVersion.Version
$build = [string]$OSversion.major+"."+[string]$OSversion.minor
$model = (Get-WmiObject Win32_ComputerSystem).Model
$isInDomain = (Get-WmiObject Win32_ComputerSystem).partofdomain
$defaultGW = (Get-NetIPConfiguration).IPv4DefaultGateway.NextHop
$GBcalc = 1073741824
$isHyperV = $false
$isHyperVhost = $false
$isHyperVDC = $false
if ($myFQDN -match "hyperv") {
    $isHyperV = $true
    $isHyperVDC = (Get-WindowsFeature | Where-Object {$_.Name -eq "AD-Domain-Services"}).installed
}
if ($hostname -match "hyperv") {
    $isHyperVhost = $true
}

$text = $text1 = $text2 = $text3 = ""

### check files ###
$result_file = $date_folder+"\result"+$time+".txt"
$system_spec_file = $date_folder+"\system_spec.txt"
$dns_file = $date_folder+"\dns_check.txt"
$tz_file = $date_folder+"\timezone_check.txt"
$connect_file = $date_folder+"\connect_check.txt"
$SW_check_file = $date_folder+"\sw_check.txt"
$secpol_file = $date_folder+"\secpol.txt"
$event_log_file = $date_folder+"\eventlog_reader_check.txt"
$admin_members_file = $date_folder+"\local_admins.txt"
$account_check_file = $date_folder+"\account_check.txt"
$PIM_check_file = $date_folder+"\pim_check.txt"
$hardening_check_file = $date_folder+"\hardening.txt"
$logsize_check_file = $date_folder+"\log_size.txt"
$automatic_services_check_file = $date_folder+"\auto_services.txt"
$eventlog_check_file = $date_folder+"\eventlog.txt"
$device_error_check_file = $date_folder+"\device_check.txt"
$firewall_check_file = $date_folder+"\firewall.txt"
$patching_check_file = $date_folder+"\patching.txt"
$license_check_file = $date_folder+"\licence.txt"
$teaming_check_file = $date_folder+"\teaming.txt"
$HBA_check_file = $date_folder+"\HBA.txt"
$SMH_check_file = $date_folder+"\SMH.txt"
$VMtools_check_file = $date_folder+"\vmtools.txt"

#variables
$dat_file_to_check = "C:\Program Files (x86)\Common Files\McAfee\Engine\avvnames.dat" #AV Dat file to check the AV update
$versionToCheck_vmtools = "10.0.9.55792" #VMTools
$versionToCheck_HBA = "9.1.17.25" #HBA Version

#NBU burmgt specs
$server_type_cpu = 1
$server_type_ram = 2
$server_type_os_disk = 100
$server_type_other_disks = @("E:")
$server_type_other_disks_sizes = @(100)

#set the check type for better filtering
$type = ""

#result write function
function result_write {
    param($hostname, $type, $check, $result, $comment)
    $result = $hostname+";"+$type+";"+$check+";"+$result+";"+$comment+"`n`r"
    Add-Content $result_file $result
}

#function to check timezone and write result
function timezone_check {
    param($content, $city)
    if ($content -match $city) {
        result_write $hostname $type "timezone" "OK" "N/A"
    }
    else {
        result_write $hostname $type "timezone" "not OK" "wrong timezone: $script:tz"
    }
}

function socket_connect {
    param($computers, $port)
    "connection Check" | Out-File $script:connect_file -Encoding ascii
    foreach ($computer in $computers) {
        $socket = New-Object Net.Sockets.TcpClient #create new socket object
        $socket.Connect($computer, $port) #connect to computer on port
        $connect_result = $computer+": "+$socket.Connected
        Add-Content $script:connect_file $connect_result
        if ($socket.Connected) {
            result_write $script:hostname $type "HPSA connection check" "OK" $computer
            $socket.Close()
        }
        else {
            result_write $script:hostname $type "HPSA connection check" "not OK" "could not connect to satelite $computer on port $port"
        }
        try { #PS version 2 doesn't recognize dispose method
            $socket.Dispose()
        }
        catch {
            $socket = $null
        }
        $socket = $null
    }
}

#create RTPA folder
if (-not (Test-Path $RTPA_folder)) { #test for existence
    if (New-Item -Path $RTPA_folder -ItemType Directory) { #create folder and test for success
        if (-not (New-Item -Path $date_folder -ItemType Directory)) { #create current date directory and test for success, if false terminate script
            Write-Host $hostname "Unable to create RTPA date folder, unable to create temp files. Termination."
            exit(1)
        }
    }
    else { #terminate script if unable to create the RTPA folder
        Write-Host $hostname "Unable to create RTPA folder, unable to create temp files. Termination."
        exit(1)
    }
}
else { #test and create date folder
    if (-not (Test-Path $date_folder)) { #test for existence
        if (-not (New-Item -Path $date_folder -ItemType Directory)) { #create current date directory and test for success, if false terminate script
            Write-Host $hostname "Unable to create RTPA date folder, unable to create temp files. Termination."
            exit(1)
        }
    }
}

#write header to result file
$header | Out-File $result_file -Encoding ascii


######## --- System specifications --- ########
#CPU + RAM + DISKS
$type = "system specs"

$specs = Get-WmiObject Win32_ComputerSystem | Select-Object *
$specs | Out-File $system_spec_file -Encoding ascii

$system_spec_file_tmp = $date_folder+"\system_specs_temp.txt"
$disks = Get-WmiObject Win32_LogicalDisk | Select-Object *
$disks | Out-File $system_spec_file_tmp -Encoding ascii
(Get-Content $system_spec_file_tmp) | Add-Content $system_spec_file

if ($hostname -match "_hostname_match_") {
    $cpu = $server_type_cpu
    $ram = $server_type_ram
    $os_disk = $server_type_os_disk
    $other_disks = $server_type_other_disks
    $other_disks_sizes = $server_type_other_disks_sizes
}
else {
    $cpu = $ram = $os_disk = $other_disks = $other_disks_sizes = $false
}

if ($cpu -and $ram -and $os_disk -and $other_disks -and $other_disks_sizes) {
    if ($cpu -eq $specs.NumberOfLogicalProcessors) {
        result_write $hostname $type "CPU count" "OK" "N/A"
    }
    else {
        [string]$text = "CPU count is " + $specs.NumberOfLogicalProcessors + " and should be " + $cpu
        result_write $hostname $type "CPU count" "not OK" $text
    }

    [int]$ramsize = ($specs.TotalPhysicalMemory/$GBcalc)
    if ($ram -eq $ramsize) {
        result_write $hostname $type "RAM size" "OK" "N/A"
    }
    else {
        [string]$text = "RAM size is " + [string]$ramsize + "GB and should be " + $ram + "GB"
        result_write $hostname $type "RAM size" "not OK" $text
    }

    $system_disk = Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DeviceID -eq "C:"}
    [int]$diskSize = ($system_disk.Size/$GBcalc)
    if ($os_disk -eq $diskSize) {
        result_write $hostname $type "System disk size" "OK" "N/A"
    }
    else {
        [string]$text = "System disk size is " + [string]$diskSize + "GB and should be " + $os_disk + "GB"
        result_write $hostname $type "System disk size" "not OK" $text
    }

    $disk_order = 0
    foreach ($disk in $other_disks) {
        $other_disk = Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DeviceID -eq $disk}
        [int]$diskSize = ($other_disk.Size/$GBcalc)
        if ($other_disks_sizes[$disk_order] -eq $diskSize) {
            result_write $hostname $type "System disk size" "OK" "N/A"
        }
        else {
            [string]$text = $disk + " disk size is " + [string]$diskSize + "GB and should be " + $other_disks_sizes[$disk_order] + "GB"
            result_write $hostname $type "System disk size" "not OK" $text
        }
        $disk_order++
    }
}
else {
    $cpu_count = $specs.NumberOfLogicalProcessors
    result_write $hostname $type "CPU count" $cpu_count "N/A"

    [int]$ram_size = ($specs.TotalPhysicalMemory/$GBcalc)
    [string]$text = [string]$ram_size + "GB"
    result_write $hostname $type "RAM size" $text "N/A"

    $disks = Get-WmiObject Win32_LogicalDisk
    foreach ($disk in $disks) {
        if (($disk.DeviceID -eq "C:") -and ($model -notmatch "ProLiant")) {
            [int]$diskSize = ($disk.Size/$GBcalc)
            if ($diskSize -eq 100) {
                result_write $hostname $type "System disk size" "OK" "N/A"
            }
            else {
                [string]$text = "Disk size is " + [string]$diskSize + "GB and should be 100GB"
                result_write $hostname $type "System disk size" "not OK" $text
            }
        }
        else {
            if ($disk.MediaType -ne 12) { #12 is fixed media, other types are removable/floppy/CD
                continue
            }
            $text1 = $disk.DeviceID + " disk size"
            [int]$diskSize = ($disk.Size/$GBcalc)
            [string]$text2 = [string]$diskSize + "GB"
            result_write $hostname $type $text1 $text2 "N/A"
        }
    }
}

#PAGEFILE size + location
$pagefile = Get-WmiObject Win32_PageFileUsage | Select-Object *
$pagefile_file_tmp = $date_folder + "\pagefile_tmp.txt"
$pagefile | Out-File $pagefile_file_tmp -Encoding ascii
(Get-Content $pagefile_file_tmp) | Add-Content $system_spec_file
#Add-Content $system_spec_file $pagefile

[int]$pagefile_size = $pagefile.AllocatedBaseSize/1024
$pagefile_location = $pagefile.Caption
[string]$text = [string]$pagefile_size + "GB"
result_write $hostname $type "Page file size" $text "N/A"
result_write $hostname $type "Page file location" $pagefile_location "N/A"


######## --- OPC TEST --- ########
#check type
$type = "monitoring"


######## --- DNS check --- ########
#check type
$type = "default"

#with nslookup
if ($datacenter -match "_DC_NAME_") {
    $primaryDC = "_PRIMARY_DC_NAME_"
}
elseif ($datacenter -match "_DC_NAME_") {
    $primaryDC = "_PRIMARY_DC_NAME_"
}

$dnsServer = "_FQDN_"

if ($build -eq "6.2" -or $build -eq "6.3") { #for 2012, possibly 2016
    try {
        Resolve-DnsName -Name $myFQDN -Server $dnsServer -NoHostsFile -DnsOnly -Type A | Out-File $dns_file -Encoding ascii
    }
    catch {
        $error[0] | Out-File $dns_file -Encoding ascii
    }
}
else { #only 2008
    try {
        [System.Net.Dns]::GetHostAddresses($myFQDN) | Out-File $dns_file -Encoding ascii
    }
    catch {
        $error[0] | Out-File $dns_file -Encoding ascii
    }
}

Add-Content $dns_file $dnsServer
Add-Content $dns_file $myFQDN

$tmp_content = Get-Content $dns_file
if ($tmp_content -notmatch "DNS name does not exist|No such host is known") {
    result_write $hostname $type "dns" "OK" "N/A"
}
else {
    result_write $hostname $type "dns" "not OK" "no DNS records could be found"
}

######## --- timezone check --- ########
#check type
$type = "server settings"

$tz = ([System.TimeZoneInfo]::Local).DisplayName
$tz | Out-File $tz_file -Encoding ascii

$tmp_content = Get-Content $tz_file
if ($datacenter -match "_DC_NAME_") { #datacenter related timezone check
    timezone_check $tmp_content "_TIMEZONE_NAME_"
}
elseif ($datacenter -match "_DC_NAME_") {
    timezone_check $tmp_content "_TIMEZONE_NAME_"
}

#check type
$type = "monitoring"


$port = 3001
if ($datacenter -match "_DC_NAME_") {
    $satelites = @("_IP_1_","_IP_2_")
    socket_connect $satelites $port
}
elseif ($datacenter -match "_DC_NAME_") {
    $satelites = @("_IP_1_","_IP_2_")
    socket_connect $satelites $port
}


######## --- software installation check --- ########
#check type
$type = "software"

$SW_check_file_tmp = $date_folder+"\sw_check_tmp.txt"

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, DisplayVersion, InstallDate | Out-File $SW_check_file -Encoding ascii
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallDate | Out-File $SW_check_file_tmp -Encoding ascii

(Get-Content $SW_check_file_tmp) | Add-Content $SW_check_file

$tmp_content = Get-Content $SW_check_file

if ($tmp_content -match "_SW_NAME_") {
    result_write $hostname $type "_SW_NAME_ installed" "OK" "N/A"
}
else {
    result_write $hostname $type "_SW_NAME_ installed" "not OK" "not installed"
}

if ($tmp_content -match "_SW_NAME_") {
    result_write $hostname $type "_SW_NAME_ installed" "OK" "N/A"
}
else {
    result_write $hostname $type "_SW_NAME_ installed" "not OK" "not installed"
}



######## --- account checks --- ########
#check type
$type = "account check"

$secpol = invoke-expression -command "secedit /export /cfg $secpol_file" #security policy export to check several deny logon rights
net localgroup administrators | Out-File $admin_members_file -Encoding ascii #export all local administrators
net localgroup "event log readers" | Out-File $event_log_file -Encoding ascii #export all eventlog readers

#check for user existence and group membership
net localgroup users | Out-File $account_check_file -Encoding ascii


$tmp_content = Get-Content $account_check_file
if ($tmp_content -match "_ACCOUNT_NAME_") {
    result_write $hostname $type "user existence" "OK" "N/A"
    $tmp_content = Get-Content $event_log_file
    if ($tmp_content -match "Event Log Readers") {
        result_write $hostname $type "user in Event Log Readers group" "OK" "N/A"
    }
    else {
        result_write $hostname $type "user in Event Log Readers group" "not OK" "user is missing in group"
    }
}
else {
    result_write $hostname $type "user existence" "not OK" "user not created"
}

Add-Content $account_check_file "`r`n"

if (-not $isInDomain -or $isHyperV) { 
    #check for security policy denial
    $tmp_content = Get-Content $secpol_file
    $tmp = $tmp_content | Where-Object {$_ -match "SeDenyInteractiveLogonRight|SeDenyRemoteInteractiveLogonRight|SeDenyBatchLogonRight|SeDenyServiceLogonRight"}
    Add-Content $account_check_file $tmp
    #deny logon locally
    if ($tmp_content | Select-String "SeDenyInteractiveLogonRight" | Where-Object {$_ -match "_ACCOUNT_NAME_"}) {
        result_write $hostname $type "deny interactive logon" "OK" "N/A"
    }
    else {
        result_write $hostname $type "deny interactive logon" "not OK" "missing policy settings"
    }
    #deny logon via RDP
    if ($tmp_content | Select-String "SeDenyRemoteInteractiveLogonRight" | Where-Object {$_ -match "_ACCOUNT_NAME_"}) {
        result_write $hostname $type "deny RDP logon" "OK" "N/A"
    }
    else {
        result_write $hostname $type "deny RDP logon" "not OK" "missing policy settings"
    }
    #deny logon as a batch job
    if ($tmp_content | Select-String "SeDenyBatchLogonRight" | Where-Object {$_ -match "_ACCOUNT_NAME_"}) {
        result_write $hostname $type "deny batch logon" "OK" "N/A"
    }
    else {
        result_write $hostname $type "deny batch logon" "not OK" "missing policy settings"
    }
    #deny logon as a service
    if ($tmp_content | Select-String "SeDenyServiceLogonRight" | Where-Object {$_ -match "_ACCOUNT_NAME_"}) {
        result_write $hostname $type "deny service logon" "OK" "N/A"
    }
    else {
        result_write $hostname $type "deny service logon" "not OK" "missing policy settings"
    }
}


#PIM
#check type
$type = "PIM"

$tmp_content = Get-Content $admin_members_file
net localgroup users | Out-File $PIM_check_file -Encoding ascii
$pim_content = Get-Content $PIM_check_file


if ($pim_content | Select-String "_acc_2_") { #check if created
    result_write $hostname $type "_acc_2_ account creation" "OK" "N/A"
}
else {
    result_write $hostname $type "_acc_2_ account creation" "not OK" "not created"
}
if ($tmp_content | Select-String "_acc_2_") { #check if administrator
    result_write $hostname $type "_acc_2_ account admin" "OK" "N/A"
}
else {
    result_write $hostname $type "_acc_2_ account admin" "not OK" "not in administrators"
}


if ($isHyperVhost) {
    $maxI = 0
}
elseif ($isHyperV -and (-not $isHyperVhost) -and (-not $isHyperVDC)) {
    $maxI = 3
}
else {
    $maxI = 11
}
for ($i = 1; $i -lt $maxI; $i++) {
    if ($pim_content | Select-String "_acc_$i") { #check if created
        result_write $hostname $type "_acc_$i account creation" "OK" "N/A"
    }
    else {
        result_write $hostname $type "_acc_$i account creation" "not OK" "not created"
    }
    if ($tmp_content | Select-String "_acc_$i") { #check if administrator
        result_write $hostname $type "_acc_$i account admin" "OK" "N/A"
    }
    else {
        result_write $hostname $type "_acc_$i account admin" "not OK" "not in administrators"
    }
}


######## --- Hardening script check --- ########
#check type
$type = "hardening"

if (-not $isInDomain -or $isHyperV) { #GPO rewrites this
    #checking for Log size (system, security, application)
    $logs = @("system", "security", "application")
    $log_sizes = @(102400, 1100000, 102400)
    $log_retention_days = @(7, 7, 7)

    Get-Eventlog -list | Select-Object -property * | Out-File $hardening_check_file -Encoding ascii
    "" | Out-File $logsize_check_file -Encoding ascii
    for ($i=0; $i -lt $logs.Count; $i++) {
        $log_check = Get-Eventlog -list | Where-Object {$_.Log -match $logs[$i]} | Select-Object MaximumKilobytes, MinimumRetentionDays
        Add-Content $logsize_check_file $logs[$i]
        $text1 = "maximum size: "+[string]($log_check.MaximumKilobytes)
        $text2 = "retention days: "+[string]($log_check.MinimumRetentionDays)
        Add-Content $logsize_check_file $text1
        Add-Content $logsize_check_file $text2
        Add-Content $logsize_check_file "`r`n"
        if (($log_check.MaximumKilobytes -ge $log_sizes[$i])) {
            $text = $logs[$i]+" log size check"
            result_write $hostname $type $text "OK" "N/A"
        }
        else {
            $text1 = $logs[$i]+" log size check"
            $text2 = "wrong size: "+$log_check.MaximumKilobytes+", should be: "+$log_sizes[$i]
            result_write $hostname $type $text1 "not OK" $text2
        }
        if ($log_check.MinimumRetentionDays -eq $log_retention_days[$i]) {
            $text = $logs[$i]+" retention days check"
            result_write $hostname $type $text "OK" "N/A"
        }
        else {
            $text1 = $logs[$i]+" retention days"
            $text2 = "wrong setting: "+$log_check.MinimumRetentionDays+", should be: "+$log_retention_days[$i]
            result_write $hostname $type $text1 "not OK" $text2
        }
    }
}

#security policy check
$tmp_content = Get-Content $secpol_file

if (-not $isInDomain -or $isHyperV) { #GPO rewrites this
    #logon attempts
    if ($tmp_content -match "LockoutBadCount = 6") {
        result_write $hostname $type "lockout count" "OK" "N/A"
    }
    else {
        result_write $hostname $type "lockout count" "not OK" "not set to 6"
    }

    #audit logon types
    if ($tmp_content -match "AuditLogonEvents = 2") {
        result_write $hostname $type "audit logon events" "OK" "N/A"
    }
    else {
        result_write $hostname $type "audit logon events" "not OK" "not set to failure (2)"
    }
}
#logoff after 1 hour
if ($tmp_content -match "ForceLogoffWhenHourExpire = 1") {
    result_write $hostname $type "logoff after hour" "OK" "N/A"
}
else {
    result_write $hostname $type "logoff after hour" "not OK" "not enabled (not set to 1)"
}


#deny interactive logon rights, batch logon and RDP logon for _acc_1_, _acc_2_ and _acc_3_
$settings = @("SeDenyInteractiveLogonRight", "SeDenyBatchLogonRight", "SeDenyRemoteInteractiveLogonRight")
if (-not $isInDomain) { #GPO rewrites this
    $accounts = @("_acc_1_", "_acc_2_", "_acc_3_")
}
else {
    $accounts = $null
}
foreach ($setting in $settings) {
    $tmp = $tmp_content | Select-String $setting
    if ($isHyperV) {
        if ($setting -eq "SeDenyInteractiveLogonRight") {
            if (-not $isHyperVDC) {
                $accounts = @("_acc_1_", "_acc_2_", "_acc_3_", "domain\_hyper_acc_1_", "domain\_hyper_acc_2_")
            }
            else {
                $accounts = @("domain\_hyper_acc_1_", "domain\_hyper_acc_2_")
            }
        }
        elseif ($setting -eq "SeDenyBatchLogonRight") {
            if (-not $isHyperVDC) {
                $accounts = @("_acc_1_", "_acc_2_", "_acc_3_", "domain\_hyper_acc_1_", "domain\_hyper_acc_1__RunAs", "domain\_hyper_acc_3_", "domain\_hyper_acc_4_")
            }
            else {
                $accounts = @("domain\_hyper_acc_1_", "domain\_hyper_acc_1__RunAs", "domain\_hyper_acc_3_", "domain\_hyper_acc_4_")
            }
        }
        elseif ($setting -eq "SeDenyRemoteInteractiveLogonRight") {
            if (-not $isHyperVDC) {
                $accounts = @("_acc_1_", "_acc_2_", "_acc_3_", "domain\_hyper_acc_1_", "domain\_hyper_acc_2_", "domain\_hyper_acc_1__RunAs", "domain\_hyper_acc_3_", "domain\_hyper_acc_4_")
            }
            else {
                $accounts = @("domain\_hyper_acc_1_", "domain\_hyper_acc_2_", "domain\_hyper_acc_1__RunAs", "domain\_hyper_acc_3_", "domain\_hyper_acc_4_")
            }
        }
    }
    if ($accounts) {
        foreach ($account in $accounts) {
            #check first if user _acc_1_ exists
            if ($account -eq "_acc_1_") {
                $cyg_exists = net localgroup users | Where-Object {$_ -match "_acc_1_"}
                # $cyg_exists = Get-WmiObject Win32_UserAccount | Where-Object {$_.Name -eq "_acc_1_"}
                if (-not $cyg_exists) {
                    continue
                }
            }
            $text = $account+": "+$setting
            if ($account -match "hyperv") {
                $objUser = $strSID = $null
                $sidSplit = $account.split("\")
                $objUser = New-Object System.Security.Principal.NTAccount($sidSplit[0], $sidSplit[1]) 
                $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
                if ($strSID) {
                    $account = $strSID.Value
                }
                else {
                    $account = "no value"
                }
            }
            if (($tmp -match $account)) {
                result_write $hostname $type $text "OK" "N/A"
            }
            else {
                result_write $hostname $type $text "not OK" "user not defined in security policy"
            }
        }
    }
}

#deny server operator (not included) SeBackupPrivilege, SeSystemtimePrivilege
$settings = @("SeBackupPrivilege", "SeSystemtimePrivilege")
foreach ($setting in $settings) {
    $tmp = $tmp_content | Select-String $setting
    $text = "Server Operators (S-1-5-32-549) not included in "+$setting
    if ($tmp -match "S-1-5-32-549") {
        result_write $hostname $type $text "not OK" "user still in security policy"
    }
    else {
        result_write $hostname $type $text "OK" "N/A"
    }
}

#registry settings check for screensaver and for 2012 and newer also inactivity timeout
$item = Get-ItemProperty -path "HKLM:system\software\microsoft\windows nt\currentversion\winlogon"
Add-Content $hardening_check_file $item.Pspath
$text = "ScreenSaverGracePeriod: "+$item.ScreenSaverGracePeriod+"`r`n"
Add-Content $hardening_check_file $text
if ($item) {
    if ($item.ScreenSaverGracePeriod -eq 0) {
        result_write $hostname $type "ScreenSaverGracePeriod" "OK" "N/A"
    }
    else {
        $text = "HKLM:system\software\microsoft\windows nt\currentversion\winlogon\ScreenSaverGracePeriod value is "+$item.ScreenSaverGracePeriod+", should be 0"
        result_write $hostname $type "ScreenSaverGracePeriod" "not OK" $text
    }
}
else {
    result_write $hostname $type "ScreenSaverGracePeriod" "not OK" "Key: HKLM:system\software\microsoft\windows nt\currentversion\winlogon\ScreenSaverGracePeriod is not set"
}

#check for 2012 version of OS
if ($build -eq "6.2" -or $build -eq "6.3") {
    $item = Get-ItemProperty -path "HKLM:Software\Microsoft\Windows\CurrentVersion\Policies\System"
    Add-Content $hardening_check_file $item.Pspath
    $text = "InactivityTimeoutSecs: "+$item.InactivityTimeoutSecs+"`r`n"
    if ($isInDomain) { #different value for screensaver for HyperV
        $SSvalueToCheck = 900
    }
    elseif (-not $isInDomain) {
        $SSvalueToCheck = 1800
    }
    Add-Content $hardening_check_file $text
    if ($item) {
        if ($item.InactivityTimeoutSecs -eq $SSvalueToCheck) {
            result_write $hostname $type "InactivityTimeoutSecs" "OK" "N/A"
        }
        else {
            $text = "HKLM:Software\Microsoft\Windows\CurrentVersion\Policies\System\InactivityTimeoutSecs value is "+$item.InactivityTimeoutSecs+", should be " + $SSvalueToCheck
            result_write $hostname $type "InactivityTimeoutSecs" "not OK" $text
        }
    }
    else {
        result_write $hostname $type "InactivityTimeoutSecs" "not OK" "Key: HKLM:Software\Microsoft\Windows\CurrentVersion\Policies\System\InactivityTimeoutSecs is not set"
    }
}

$item = Get-ItemProperty -path "HKLM:System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server"
Add-Content $hardening_check_file $item.Pspath
$text = "Enabled: "+$item.Enabled+"`r`n"
Add-Content $hardening_check_file $text
if ($item) {
    if ($item.Enabled -eq 0) {
        result_write $hostname $type "SSL 3.0 Server: Enabled" "OK" "N/A"
    }
    else {
        $text = "HKLM:System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server\Enabled value is "+$item.Enabled+", should be 0"
        result_write $hostname $type "SSL 3.0 Server: Enabled" "not OK" $text
    }
}
else {
    result_write $hostname $type "SSL 3.0 Server: Enabled" "not OK" "Key: HKLM:System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server\Enabled is not set"
}

$item = Get-ItemProperty -path "HKLM:System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client"
Add-Content $hardening_check_file $item.Pspath
$text = "Enabled: "+$item.Enabled+"`r`n"
Add-Content $hardening_check_file $text
if ($item) {
    if ($item.Enabled -eq 0) {
        result_write $hostname $type "SSL 3.0 Client: Enabled" "OK" "N/A"
    }
    else {
        $text = "HKLM:System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client\Enabled value is "+$item.Enabled+", should be 0"
        result_write $hostname $type "SSL 3.0 Client: Enabled" "not OK" $text
    }
}
else {
    result_write $hostname $type "SSL 3.0 Client: Enabled" "not OK" "Key: HKLM:System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client\Enabled is not set"
}


######## --- NTP Status --- ########
$type = "server settings"
$syncType = (Get-ItemProperty -Path "HKLM:System\CurrentControlSet\Services\W32Time\Parameters").Type
$syncServerTmp = (Get-ItemProperty -Path "HKLM:System\CurrentControlSet\Services\W32Time\Parameters").NtpServer
$tmp = $syncServerTmp.split(",")
$syncServer = $tmp[0]
if ($isInDomain) {
    if ($syncType -eq "NT5DS") {
        result_write $hostname $type "Time Sync" "OK" "N/A"
    }
    else {
        result_write $hostname $type "Time Sync" "not OK" "server is not synchronizing with DC"
    }
}
else {
    if ($syncType -eq "NTP") {
        if ($syncServer -eq $defaultGW) {
            result_write $hostname $type "Time Sync" "OK" "N/A"
        }
        else {
            result_write $hostname $type "Time Sync" "not OK" "Default GW is not set as NTP server"
        }
    }
    else {
        result_write $hostname $type "Time Sync" "not OK" "Time sync is not configured properly"
    }
}


######## --- Automatic services --- ########
Get-Service | Select-Object Status, DisplayName, StartType | Out-File $automatic_services_check_file -Encoding ascii

$services = Get-Service | Select-Object Status, DisplayName, StartType | Where-Object {$_.StartType -eq "Automatic" -and $_.Status -eq "Stopped"}
if ($services) {
    $text = "some automatic services are not running: "
    foreach ($service in $services) {
        $text += $service.DisplayName+", "
    }
    result_write $hostname $type "automatic services" "not OK" $text
}
else {
    result_write $hostname $type "automatic services" "OK" "N/A"
}

######## --- Event errors --- ########
$days_to_check = 5
"" | Out-File $eventlog_check_file -Encoding ascii
$eventlogs = @("System", "Application")
$unexpected_shutdown = $false
foreach ($eventlog in $eventlogs) {
    $errors = Get-EventLog -LogName $eventlog -EntryType Error -After ((Get-Date).Date.AddDays(-$days_to_check))
    Add-Content $eventlog_check_file $eventlog
    foreach ($err in $errors) {
        $text1 = "time: "+$err.TimeGenerated
        $text2 = "source: "+$err.Source
        $text4 = "eventID: "+$err.EventID
        $text3 = "message: "+$err.Message+"`r`n"
        Add-Content $eventlog_check_file $text1
        Add-Content $eventlog_check_file $text2
        Add-Content $eventlog_check_file $text4
        Add-Content $eventlog_check_file $text3
        if (($err.EventID -eq "6008" -and $err.Source -eq "Eventlog") -or ($err.EventID -eq "41" -and $err.Source -match "Kernel")) {
            $unexpected_shutdown = $true
        }
    }
    $errors_count = (Get-EventLog -LogName $eventlog -EntryType Error -After ((Get-Date).Date.AddDays(-$days_to_check))).count
    $text1 = $eventlog+" event log"
    if ($errors_count -ne 0) {
        if ($unexpected_shutdown -and $eventlog -eq "System") {
            $text3 = ", with Unexpected shutdown, check!"
        }
        else {
            $text3 = ""
        }
        $text2 = [string]$errors_count+" errors found in last "+$days_to_check+" day(s)"+$text3
        result_write $hostname $type $text1 "not OK" $text2
    }
    else {
        result_write $hostname $type $text1 "OK" "N/A"
    }
}

######## --- Device manager errors --- ########
$type = "device manager"

$devices = Get-WmiObject Win32_PnPEntity | Select-Object Name, Status, ConfigManagerErrorCode
$devices | Out-File $device_error_check_file -Encoding ascii
$deviceErrorCount = 0

foreach ($device in $devices) {
    if (($device.Status -ne "OK" -or $device.Status -ne "") -and $device.ConfigManagerErrorCode -ne 0) {
        $deviceErrorCount++
    }
}
if ($deviceErrorCount -eq 0) {
    result_write $hostname $type "device errors" "OK" "N/A"
}
else {
    result_write $hostname $type "device errors" "not OK" "number of errors found: $deviceErrorCount"
}

######## --- Windows Firewall --- ########
$type = "OS settings"

$fwSettings = Get-NetFirewallProfile
$fwSettings | Out-File $firewall_check_file -Encoding ascii

foreach ($setting in $fwSettings) {
    $fwprofile = $setting.name
    if ($setting.enabled -eq "True") {
        result_write $hostname $type "$fwprofile profile firewall settings" "not OK" "firewall is enabled"
    }
    else {
        result_write $hostname $type "$fwprofile profile firewall settings" "OK" "N/A"
    }
}

######## --- Windows Patching --- ########
#find if there was any patching activity in last 30 days
$patches = Get-WmiObject Win32_QuickFixEngineering | Where-Object {$_.InstalledOn} | Where-Object {(Get-date($_.Installedon)) -gt (get-date).adddays(-30)}
$patches | Out-File $patching_check_file -Encoding ascii

if ($patches) {
    result_write $hostname $type "OS patching" "OK" "N/A"
}
else {
    result_write $hostname $type "OS patching" "not OK" "No patching in last 30 days"
}

######## --- Hostsfile check --- ########
if (-not $isHyperVhost) {
    $tmp_content = Get-Content "C:\Windows\System32\drivers\etc\hosts"
    if ($tmp_content -match $myFQDN) {
        result_write $hostname $type "hostfile check for server itself" "OK" "N/A"
    }
    else {
        result_write $hostname $type "hostfile check for server itself" "not OK" "entry for server is missing"
    }
    
}

######## --- Licence status --- ########
$license = Get-WmiObject SoftwareLicensingProduct | Where-Object {$_.LicenseStatus -eq 1}
$license | Out-File $license_check_file -Encoding ascii
if ($license) {
    result_write $hostname $type "OS activated" "OK" "N/A"
}
else {
    result_write $hostname $type "OS activated" "not OK" "OS is not activated"
}

######## --- UAC settings --- ########
if ((Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System).EnableLUA -eq "0") {
    result_write $hostname $type "UAC status" "OK" "N/A"
}
else {
    result_write $hostname $type "UAC status" "not OK" "not disabled completely"
}

if ($model -match "ProLiant") {
    $type = "Physical server only"

    ######## --- NIC teaming --- ########
    $teaming = Get-NetLbfoTeam
    $teaming | Out-File $teaming_check_file -Encoding ascii

    if ($teaming) {
        result_write $hostname $type "NIC teaming" "OK" "N/A"
    }
    else {
        result_write $hostname $type "NIC teaming" "not OK" "no teaming set"
    }

    ######## --- HBA driver version --- ########
    $HBA = (Get-Item "C:\Windows\System32\drivers\ql2300.sys").VersionInfo | Select-Object *
    $HBA | Out-File $HBA_check_file -Encoding ascii

    $fileVersion = $HBA.FileVersion
    if ([System.Version]$fileVersion -ge [System.Version]$versionToCheck_HBA) {
        result_write $hostname $type "HBA Driver version" "OK" "N/A"
    }
    else {
        result_write $hostname $type "HBA Driver version" "not OK" "HBA driver is old. Version is $fileVersion and should be $versionToCheck_HBA"
    }

    ######## --- SMH service disabled --- ########
    $SMH = Get-Service | Select-Object StartType, Status | Where-Object {$_.DisplayName -match "Homepage"}
    if ($SMH) {
        $SMH | Out-File $SMH_check_file -Encoding ascii
        if ($SMH.status -eq "Running") {
            result_write $hostname $type "SMH service not running" "not OK" "service is running"
        }
        else {
            result_write $hostname $type "SMH service not running" "OK" "N/A"
        }
        if ($SMH.StartType -eq "Disabled") {
            result_write $hostname $type "SMH service startype (disabled)" "OK" "N/A"
        }
        else {
            result_write $hostname $type "SMH service startype (disabled)" "not OK" "service is not disabled"
        }
    }
    else {
        "SMH not installed" | Out-File $SMH_check_file -Encoding ascii
        result_write $hostname $type "System Management Homepage" "OK" "Not installed"
    }
}

######## --- VMTools version check --- ########
if ($model -match "vmware") {
    $type = "VM check only"

    $VMTools = (Get-Item "C:\Program Files\VMware\VMware Tools\vmtoolsd.exe").VersionInfo | Select-Object *
    $VMTools | Out-File $VMtools_check_file -Encoding ascii

    $fileVersion = $VMTools.FileVersion
    if ([System.Version]$fileVersion -ge [System.Version]$versionToCheck_vmtools) {
        result_write $hostname $type "VMtools version" "OK" "N/A"
    }
    else {
        result_write $hostname $type "VMtools version" "not OK" "VMtools version is old. Version is $fileVersion and should be $versionToCheck_vmtools"
    }
}
Get-Content $result_file | Where-Object {$_}