full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/Send-PushbulletMessage.ps1
Send-PushbulletMessage.ps1
Function Send-PushbulletMessage { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [hashtable]$PushbulletNotificationSink, [string]$Subject, [string]$Body, [bool]$Critical ) $finalMessageBody = @{ device_iden = $PushbulletNotificationSink.DeviceId type = "note" title = $subject body = $body } #$pushbulletSendUrl = "https://api.pushbullet.com/v2/pushes" #$headers = @{ 'Access-Token' = $PushbulletNotificationSink.AccessToken } $params = @{ Uri = "https://api.pushbullet.com/v2/pushes" Headers = @{ 'Access-Token' = $PushbulletNotificationSink.AccessToken } Method = "Post" Body = $finalMessageBody ErrorAction = "SilentlyContinue" } if ($PoShMonConfiguration.General.InternetAccessRunAsAccount -ne $null) { $params.Add("Credential", $PoShMonConfiguration.General.InternetAccessRunAsAccount) } if ($PoShMonConfiguration.General.ProxyAddress -ne $null) { $params.Add("Proxy", $PoShMonConfiguration.General.ProxyAddress) } $sendMessage = Invoke-WebRequest @params }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/New-PushbulletRepairMessageSubject.ps1
New-PushbulletRepairMessageSubject.ps1
Function New-PushbulletRepairMessageSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) return "[PoShMon $($PoShMonConfiguration.General.EnvironmentName) Repair Results]`r`n" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/New-PushbulletExceptionSubject.ps1
New-PushbulletExceptionSubject.ps1
Function New-PushbulletExceptionSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [ValidateSet("Monitoring", "Repairing")] [string]$Action = "Monitoring" ) return "[PoshMon $($PoShMonConfiguration.General.EnvironmentName) $Action]`r`n" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/New-PushbulletMessageBody.ps1
New-PushbulletMessageBody.ps1
Function New-PushbulletMessageBody { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [ValidateSet("All","OnlyOnFailure","None")][string]$SendNotificationsWhen, [System.Collections.ArrayList]$TestOutputValues, [TimeSpan]$TotalElapsedTime ) $messageBody = '' foreach ($testOutputValue in $testOutputValues) { if ($testOutputValue.NoIssuesFound) { $foundValue = "No" } else { $foundValue = "Yes" } if ($testOutputValue.ContainsKey("Exception")) { $foundValue += " (Exception occurred)" } $messageBody += "$($testOutputValue.SectionHeader) : issue(s) found - $foundValue `r`n" } return $messageBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Get-OSTestNames.ps1
Get-OSTestNames.ps1
Function Get-OSTestNames { [CmdletBinding()] Param( ) $tests = Get-OSTests return "'" + [system.String]::Join("','", $tests) + "'" #formatted easily for use in TestsToSkip }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Get-OSMerges.ps1
Get-OSMerges.ps1
Function Get-OSMerges { [CmdletBinding()] Param( ) $tests = [string[]]@( "WinOSTests" ) return $tests }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-ServiceStatePartial.ps1
Test-ServiceStatePartial.ps1
Function Test-ServiceStatePartial { [CmdletBinding()] param ( [string]$ServerName, [string[]]$Services, [string]$ServiceState = "Running" ) $NoIssuesFound = $true $serviceFoundOnServer = Get-Service -ComputerName $ServerName $itemOutputValues = @() foreach ($service in $Services) { Write-Verbose "`t`t Checking '$service'..." $serviceFound = $serviceFoundOnServer | Where Name -eq $service $highlight = "" if ($serviceFound -eq $null) { $NoIssuesFound = $false $highlight += "Status" Write-Host "Service '$service' on $serverName Not Found!" -ForegroundColor Red $outputItem = @{ 'DisplayName' = "[Not Found]"; 'Name' = $service; 'Status' = "[Not Found]"; 'Highlight' = $highlight } } else { if ($ServiceState -ne $serviceFound.Status) { $NoIssuesFound = $false $highlight += "Status" Write-Host "'$service' on $serverName state incorrect - expected $ServiceState" -ForegroundColor Red } else { Write-Verbose "`t`t'$service' found and in correct state" } $outputItem = [pscustomobject]@{ 'ServerName' = $ServerName; 'DisplayName' = $serviceFound.DisplayName; 'Name' = $serviceFound.Name; 'Status' = $serviceFound.Status; 'Highlight' = $highlight } } $itemOutputValues += $outputItem } $groupedoutputItem = @{ #'GroupName' = $serverName 'GroupOutputValues' = $itemOutputValues 'NoIssuesFound' = $NoIssuesFound } return $groupedoutputItem }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Invoke-OSMonitoring.ps1
Invoke-OSMonitoring.ps1
Function Invoke-OSMonitoring { [CmdletBinding()] Param( [parameter(Mandatory=$true, HelpMessage="A PoShMonConfiguration instance - use New-PoShMonConfiguration to create it")] [hashtable]$PoShMonConfiguration ) $outputValues = Invoke-MonitoringCore ` -PoShMonConfiguration $PoShMonConfiguration ` -TestList (Get-OSTests) ` -MergesList (Get-OSMerges) return $outputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-EventLogs.ps1
Test-EventLogs.ps1
Function Test-EventLogs { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) $allTestsOutput = @() foreach ($SeverityCode in $PoShMonConfiguration.OperatingSystem.EventLogCodes) { $mainOutput = Get-InitialOutputWithTimer -SectionHeader "$SeverityCode Event Log Issues" -GroupBy 'ServerName' -OutputHeaders ([ordered]@{ 'EventID' = 'Event ID'; 'InstanceCount' = 'Count'; 'Source' = 'Source'; 'User' = 'User'; 'Timestamp' = 'Timestamp'; 'Message' ='Message' }) $wmiStartDate = (Get-Date).AddMinutes(-$PoShMonConfiguration.General.MinutesToScanHistory) $wmidate = new-object -com Wbemscripting.swbemdatetime $wmidate.SetVarDate($wmiStartDate, $true) $wmiStartDateWmi = $wmidate.value foreach ($serverName in $PoShMonConfiguration.General.ServerNames) { $itemOutputValues = @() $eventLogEntryGroups = Get-GroupedEventLogItemsBySeverity -ComputerName $serverName -SeverityCode $SeverityCode -WmiStartDate $wmiStartDateWmi Write-Verbose "`t$serverName" if ($eventLogEntryGroups.Count -gt 0) { foreach ($eventLogEntryGroup in $eventLogEntryGroups) { $currentEntry = $eventLogEntryGroup.Group[0] if ($EventIDIgnoreList.Count -eq 0 -or $EventIDIgnoreList.ContainsKey($currentEntry.EventCode) -eq $false) { $mainOutput.NoIssuesFound = $false Write-Warning ("`t`t" + $currentEntry.EventCode.ToString() + ' : ' + $eventLogEntryGroup.Count + ' : ' + $currentEntry.SourceName + ' : ' + $currentEntry.User + ' : ' + $currentEntry.ConvertToDateTime($currentEntry.TimeGenerated) + ' - ' + $currentEntry.Message) # $outputItem = @{ $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverName; 'EventID' = $currentEntry.EventCode; 'InstanceCount' = $eventLogEntryGroup.Count; 'Source' = $currentEntry.SourceName; 'User' = $currentEntry.User; 'Timestamp' = $currentEntry.ConvertToDateTime($currentEntry.TimeGenerated); 'Message' = $currentEntry.Message } # $itemOutputValues += $outputItem } } # $mainOutput.OutputValues += @{ # 'GroupName' = $serverName # 'GroupOutputValues' = $itemOutputValues # } } if ($mainOutput.NoIssuesFound) { Write-Verbose "`t`tNo Entries Found In Time Specified" # $mainOutput.OutputValues += @{ # 'GroupName' = $serverName # 'GroupOutputValues' = @() # } $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverName; } } } $allTestsOutput += (Complete-TimedOutput $mainOutput) } return $allTestsOutput }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-ServiceState.ps1
Test-ServiceState.ps1
Function Test-ServiceState { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.OperatingSystem -eq $null) { throw "'OperatingSystem' configuration not set properly on PoShMonConfiguration parameter." } #if ($PoShMonConfiguration.OperatingSystem.WindowsServices.Count -eq 0) { throw "'WindowsServices' configuration not set properly on PoShMonConfiguration.OperatingSystem parameter." } if ($PoShMonConfiguration.OperatingSystem.WindowsServices.Count -gt 0) { $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Windows Service State" -GroupBy 'ServerName' -OutputHeaders ([ordered]@{ 'DisplayName' = 'Display Name'; 'Name' = 'Name'; 'Status' = 'Status' }) foreach ($serverName in $PoShMonConfiguration.General.ServerNames) { $groupedoutputItem = Test-ServiceStatePartial -ServerName $serverName -Services $PoShMonConfiguration.OperatingSystem.WindowsServices $mainOutput.NoIssuesFound = $mainOutput.NoIssuesFound -and $groupedoutputItem.NoIssuesFound #$mainOutput.OutputValues += $groupedoutputItem foreach ($item in $groupedoutputItem.GroupOutputValues) { $mainOutput.OutputValues += $item } } return (Complete-TimedOutput $mainOutput) } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-ComputerTime.ps1
Test-ComputerTime.ps1
Function Test-ComputerTime { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) #if ($PoShMonConfiguration.OperatingSystem -eq $null) { throw "'OperatingSystem' configuration not set properly on PoShMonConfiguration parameter." } $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Server Clock Review" -OutputHeaders ([ordered]@{ 'ServerName' = 'Server Name'; 'CurrentTime' = 'Current Time'; 'LastBootUptime' = 'Last Boot Time'; }) $results = Get-WmiObject Win32_OperatingSystem -Computername $PoShMonConfiguration.General.ServerNames | ` ForEach { return [pscustomobject]@{ "PSComputerName" = $_.PSComputerName "DateTime" = $_.ConvertToDateTime($_.LocalDateTime) "LastBootUptime" = $_.ConvertToDateTime($_.LastBootUptime) } } | Sort "DateTime" -Descending # this is a poor measure - it ignores timezones - but it's good enough for what I need now... $difference = [timespan]::new(0) if ($results.Count -gt 1) { for ($i=0;$i -lt $results.count - 1;$i++) { $difference += $results[$i].DateTime.Subtract($results[$i + 1].DateTime) } } else { # if it's just a single server being tested, compare it against the local machine that PoShMon is running on $difference += (Get-Date).Subtract($results[0].DateTime) } foreach ($serverResult in $results) { Write-Verbose ("`t" + $serverResult.PSComputerName + ": " + $serverResult.DateTime.ToShortTimeString()) $highlight = @() if ($difference.Minutes -ge $PoShMonConfiguration.OperatingSystem.AllowedMinutesVarianceBetweenServerTimes) { $mainOutput.NoIssuesFound = $false $highlight += "CurrentTime" Write-Warning "`tDifference ($($difference.Minutes)) is above variance threshold minutes ($($PoShMonConfiguration.OperatingSystem.AllowedMinutesVarianceBetweenServerTimes))" } $startDateTime = (Get-Date).AddMinutes(-$PoShMonConfiguration.General.MinutesToScanHistory) if ($serverResult.LastBootUptime -ge $startDateTime) { $mainOutput.NoIssuesFound = $false $highlight += "LastBootUptime" Write-Warning "`tLastBootUptime ($($serverResult.LastBootUptime)) is within the last $($PoShMonConfiguration.General.MinutesToScanHistory) minutes" } $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverResult.PSComputerName 'CurrentTime' = $serverResult.DateTime.ToString() 'LastBootUptime' = $serverResult.LastBootUptime.ToString() 'Highlight' = $highlight } } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Get-GroupedEventLogItemsBySeverity.ps1
Get-GroupedEventLogItemsBySeverity.ps1
Function Get-GroupedEventLogItemsBySeverity { param ( [string]$ComputerName, [string]$SeverityCode = "Warning", $WmiStartDate ) $events = Get-WmiObject win32_NTLogEvent -ComputerName $ComputerName -filter "(logfile='Application') AND (Type ='$severityCode') And TimeGenerated > '$wmiStartDate'" | Group-Object EventCode, Message return $events }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Get-OSTests.ps1
Get-OSTests.ps1
Function Get-OSTests { [CmdletBinding()] Param( ) $tests = [string[]]@( "EventLogs", "CPULoad", "Memory", "DriveSpace", "ComputerTime", "ServiceState" ) return $tests }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Merge-WinOSTests.ps1
Merge-WinOSTests.ps1
Function Merge-WinOSTests { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues ) $mergableOutputValues = $TestOutputValues | Where SectionHeader -In "Server CPU Load Review", "Memory Review", "Server Clock Review" if ($mergableOutputValues.SectionHeader.Count -gt 1) #make sure there's enough to merge by counting the headers { $newOutput = Get-InitialOutput -SectionHeader "Server Overview" -OutputHeaders ([ordered]@{ 'ServerName' = 'Server Name' }) foreach ($outputItem in $mergableOutputValues[0].OutputValues) { $newOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $outputItem.ServerName 'Highlight' = @() } } $cpuOutput = $mergableOutputValues | Where SectionHeader -eq "Server CPU Load Review" if ($cpuOutput -ne $null) { $newOutput.OutputHeaders.Add('CPULoad', 'CPU Load (%)') foreach ($currentCpuItem in $cpuOutput.OutputValues) { $cpuValue = $currentCpuItem.CPULoad foreach ($outputValue in $newOutput.OutputValues) { if ($outputValue.ServerName -eq $currentCpuItem.ServerName) { $outputValue | Add-Member -MemberType NoteProperty -Name 'CPULoad' -Value $cpuValue foreach ($highlight in $currentCpuItem.Highlight) { $outputValue.Highlight += $highlight } } } } if ($cpuOutput.NoIssuesFound -eq $false) { $newOutput.NoIssuesFound = $false} $newOutput.ElapsedTime += $cpuOutput.ElapsedTime $TestOutputValues.Remove($cpuOutput) } $memoryOutput = $mergableOutputValues | Where SectionHeader -eq "Memory Review" if ($memoryOutput -ne $null) { $newOutput.OutputHeaders.Add('Memory', 'Memory (GB)') foreach ($currentMemoryItem in $memoryOutput.OutputValues) { $totalMemoryValue = $currentMemoryItem.TotalMemory $freeMemoryValue = $currentMemoryItem.FreeMemory $freeMemoryPerc = $freeMemoryValue.Substring($freeMemoryValue.IndexOf(" ") + 1) $freeMemoryValue = $freeMemoryValue.Substring(0, $freeMemoryValue.IndexOf(" ")) $finalMemory = "$freeMemoryValue / $totalMemoryValue $freeMemoryPerc" foreach ($outputValue in $newOutput.OutputValues) { if ($outputValue.ServerName -eq $currentMemoryItem.ServerName) { $outputValue | Add-Member -MemberType NoteProperty -Name 'Memory' -Value $finalMemory if ($currentMemoryItem.Highlight.Contains("FreeMemory")) { $outputValue.Highlight += 'Memory' } } } } if ($memoryOutput.NoIssuesFound -eq $false) { $newOutput.NoIssuesFound = $false} $newOutput.ElapsedTime += $memoryOutput.ElapsedTime $TestOutputValues.Remove($memoryOutput) } $timeOutput = $mergableOutputValues | Where SectionHeader -eq "Server Clock Review" if ($timeOutput -ne $null) { $newOutput.OutputHeaders.Add('CurrentTime', 'Current Time') $newOutput.OutputHeaders.Add('LastBootUptime', 'Last Boot Time') foreach ($currentItem in $timeOutput.OutputValues) { foreach ($outputValue in $newOutput.OutputValues) { if ($outputValue.ServerName -eq $currentItem.ServerName) { $outputValue | Add-Member -MemberType NoteProperty -Name 'CurrentTime' -Value $currentItem.CurrentTime $outputValue | Add-Member -MemberType NoteProperty -Name 'LastBootUptime' -Value $currentItem.LastBootUptime if ($currentItem.Highlight.Contains("CurrentTime")) { $outputValue.Highlight += 'CurrentTime' } if ($currentItem.Highlight.Contains("LastBootUptime")) { $outputValue.Highlight += 'LastBootUptime' } } } } if ($timeOutput.NoIssuesFound -eq $false) { $newOutput.NoIssuesFound = $false} $newOutput.ElapsedTime += $timeOutput.ElapsedTime $TestOutputValues.Remove($timeOutput) } $TestOutputValues.Insert(0, $newOutput) } return $TestOutputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-CPULoad.ps1
Test-CPULoad.ps1
Function Test-CPULoad { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.OperatingSystem -eq $null) { throw "'OperatingSystem' configuration not set properly on PoShMonConfiguration parameter." } $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Server CPU Load Review" -OutputHeaders ([ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' }) if ($PoShMonConfiguration.General.ServerNames -eq $env:COMPUTERNAME) { $results = Get-Counter "\processor(_total)\% processor time" } else { $results = Get-Counter "\processor(_total)\% processor time" -Computername $PoShMonConfiguration.General.ServerNames } foreach ($counterResult in $results.CounterSamples) { if ($PoShMonConfiguration.General.ServerNames -eq "localhost" -or $PoShMonConfiguration.General.ServerNames -eq $env:COMPUTERNAME) { $serverName = "localhost" } else { $serverName = $counterResult.Path.Substring(2, $counterResult.Path.LastIndexOf("\\") - 2).ToUpper() } $cpuLoad = $counterResult.CookedValue $highlight = @() $cpuPercentValue = $(($cpuLoad / 100).ToString("00%")) Write-Verbose "`t$($serverName): $cpuPercentValue" if ($cpuLoad -gt $PoShMonConfiguration.OperatingSystem.CPULoadThresholdPercent) { $mainOutput.NoIssuesFound = $false $highlight += "CPULoad" Write-Warning "`tCPU Load ($cpuPercentValue) is above variance threshold ($($PoShMonConfiguration.OperatingSystem.CPULoadThresholdPercent)%)" } $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverName 'CPULoad' = $cpuPercentValue 'Highlight' = $highlight } } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-Memory.ps1
Test-Memory.ps1
Function Test-Memory { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.OperatingSystem -eq $null) { throw "'OperatingSystem' configuration not set properly on PoShMonConfiguration parameter." } $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Memory Review" -OutputHeaders ([ordered]@{ 'ServerName' = 'Server Name'; 'TotalMemory' = 'Total Memory (GB)'; 'FreeMemory' = 'Free Memory (GB) (%)' }) $results = Get-WmiObject Win32_OperatingSystem -ComputerName $PoShMonConfiguration.General.ServerNames foreach ($serverResult in $results) { $freeMemoryPercent = $serverResult.FreePhysicalMemory / $serverResult.TotalVisibleMemorySize * 100 $highlight = @() $totalSpace = $serverResult.TotalVisibleMemorySize/1MB $freeSpace = $serverResult.FreePhysicalMemory/1MB Write-Verbose ("`t" + $serverResult.PSComputerName + " : " + $totalSpace.ToString(".00") + " : " + $freeSpace.ToString(".00") + " (" + $freeMemoryPercent.ToString("00") + "%)") if ($freeMemoryPercent -lt $PoShMonConfiguration.OperatingSystem.FreeMemoryThresholdPercent) { $mainOutput.NoIssuesFound = $false $highlight += "FreeMemory" Write-Warning "`t`tFree memory ($($freeMemoryPercent.ToString("0") + "%")) is below variance threshold ($($PoShMonConfiguration.OperatingSystem.FreeMemoryThresholdPercent))" } $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverResult.PSComputerName 'TotalMemory' = $totalSpace.ToString(".00"); 'FreeMemory' = $freeSpace.ToString(".00") + " (" + $freeMemoryPercent.ToString("00") + "%)"; 'Highlight' = $highlight } } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OS/Test-DriveSpace.ps1
Test-DriveSpace.ps1
Function Test-DriveSpace { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.OperatingSystem -eq $null) { throw "'OperatingSystem' configuration not set properly on PoShMonConfiguration parameter." } $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Harddrive Space Review" -GroupBy 'ServerName' -OutputHeaders ([ordered]@{ 'DriveLetter' = 'Drive Letter'; 'TotalSpace' = 'Total Space (GB)'; 'FreeSpace' = 'Free Space (GB) (%)' }) foreach ($serverName in $PoShMonConfiguration.General.ServerNames) { Write-Verbose "`t$serverName" $itemOutputValues = @() $serverDriveSpace = Get-WmiObject win32_logicaldisk -Computername $serverName #this could be optimised to go to all servers at the same time.. foreach ($drive in ($serverDriveSpace | Where DriveType -eq 3)) { $totalSpace = $drive.Size/1GB $freeSpace = $drive.FreeSpace/1GB $freeSpacePercent = $freeSpace / $totalSpace * 100 $highlight = @() Write-Verbose ("`t`t" + $drive.DeviceID + " : " + $totalSpace.ToString(".00") + " : " + $freeSpace.ToString(".00") + " (" + $freeSpacePercent.ToString("00") + "%)") if ($PoShMonConfiguration.OperatingSystem.DriveSpaceThresholdPercent -gt 0) { if ($freeSpacePercent -lt $PoShMonConfiguration.OperatingSystem.DriveSpaceThresholdPercent) { $mainOutput.NoIssuesFound = $false $highlight += "FreeSpace" Write-Warning "`t`tFree drive Space ($("{0:N0}" -f $freeSpacePercent)%) is below variance threshold ($($PoShMonConfiguration.OperatingSystem.DriveSpaceThresholdPercent)%)" } } elseif ($freeSpace -lt $PoShMonConfiguration.OperatingSystem.DriveSpaceThreshold) { $mainOutput.NoIssuesFound = $false $highlight += "FreeSpace" Write-Warning "`t`tFree drive Space ($($freeSpace.ToString(".00"))) is below variance threshold ($($PoShMonConfiguration.OperatingSystem.DriveSpaceThreshold))" } # $outputItem = @{ $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverName; 'DriveLetter' = $drive.DeviceID; 'TotalSpace' = $totalSpace.ToString(".00"); 'FreeSpace' = $freeSpace.ToString(".00") + " (" + $freeSpacePercent.ToString("00") + "%)"; 'Highlight' = $highlight } $itemOutputValues += $outputItem } # $mainOutput.OutputValues += @{ # 'GroupName' = $serverName # 'GroupOutputValues' = $itemOutputValues # } } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Core/Initialize-Notifications.ps1
Initialize-Notifications.ps1
Function Initialize-Notifications { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues, [TimeSpan]$TotalElapsedTime ) if ($TestOutputValues.Count -gt 0) # it could be zero if an exception occurred prior to even running the first test { $noIssuesFound = Confirm-NoIssuesFound $TestOutputValues if ($PoShMonConfiguration["Notifications"].Count -gt 0) { foreach ($configurationItem in $PoShMonConfiguration["Notifications"]) { if ($configurationItem.TypeName.StartsWith("PoShMon.ConfigurationItems.NotificationCollection")) { $sendNotificationsWhen = $configurationItem.TypeName.Substring("PoShMon.ConfigurationItems.NotificationCollection-".Length) if ($sendNotificationsWhen -eq "None") { Write-Verbose "Notifications set to not send. Issues found: $noIssuesFound" } elseif ($NoIssuesFound -and $sendNotificationsWhen -eq "OnlyOnFailure") { Write-Verbose "No major issues encountered, skipping '$sendNotificationsWhen' notifications" } else { Send-MonitoringNotifications -PoShMonConfiguration $PoShMonConfiguration -NotificationSinks $configurationItem.Sinks -SendNotificationsWhen $sendNotificationsWhen -TestOutputValues $TestOutputValues -TotalElapsedTime $TotalElapsedTime } } } } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Core/Send-MonitoringNotifications.ps1
Send-MonitoringNotifications.ps1
Function Send-MonitoringNotifications { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$NotificationSinks, [ValidateSet("All","OnlyOnFailure","None")][string]$SendNotificationsWhen, [System.Collections.ArrayList]$TestOutputValues, [TimeSpan]$TotalElapsedTime ) $atLeastOneFailure = $false foreach ($testOutputValue in $testOutputValues) { if ($SendNotificationsWhen -eq "OnlyOnFailure" -and $testOutputValue.NoIssuesFound -eq $false) { $atLeastOneFailure = $true break } } foreach ($notificationSink in $NotificationSinks) { if ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.Email') { Send-PoShMonEmail ` -PoShMonConfiguration $PoShMonConfiguration ` -EmailNotificationSink $notificationSink ` -Subject (New-EmailSubject $PoShMonConfiguration $TestOutputValues) ` -Body (New-EmailBody $PoShMonConfiguration $SendNotificationsWhen $TestOutputValues $TotalElapsedTime) ` -Critical $atLeastOneFailure } elseif ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.Pushbullet') { Send-PushbulletMessage ` -PoShMonConfiguration $PoShMonConfiguration ` -PushbulletNotificationSink $notificationSink ` -Subject (New-PushbulletMessageSubject $PoShMonConfiguration $TestOutputValues) ` -Body (New-PushbulletMessageBody $PoShMonConfiguration $SendNotificationsWhen $TestOutputValues $TotalElapsedTime) ` -Critical $atLeastOneFailure } elseif ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.O365Teams') { Send-O365TeamsMessage ` -PoShMonConfiguration $PoShMonConfiguration ` -O365TeamsNotificationSink $notificationSink ` -Subject (New-O365TeamsMessageSubject $PoShMonConfiguration $TestOutputValues) ` -Body (New-O365TeamsMessageBody $PoShMonConfiguration $SendNotificationsWhen $TestOutputValues $TotalElapsedTime) ` -Critical $atLeastOneFailure } else { Write-Error "Notitication Sink '$notificationSink.TypeName' type not found" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Core/Send-ExceptionNotifications.ps1
Send-ExceptionNotifications.ps1
Function Send-ExceptionNotifications { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Exception]$Exception, [ValidateSet("Monitoring", "Repairing")] [string]$Action = "Monitoring" ) $bodyAction = if ($Action -eq "Monitoring") { "monitor" } else { "repair" } if ($PoShMonConfiguration["Notifications"].Count -gt 0) { foreach ($configurationItem in $PoShMonConfiguration["Notifications"]) { if ($configurationItem.TypeName.StartsWith("PoShMon.ConfigurationItems.NotificationCollection")) { foreach ($notificationSink in $configurationItem.Sinks) { if ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.Email') { Send-PoShMonEmail ` -PoShMonConfiguration $PoShMonConfiguration ` -EmailNotificationSink $notificationSink ` -Subject (New-EmailExceptionSubject $PoShMonConfiguration $Action) ` -Body (New-EmailExceptionBody $Exception $bodyAction) ` -Critical $true } elseif ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.Pushbullet') { Send-PushbulletMessage ` -PoShMonConfiguration $PoShMonConfiguration ` -PushbulletNotificationSink $notificationSink ` -Subject (New-PushbulletExceptionSubject $PoShMonConfiguration $Action) ` -Body (New-PushbulletExceptionBody $Exception $bodyAction) ` -Critical $true } elseif ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.O365Teams') { Send-O365TeamsMessage ` -PoShMonConfiguration $PoShMonConfiguration ` -O365TeamsNotificationSink $notificationSink ` -Subject (New-O365TeamsExceptionSubject $PoShMonConfiguration $Action) ` -Body (New-O365TeamsExceptionBody $Exception $bodyAction) ` -Critical $true } else { Write-Error "Notitication Sink '$notificationSink.TypeName' type not found" } } } } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Core/Initialize-RepairNotifications.ps1
Initialize-RepairNotifications.ps1
Function Initialize-RepairNotifications { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) if ($RepairOutputValues.Count -gt 0) { if ($PoShMonConfiguration["Notifications"].Count -gt 0) { foreach ($configurationItem in $PoShMonConfiguration["Notifications"]) { if ($configurationItem.TypeName.StartsWith("PoShMon.ConfigurationItems.NotificationCollection")) { $sendNotificationsWhen = $configurationItem.TypeName.Substring("PoShMon.ConfigurationItems.NotificationCollection-".Length) if ($sendNotificationsWhen -eq "None") { Write-Verbose "Notifications set to not send" } else { Send-RepairNotifications -PoShMonConfiguration $PoShMonConfiguration -NotificationSinks $configurationItem.Sinks -RepairOutputValues $RepairOutputValues } } } } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Core/Send-RepairNotifications.ps1
Send-RepairNotifications.ps1
Function Send-RepairNotifications { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$NotificationSinks, [object[]]$RepairOutputValues ) foreach ($notificationSink in $NotificationSinks) { if ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.Email') { Send-PoShMonEmail ` -PoShMonConfiguration $PoShMonConfiguration ` -EmailNotificationSink $notificationSink ` -Subject (New-EmailRepairSubject $PoShMonConfiguration $RepairOutputValues) ` -Body (New-EmailRepairBody $PoShMonConfiguration $RepairOutputValues) ` -Critical $false } elseif ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.Pushbullet') { Send-PushbulletMessage ` -PoShMonConfiguration $PoShMonConfiguration ` -PushbulletNotificationSink $notificationSink ` -Subject (New-PushbulletRepairMessageSubject $PoShMonConfiguration $RepairOutputValues) ` -Body (New-PushbulletRepairMessageBody $PoShMonConfiguration $RepairOutputValues) ` -Critical $false } elseif ($notificationSink.TypeName -eq 'PoShMon.ConfigurationItems.Notifications.O365Teams') { Send-O365TeamsMessage ` -PoShMonConfiguration $PoShMonConfiguration ` -O365TeamsNotificationSink $notificationSink ` -Subject (New-O365TeamsRepairMessageSubject $PoShMonConfiguration $RepairOutputValues) ` -Body (New-O365TeamsRepairMessageBody $PoShMonConfiguration $RepairOutputValues) ` -Critical $false } else { Write-Error "Notitication Sink '$notificationSink.TypeName' type not found" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Shared/Send-PoShMonEmail.ps1
Send-PoShMonEmail.ps1
Function Send-PoShMonEmail { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [hashtable]$EmailNotificationSink, [string]$Subject, [string]$Body, [bool]$Critical = $false ) Write-Verbose $Body $priority = if ($Critical) { [System.Net.Mail.MailPriority]::High } else { [System.Net.Mail.MailPriority]::Normal } $params = @{ Subject = $Subject Body = $Body BodyAsHtml = $true To = $EmailNotificationSink.ToAddress From = $EmailNotificationSink.FromAddress Priority = $priority SmtpServer = $EmailNotificationSink.SmtpServer } if ($PoShMonConfiguration.General.InternetAccessRunAsAccount -ne $null) { $params.Add("Credential", $PoShMonConfiguration.General.InternetAccessRunAsAccount) } #Send-MailMessage -Subject $Subject -Body $Body -BodyAsHtml -To $EmailNotificationSink.ToAddress -From $EmailNotificationSink.FromAddress -Priority $priority -SmtpServer $EmailNotificationSink.SmtpServer #-Port $EmailNotificationSink.Port -UseSsl $EmailNotificationSink.UseSSL Send-MailMessage @params }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.SelfHealing.Core/Invoke-Repairs.ps1
Invoke-Repairs.ps1
Function Invoke-Repairs { [CmdletBinding()] Param( [string[]]$RepairScripts, [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$PoShMonOutputValues ) Begin { $outputValues = @() } Process { foreach ($repairScript in $RepairScripts) { if (Test-Path $repairScript) { . $repairScript # Load the script $repairFunctionName = $repairScript | Get-Item | Select -ExpandProperty BaseName try { $outputValues += & $repairFunctionName $PoShMonConfiguration $PoShMonOutputValues } catch { $outputValues += @{ "SectionHeader" = $repairFunctionName; "Exception" = $_.Exception } } } else { Write-Warning "Script not found, will be skipped: $scriptToImport" } } } End { return $outputValues } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.SelfHealing.Core/Repair-Environment.ps1
Repair-Environment.ps1
Function Repair-Environment { [CmdletBinding()] Param( [hashtable]$poShMonConfiguration, [System.Collections.ArrayList]$PoShMonOutputValues, [string[]]$RepairScripts ) #$commands = Add-Scripts $RepairScripts try { $repairOutput = Invoke-Repairs $RepairScripts $PoShMonConfiguration $PoShMonOutputValues } catch { Send-ExceptionNotifications -PoShMonConfiguration $PoShMonConfiguration -Exception $_.Exception -Action "Repairing" } Initialize-RepairNotifications -PoShMonConfiguration $PoShMonConfiguration -RepairOutputValues $repairOutput }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.SelfHealing.Core/Sample-Repair-WindowsServiceState.ps1
Sample-Repair-WindowsServiceState.ps1
<# #> Function Repair-WindowsServiceState { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$PoShMonOutputValues ) $stoppedServices = $PoShMonOutputValues | Where { $_.SectionHeader -EQ "Windows Service State" -and $_.NoIssuesFound -eq $false } $repairOutput = @() foreach ($groupOutputValue in $stoppedServices.OutputValues) { $serverName = $groupOutputValue.GroupName $services = $groupOutputValue.GroupOutputValues | Where { $_.Highlight.Count -gt 0 } $serviceNames = @() foreach ($service in $services) { $serviceNames += $service.Name } Invoke-Command -ComputerName $serverName -ScriptBlock { param($serviceNames) $serviceNames | Start-Service $serviceNames | Set-Service -StartupType Automatic #Presumably if it's meant to be running, it should be set to auto start... } -ArgumentList $serviceNames $repairOutput += @{ "SectionHeader" = "Windows Service State on $serverName" "RepairResult" = "The following sevices were re-started: $serviceNames" } } return $repairOutput }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Exceptions/New-EmailExceptionSubject.ps1
New-EmailExceptionSubject.ps1
Function New-EmailExceptionSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [ValidateSet("Monitoring", "Repairing")] [string]$Action = "Monitoring" ) return "[PoshMon] $($PoShMonConfiguration.General.EnvironmentName) $Action - Exception Occurred" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Exceptions/New-EmailExceptionBody.ps1
New-EmailExceptionBody.ps1
Function New-EmailExceptionBody { [CmdletBinding()] Param( [System.Exception]$Exception, [string]$Action = "monitor" ) $emailBody = "" $emailBody += "An exception occurred while trying to $Action the environment.`r`n" $emailBody += "Details: $($Exception.ToString())" return $emailBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Web/Test-WebSites.ps1
Test-WebSites.ps1
Function Test-WebSites { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) $allTestsOutput = @() foreach ($websiteDetailKey in $PoShMonConfiguration.WebSite.WebsiteDetails.Keys) { $siteUrl = $websiteDetailKey $textToLocate = $PoShMonConfiguration.WebSite.WebsiteDetails[$websiteDetailKey] $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Web Test - $siteUrl" -OutputHeaders ([ordered]@{ 'ServerName' = 'Server'; 'StatusCode' = 'Status Code'; 'Outcome' = 'Outcome' }) For ($i = -1; $i -lt $PoShMonConfiguration.General.ServerNames.Count; $i++) { $serverName = '(Direct)' $highlight = @() if ($i -eq -1) # Direct Call { Write-Verbose ("`tScanning Site $siteUrl (Direct)") $webRequest = Invoke-WebRequest $siteUrl -UseDefaultCredentials } else { $serverName = $PoShMonConfiguration.General.ServerNames[$i] Write-Verbose ("`tScanning Site $siteUrl on $serverName") $webRequest = Invoke-RemoteWebRequest -siteUrl $siteUrl -ServerName $serverName -ConfigurationName $PoShMonConfiguration.General.ConfigurationName } if ($webRequest.StatusCode -ne 200) { $mainOutput.NoIssuesFound = $false $highlight += 'Outcome' $outcome = $webRequest.StatusDescription } else { if ($webRequest.Content.ToLower().Contains($textToLocate.ToLower())) { $outcome = "Specified Page Content Found" } else { $highlight += 'Outcome' $mainOutput.NoIssuesFound = $false $outcome = "Specified Page Content Not Found" } } Write-Verbose "`t`t$serverName : $($webRequest.StatusCode) : $outcome" $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $serverName; 'StatusCode' = $webRequest.StatusCode; 'Outcome' = $outcome 'Highlight' = $highlight } } $allTestsOutput += (Complete-TimedOutput $mainOutput) } return $allTestsOutput }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Web/Invoke-RemoteWebRequest.ps1
Invoke-RemoteWebRequest.ps1
Function Invoke-RemoteWebRequest { [CmdletBinding()] param ( [string]$SiteUrl, [string]$ServerName, [string]$ConfigurationName ) Write-Verbose "Connecting to $ServerName..." try { $remoteSession = New-PSSession -ComputerName $ServerName -ConfigurationName $ConfigurationName $webResponse = Invoke-Command -Session $remoteSession -ScriptBlock { param($SiteUrl) Invoke-WebRequest $SiteUrl -UseDefaultCredentials } -ArgumentList $SiteUrl } finally { Disconnect-RemoteSession $remoteSession } return $webResponse }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Get-InitialOutputWithTimer.ps1
Get-InitialOutputWithTimer.ps1
Function Get-InitialOutputWithTimer { [CmdletBinding()] param ( [string]$SectionHeader, [string]$GroupBy = $null, [System.Collections.Specialized.OrderedDictionary]$OutputHeaders, [string]$HeaderUrl = $null, [string]$LinkColumn = $null ) $initialOutput = Get-InitialOutput @PSBoundParameters $initialOutput.StopWatch = [System.Diagnostics.Stopwatch]::StartNew() return $initialOutput }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Invoke-Tests.ps1
Invoke-Tests.ps1
Function Invoke-Tests { [CmdletBinding()] Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$TestToRuns, [hashtable]$PoShMonConfiguration ) Begin { $outputValues = New-Object System.Collections.ArrayList #@(); } Process { foreach ($test in $TestToRuns) { try { $outputValues += & ("Test-" + $test) $PoShMonConfiguration } catch { $outputValues += @{ "SectionHeader" = $test; "NoIssuesFound" = $false; "Exception" = $_.Exception } } } } End { return $outputValues } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Complete-TimedOutput.ps1
Complete-TimedOutput.ps1
Function Complete-TimedOutput { [CmdletBinding()] param( [Hashtable]$TestOutputValues ) $TestOutputValues.StopWatch.Stop() $TestOutputValues.ElapsedTime = $TestOutputValues.StopWatch.Elapsed $TestOutputValues.Remove("StopWatch") $issuesFound = if ($TestOutputValues.NoIssuesFound) { "No" } else { "Yes" } Write-Verbose "Complete '$($TestOutputValues.SectionHeader)' Test, Issues Found: $issuesFound" return $TestOutputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Get-InitialOutput.ps1
Get-InitialOutput.ps1
Function Get-InitialOutput { [CmdletBinding()] param ( [string]$SectionHeader, [string]$GroupBy = $null, [System.Collections.Specialized.OrderedDictionary]$OutputHeaders, [string]$HeaderUrl = $null, [string]$LinkColumn = $null ) Write-Verbose "Initiating '$SectionHeader' Test..." $initialOutput = @{ "SectionHeader" = $sectionHeader; "NoIssuesFound" = $true; "OutputHeaders" = $OutputHeaders; "OutputValues" = @(); } if ($GroupBy -ne $null -and $GroupBy -ne '') { $initialOutput.GroupBy = $GroupBy } if ($HeaderUrl -ne $null -and $HeaderUrl -ne '') { $initialOutput.HeaderUrl = $HeaderUrl } if ($LinkColumn -ne $null -and $LinkColumn -ne '') { $initialOutput.LinkColumn = $LinkColumn } return $initialOutput }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Optimize-Output.ps1
Optimize-Output.ps1
Function Optimize-Output { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues, [string[]]$OutputOptimizationList ) Write-Verbose "Optimizing Output..." foreach ($optimizationFunction in $OutputOptimizationList) { $TestOutputValues = & ("Resolve-" + $optimizationFunction) $PoShMonConfiguration $TestOutputValues } return $TestOutputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Invoke-MonitoringCore.ps1
Invoke-MonitoringCore.ps1
Function Invoke-MonitoringCore { [CmdletBinding()] Param( [parameter(Mandatory=$true)] [hashtable]$PoShMonConfiguration, [parameter(Mandatory=$true)] [string[]]$TestList, [Parameter(HelpMessage="In the case of a Farm product, such as SharePoint, provide a function to call to auto-discover the remaining servers")] [string]$FarmDiscoveryFunctionName = $null, [string[]]$OutputOptimizationList = @(), [string[]]$MergesList = @() ) if ($PoShMonConfiguration.TypeName -ne 'PoShMon.Configuration') { throw "PoShMonConfiguration is not of the correct type - please use New-PoShMonConfiguration to create it" } Compare-SkippedTestsToActual $PoShMonConfiguration $TestList $stopWatch = [System.Diagnostics.Stopwatch]::StartNew() try { # Auto-Discover Servers if ($FarmDiscoveryFunctionName -ne $null -and $FarmDiscoveryFunctionName -ne '') { $PoShMonConfiguration.General.ServerNames = & $FarmDiscoveryFunctionName $PoShMonConfiguration } # Perform the actual main monitoring tests $outputValues = $TestList | ` Remove-SkippedTests -PoShMonConfiguration $PoShMonConfiguration | ` Invoke-Tests -PoShMonConfiguration $PoShMonConfiguration # Resolve any output issues with all test output (e.g. High CPU might be explained because of something in another test's output) if ($OutputOptimizationList.Count -gt 0) { $outputValues = Optimize-Output $PoShMonConfiguration $outputValues $OutputOptimizationList } $outputValues = Invoke-Merges $PoShMonConfiguration $outputValues $MergesList } catch { Send-ExceptionNotifications -PoShMonConfiguration $PoShMonConfiguration -Exception $_.Exception } finally { if ($PoShMonConfiguration.General.PrimaryServerName -ne $null -and $PoShMonConfiguration.General.PrimaryServerName -ne '') { $remoteSession = $Global:PoShMon_RemoteSession #Get-PSSession -ComputerName $PoShMonConfiguration.General.PrimaryServerName -Name $PoShMonConfiguration.General.RemoteSessionName -ConfigurationName $PoShMonConfiguration.General.ConfigurationName -ErrorAction SilentlyContinue if ($remoteSession -ne $null) { Remove-PSSession $remoteSession } } $stopWatch.Stop() } Initialize-Notifications -PoShMonConfiguration $PoShMonConfiguration -TestOutputValues $outputValues -TotalElapsedTime $stopWatch.Elapsed return $outputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Invoke-Merges.ps1
Invoke-Merges.ps1
Function Invoke-Merges { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues, [string[]]$MergesToRuns ) Begin { } Process { foreach ($merge in $MergesToRuns) { #try { $TestOutputValues = & ("Merge-" + $merge) $PoShMonConfiguration $TestOutputValues #} catch { #} } } End { return $TestOutputValues } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Confirm-NoIssuesFound.ps1
Confirm-NoIssuesFound.ps1
Function Confirm-NoIssuesFound { [CmdletBinding()] param( $TestOutputValues ) $NoIssuesFound = $true foreach ($testOutputValue in $testOutputValues) { $NoIssuesFound = $NoIssuesFound -and $testOutputValue.NoIssuesFound if ($testOutputValue.NoIssuesFound -eq $false) { break; } } return $NoIssuesFound }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Compare-SkippedTestsToActual.ps1
Compare-SkippedTestsToActual.ps1
Function Compare-SkippedTestsToActual { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [string[]]$TestList ) if (($PoShMonConfiguration.General.TestsToSkip -join '') -eq '') { $PoShMonConfiguration.General.TestsToSkip = @() } foreach ($skippedTest in $poShMonConfiguration.General.TestsToSkip) { if (!$TestList.Contains($skippedTest)) { Write-Warning "$skippedTest is specified to be skipped, but no such test exists" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.Core/Remove-SkippedTests.ps1
Remove-SkippedTests.ps1
Function Remove-SkippedTests { [CmdletBinding()] Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$AllTests, [hashtable]$PoShMonConfiguration ) Begin { $tests = [string[]]@() } Process { foreach ($test in $AllTests) { if (!$poShMonConfiguration.General.TestsToSkip.Contains($test)) { $tests += $test } } } End { return $tests } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-EmailSubject.ps1
New-EmailSubject.ps1
Function New-EmailSubject { [CmdletBinding()] param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues ) $issueCount = 0 foreach ($outputValue in $TestOutputValues) { if (($outputValue.NoIssuesFound -eq $false)) { $issueCount++ } } $subject = "[PoshMon] $($PoShMonConfiguration.General.EnvironmentName) Monitoring Results ($issueCount Issue(s) Found)" return $subject }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-EmailHeader.ps1
New-EmailHeader.ps1
Function New-EmailHeader { [CmdletBinding()] param( [hashtable]$PoShMonConfiguration ) $emailSection = '' $emailSection += '<head><title>' + $ReportTitle + '</title></head>' $emailSection += '<body style="font-family: verdana; font-size: 12px;">' $emailSection += '<table width="100%" style="border-collapse: collapse; ">' $emailSection += '<tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr>' $emailSection += '<tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #1D6097; color: #FFFFFF; Padding: 20px;"><h1>PoShMon Monitoring Report</h1></td><td style="background-color: lightgray">&nbsp;</td></tr>' $emailSection += '<tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 10px; padding-left: 20px">' + $PoShMonConfiguration.General.EnvironmentName + ' Environment</td><td style="background-color: lightgray">&nbsp;</td></tr>' $emailSection += '<tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: lightgray; padding-top: 20px;">' #start main body return $emailSection; }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-OutputHeadersEmailBody.ps1
New-OutputHeadersEmailBody.ps1
Function New-OutputHeadersEmailBody { [cmdletbinding()] param( $outputHeaders ) $emailBody = '' foreach ($headerKey in $outputHeaders.Keys) { $header = $outputHeaders[$headerKey] $emailBody += '<th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">' + $header + '</th>' } return $emailBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-EmailBody.ps1
New-EmailBody.ps1
Function New-EmailBody { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [ValidateSet("All","OnlyOnFailure","None")][string]$SendNotificationsWhen, [System.Collections.ArrayList]$TestOutputValues, [TimeSpan]$TotalElapsedTime ) $emailBody = '' $emailBody += New-EmailHeader $PoShMonConfiguration foreach ($testOutputValue in $testOutputValues) { if ($SendNotificationsWhen -eq "All" -or $testOutputValue.NoIssuesFound -eq $false) { $emailBody += New-TestOutputEmailBody -Output $testOutputValue } } $emailBody += New-EmailFooter $PoShMonConfiguration $TotalElapsedTime return $emailBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-OutputValuesEmailBody.ps1
New-OutputValuesEmailBody.ps1
Function New-OutputValuesEmailBody { [cmdletbinding()] param( $outputHeaders, $outputValues, $LinkColumn = $null ) $emailSection = '' Add-Type -AssemblyName System.Web $counter = 0 foreach ($outputValue in $outputValues) { $rowStyle = if ($counter % 2 -eq 0) { "" } else { "background-color: #e1e3e8" } $tempRow = "" foreach ($headerKey in $outputHeaders.Keys) { #$fieldValue = $outputValue[$headerKey] #Would need to change to something like $outputValue.psobject.Properties["Message"].Value if this changes to a pscustomobject $fieldValue = $outputValue.psobject.Properties[$headerKey].Value #if ($outputValue['Highlight'] -ne $null -and $outputValue['Highlight'].Contains($headerKey)) { if ($outputValue.psobject.Properties['Highlight'].Value -ne $null -and $outputValue.psobject.Properties['Highlight'].Value.Contains($headerKey)) { $style = 'font-weight: bold; color: red;"' $rowStyle = "background-color: #FCCFC5" } else { $style = '' } $align = 'left' $temp = '' if ([decimal]::TryParse($fieldValue, [ref]$temp)) { $align = 'right' } $fieldValue = [System.Web.HttpUtility]::HtmlEncode($fieldValue) if ($LinkColumn -ne $null -and $LinkColumn -ne '' -and $headerKey -eq $LinkColumn) { $linkValue = $outputValue.psobject.Properties['ItemLink'].Value if ($linkValue -ne $null -and $linkValue -ne '') { $fieldValue = "<a href=""$linkValue"">$fieldValue</a>" } } $tempRow += '<td valign="top" style="border: 1px solid #CCCCCC;' + $style + '" align="' + $align +'">' + $fieldValue + '</td>' } $emailSection += "<tr style=""$rowStyle"">" $emailSection += $tempRow $counter++ $emailSection += '</tr>' } return $emailSection }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-TestOutputEmailBody.ps1
New-TestOutputEmailBody.ps1
Function New-TestOutputEmailBody { [cmdletbinding()] param( $Output ) $emailSection = '' $title = $output.SectionHeader if ($output.ContainsKey("ElapsedTime")) { $title += $(" ({0:F2} Seconds)" -f $output["ElapsedTime"].TotalSeconds) } #$emailSection += "<p><h2>$title</h2>" #$emailSection += "<br/>" #$emailSection += '<p style="margin: 15px;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3">' $emailSection += '<div style="width:100%; background-color: #FFFFFF;">' $emailSection += '<table style="border-collapse: collapse; min-width: 500px; " cellpadding="3">' $emailSection += "<thead><tr><th align=""left"" style=""border: 1px solid CCCCCC; background-color: #1D6097;"" colspan=""$($output.OutputHeaders.Keys.Count - 1)"">" $emailSection += "<h2 style=""font-size: 16px; color: #FFFFFF"">$title</h2>" $emailSection += "<th align=""right"" style=""border: 1px solid CCCCCC; background-color: #1D6097;"">" if ($output.ContainsKey("HeaderUrl")) { $emailSection += "<a href=""$($output.HeaderUrl)"">[link]</a>" } $emailSection += "</th></tr></thead>" if ($output.ContainsKey("Exception")) { $emailSection += "<tbody><tr><td style=""background-color: #FCCFC5"">An Exception Occurred: $($output.Exception.ToString())</td></tr></tbody>" } <# elseif ($output.OutputValues -ne $null -and $output.OutputValues.Count -gt 0 -and ` $output.OutputValues[0].ContainsKey("GroupName")) #grouped output { foreach ($groupOutputValue in $output.OutputValues) { #$emailSection += '<thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="' + $output.OutputHeaders.Keys.Count + '">' + $groupOutputValue.GroupName + '</th></tr><tr>' $emailSection += '<thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="2">' + $groupOutputValue.GroupName + '</th></tr></thead>' $emailSection += '<tbody><tr><td style="padding-left: 25px">&nbsp;</td><td><table style="border-collapse: collapse;" cellpadding="3"><thead><tr>' $emailSection += (New-OutputHeadersEmailBody -outputHeaders $output.OutputHeaders) + '</tr></thead><tbody>' $emailSection += (New-OutputValuesEmailBody -outputHeaders $output.OutputHeaders -outputValues $groupOutputValue.GroupOutputValues) + '</tbody>' #$emailSection += '<tr style="border: 0px;"><td style="font-size: 6px;" colspan="' + $output.OutputHeaders.Keys.Count + '">&nbsp</td></tr>' $emailSection += '</table></td></tr></tbody>' }#> elseif ($output.ContainsKey("GroupBy")) { $groups = $output.OutputValues | Group $output["GroupBy"] foreach ($group in $groups) { $emailSection += '<thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="2">' + $group.Name + '</th></tr></thead>' $emailSection += '<tbody><tr><td style="padding-left: 25px">&nbsp;</td><td><table style="border-collapse: collapse;" cellpadding="3"><thead><tr>' $emailSection += (New-OutputHeadersEmailBody -outputHeaders $output.OutputHeaders) + '</tr></thead><tbody>' $emailSection += (New-OutputValuesEmailBody -outputHeaders $output.OutputHeaders -outputValues $group.Group -LinkColumn $output.LinkColumn) + '</tbody>' $emailSection += '</table></td></tr></tbody>' } } else { #non-grouped output $emailSection += '<thead><tr>' + (New-OutputHeadersEmailBody -outputHeaders $output.OutputHeaders) + '</tr></thead><tbody>' $emailSection += (New-OutputValuesEmailBody -outputHeaders $output.OutputHeaders -outputValues $output.OutputValues -LinkColumn $output.LinkColumn) + '</tbody>' } $emailSection += '</table></div><br/>' return $emailSection }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Monitoring/New-EmailFooter.ps1
New-EmailFooter.ps1
Function New-EmailFooter { [CmdletBinding()] param( [hashtable]$PoShMonConfiguration, [TimeSpan]$TotalElapsedTime ) $emailSection = '' $emailSection += '</td><td style="background-color: lightgray">&nbsp;</td></tr>' #end main body $emailSection += '<tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 20px">' $SkippedTests = $PoShMonConfiguration.General.TestsToSkip $emailSection += '<b>Skipped Tests:</b> ' if ($SkippedTests.Count -eq 0) { $emailSection += "None" } else { $emailSection += ($SkippedTests -join ", ") + "" } if ($TotalElapsedTime -ne $null) { $emailSection += "<br/><b>Total Elapsed Time (Seconds):</b> $("{0:F2}" -f $TotalElapsedTime.TotalSeconds) ($("{0:F2}" -f $TotalElapsedTime.TotalMinutes) Minutes)" } $currentVersion = Get-Module PoShMon -ListAvailable | Select -First 1 | Sort Version $emailSection += '</td><td style="background-color: lightgray">&nbsp;</td></tr>' #end main body $emailSection += '<tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #1D6097; color: #FFFFFF; padding: 20px" align="center">' $emailSection += "PoShMon Version $($currentVersion.Version.ToString()) ($(Get-VersionUpgradeInformation $PoShMonConfiguration))" $emailSection += '</td><td style="background-color: lightgray">&nbsp;</td></tr>' $emailSection += '<tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr>' $emailSection += '</table><br/>' $emailSection += '</body>' return $emailSection; }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPDistributedCacheHealth.ps1
Test-SPDistributedCacheHealth.ps1
Function Test-SPDistributedCacheHealth { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession [hashtable]$PoShMonConfiguration ) $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Distributed Cache Status" -OutputHeaders ([ordered]@{ 'Server' = 'Server'; 'Status' = 'Status' }) $cacheServers = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { return Get-SPServiceInstance | ? {($_.service.tostring()) -eq "SPDistributedCacheService Name=AppFabricCachingService"} | select Server, Status } # Possible extensions: <# Use-CacheCluster Get-CacheHost Get-CacheClusterHealth #> foreach ($cacheServer in $cacheServers) { $highlight = @() Write-Verbose "`t$($cacheServer.Server.DisplayName) : $($cacheServer.Status.Value)" if ($cacheServer.Status.Value -ne 'Online') { $mainOutput.NoIssuesFound = $false Write-Warning ("`t" + $cacheServer.Server.DisplayName + " is listed as " + $cacheServer.Status.Value) $highlight += 'Status' } $mainOutput.OutputValues += [pscustomobject]@{ 'Server' = $cacheServer.Server.DisplayName; 'Status' = $cacheServer.Status.Value; 'Highlight' = $highlight } } return (Complete-TimedOutput $mainOutput) } <# $output = Test-SPDistributedCacheHealth $remoteSession -Verbose #>
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPDatabaseHealth.ps1
Test-SPDatabaseHealth.ps1
Function Test-SPDatabaseHealth { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession [hashtable]$PoShMonConfiguration ) $mainOutput = Get-InitialOutputWithTimer ` -SectionHeader "Database Status" ` -OutputHeaders ([ordered]@{ 'DatabaseName' = 'Database Name'; 'Size' = 'Size (GB)'; 'NeedsUpgrade' = 'Needs Upgrade?' }) ` -HeaderUrl ($PoShMonConfiguration.SharePoint.CentralAdminUrl + "/_admin/DatabaseStatus.aspx") ` -LinkColumn 'DatabaseName' $spDatabases = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { return Get-SPDatabase | Sort DiskSizeRequired -Descending } foreach ($spDatabase in $spDatabases) { $needsUpgradeText = if ($spDatabase.NeedsUpgrade) {"Yes"} else {"No"} $SizeText = ($spDatabase.DiskSizeRequired/1GB).ToString(".00") Write-Verbose "`t$($spDatabase.DisplayName) : $needsUpgradeText : $SizeText GB" $highlight = @() if ($spDatabase.NeedsUpgrade) { $mainOutput.NoIssuesFound = $false $highlight += 'NeedsUpgrade' Write-Warning ("`t" + $spDatabase.DisplayName + " (" + $spDatabase.ApplicationName + ") is listed as Needing Upgrade") } if ($spDatabase.Type -eq 'Content Database') { $itemLink = ($PoShMonConfiguration.SharePoint.CentralAdminUrl + "/_admin/oldcntdb.aspx?DatabaseId={$($spDatabase.Id)}") } else { $itemLink = '' } $mainOutput.OutputValues += [pscustomobject]@{ 'DatabaseName' = $spDatabase.DisplayName; 'NeedsUpgrade' = $needsUpgradeText 'Size' = $SizeText; 'Highlight' = $highlight 'ItemLink' = $itemLink } } return (Complete-TimedOutput $mainOutput) } <# $output = Test-SPDatabaseHealth $remoteSession -Verbose #>
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Invoke-SPMonitoring.ps1
Invoke-SPMonitoring.ps1
Function Invoke-SPMonitoring { [CmdletBinding()] Param( [parameter(Mandatory=$true, HelpMessage="A PoShMonConfiguration instance - use New-PoShMonConfiguration to create it")] [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.SharePoint -eq $null) { $PoShMonConfiguration.SharePoint = SharePoint } $outputValues = Invoke-MonitoringCore ` -PoShMonConfiguration $PoShMonConfiguration ` -TestList (Get-SPTests) ` -FarmDiscoveryFunctionName 'Get-ServersInSPFarm' ` -OutputOptimizationList (Get-SPResolutions) ` -MergesList (Get-SPMerges) return $outputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Get-SPResolutions.ps1
Get-SPResolutions.ps1
Function Get-SPResolutions { [CmdletBinding()] Param( ) $tests = [string[]]@( "HighCPUWhileSearchRunning" ) return $tests }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPJobHealth.ps1
Test-SPJobHealth.ps1
Function Test-SPJobHealth { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession, [hashtable]$PoShMonConfiguration ) #'WebApplicationName' = 'Web Application Name'; $mainOutput = Get-InitialOutputWithTimer ` -SectionHeader "Failing Timer Jobs" ` -OutputHeaders ([ordered]@{ 'JobDefinitionTitle' = 'Job Definition Title'; 'EndTime' = 'End Time'; 'ServerName' = 'Server Name'; 'ErrorMessage' ='Error Message' }) ` -HeaderUrl ($PoShMonConfiguration.SharePoint.CentralAdminUrl + "/_admin/TimerJobHistory.aspx?View=5") $startDate = (Get-Date).AddMinutes(-$PoShMonConfiguration.General.MinutesToScanHistory) #.ToUniversalTime() $jobHistoryEntries = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { param($StartDate) $farm = Get-SPFarm $timerJobService = $farm.TimerService $jobHistoryEntries = $timerJobService.JobHistoryEntries | Where-Object { $_.Status -eq "Failed" -and $_.StartTime -gt $StartDate } return $jobHistoryEntries } -ArgumentList $startDate if ($jobHistoryEntries.Count -gt 0) { $mainOutput.NoIssuesFound = $false foreach ($jobHistoryEntry in $jobHistoryEntries) { Write-Warning ("`t" + $jobHistoryEntry.JobDefinitionTitle + " at " + $jobHistoryEntry.EndTime + " on " + $jobHistoryEntry.ServerName + " for " + $jobHistoryEntry.WebApplicationName + " : " + $jobHistoryEntry.ErrorMessage) $mainOutput.OutputValues += [pscustomobject]@{ 'JobDefinitionTitle' = $jobHistoryEntry.JobDefinitionTitle; 'EndTime' = $jobHistoryEntry.EndTime; 'ServerName' = $jobHistoryEntry.ServerName; #'WebApplicationName' = $jobHistoryEntry.WebApplicationName; 'ErrorMessage' = $jobHistoryEntry.ErrorMessage } } } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPSearchHealth.ps1
Test-SPSearchHealth.ps1
Function Test-SPSearchHealth { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession [hashtable]$PoShMonConfiguration ) Write-Verbose "Getting Search Service App..." $searchApp = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { Get-SPServiceApplication | Where TypeName -eq 'Search Service Application' } $mainOutput = Get-InitialOutputWithTimer ` -SectionHeader "Search Status" ` -OutputHeaders ([ordered]@{ 'ComponentName' = 'Component'; 'ServerName' = 'Server Name'; 'State' = 'State' }) ` -HeaderUrl ($PoShMonConfiguration.SharePoint.CentralAdminUrl + "/SearchAdministration.aspx?appid=" + $searchApp.Id) $remoteComponents = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { $ssa = Get-SPEnterpriseSearchServiceApplication $searchComponentStates = Get-SPEnterpriseSearchStatus -SearchApplication $ssa -Detailed #| Where State -ne "Active" $componentTopology = Get-SPEnterpriseSearchComponent -SearchTopology $ssa.ActiveTopology | Select Name,ServerName return @{ "SearchComponentStates" = $searchComponentStates; "ComponentTopology" = $componentTopology } } foreach ($searchComponentState in $remoteComponents.SearchComponentStates) { $highlight = @() foreach ($componentTopologyItem in $remoteComponents.ComponentTopology) { if ($componentTopologyItem.Name.ToLower() -eq $searchComponentState.Name.ToLower()) { Write-Verbose ("`t" + $componentTopologyItem.Name + " is in the following state: " + $searchComponentState.State) if ($searchComponentState.State -ne "Active") { $mainOutput.NoIssuesFound = $false $highlight += 'State' Write-Warning ("`t" + $componentTopologyItem.Name + " is not listed as 'Active'. State: " + $searchComponentState.State) } $mainOutput.OutputValues += [pscustomobject]@{ 'ComponentName' = $componentTopologyItem.Name; 'ServerName' = $componentTopologyItem.ServerName; 'State' = $searchComponentState.State; 'Highlight' = $highlight } } } } return (Complete-TimedOutput $mainOutput) } <# $output = Test-SPSearchHealth $remoteSession #>
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Get-SPMerges.ps1
Get-SPMerges.ps1
Function Get-SPMerges { [CmdletBinding()] Param( ) $tests = [string[]]@( "WinOSTests" ) return $tests }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPUPSSyncHealth.ps1
Test-SPUPSSyncHealth.ps1
Function Test-SPUPSSyncHealth { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession, [hashtable]$PoShMonConfiguration ) Write-Verbose "Getting UPS Service App..." $upsApp = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { Get-SPServiceApplication | Where TypeName -eq 'User Profile Service Application' } $mainOutput = Get-InitialOutputWithTimer ` -SectionHeader "User Profile Sync State" ` -OutputHeaders ([ordered]@{ 'ManagementAgent' = 'Management Agent'; 'RunProfile' = 'Run Profile'; 'RunStartTime' = 'Run Start Time'; 'ErrorDetail' = 'ErrorDetail' }) ` -HeaderUrl ($PoShMonConfiguration.SharePoint.CentralAdminUrl + "/_layouts/15/ManageUserProfileServiceApplication.aspx?ApplicationID=" + $upsApp.Id) Write-Verbose "`tGetting SharePoint service list to locate UPS Sync server..." $upsServiceInstance = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { return Get-SPServiceInstance | Where { $_.TypeName -eq 'User Profile Synchronization Service' -and $_.Status -eq "Online" } | Select Server } if ($upsServiceInstance -ne $null) { $runStartDate = (Get-Date).AddMinutes(-$PoShMonConfiguration.General.MinutesToScanHistory).ToString("yyyy-MM-dd HH:mm:ss") $FimRunHistory = Get-WmiObject -Namespace "root\MicrosoftIdentityIntegrationServer" -class "MIIS_RunHistory" -ComputerName $upsServiceInstance.Server.DisplayName -Filter "RunStartTime >'$runStartDate'" $failedRuns = $FimRunHistory | Where RunStatus -NotIn "success","in-progress" if ($failedRuns -ne $null -and $failedRuns.GetType().Name -eq 'ManagementObject') #only 1 occurred - force it to be an array { $failedRuns = ,$failedRuns } if ($failedRuns.Count -gt 0) { $mainOutput.NoIssuesFound = $false foreach($failedRun in $failedRuns) { [xml]$failedRunXml = $failedRun.RunDetails().ReturnValue $maName = $failedRunXml."run-history"."run-details"."ma-name" $runprofileName = $failedRunXml."run-history"."run-details"."run-profile-name" $steps = $failedRunXml."run-history"."run-details"."step-details" foreach($step in $steps) { if ($step."step-result" -ne "success") { $stepNumber = $step."step-number" $stepResult = $step."step-result" $connectionErrors = $step."ma-connection" $syncErrors = $step."synchronization-errors" if ($connectionErrors -ne "") { $errors = $connectionErrors } else { $errors = $syncErrors } Write-Warning "`tStep $stepNumber has status of $stepResult : $($errors.InnerXml)" $mainOutput.OutputValues += [pscustomobject]@{ 'ManagementAgent' = $maName; 'RunProfile' = $runprofileName; 'RunStartTime' = [DateTime]::Parse($failedRun.RunStartTime).ToString("yyyy-MM-dd HH:mm:ss") 'ErrorDetail' = $errors.InnerXml; } } } } } } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Get-SPTests.ps1
Get-SPTests.ps1
Function Get-SPTests { [CmdletBinding()] Param( ) $tests = [string[]]@( #"FarmHealth", "EventLogs", "CPULoad", "Memory", "DriveSpace", "ComputerTime", "SPServerStatus", "SPWindowsServiceState", "SPJobHealth", "SPDatabaseHealth", "SPDistributedCacheHealth", "SPSearchHealth", "SPUPSSyncHealth", "WebSites" ) return $tests }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPWindowsServiceState.ps1
Test-SPWindowsServiceState.ps1
Function Test-SPWindowsServiceState { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession, [hashtable]$PoShMonConfiguration ) $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Windows Service State" -GroupBy 'ServerName' -OutputHeaders ([ordered]@{ 'DisplayName' = 'Display Name'; 'Name' = 'Name'; 'Status' = 'Status' }) Write-Verbose "`tGetting SharePoint service list..." $spServiceInstances = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { Get-SPServiceInstance | Where Service -like '* Name=*' | Select Server, Service, Status | Sort Server } $serversWithServices = @{} [System.Collections.ArrayList]$defaultServiceList = 'IISADMIN','SPAdminV4','SPTimerV4','SPTraceV4','SPWriterV4' if ($PoShMonConfiguration.OperatingSystem.WindowsServices -ne $null -and $PoShMonConfiguration.OperatingSystem.WindowsServices.Count -gt 0) { $defaultServiceList += $PoShMonConfiguration.OperatingSystem.WindowsServices } if ($PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip -ne $null -and $PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip.Count -gt 0) { foreach ($serviceToSkip in $PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip) { $defaultServiceList.Remove($serviceToSkip) } } foreach ($spServiceInstance in $spServiceInstances) { # ignore non Windows services if ($spServiceInstance.Status.Value -eq 'Online' ` -and $spServiceInstance.Service.Name -ne 'WSS_Administration' ` -and $spServiceInstance.Service.Name -ne 'spworkflowtimerv4' ` -and !$PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip.Contains($spServiceInstance.Server.DisplayName) # Skip the service if told to ) { if (!$serversWithServices.ContainsKey($spServiceInstance.Server.DisplayName)) { $serversWithServices.Add($spServiceInstance.Server.DisplayName, $defaultServiceList) } $serversWithServices[$spServiceInstance.Server.DisplayName] += $spServiceInstance.Service.Name } } Write-Verbose "`tGetting state of services per server..." foreach ($serverWithServicesKey in $serversWithServices.Keys) { $serverWithServices = $serversWithServices[$serverWithServicesKey] $groupedoutputItem = Test-ServiceStatePartial -ServerName $serverWithServicesKey -Services $serverWithServices $mainOutput.NoIssuesFound = $mainOutput.NoIssuesFound -and $groupedoutputItem.NoIssuesFound #$mainOutput.OutputValues += $groupedoutputItem foreach ($item in $groupedoutputItem.GroupOutputValues) { $mainOutput.OutputValues += $item } } return (Complete-TimedOutput $mainOutput) } <# $output = Test-SPWindowsServiceState -RemoteSession $remoteSession -WindowsServices $WindowsServices #>
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Get-SPServerForRemoteServer.ps1
Get-SPServerForRemoteServer.ps1
Function Get-SPServerForRemoteServer { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration, [string]$ServerName ) try { $remoteSession = New-PSSession -ComputerName $ServerName -ConfigurationName $PoShMonConfiguration.General.ConfigurationName $server = Invoke-Command -Session $remoteSession -ScriptBlock { Add-PSSnapin Microsoft.SharePoint.PowerShell Get-SPServer | Where Address -eq $env:COMPUTERNAME } return $server } finally { Disconnect-RemoteSession $remoteSession } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Resolve-HighCPUWhileSearchRunning.ps1
Resolve-HighCPUWhileSearchRunning.ps1
Function Resolve-HighCPUWhileSearchRunning { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues ) Write-Verbose "`tResolving High CPU While Search is running" $highCpuOutputValues = $TestOutputValues | Where { $_.SectionHeader -EQ "Server CPU Load Review" -and $_.NoIssuesFound -eq $false } if ($highCpuOutputValues.Count -gt 0) # CPU usage is high, let's see why { $remoteComponents = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { $contentSources = Get-SPEnterpriseSearchServiceApplication | Get-SPEnterpriseSearchCrawlContentSource | Where CrawlState -Like "*crawl*" $ssa = Get-SPEnterpriseSearchServiceApplication $componentTopology = Get-SPEnterpriseSearchComponent -SearchTopology $ssa.ActiveTopology | Select Name, ServerName return @{ "ContentSources" = $contentSources; "ComponentTopology" = $componentTopology } } if ($remoteComponents.contentSources.Name -ne "" -or $remoteComponents.contentSources.Count -gt 0) #there's at least one content source currently crawling { $crawlServers = $remoteComponents.componentTopology | Where Name -NotLike 'QueryProcessing*' | Select -ExpandProperty ServerName $highCpuServers = $highCpuOutputValues.OutputValues | Where { $_.Highlight.Count -gt 0 } foreach ($highCpuServer in $highCpuServers) { if ($crawlServers.Contains($highCpuServer.ServerName)) { $highCpuServer.Highlight = @() } } } else # It's not what we thought - a Search crawl running, carry on as usual { Write-Verbose "`tResolution not applicable, will report as usual" return $TestOutputValues } } else { Write-Verbose "`tNothing found to resolve, will report as usual" } $highCpuServers = $highCpuOutputValues.OutputValues | Where { $_.Highlight.Count -gt 0 } if ($highCpuServers.Count -eq 0 -and $highCpuOutputValues.NoIssuesFound -eq $false) { $highCpuOutputValues.NoIssuesFound = $true } return $TestOutputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Get-ServersInSPFarm.ps1
Get-ServersInSPFarm.ps1
Function Get-ServersInSPFarm { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration ) #try #{ $remoteSession = Connect-PrimaryServer -PoShMonConfiguration $PoShMonConfiguration -InitiationScriptBlock { Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue } # Auto-Discover Central Admin url if ($PoShMonConfiguration.SharePoint.CentralAdminUrl -eq $null -or $PoShMonConfiguration.SharePoint.CentralAdminUrl -eq '') { $PoShMonConfiguration.SharePoint.CentralAdminUrl = Invoke-Command -Session $remoteSession -ScriptBlock { $ca = Get-SPWebApplication -IncludeCentralAdministration | Where IsAdministrationWebApplication -eq $true return $ca.url.Substring(0, $ca.url.Length - 1) } } # Auto-Discover Servers $serverNames = Invoke-Command -Session $remoteSession -ScriptBlock { Get-SPServer | Where Role -ne "Invalid" | Select -ExpandProperty Name } return $serverNames #} catch { # throw $_.Exception #} finally { # if ($remoteSession -ne $null) # { Disconnect-PSSession $remoteSession -ErrorAction SilentlyContinue | Out-Null } #} }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-SPServerStatus.ps1
Test-SPServerStatus.ps1
Function Test-SPServerStatus { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) $mainOutput = Get-InitialOutputWithTimer ` -SectionHeader "Farm Server Status" ` -OutputHeaders ([ordered]@{ 'ServerName' = 'Server Name'; 'Role' = 'Role'; 'NeedsUpgrade' = 'Needs Upgrade?'; 'Status' ='Status' }) ` -HeaderUrl ($PoShMonConfiguration.SharePoint.CentralAdminUrl + "/_admin/FarmServers.aspx") foreach ($ServerName in $PoShMonConfiguration.General.ServerNames) # $farm.Servers { $server = Get-SPServerForRemoteServer -PoShMonConfiguration $PoShMonConfiguration -ServerName $ServerName $highlight = @() Write-Verbose "`t$($server.DisplayName) : $($server.Status) : $($server.NeedsUpgrade)" if ($server.NeedsUpgrade) { $needsUpgradeValue = "Yes" $highlight += 'NeedsUpgrade' $mainOutput.NoIssuesFound = $false Write-Warning "`t$($server.DisplayName) is listed as Needing Upgrade" } else { $needsUpgradeValue = "No" } if ($server.Status -ne 'Online') { $highlight += 'Status' $mainOutput.NoIssuesFound = $false Write-Warning "`t$($server.DisplayName) is not listed as Online. Status: $($server.Status)" } $mainOutput.OutputValues += [pscustomobject]@{ 'ServerName' = $server.DisplayName; 'NeedsUpgrade' = $needsUpgradeValue; 'Status' = $server.Status.ToString(); 'Role' = $server.Role.ToString(); 'Highlight' = $highlight } } return (Complete-TimedOutput $mainOutput) } <# $output = Test-SPServerStatus -Verbose #>
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Get-SPTestNames.ps1
Get-SPTestNames.ps1
Function Get-SPTestNames { [CmdletBinding()] Param( ) $tests = Get-SPTests return "'" + [system.String]::Join("','", $tests) + "'" #formatted easily for use in TestsToSkip }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.SharePoint/Test-FarmHealth.ps1
Test-FarmHealth.ps1
Function Test-FarmHealth { [CmdletBinding()] param ( #[System.Management.Automation.Runspaces.PSSession]$RemoteSession [hashtable]$PoShMonConfiguration ) $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Farm Overview" -OutputHeaders ([ordered]@{ 'ConfigDB' = 'Config DB Name'; 'BuildVersion' = 'Build Version'; 'Status' = 'Status'; 'NeedsUpgrade' = 'Needs Upgrade?' }) $farm = Invoke-RemoteCommand -PoShMonConfiguration $PoShMonConfiguration -ScriptBlock { return Get-SPFarm | Select Name, BuildVersion, Status, NeedsUpgrade } if ($farm.Status.Value -ne 'Online') { $mainOutput.NoIssuesFound = $false $highlight += 'Status' Write-Host "Farm Status is $($farm.Status.Value)" -ForegroundColor Yellow } if ($farm.NeedsUpgrade -eq $true) { $mainOutput.NoIssuesFound = $false $highlight += 'NeedsUpgrade' Write-Host "Farm needs upgrade" -ForegroundColor Yellow } $mainOutput.OutputValues += [pscustomobject]@{ 'ConfigDB' = $farm.Name; 'BuildVersion' = $farm.BuildVersion; 'Status' = $farm.Status.Value; 'NeedsUpgrade' = if ($farm.NeedsUpgrade) { "Yes" } else { "No" }; 'Highlight' = $highlight } return (Complete-TimedOutput $mainOutput) } <# $output = Test-SPSearchHealth $remoteSession #>
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Get-VersionUpgradeInformation.ps1
Get-VersionUpgradeInformation.ps1
Function Get-VersionUpgradeInformation { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.General.SkipVersionUpdateCheck) { return "Version check skipped" } else { $currentVersion = Get-Module PoShMon -ListAvailable | Select -First 1 | Sort Version try { $galleryVersion = Find-Module PoShMon -Repository PSGallery if ($currentVersion.Version -lt $galleryVersion.Version) { return "New version available - run 'Update-PoShMon' command" } else { return "Latest version installed" } } catch { return "Version Update information not available (check Internet access for RunAs account)" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Add-Scripts.ps1
Add-Scripts.ps1
Function Add-Scripts { [CmdletBinding()] Param( [string[]]$RepairScripts ) $scriptsLoaded = @() Foreach($scriptToImport in $RepairScripts) { if (Test-Path $scriptToImport) { . $scriptToImport $scriptsLoaded += $scriptToImport | Get-Item | Select -ExpandProperty BaseName } else { Write-Warning "Script not found, will be skipped: $scriptToImport" } } return $scriptsLoaded }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Connect-PrimaryServer.ps1
Connect-PrimaryServer.ps1
Function Connect-PrimaryServer { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [scriptblock]$InitiationScriptBlock, [object[]]$ArgumentList = $null ) $remoteSession = Connect-RemoteSession $PoShMonConfiguration if ($InitiationScriptBlock -ne $null -and $InitiationScriptBlock -ne "") { Invoke-Command -Session $remoteSession -ScriptBlock $InitiationScriptBlock -ArgumentList $ArgumentList } $Global:PoShMon_RemoteSession = $remoteSession return $remoteSession }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Update-PoShMon.ps1
Update-PoShMon.ps1
Function Update-PoShMon { [CmdletBinding()] param( ) $currentVersion = Get-Module PoShMon -ListAvailable | Select -First 1 | Sort Version $galleryVersion = Find-Module PoShMon -Repository PSGallery if ($currentVersion.Version -eq $galleryVersion.Version) { Write-Host "Latest version already installed, skipping update" } else { if ((Get-Module PoShMon)) { Remove-Module PoShMon -ErrorAction SilentlyContinue } Update-Module PoShMon Install-Module PoShMon $upgradedVersion = Get-Module PoShMon -ListAvailable | Select -First 1 | Sort Version if ($upgradedVersion.Version -eq $galleryVersion.Version) { Write-Host "PoShMon version upgrade to $($upgradedVersion.Version.ToString())" } else { "Upgrade failed" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Disconnect-RemoteSession.ps1
Disconnect-RemoteSession.ps1
Function Disconnect-RemoteSession { [cmdletbinding()] param( $RemoteSession ) Remove-PSSession $RemoteSession }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Invoke-RemoteCommand.ps1
Invoke-RemoteCommand.ps1
Function Invoke-RemoteCommand { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [scriptblock]$scriptBlock, [object[]]$ArgumentList = $null ) #try #{ if ($Global:PoShMon_RemoteSession -eq $null) { throw "No Remote Session Defined" } #$remoteSession = Connect-PSSession -ComputerName $PoShMonConfiguration.General.PrimaryServerName -Name $PoShMonConfiguration.General.RemoteSessionName -ConfigurationName $PoShMonConfiguration.General.ConfigurationName #return Invoke-Command -Session $RemoteSession -ScriptBlock $scriptBlock -ArgumentList $ArgumentList return Invoke-Command -Session $Global:PoShMon_RemoteSession -ScriptBlock $scriptBlock -ArgumentList $ArgumentList #} catch { # throw $_.Exception #} finally { # if ($remoteSession -ne $null) # { Disconnect-PSSession $remoteSession -ErrorAction SilentlyContinue | Out-Null } # #{ Disconnect-RemoteSession $remoteSession -ErrorAction SilentlyContinue } #} }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Shared/Connect-RemoteSession.ps1
Connect-RemoteSession.ps1
Function Connect-RemoteSession { [cmdletbinding()] param( [hashtable]$PoShMonConfiguration ) if ($PoShMonConfiguration.General.ConfigurationName -ne $null) { $remoteSession = New-PSSession -ComputerName $PoShMonConfiguration.General.PrimaryServerName -Name $PoShMonConfiguration.General.RemoteSessionName -ConfigurationName $PoShMonConfiguration.General.ConfigurationName } else { $remoteSession = New-PSSession -ComputerName $PoShMonConfiguration.General.PrimaryServerName -Name $PoShMonConfiguration.General.RemoteSessionName } return $remoteSession }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Repairs/New-EmailRepairFooter.ps1
New-EmailRepairFooter.ps1
Function New-EmailRepairFooter { [CmdletBinding()] param( ) $emailSection = '' $emailSection += '</body>' return $emailSection; }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Repairs/New-EmailRepairHeader.ps1
New-EmailRepairHeader.ps1
Function New-EmailRepairHeader { [CmdletBinding()] param( [string]$ReportTitle = "PoShMon Repairs Report" ) $emailSection = '<head><title>' + $ReportTitle + '</title></head><body><h1>' + $ReportTitle + '</h1>' return $emailSection; }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Repairs/New-EmailRepairOutputBody.ps1
New-EmailRepairOutputBody.ps1
Function New-EmailRepairOutputBody { [cmdletbinding()] param( $Output ) $emailSection = '' $title = $output.SectionHeader $emailSection += "<p><h1>$title</h1>" $emailSection += '<table border="1">' if ($output.ContainsKey("Exception")) { $emailSection += "<tbody><tr><td>An Exception Occurred</td></tr><tr><td>$($output.Exception.ToString())</td></tr></tbody>" } else { $emailSection += "<tbody><tr><td>$($output.RepairResult)</td></tr></tbody>" } $emailSection += '</table>' return $emailSection }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Repairs/New-EmailRepairBody.ps1
New-EmailRepairBody.ps1
Function New-EmailRepairBody { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) $emailBody = '' $emailBody += New-EmailRepairHeader "$($PoShMonConfiguration.General.EnvironmentName) Repairs Report" foreach ($repairOutputValue in $RepairOutputValues) { $emailBody += New-EmailRepairOutputBody -Output $repairOutputValue } $emailBody += New-EmailRepairFooter return $emailBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Email.Repairs/New-EmailRepairSubject.ps1
New-EmailRepairSubject.ps1
Function New-EmailRepairSubject { [CmdletBinding()] param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) $subject = "[PoshMon] $($PoShMonConfiguration.General.EnvironmentName) Repair Results ($($RepairOutputValues.Count) Repairs(s) Performed)" return $subject }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/PoShMon.Tests.ps1
PoShMon.Tests.ps1
Import-Module Pester $path = (Split-Path -Parent $MyInvocation.MyCommand.Path) $testsPath = "$path\CI" Invoke-Pester -Path $testsPath #-CodeCoverage "$sutPath\*\*.ps1" #$scriptFiles = @( Get-ChildItem -Path "$path\*\*.ps1" -Recurse -ErrorAction SilentlyContinue ) #$scriptFiles = @( Get-ChildItem -Path "$path\CI\*\*.ps1" -Recurse -ErrorAction SilentlyContinue ) #$scriptFiles = @( Get-ChildItem -Path "$path\CI\Integration\*\*.ps1" -Recurse -ErrorAction SilentlyContinue ) #$scriptFiles = @( Get-ChildItem -Path "$path\CI\Unit\*\*.ps1" -Recurse -ErrorAction SilentlyContinue ) #$testResultSettings = @{ } #$testsPath = "$path\CI" #$testsPath = "$path\CI\Integration" <# $filesToTest = @() $sutPath = Join-Path (Split-Path -Parent $path) -ChildPath ('\Functions') -Resolve Foreach($import in $scriptFiles) { $sutFileName = (Split-Path -Leaf $import).Replace(".Tests", "") if (!$filesToTest.Contains($sutFileName)) { $fileToTest = Get-ChildItem -Path "$sutPath\*\$sutFileName" -Recurse $filesToTest += $fileToTest.FullName } #Invoke-Pester -Script $import # -PassThru $testResultSettings #. $import } #> # $testResultSettings
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/appveyorCITests.ps1
appveyorCITests.ps1
#based on code from https://github.com/RamblingCookieMonster/PSDiskPart/ $ProjectRoot = $ENV:APPVEYOR_BUILD_FOLDER Set-Location $ProjectRoot #$path = (Split-Path -Parent $MyInvocation.MyCommand.Path) Import-Module Pester Invoke-Pester -Path "$ProjectRoot\src\Tests\CI" -CodeCoverage "$ProjectRoot\src\Functions\*\*.ps1" -OutputFormat NUnitXml -OutputFile "$ProjectRoot\RawTestResults.xml" -PassThru | ` Export-Clixml -Path "$ProjectRoot\PesterTestResults.xml" #Invoke-Pester -Path "$ProjectRoot\src\Tests\Integration" -OutputFormat NUnitXml -OutputFile "$ProjectRoot\RawIntegrationTestResults.xml" -PassThru | ` # Export-Clixml -Path "$ProjectRoot\PesterIntegrationTestResults.xml" #Show status... $AllFiles = Get-ChildItem -Path $ProjectRoot\*Results.xml | Select -ExpandProperty FullName "`n`tSTATUS: Finalizing results`n" "COLLATING FILES:`n$($AllFiles | Out-String)" #Upload results for test page Get-ChildItem -Path $ProjectRoot\Raw*TestResults.xml | Foreach-Object { $Address = "https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)" $Source = $_.FullName "UPLOADING FILES: $Address $Source" (New-Object 'System.Net.WebClient').UploadFile( $Address, $Source ) } #What failed? $Results = @( Get-ChildItem -Path "$ProjectRoot\Pester*TestResults.xml" | Import-Clixml ) $FailedCount = $Results | Select -ExpandProperty FailedCount | Measure-Object -Sum | Select -ExpandProperty Sum if ($FailedCount -gt 0) { $FailedItems = $Results | Select -ExpandProperty TestResult | Where {$_.Passed -notlike $True} "FAILED TESTS SUMMARY:`n" $FailedItems | ForEach-Object { $Test = $_ [pscustomobject]@{ Describe = $Test.Describe Context = $Test.Context Name = "It $($Test.Name)" Result = $Test.Result } } | Sort Describe, Context, Name, Result | Format-List throw "$FailedCount tests failed." }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/Non-CI/ExternalDependencies/PoShMon.Notifications.O365Teams/Send-O365TeamsMessage.Tests.ps1
Send-O365TeamsMessage.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") $o365TeamsConfigPath = [Environment]::GetFolderPath("MyDocuments") + "\o365TeamsConfig.json" if (Test-Path $o365TeamsConfigPath) # only run this test if there's a config to send notifications { Describe "Send-O365TeamsMessage" { It "Should send an O365 Teams message" { $o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'ZAMGNTSPAPP1' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { O365Teams -TeamsWebHookUrl $o365TeamsConfig.TeamsWebHookUrl } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test With A Long Name" "OutputHeaders" = @{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "GroupName" = "Server 1" "GroupOutputValues" = @( @{ "EventID" = 123 "Message" = "Message 1" }, @{ "EventID" = 456 "Message" = "Message 2" } ) }, @{ "GroupName" = "Server 2" "GroupOutputValues" = @( @{ "EventID" = 789 "Message" = "Message 3" } ) } ) } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Component" = 123 "State" = "State 1" }, @{ "Component" = 456 "State" = "State 2" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $actual = Send-O365TeamsMessage $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks "All" $testMonitoringOutput $totalElapsedTime } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/Non-CI/ExternalDependencies/PoShMon.Notifications.Pushbullet/Send-PushbulletMessage.Tests.ps1
Send-PushbulletMessage.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") $pushbulletConfigPath = [Environment]::GetFolderPath("MyDocuments") + "\pushbulletconfig.json" if (Test-Path $pushbulletConfigPath) # only run this test if there's a config to send notifications { Describe "Send-PushbulletMessage" { It "Should send a Pushbullet message" { $pushbulletConfig = Get-Content -Raw -Path $pushbulletConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'ZAMGNTSPAPP1' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Pushbullet ` -AccessToken $pushbulletConfig.AccessToken ` -DeviceId $pushbulletConfig.DeviceId } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test With A Long Name" "OutputHeaders" = @{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "GroupName" = "Server 1" "GroupOutputValues" = @( @{ "EventID" = 123 "Message" = "Message 1" }, @{ "EventID" = 456 "Message" = "Message 2" } ) }, @{ "GroupName" = "Server 2" "GroupOutputValues" = @( @{ "EventID" = 789 "Message" = "Message 3" } ) } ) } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Component" = 123 "State" = "State 1" }, @{ "Component" = 456 "State" = "State 2" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $actual = Send-PushbulletMessage $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks "subject" "body message" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/Non-CI/ExternalDependencies/PoShMon.Notifications.Email.Monitoring/New-EmailBody.Tests.ps1
New-EmailBody.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "New-EmailBody" { It "Should return a the correct html for given test output" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test" "OutputHeaders" = [ordered]@{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "GroupName" = "Server 1" "GroupOutputValues" = @( @{ "EventID" = 123 "Message" = "Message 1 Something long goes here possibly multiline" }, @{ "EventID" = 456 "Message" = "Message 2 Lorem ipsum dolor sit amet, consectetuer adipiscing elit #Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.`r`nNunc viverra imperdiet enim. Fusce est. Vivamus a tellus.`r`nPellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci." "Highlight" = @("Message") }, @{ "EventID" = 678 "Message" = "Message 2" } ) }, @{ "GroupName" = "Server 2" "GroupOutputValues" = @( @{ "EventID" = 789 "Message" = "Message 3" } ) } ) } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = "Comp 123" "State" = "State 1" }, @{ "ComponentName" = "Comp 456" "State" = "State 2" }, @{ "ComponentName" = "Comp 567" "State" = "State 3" }, @{ "ComponentName" = "Comp 887" "State" = "State 4" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = '<head><title>SharePoint Monitoring Report</title></head><body><h1>SharePoint Monitoring Report</h1><p><h1>Grouped Test (60.00 Seconds)</h1><table border="1"><thead><tr><th align="left" colspan="2"><h2>Server 1</h2></th></tr><tr><th align="left">Message</th><th align="left">Event ID</th></tr></thead><tbody><tr><td valign="top" align="left">Message 1</td><td valign="top" align="right">123</td></tr><tr><td valign="top" align="left">Message 2</td><td valign="top" align="right">456</td></tr></tbody><thead><tr><th align="left" colspan="2"><h2>Server 2</h2></th></tr><tr><th align="left">Message</th><th align="left">Event ID</th></tr></thead><tbody><tr><td valign="top" align="left">Message 3</td><td valign="top" align="right">789</td></tr></tbody></table><p><h1>Ungrouped Test (60.00 Seconds)</h1><table border="1"><thead><tr><th align="left">State</th><th align="left">Component</th></tr></thead><tbody><tr><td valign="top" align="left">State 1</td><td valign="top" align="right">123</td></tr><tr><td valign="top" align="left">State 2</td><td valign="top" align="right">456</td></tr></tbody></table><p>Skipped Tests: SPServerStatus, WindowsServiceState, SPFailingTimerJobs, SPDatabaseHealth, SPSearchHealth, SPDistributedCacheHealth, WebTests</p><p>Total Elapsed Time (Seconds): 180.00 (3.00 Minutes)</p><p>PoShMon Version: ' + $currentVersion + '</p></body>' $actual = New-EmailBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $htmlFile = "C:\Temp\emailhtml.htm" $actual | Out-File $htmlFile -Force Start-Process $htmlFile #$actual | Should Be $expected } It "Should return a the correct html for given test output [if the output structure changes]" -Skip { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test" "OutputHeaders" = @{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "GroupBy" = "Server" "OutputValues" = @( [PSCustomObject]@{ "EventID" = 123 "Message" = "Message 1" "Server" = "Server 1" }, [PSCustomObject]@{ "EventID" = 456 "Message" = "Message 2" "Server" = "Server 1" }, [PSCustomObject]@{ "EventID" = 789 "Message" = "Message 3" "Server" = "Server 2" } ) } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [PSCustomObject]@{ "ComponentName" = 123 "State" = "State 1" }, [PSCustomObject]@{ "ComponentName" = 456 "State" = "State 2" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = '<head><title>SharePoint Monitoring Report</title></head><body><h1>SharePoint Monitoring Report</h1><p><h1>Grouped Test (60.00 Seconds)</h1><table border="1"><thead><tr><th align="left" colspan="2"><h2>Server 1</h2></th></tr><tr><th align="left">Message</th><th align="left">Event ID</th></tr></thead><tbody><tr><td valign="top" align="left">Message 1</td><td valign="top" align="right">123</td></tr><tr><td valign="top" align="left">Message 2</td><td valign="top" align="right">456</td></tr></tbody><thead><tr><th align="left" colspan="2"><h2>Server 2</h2></th></tr><tr><th align="left">Message</th><th align="left">Event ID</th></tr></thead><tbody><tr><td valign="top" align="left">Message 3</td><td valign="top" align="right">789</td></tr></tbody></table><p><h1>Ungrouped Test (60.00 Seconds)</h1><table border="1"><thead><tr><th align="left">State</th><th align="left">Component</th></tr></thead><tbody><tr><td valign="top" align="left">State 1</td><td valign="top" align="right">123</td></tr><tr><td valign="top" align="left">State 2</td><td valign="top" align="right">456</td></tr></tbody></table><p>Skipped Tests: SPServerStatus, WindowsServiceState, SPFailingTimerJobs, SPDatabaseHealth, SPSearchHealth, SPDistributedCacheHealth, WebTests</p><p>Total Elapsed Time (Seconds): 180.00 (3.00 Minutes)</p><p>PoShMon Version: ' + $currentVersion + '</p></body>' $actual = New-EmailBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $actual | Should Be $expected } It "Should return a the correct html if an exception occurs in a test" -Skip { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When OnlyOnFailure { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Test1" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = 123 "State" = "State 1" }, @{ "ComponentName" = 456 "State" = "State 2" } ) }, @{ "SectionHeader" = "Test2 - Failed" "NoIssuesFound" = $false "Exception" = [Exception]::new("Something went wrong") } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = '<head><title>SharePoint Monitoring Report</title></head><body><h1>SharePoint Monitoring Report</h1><p><h1>Test1 (60.00 Seconds)</h1><table border="1"><thead><tr><th align="left">State</th><th align="left">Component</th></tr></thead><tbody><tr><td valign="top" align="left">State 1</td><td valign="top" align="right">123</td></tr><tr><td valign="top" align="left">State 2</td><td valign="top" align="right">456</td></tr></tbody></table><p><h1>Test2 - Failed</h1><table border="1"><tbody><tr><td>An Exception Occurred</td></tr><tr><td>System.Exception: Something went wrong</td></tr></tbody></table><p>Skipped Tests: SPServerStatus, WindowsServiceState, SPFailingTimerJobs, SPDatabaseHealth, SPSearchHealth, SPDistributedCacheHealth, WebTests</p><p>Total Elapsed Time (Seconds): 180.00 (3.00 Minutes)</p><p>PoShMon Version: ' + $currentVersion + '</p></body>' $actual = New-EmailBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $actual | Should Be $expected } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Configuration/New-PoShMonConfiguration.Tests.ps1
New-PoShMonConfiguration.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "New-PoShMonConfiguration" { It "Should work with a minimal configuration" { $env:COMPUTERNAME = "THESERVERNAME" $poShMonConfiguration = New-PoShMonConfiguration {} $poShMonConfiguration.General.ServerNames | Should Be "THESERVERNAME" $poShMonConfiguration.General.PrimaryServerName | Should Be "" } It "Should work with a full configuration (Servers list)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'OS Base Test' ` -MinutesToScanHistory 60 ` -ServerNames 'Server01','Server02' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'Memory' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi" } } $poShMonConfiguration.General.ServerNames | Should Be 'Server01','Server02' $poShMonConfiguration.General.PrimaryServerName | Should Be "" } It "Should work with a full configuration (primary server)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'OS Base Test' ` -MinutesToScanHistory 60 ` -PrimaryServerName "Server1" ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'Memory' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi" } } $poShMonConfiguration.General.ServerNames | Should Be $null $poShMonConfiguration.General.PrimaryServerName | Should Be "Server1" } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Configuration/O365Teams.Tests.ps1
O365Teams.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "O365TeamsConfiguration" { It "Should return a matching configuration to what was supplied" { $testWebhookUrl = "https://outlook.office.com/webhook/" $actual = New-PoShMonConfiguration { Notifications -When OnlyOnFailure { Email ` -ToAddress "someone@email.com" ` -FromAddress "bob@jones.com" ` -SmtpServer "smtp.company.com" ` -Port 27 O365Teams -TeamsWebHookUrl $testWebhookUrl } } $actual.Notifications.Sinks.Count | Should Be 2 $actual.Notifications.Sinks[1].TypeName | Should Be 'PoShMon.ConfigurationItems.Notifications.O365Teams' $actual.Notifications.Sinks[1].TeamsWebHookUrl | Should Be $testWebhookUrl } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Notifications.O365Teams/New-O365TeamsMessageBody.Tests.ps1
New-O365TeamsMessageBody.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "New-O365TeamsMessageBody" { InModuleScope PoShMon { It "Should return a the correct output for given test output" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test" "OutputHeaders" = @{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "GroupName" = "Server 1" "GroupOutputValues" = @( @{ "EventID" = 123 "Message" = "Message 1" }, @{ "EventID" = 456 "Message" = "Message 2" } ) }, @{ "GroupName" = "Server 2" "GroupOutputValues" = @( @{ "EventID" = 789 "Message" = "Message 3" } ) } ) } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = 123 "State" = "State 1" }, @{ "ComponentName" = 456 "State" = "State 2" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = "Grouped Test : issue(s) found - No `r`nUngrouped Test : issue(s) found - Yes `r`n" $actual = New-O365TeamsMessageBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $actual | Should Be $expected } It "Should return a the correct output if an exception occurs in a test" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When OnlyOnFailure { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Test1" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = 123 "State" = "State 1" }, @{ "ComponentName" = 456 "State" = "State 2" } ) }, @{ "SectionHeader" = "Test2 - Failed" "NoIssuesFound" = $false "Exception" = [Exception]::new("Something went wrong") } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = "Test1 : issue(s) found - No `r`nTest2 - Failed : issue(s) found - Yes (Exception occurred) `r`n" $actual = New-O365TeamsMessageBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $actual | Should Be $expected } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Notifications.Pushbullet/New-PushbulletMessageBody.Tests.ps1
New-PushbulletMessageBody.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "New-PushbulletMessageBody" { InModuleScope PoShMon { It "Should return a the correct output for given test output" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test" "OutputHeaders" = @{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "GroupName" = "Server 1" "GroupOutputValues" = @( @{ "EventID" = 123 "Message" = "Message 1" }, @{ "EventID" = 456 "Message" = "Message 2" } ) }, @{ "GroupName" = "Server 2" "GroupOutputValues" = @( @{ "EventID" = 789 "Message" = "Message 3" } ) } ) } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = 123 "State" = "State 1" }, @{ "ComponentName" = 456 "State" = "State 2" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = "Grouped Test : issue(s) found - No `r`nUngrouped Test : issue(s) found - Yes `r`n" $actual = New-PushbulletMessageBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $actual | Should Be $expected } It "Should return a the correct output if an exception occurs in a test" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When OnlyOnFailure { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Test1" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = 123 "State" = "State 1" }, @{ "ComponentName" = 456 "State" = "State 2" } ) }, @{ "SectionHeader" = "Test2 - Failed" "NoIssuesFound" = $false "Exception" = [Exception]::new("Something went wrong") } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $currentVersion = (Get-Module PoShmon).Version.ToString() $expected = "Test1 : issue(s) found - No `r`nTest2 - Failed : issue(s) found - Yes (Exception occurred) `r`n" $actual = New-PushbulletMessageBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime -Verbose $actual | Should Be $expected } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Test-DriveSpace.Tests.ps1
Test-DriveSpace.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-DriveSpace" { InModuleScope PoShMon { class DiskMock { [string]$DeviceID [int]$DriveType [string]$ProviderName [UInt64]$Size [UInt64]$FreeSpace [string]$VolumeName DiskMock ([string]$NewDeviceID, [int]$NewDriveType, [String]$NewProviderName, [UInt64]$NewSize, [UInt64]$NewFreeSpace, [String]$NewVolumeName) { $this.DeviceID = $NewDeviceID; $this.DriveType = $NewDriveType; $this.ProviderName = $NewProviderName; $this.Size = $NewSize; $this.FreeSpace = $NewFreeSpace; $this.VolumeName = $NewVolumeName; } } #It "Should throw an exception if no OperatingSystem configuration is set" { # # $poShMonConfiguration = New-PoShMonConfiguration { # } # # { Test-DriveSpace $poShMonConfiguration } | Should throw #} It "Should return a matching output structure" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]15GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -DriveSpaceThreshold 0 # zero will trigger the default, 10 (GB) } $actual = Test-DriveSpace $poShMonConfiguration $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("GroupBy") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be 3 #$valuesGroup1 = $actual.OutputValues[0] #$valuesGroup1.Keys.Count | Should Be 2 #$values1 = $valuesGroup1.GroupOutputValues[0] #$values1.Keys.Count | Should Be 4 #$values1.ContainsKey("DriveLetter") | Should Be $true #$values1.ContainsKey("TotalSpace") | Should Be $true #$values1.ContainsKey("FreeSpace") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true $actual.OutputValues[0].DriveLetter | Should Be "C:" $actual.OutputValues[0].TotalSpace | Should Be "50.00" $actual.OutputValues[0].FreeSpace | Should Be "15.00 (30%)" $actual.OutputValues[0].Highlight.Count | Should Be 0 } It "Should write the expected Verbose output (fixed)" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]13.76GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem # zero will trigger the default, 10 (GB) } $actual = Test-DriveSpace $poShMonConfiguration -Verbose $output = $($actual = Test-DriveSpace $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Initiating 'Harddrive Space Review' Test..." $output[1].ToString() | Should Be "`tlocalhost" $output[2].ToString() | Should Be "`t`tC: : 50.00 : 13.76 (28%)" $output[3].ToString() | Should Be "Complete 'Harddrive Space Review' Test, Issues Found: No" } It "Should write the expected Warning output (fixed)" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]5.143GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -DriveSpaceThreshold 0 # zero will trigger the default, 10 (GB) } $actual = Test-DriveSpace $poShMonConfiguration $output = $($actual = Test-DriveSpace $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`t`tFree drive Space (5.14) is below variance threshold (10)" } It "Should write the expected Warning output (percent)" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]5.945GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -DriveSpaceThresholdPercent 95 # zero will trigger the default, 10 (GB) } $actual = Test-DriveSpace $poShMonConfiguration $output = $($actual = Test-DriveSpace $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`t`tFree drive Space (12%) is below variance threshold (95%)" } It "Should not warn on space above threshold" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]11GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -DriveSpaceThreshold 0 # zero will trigger the default, 10 (GB) } $actual = Test-DriveSpace $poShMonConfiguration $actual.NoIssuesFound | Should Be $true $actual.OutputValues.GroupOutputValues.Highlight.Count | Should Be 0 } It "Should warn on space below threshold (default)" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]5GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -DriveSpaceThreshold 0 # zero will trigger the default, 10 (GB) } $actual = Test-DriveSpace $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'FreeSpace' } It "Should warn on space below specified threshold (fixed)" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]15GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -DriveSpaceThreshold 20 } $actual = Test-DriveSpace $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'FreeSpace' } It "Should warn on space above specified threshold (percent)" { Mock -CommandName Get-WmiObject -MockWith { return @( [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]21GB, "MyCDrive") [DiskMock]::new('D:', 3, "", [UInt64]50GB, [UInt64]44GB, "MyEDrive") ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -DriveSpaceThresholdPercent 50 } $actual = Test-DriveSpace $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'FreeSpace' } It "Should not warn on space below specified threshold (percent)" { Mock -CommandName Get-WmiObject -MockWith { return [DiskMock]::new('C:', 3, "", [UInt64]50GB, [UInt64]15GB, "MyCDrive") } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -DriveSpaceThresholdPercent 5 } $actual = Test-DriveSpace $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $true $actual.OutputValues.GroupOutputValues.Highlight.Count | Should Be 0 } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Test-ComputerTime.Tests.ps1
Test-ComputerTime.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-ComputerTime" { InModuleScope PoShMon { class ServerTimeMock { [string]$PSComputerName [datetime]$DateTime [datetime]$LocalDateTime [datetime]$LastBootUptime [int]$Year [int]$Month [int]$Day [int]$Hour [int]$Minute [int]$Second ServerTimeMock ([string]$NewPSComputerName, [datetime]$NewDateTime, [datetime]$NewLastBootUptime) { $this.PSComputerName = $NewPSComputerName; $this.DateTime = $NewDateTime $this.LocalDateTime = $NewDateTime $this.LastBootUptime = $NewLastBootUptime } [datetime] ConvertToDateTime([datetime]$something) { return $something } } #It "Should throw an exception if no OperatingSystem configuration is set" { # # $poShMonConfiguration = New-PoShMonConfiguration { } # # { Test-ComputerTime $poShMonConfiguration } | Should throw #} It "Should return a matching output structure" { Mock -ModuleName PoShMon Get-WmiObject { return [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2017, 1, 1, 10, 15, 0)) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration $actual.Keys.Count | Should Be 5 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be 3 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be 3 $actual.OutputValues[0].ServerName | Should Be 'Server1' $actual.OutputValues[0].CurrentTime | Should Be ([datetime]::new(2017, 1, 1, 10, 15, 0)).ToString() $actual.OutputValues[0].LastBootUptime | Should Be ([datetime]::new(2017, 1, 1, 10, 15, 0)).ToString() $actual.OutputValues[0].Highlight[0] | Should Be 'CurrentTime' } It "Should write the expected Verbose output" { Mock -CommandName Get-WmiObject -MockWith { return [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) } Mock -CommandName Get-Date -MockWith { Return [datetime]::new(2017, 1, 1, 10, 15, 0) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration -Verbose $output = $($actual = Test-ComputerTime $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 3 $output[0].ToString() | Should Be "Initiating 'Server Clock Review' Test..." $output[1].ToString() | Should Be "`tServer1: 10:15 AM" $output[2].ToString() | Should Be "Complete 'Server Clock Review' Test, Issues Found: No" } It "Should write the expected Warning output for time difference" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 09, 0), [datetime]::new(2016, 1, 1, 10, 09, 0)) ) } Mock -CommandName Get-Date -MockWith { Return [datetime]::new(2017, 1, 1, 10, 15, 0) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration $output = $($actual = Test-ComputerTime $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`tDifference (6) is above variance threshold minutes (1)" } It "Should write the expected Warning output for recent reboot" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 09, 0), [datetime]::new(2017, 1, 1, 10, 08, 0)) ) } Mock -CommandName Get-Date -MockWith { Return [datetime]::new(2017, 1, 1, 10, 09, 0) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration $output = $($actual = Test-ComputerTime $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`tLastBootUptime (01/01/2017 10:08:00) is within the last 15 minutes" } It "Should warn on different server time (to local PoShMon machine)" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', (Get-Date -Year 2017 -Month 1 -Day 1 -Hour 10 -Minute 15).AddMinutes(-6), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } Mock -CommandName Get-Date -MockWith { Return [datetime]::new(2017, 1, 1, 10, 15, 0) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be "CurrentTime" } It "Should not warn on matching server times" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should not warn on server time differences within default threshold" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 10, 14, 30), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should warn on server times with differences above default threshold" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 10, 12, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-ComputerTime $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 3 $actual.OutputValues.Highlight[0] | Should Be "CurrentTime" } It "Should not warn on server time differences within configured threshold" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 1, 09, 48, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server4', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -AllowedMinutesVarianceBetweenServerTimes 31 } $actual = Test-ComputerTime $poShMonConfiguration $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should warn on server times with differences above configured threshold" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 10, 12, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 1, 10, 15, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -AllowedMinutesVarianceBetweenServerTimes 2 } $actual = Test-ComputerTime $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 3 $actual.OutputValues.Highlight[0] | Should Be "CurrentTime" } It "Should not warn on server times with differences within default threshold across hour boundaries" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 1, 11, 01, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 10, 59, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 1, 11, 01, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -AllowedMinutesVarianceBetweenServerTimes 3 } $actual = Test-ComputerTime $poShMonConfiguration $actual.NoIssuesFound | Should Be $true } It "Should not warn on server times with differences within default threshold across day boundaries" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 2, 00, 01, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 23, 59, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 2, 00, 01, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -AllowedMinutesVarianceBetweenServerTimes 3 } $actual = Test-ComputerTime $poShMonConfiguration $actual.NoIssuesFound | Should Be $true } It "Should only warn servers recently rebooted" { Mock -CommandName Get-WmiObject -MockWith { return @( [ServerTimeMock]::new('Server1', [datetime]::new(2017, 1, 2, 00, 01, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) [ServerTimeMock]::new('Server2', [datetime]::new(2017, 1, 1, 23, 59, 0), [datetime]::new(2017, 1, 1, 10, 5, 0)) [ServerTimeMock]::new('Server3', [datetime]::new(2017, 1, 2, 00, 01, 0), [datetime]::new(2016, 1, 1, 10, 15, 0)) ) } Mock -CommandName Get-Date -MockWith { Return [datetime]::new(2017, 1, 1, 10, 15, 0) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem -AllowedMinutesVarianceBetweenServerTimes 3 } $actual = Test-ComputerTime $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues[2].Highlight | Should Be "LastBootUptime" } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Test-CPULoad.Tests.ps1
Test-CPULoad.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-CPULoad" { InModuleScope PoShMon { class CounterSampleMock { [string]$Path [double]$CookedValue CounterSampleMock ([string]$NewPath, [double]$NewCookedValue) { $this.Path = $NewPath; $this.CookedValue = $NewCookedValue; } } class CounterResultsMock { [datetime]$Timestamp [CounterSampleMock[]]$CounterSamples CounterResultsMock ([datetime]$NewTimestamp, [CounterSampleMock[]]$NewCounterSamples) { $this.Timestamp = $NewTimestamp; $this.CounterSamples = $NewCounterSamples; } } #It "Should throw an exception if no OperatingSystem configuration is set" { # # $poShMonConfiguration = New-PoShMonConfiguration { } # # { Test-CPULoad $poShMonConfiguration } | Should throw #} It "Should return a matching output structure" { Mock -CommandName Get-Counter -MockWith { $sample1 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 12.345) $sample2 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 56.789) $samples = @($sample1, $sample2) $timestamp = Get-Date return [CounterResultsMock]::new($timestamp, $samples) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames '.' OperatingSystem } $actual = Test-CPULoad $poShMonConfiguration $actual.Keys.Count | Should Be 5 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be 2 $actual.OutputValues[1].ServerName | Should Be 'Server1' $actual.OutputValues[1].CPULoad | Should Be '57%' $actual.OutputValues[1].Highlight.Count | Should Be 0 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be 3 #$values1.ContainsKey("ServerName") | Should Be $true #$values1.ContainsKey("CPULoad") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Get-Counter -MockWith { $sample1 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 12.345) $sample2 = [CounterSampleMock]::new("\\Server2\\processor(_total)\% processor time", 56.789) $samples = @($sample1, $sample2) $timestamp = Get-Date return [CounterResultsMock]::new($timestamp, $samples) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames '.' OperatingSystem } $actual = Test-CPULoad $poShMonConfiguration -Verbose $output = $($actual = Test-CPULoad $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Initiating 'Server CPU Load Review' Test..." $output[1].ToString() | Should Be "`tSERVER1: 12%" $output[2].ToString() | Should Be "`tSERVER2: 57%" $output[3].ToString() | Should Be "Complete 'Server CPU Load Review' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Get-Counter -MockWith { $sample1 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 12.345) $sample2 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 97.789) $samples = @($sample1, $sample2) $timestamp = Get-Date return [CounterResultsMock]::new($timestamp, $samples) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames '.' OperatingSystem } $output = $($actual = Test-CPULoad $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`tCPU Load (98%) is above variance threshold (90%)" } It "Should not warn on CPU below threshold" { Mock -CommandName Get-Counter -MockWith { $sample1 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 12.345) $sample2 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 56.789) $samples = @($sample1, $sample2) $timestamp = Get-Date return [CounterResultsMock]::new($timestamp, $samples) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem } $actual = Test-CPULoad $poShMonConfiguration $actual.NoIssuesFound | Should Be $true $actual.OutputValues.GroupOutputValues.Highlight.Count | Should Be 0 } It "Should warn on CPU above threshold" { Mock -CommandName Get-Counter -MockWith { $sample1 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 12.345) $sample2 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 97.789) $samples = @($sample1, $sample2) $timestamp = Get-Date return [CounterResultsMock]::new($timestamp, $samples) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem } $actual = Test-CPULoad $poShMonConfiguration $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'CPULoad' } It "Should use the configuration threshold properly" { Mock -CommandName Get-Counter -MockWith { $sample1 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 12.345) $sample2 = [CounterSampleMock]::new("\\Server1\\processor(_total)\% processor time", 57.789) $samples = @($sample1, $sample2) $timestamp = Get-Date return [CounterResultsMock]::new($timestamp, $samples) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -CPULoadThresholdPercent 50 } $actual = Test-CPULoad $poShMonConfiguration $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'CPULoad' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Invoke-OSMonitoring.Tests.ps1
Invoke-OSMonitoring.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Invoke-OSMonitoring" { It "Should work with a minimal configuration" { $poShMonConfiguration = New-PoShMonConfiguration {} Mock -CommandName Invoke-Tests -ModuleName PoShMon -Verifiable -MockWith { Begin { $outputValues = @() } Process { foreach ($test in $TestToRuns) { $outputValues += @{ "SectionHeader" = "Mock Test: $test" "OutputHeaders" = @{ 'Item1' = 'Item 1'; } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Item1" = 123 "State" = "State 1" } ) } } } End { return $outputValues } } Mock -CommandName Initialize-Notifications -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose "Tests Run:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } $actual = Invoke-OSMonitoring $poShMonConfiguration -Verbose Assert-VerifiableMocks } It "Should work with a full configuration (Servers list)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'OS Base Test' ` -MinutesToScanHistory 60 ` -ServerNames 'Server01','Server02' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'Memory' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi" } } Mock -CommandName Invoke-Tests -ModuleName PoShMon -Verifiable -MockWith { Begin { $outputValues = @() } Process { foreach ($test in $TestToRuns) { $outputValues += @{ "SectionHeader" = "Mock Test: $test" "OutputHeaders" = @{ 'Item1' = 'Item 1'; } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Item1" = 123 "State" = "State 1" } ) } } } End { return $outputValues } } Mock -CommandName Initialize-Notifications -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose "Tests Run:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } $actual = Invoke-OSMonitoring $poShMonConfiguration -Verbose Assert-VerifiableMocks } It "Should work with a full configuration (primary server)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'OS Base Test' ` -MinutesToScanHistory 60 ` -PrimaryServerName "Server1" ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'Memory' Notifications -When All { Email -ToAddress "someone@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi" } } Mock -CommandName Invoke-Tests -ModuleName PoShMon -Verifiable -MockWith { Begin { $outputValues = @() } Process { foreach ($test in $TestToRuns) { $outputValues += @{ "SectionHeader" = "Mock Test: $test" "OutputHeaders" = @{ 'Item1' = 'Item 1'; } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Item1" = 123 "State" = "State 1" } ) } } } End { return $outputValues } } Mock -CommandName Initialize-Notifications -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose "Tests Run:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } $actual = Invoke-OSMonitoring $poShMonConfiguration -Verbose Assert-VerifiableMocks } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Merge-WinOSTests.Tests.ps1
Merge-WinOSTests.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Merge-WinOSTests" { It "Should return a matching output structure" { $poShMonConfiguration = New-PoShMonConfiguration { General -EnvironmentName 'SharePoint' -PrimaryServerName 'Server1' } $testMonitoringOutput = [System.Collections.ArrayList]@( @{ "SectionHeader" = "Server CPU Load Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "CPULoad" = "5%" }, [pscustomobject]@{ "ServerName" = "Server2" "CPULoad" = "13%" } ) } @{ "SectionHeader" = "Memory Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'TotalMemory' = 'Total Memory (GB)'; 'FreeMemory' = 'Free Memory (GB) (%)' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "TotalMemory" = "7.93" "FreeMemory" = "2.71 (35%)" "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "TotalMemory" = "7.93" "FreeMemory" = "0.91 (3%)" "Highlight" = @("FreeMemory") } ) } @{ "SectionHeader" = "Another Test" "OutputHeaders" = [ordered]@{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ComponentName" = 123 "State" = "State 1" }, @{ "ComponentName" = 456 "State" = "State 2" } ) } ) $actual = Merge-WinOSTests $poShMonConfiguration $testMonitoringOutput $actual[0].Keys.Count | Should Be 5 $actual[0].ContainsKey("NoIssuesFound") | Should Be $true $actual[0].ContainsKey("OutputHeaders") | Should Be $true $actual[0].ContainsKey("OutputValues") | Should Be $true $actual[0].ContainsKey("SectionHeader") | Should Be $true $actual[0]["SectionHeader"] | Should Be "Server Overview" $actual[0].ContainsKey("ElapsedTime") | Should Be $true $headers = $actual[0].OutputHeaders $headers.Keys.Count | Should Be 3 $actual[0].OutputValues[1].ServerName | Should Be 'Server2' $actual[0].OutputValues[1].CPULoad | Should Be '13%' $actual[0].OutputValues[1].Memory | Should Be '0.91 / 7.93 (3%)' $actual[0].OutputValues[1].Highlight.Count | Should Be 1 } It "Should merge all matching tests" { $poShMonConfiguration = New-PoShMonConfiguration { General -EnvironmentName 'SharePoint' -PrimaryServerName 'Server1' } $currentTime = Get-Date $lastBootTime = (Get-Date).AddDays(-1) $testMonitoringOutput = [System.Collections.ArrayList]@( @{ "SectionHeader" = "Server CPU Load Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "CPULoad" = "5%" }, [pscustomobject]@{ "ServerName" = "Server2" "CPULoad" = "13%" } ) } @{ "SectionHeader" = "Memory Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'TotalMemory' = 'Total Memory (GB)'; 'FreeMemory' = 'Free Memory (GB) (%)' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-2)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "TotalMemory" = "7.93" "FreeMemory" = "2.71 (35%)" "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "TotalMemory" = "7.93" "FreeMemory" = "0.91 (3%)" "Highlight" = @("FreeMemory") } ) } @{ "SectionHeader" = "Server Clock Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'CurrentTime' = 'Current Time'; 'LastBootUptime' = 'Last Boot Time'; } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "CurrentTime" = $currentTime.ToString() "LastBootUptime" = $lastBootTime.ToString() "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "CurrentTime" = $currentTime.ToString() "LastBootUptime" = $lastBootTime.ToString() "Highlight" = @("CurrentTime", "LastBootUptime") } ) } @{ "SectionHeader" = "Another Test" "OutputHeaders" = [ordered]@{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ComponentName" = 123 "State" = "State 1" }, [pscustomobject]@{ "ComponentName" = 456 "State" = "State 2" } ) } ) $actual = Merge-WinOSTests $poShMonConfiguration $testMonitoringOutput $actual.Count | Should Be 2 $actual[0].Keys.Count | Should Be 5 $actual[0].ContainsKey("NoIssuesFound") | Should Be $true $actual[0].ContainsKey("OutputHeaders") | Should Be $true $actual[0].ContainsKey("OutputValues") | Should Be $true $actual[0].ContainsKey("SectionHeader") | Should Be $true $actual[0]["SectionHeader"] | Should Be "Server Overview" $actual[0].ContainsKey("ElapsedTime") | Should Be $true $headers = $actual[0].OutputHeaders $headers.Keys.Count | Should Be 5 $actual[0].NoIssuesFound | Should Be $false $actual[0].OutputValues[1].ServerName | Should Be 'Server2' $actual[0].OutputValues[1].CPULoad | Should Be '13%' $actual[0].OutputValues[1].Memory | Should Be '0.91 / 7.93 (3%)' $actual[0].OutputValues[1].CurrentTime | Should Be $currentTime.ToString() $actual[0].OutputValues[1].LastBootUptime | Should Be $lastBootTime.ToString() $actual[0].OutputValues[1].Highlight.Count | Should Be 3 $actual[0].OutputValues[1].Highlight[0] | Should Be "Memory" $actual[0].OutputValues[1].Highlight[1] | Should Be "CurrentTime" $actual[0].OutputValues[1].Highlight[2] | Should Be "LastBootUptime" $actual[0].ElapsedTime | Should Be ([timespan]::new(0, 6, 0)) $actual[1]["SectionHeader"] | Should Be "Another Test" } It "Should show NoIssuesFound if all Tests are fine" { $poShMonConfiguration = New-PoShMonConfiguration { General -EnvironmentName 'SharePoint' -PrimaryServerName 'Server1' } $currentTime = Get-Date $lastBootTime = (Get-Date).AddDays(-1) $testMonitoringOutput = [System.Collections.ArrayList]@( @{ "SectionHeader" = "Server CPU Load Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "CPULoad" = "5%" "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "CPULoad" = "13%" "Highlight" = @() } ) } @{ "SectionHeader" = "Memory Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'TotalMemory' = 'Total Memory (GB)'; 'FreeMemory' = 'Free Memory (GB) (%)' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-2)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "TotalMemory" = "7.93" "FreeMemory" = "2.71 (35%)" "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "TotalMemory" = "7.93" "FreeMemory" = "0.91 (3%)" "Highlight" = @() } ) } @{ "SectionHeader" = "Server Clock Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'CurrentTime' = 'Current Time'; 'LastBootUptime' = 'Last Boot Time'; } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "CurrentTime" = $currentTime.ToString() "LastBootUptime" = $lastBootTime.ToString() "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "CurrentTime" = $currentTime.ToString() "LastBootUptime" = $lastBootTime.ToString() "Highlight" = @() } ) } @{ "SectionHeader" = "Another Test" "OutputHeaders" = [ordered]@{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ComponentName" = 123 "State" = "State 1" }, [pscustomobject]@{ "ComponentName" = 456 "State" = "State 2" } ) } ) $actual = Merge-WinOSTests $poShMonConfiguration $testMonitoringOutput $actual.Count | Should Be 2 $actual[0].Keys.Count | Should Be 5 $actual[0].ContainsKey("NoIssuesFound") | Should Be $true $actual[0].ContainsKey("OutputHeaders") | Should Be $true $actual[0].ContainsKey("OutputValues") | Should Be $true $actual[0].ContainsKey("SectionHeader") | Should Be $true $actual[0]["SectionHeader"] | Should Be "Server Overview" $actual[0].ContainsKey("ElapsedTime") | Should Be $true $headers = $actual[0].OutputHeaders $headers.Keys.Count | Should Be 5 $actual[0].NoIssuesFound | Should Be $true $actual[0].OutputValues[1].ServerName | Should Be 'Server2' $actual[0].OutputValues[1].CPULoad | Should Be '13%' $actual[0].OutputValues[1].Memory | Should Be '0.91 / 7.93 (3%)' $actual[0].OutputValues[1].CurrentTime | Should Be $currentTime.ToString() $actual[0].OutputValues[1].LastBootUptime | Should Be $lastBootTime.ToString() $actual[0].OutputValues[1].Highlight.Count | Should Be 0 $actual[0].ElapsedTime | Should Be ([timespan]::new(0, 6, 0)) $actual[1]["SectionHeader"] | Should Be "Another Test" } It "Should not merge if only one valid test appears" { $poShMonConfiguration = New-PoShMonConfiguration { General -EnvironmentName 'SharePoint' -PrimaryServerName 'Server1' } $currentTime = Get-Date $lastBootTime = (Get-Date).AddDays(-1) $testMonitoringOutput = [System.Collections.ArrayList]@( @{ "SectionHeader" = "Memory Review" "OutputHeaders" = [ordered]@{ 'ServerName' = 'Server Name'; 'TotalMemory' = 'Total Memory (GB)'; 'FreeMemory' = 'Free Memory (GB) (%)' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-20)) "OutputValues" = @( [pscustomobject]@{ "ServerName" = "Server1" "TotalMemory" = "7.93" "FreeMemory" = "2.71 (35%)" "Highlight" = @() }, [pscustomobject]@{ "ServerName" = "Server2" "TotalMemory" = "7.93" "FreeMemory" = "0.91 (3%)" "Highlight" = @() } ) } @{ "SectionHeader" = "Another Test" "OutputHeaders" = [ordered]@{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( [pscustomobject]@{ "ComponentName" = 123 "State" = "State 1" }, [pscustomobject]@{ "ComponentName" = 456 "State" = "State 2" } ) } ) $actual = Merge-WinOSTests $poShMonConfiguration $testMonitoringOutput $actual.Count | Should Be 2 $actual[0].Keys.Count | Should Be 5 $actual[0].ContainsKey("NoIssuesFound") | Should Be $true $actual[0].ContainsKey("OutputHeaders") | Should Be $true $actual[0].ContainsKey("OutputValues") | Should Be $true $actual[0].ContainsKey("SectionHeader") | Should Be $true $actual[0]["SectionHeader"] | Should Be "Memory Review" $actual[0].ContainsKey("ElapsedTime") | Should Be $true $headers = $actual[0].OutputHeaders $headers.Keys.Count | Should Be 3 $actual[0].NoIssuesFound | Should Be $true $actual[0].OutputValues[0].ServerName | Should Be 'Server1' $actual[0].OutputValues[0].TotalMemory | Should Be "7.93" $actual[0].OutputValues[0].FreeMemory | Should Be "2.71 (35%)" $actual[0].OutputValues[0].Highlight.Count | Should Be 0 $actual[0].ElapsedTime | Should Be ([timespan]::new(0, 20, 0)) $actual[1]["SectionHeader"] | Should Be "Another Test" } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Test-ServiceState.Tests.ps1
Test-ServiceState.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-ServiceState" { InModuleScope PoShMon { class ServiceInstanceMock { [object]$Status [object]$Service [object]$Server ServiceInstanceMock ([string]$NewServerDisplayName, [string]$NewServiceName, [string]$NewStatusValue) { $this.Server = [pscustomobject]@{DisplayName=$NewServerDisplayName}; $this.Service = [pscustomobject]@{Name=$NewServiceName}; $this.Status = [pscustomobject]@{Value=$NewStatusValue}; } } It "Should return a matching output structure" { Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'NoIssuesFound' = $true 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 1 DisplayName'; 'Name' = 'Svc1'; 'Status' = "Running"; 'Highlight' = @() }, [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Running"; 'Highlight' = @() } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames "Server1" OperatingSystem -WindowsServices "ABC" } $actual = Test-ServiceState $poShMonConfiguration $headerKeyCount = 3 $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("GroupBy") | Should Be $true $actual.OutputValues[1].ServerName | Should Be 'Server1' $actual.OutputValues[1].DisplayName | Should Be 'Service 2 DisplayName' $actual.OutputValues[1].Name | Should Be 'Svc2' $actual.OutputValues[1].Status | Should Be 'Running' $actual.OutputValues[1].Highlight.Count | Should Be 0 #$valuesGroup1 = $actual.OutputValues[0] #$valuesGroup1.Keys.Count | Should Be $headerKeyCount #$values1 = $valuesGroup1.GroupOutputValues[0] #$values1.Keys.Count | Should Be ($headerKeyCount + 1) #$values1.ContainsKey("DisplayName") | Should Be $true #$values1.ContainsKey("Name") | Should Be $true #$values1.ContainsKey("Status") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'GroupName' = $ServerName 'NoIssuesFound' = $true 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 1 DisplayName'; 'Name' = 'Svc1'; 'Status' = "Running"; 'Highlight' = @() } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames "Server2" OperatingSystem -WindowsServices "ABC" } $actual = Test-ServiceState $poShMonConfiguration -Verbose $output = $($actual = Test-ServiceState $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 2 $output[0].ToString() | Should Be "Initiating 'Windows Service State' Test..." $output[1].ToString() | Should Be "Complete 'Windows Service State' Test, Issues Found: No" } It "Should pass for all running services" { Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'NoIssuesFound' = $true 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = $Services; 'Status' = "Started"; 'Highlight' = @() } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames "Server2" OperatingSystem -WindowsServices "ABC" } $actual = Test-ServiceState $poShMonConfiguration Assert-VerifiableMocks $actual.OutputValues.Count | Should Be 1 $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should fail for any service in the wrong state" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [ServiceInstanceMock]::new('Server1', 'TheService', 'Online') ) } Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'NoIssuesFound' = $false 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Stopped"; 'Highlight' = @('Status') } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames "Server1" OperatingSystem -WindowsServices "ABC" } $actual = Test-ServiceState $poShMonConfiguration $actual.NoIssuesFound | Should Be $false } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Test-EventLogs.Tests.ps1
Test-EventLogs.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-EventLogs" { InModuleScope PoShMon { class EventLogItemMock { [int]$EventCode [string]$SourceName [string]$User [datetime]$TimeGenerated [string]$Message EventLogItemMock ([int]$NewEventCode, [String]$NewSourceName, [String]$NewUser, [datetime]$NewTimeGenerated, [String]$NewMessage) { $this.EventCode = $NewEventCode; $this.SourceName = $NewSourceName; $this.User = $NewUser; $this.TimeGenerated = $NewTimeGenerated; $this.Message = $NewMessage; } [string] ConvertToDateTime([datetime]$something) { return $something.ToString() } } It "Should return a matching output structure" { Mock -CommandName Get-WmiObject -MockWith { $eventsCollection = @() $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", ([datetime]::new(2017, 1, 1, 10, 15, 0)), "Sample Message") return $eventsCollection } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem } $actual = Test-EventLogs $poShMonConfiguration -WarningAction SilentlyContinue $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("GroupBy") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be 6 $actual.OutputValues[0].ServerName | Should Be 'localhost' $actual.OutputValues[0].EventID | Should Be '123' $actual.OutputValues[0].InstanceCount | Should Be 1 $actual.OutputValues[0].Source | Should Be "Test App" $actual.OutputValues[0].User | Should Be "domain\user1" $actual.OutputValues[0].Timestamp | Should Be ([datetime]::new(2017, 1, 1, 10, 15, 0)).ToString() $actual.OutputValues[0].Message | Should Be "Sample Message" #$valuesGroup1 = $actual.OutputValues[0] #$valuesGroup1.Keys.Count | Should Be 2 #$values1 = $valuesGroup1.GroupOutputValues #$values1.Keys.Count | Should Be 6 #$values1.ContainsKey("EventID") | Should Be $true #$values1.ContainsKey("InstanceCount") | Should Be $true #$values1.ContainsKey("Source") | Should Be $true #$values1.ContainsKey("User") | Should Be $true #$values1.ContainsKey("Timestamp") | Should Be $true #$values1.ContainsKey("Message") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Get-WmiObject -MockWith { $eventsCollection = @() return $eventsCollection } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-EventLogs $poShMonConfiguration -Verbose $output = $($actual = Test-EventLogs $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Initiating 'Critical Event Log Issues' Test..." $output[1].ToString() | Should Be "`tServer1" $output[2].ToString() | Should Be "`t`tNo Entries Found In Time Specified" $output[3].ToString() | Should Be "Complete 'Critical Event Log Issues' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Get-WmiObject -MockWith { $eventsCollection = @() $date = Get-Date -Year 2017 -Month 1 -Day 1 -Hour 9 -Minute 30 -Second 15 $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date, "Sample Message") $eventsCollection += [EventLogItemMock]::new(456, "Test App2", "domain\user2", $date.AddSeconds(1), "Another Message") return $eventsCollection } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-EventLogs $poShMonConfiguration $output = $($actual = Test-EventLogs $poShMonConfiguration) 3>&1 $date = Get-Date -Year 2017 -Month 1 -Day 1 -Hour 9 -Minute 30 -Second 15 $output.Count | Should Be 2 $output[0].ToString() | Should Be "`t`t123 : 1 : Test App : domain\user1 : $($date.ToString()) - Sample Message" $output[1].ToString() | Should Be "`t`t456 : 1 : Test App2 : domain\user2 : $($date.AddSeconds(1).ToString()) - Another Message" } It "Should alert on items found" { Mock -CommandName Get-WmiObject -MockWith { $eventsCollection = @() $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", (Get-Date), "Sample Message") return $eventsCollection } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-EventLogs $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false } It "Should group per server" -Skip { #no longer valid Mock -CommandName Get-WmiObject -MockWith { $eventsCollection = @() $date = Get-Date $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date, "Sample Message") $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date.AddMinutes(-1), "Sample Message") $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date.AddMinutes(-2), "Another Sample Message") $eventsCollection += [EventLogItemMock]::new(456, "Test App", "domain\user1", $date.AddMinutes(-3), "Different Event Code") return $eventsCollection } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1', 'Server2' OperatingSystem } $actual = Test-EventLogs $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Count | Should Be 6 $actual.OutputValues[0].ServerName | Should Be "Server1" $actual.OutputValues[0].Message | Should Be "Sample Message" $actual.OutputValues[0].InstanceCount | Should Be 2 $actual.OutputValues[1].Message | Should Be "Another Sample Message" $actual.OutputValues[1].InstanceCount | Should Be 1 } It "Should group on EventID and Message" { Mock -CommandName Get-WmiObject -MockWith { $eventsCollection = @() $date = Get-Date $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date, "Sample Message") $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date.AddMinutes(-1), "Sample Message") $eventsCollection += [EventLogItemMock]::new(123, "Test App", "domain\user1", $date.AddMinutes(-2), "Another Sample Message") $eventsCollection += [EventLogItemMock]::new(456, "Test App", "domain\user1", $date.AddMinutes(-3), "Different Event Code") return $eventsCollection } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1', 'Server2' OperatingSystem } $actual = Test-EventLogs $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Count | Should Be 6 $actual.OutputValues[0].ServerName | Should Be "Server1" $actual.OutputValues[0].Message | Should Be "Sample Message" $actual.OutputValues[0].InstanceCount | Should Be 2 $actual.OutputValues[1].ServerName | Should Be "Server1" $actual.OutputValues[1].Message | Should Be "Another Sample Message" $actual.OutputValues[1].InstanceCount | Should Be 1 $actual.OutputValues[3].ServerName | Should Be "Server2" $actual.OutputValues[3].Message | Should Be "Sample Message" $actual.OutputValues[3].InstanceCount | Should Be 2 $actual.OutputValues[4].ServerName | Should Be "Server2" $actual.OutputValues[4].Message | Should Be "Another Sample Message" $actual.OutputValues[4].InstanceCount | Should Be 1 } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.OS/Test-Memory.Tests.ps1
Test-Memory.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-Memory" { InModuleScope PoShMon { class ServerMemoryMock { [string]$PSComputerName [UInt64]$TotalVisibleMemorySize [UInt64]$FreePhysicalMemory ServerMemoryMock ([string]$NewPSComputerName, [UInt64]$NewTotalVisibleMemorySize, [UInt64]$NewFreePhysicalMemory) { $this.PSComputerName = $NewPSComputerName; $this.TotalVisibleMemorySize = $NewTotalVisibleMemorySize; $this.FreePhysicalMemory = $NewFreePhysicalMemory; } } #It "Should throw an exception if no OperatingSystem configuration is set" { # # $poShMonConfiguration = New-PoShMonConfiguration { } # # { Test-Memory $poShMonConfiguration } | Should throw #} It "Should return a matching output structure" { Mock -CommandName Get-WmiObject -MockWith { return [ServerMemoryMock]::new($ComputerName, 8312456, 2837196) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-Memory $poShMonConfiguration $actual.Keys.Count | Should Be 5 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be 3 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be 4 #$values1.ContainsKey("ServerName") | Should Be $true #$values1.ContainsKey("TotalMemory") | Should Be $true #$values1.ContainsKey("FreeMemory") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true $actual.OutputValues[0].ServerName | Should Be "Server1" $actual.OutputValues[0].TotalMemory | Should Be "7.93" $actual.OutputValues[0].FreeMemory | Should Be "2.71 (34%)" $actual.OutputValues[0].Highlight.Count | Should Be 0 } It "Should write the expected Verbose output" { Mock -CommandName Get-WmiObject -MockWith { return [ServerMemoryMock]::new($ComputerName, 8312456, 2837196) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-Memory $poShMonConfiguration -Verbose $output = $($actual = Test-Memory $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 3 $output[0].ToString() | Should Be "Initiating 'Memory Review' Test..." $output[1].ToString() | Should Be "`tServer1 : 7.93 : 2.71 (34%)" $output[2].ToString() | Should Be "Complete 'Memory Review' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Get-WmiObject -MockWith { return [ServerMemoryMock]::new($ComputerName, 8312456, 300000) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-Memory $poShMonConfiguration $output = $($actual = Test-Memory $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`t`tFree memory (4%) is below variance threshold (10)" } It "Should not warn on space above threshold" { Mock -CommandName Get-WmiObject -MockWith { return [ServerMemoryMock]::new($ComputerName, 8312456, 2837196) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem } $actual = Test-Memory $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $true $actual.OutputValues.GroupOutputValues.Highlight.Count | Should Be 0 } It "Should warn on space below threshold" { Mock -CommandName Get-WmiObject -MockWith { return [ServerMemoryMock]::new('TheServer', 8312456, 10000) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'TheServer' OperatingSystem } $actual = Test-Memory $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'FreeMemory' } It "Should use the configuration threshold properly" { $memory = 8312456*0.5 Mock -CommandName Get-WmiObject -MockWith { return [ServerMemoryMock]::new($ComputerName, 8312456, $memory) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'localhost' OperatingSystem -FreeMemoryThreshold 51 } $actual = Test-Memory $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues.Highlight | Should Be 'FreeMemory' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.Web/Test-WebSite.Tests.ps1
Test-WebSite.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-Website" { InModuleScope PoShMon { class WebRequestMock { [int]$StatusCode [string]$StatusDescription [string]$Content WebRequestMock ([int]$NewStatusCode, [String]$NewStatusDescription, [String]$NewContent) { $this.StatusCode = $NewStatusCode; $this.StatusDescription = $NewStatusDescription; $this.Content = $NewContent; } } class RemoteWebRequestMock { [int]$StatusCode [string]$StatusDescription [string]$Content [string]$ServerName RemoteWebRequestMock ([int]$NewStatusCode, [String]$NewStatusDescription, [String]$NewContent, [String]$NewServerName) { $this.StatusCode = $NewStatusCode; $this.StatusDescription = $NewStatusDescription; $this.Content = $NewContent; $this.ServerName = $NewServerName; } } It "Should return a matching output structure" { Mock -CommandName Invoke-WebRequest -Verifiable -MockWith { return [WebRequestMock]::new(200, "OK", "Some Text") } Mock -CommandName Invoke-RemoteWebRequest -Verifiable -ModuleName PoShMon -MockWith { return [RemoteWebRequestMock]::new(200, "OK", "Some Text", $serverName) } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Server1','Server2' WebSite ` -WebsiteDetails @{ "http://my.website.com" = "Some Text" } } $actual = Test-WebSites $poShMonConfiguration Assert-VerifiableMocks $actual.Keys.Count | Should Be 5 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be 3 $actual.OutputValues[1].ServerName | Should Be 'Server1' $actual.OutputValues[1].StatusCode | Should Be 200 $actual.OutputValues[1].Outcome | Should Be 'Specified Page Content Found' $actual.OutputValues[1].Highlight.Count | Should Be 0 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be 4 #$values1.ContainsKey("ServerName") | Should Be $true #$values1.ContainsKey("StatusCode") | Should Be $true #$values1.ContainsKey("Outcome") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Invoke-WebRequest -MockWith { return [WebRequestMock]::new(200, "OK", "Some Text") } Mock -CommandName Invoke-RemoteWebRequest -ModuleName PoShMon -MockWith { return [RemoteWebRequestMock]::new(200, "OK", "Some Text", $serverName) } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Server1','Server2' WebSite ` -WebsiteDetails @{ "http://my.website.com" = "Some Text" } } $actual = Test-WebSites $poShMonConfiguration -Verbose $output = $($actual = Test-WebSites $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 8 $output[0].ToString() | Should Be "Initiating 'Web Test - http://my.website.com' Test..." $output[1].ToString() | Should Be "`tScanning Site http://my.website.com (Direct)" $output[2].ToString() | Should Be "`t`t(Direct) : 200 : Specified Page Content Found" $output[3].ToString() | Should Be "`tScanning Site http://my.website.com on Server1" $output[4].ToString() | Should Be "`t`tServer1 : 200 : Specified Page Content Found" $output[5].ToString() | Should Be "`tScanning Site http://my.website.com on Server2" $output[6].ToString() | Should Be "`t`tServer2 : 200 : Specified Page Content Found" $output[7].ToString() | Should Be "Complete 'Web Test - http://my.website.com' Test, Issues Found: No" } It "Should test directly and on each server" { Mock -CommandName Invoke-WebRequest -MockWith { return [WebRequestMock]::new(200, "OK", "Some Text") } Mock -CommandName Invoke-RemoteWebRequest -ModuleName PoShMon -MockWith { return [RemoteWebRequestMock]::new(200, "OK", "Some Text", $serverName) } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Server1','Server2' WebSite ` -WebsiteDetails @{ "http://my.website.com" = "Some Text" } } $actual = Test-WebSites $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Count | Should Be 3 $actual.OutputValues[0].ServerName | Should Be '(Direct)' $actual.OutputValues[1].ServerName | Should Be 'Server1' $actual.OutputValues[2].ServerName | Should Be 'Server2' } It "Should fail on server 1" { Mock -CommandName Invoke-WebRequest -Verifiable -MockWith { return [WebRequestMock]::new('200', '<html>Test Content</html>', 'OK') } Mock -CommandName Invoke-RemoteWebRequest -ModuleName PoShMon -Verifiable -MockWith { if ($ServerName -ne "Server1") { return [RemoteWebRequestMock]::new('200', 'OK', '<html>Test Content</html>', $ServerName) } else { return [RemoteWebRequestMock]::new('500', 'Server Error', '<html><title>Server Error</title></html>', $ServerName) } } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Server1','Server2' WebSite ` -WebsiteDetails @{ "http://my.website.com" = "Test Content" } } $actual = Test-WebSites $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues[1].Highlight | Should Be 'Outcome' $actual.OutputValues[1].Outcome | Should Be 'Server Error' } It "Should find matching text" { Mock -CommandName Invoke-WebRequest -Verifiable -MockWith { return [WebRequestMock]::new('200', 'OK', '<html>Test Content</html>') } Mock -CommandName Invoke-RemoteWebRequest -ModuleName PoShMon -Verifiable -MockWith { if ($ServerName -eq "Server1") { return [RemoteWebRequestMock]::new('200', 'OK', '<html>Test Content</html>', $ServerName) } else { return [RemoteWebRequestMock]::new('200', 'OK', '<html>other stuff</html>', $ServerName) } } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Server1','Server2' WebSite ` -WebsiteDetails @{ "http://my.website.com" = "Test Content" } } $actual = Test-WebSites $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues[0].Highlight.Count | Should Be 0 $actual.OutputValues[0].Outcome | Should Be 'Specified Page Content Found' $actual.OutputValues[1].Highlight.Count | Should Be 0 $actual.OutputValues[1].Outcome | Should Be 'Specified Page Content Found' $actual.OutputValues[2].Highlight | Should Be 'Outcome' $actual.OutputValues[2].Outcome | Should Be 'Specified Page Content Not Found' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Notifications.Email.Monitoring/New-EmailFooter.Tests.ps1
New-EmailFooter.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "New-EmailFooter" { InModuleScope PoShMon { class ModuleMock { [string]$Version ModuleMock ([string]$NewVersion) { $this.Version = $NewVersion; } } It "Should Show the Skipped Tests" { Mock -CommandName Get-Module -MockWith { return [ModuleMock]::new("1.2.3") } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Foo' ` -SkipVersionUpdateCheck ` -TestsToSkip 'ABC','DEF' } $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $actual = New-EmailFooter $poShMonConfiguration $totalElapsedTime $actual.IndexOf("<b>Skipped Tests:</b> ABC, DEF") -gt 0 | Should Be $true } It "Should Show 'None' for non-skipped tests" { Mock -CommandName Get-Module -MockWith { return [ModuleMock]::new("1.2.3") } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Foo' ` -SkipVersionUpdateCheck } $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $actual = New-EmailFooter $poShMonConfiguration $totalElapsedTime #Write-Host $actual $actual.IndexOf("<b>Skipped Tests:</b> None") -gt 0 | Should Be $true } It "Should Show 'None' for non-skipped tests as empty array" { Mock -CommandName Get-Module -MockWith { return [ModuleMock]::new("1.2.3") } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Foo' ` -SkipVersionUpdateCheck ` -TestsToSkip @() } $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $actual = New-EmailFooter $poShMonConfiguration $totalElapsedTime $actual.IndexOf("<b>Skipped Tests:</b> None") -gt 0 | Should Be $true } It "Should Show 'None' for non-skipped tests as empty item" -Skip { #this is now handled higher up in the stack Mock -CommandName Get-Module -MockWith { return [ModuleMock]::new("1.2.3") } $poShMonConfiguration = New-PoShMonConfiguration { General ` -ServerNames 'Foo' ` -SkipVersionUpdateCheck ` -TestsToSkip '' } $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $actual = New-EmailFooter $poShMonConfiguration $totalElapsedTime $actual.IndexOf("<b>Skipped Tests:</b> None") -gt 0 | Should Be $true } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-SPDistributedCacheHealth.Tests.ps1
Test-SPDistributedCacheHealth.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-SPDistributedCacheHealth" { InModuleScope PoShMon { class SPDistributedCacheMock { [object]$Server [object]$Status SPDistributedCacheMock ([string]$NewServerDisplayName, [string]$NewStatusValue) { $this.Server = [pscustomobject]@{DisplayName=$NewServerDisplayName}; $this.Status = [pscustomobject]@{Value=$NewStatusValue}; } } It "Should return a matching output structure" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [SPDistributedCacheMock]::new('Server1', 'Online') ) } $poShMonConfiguration = New-PoShMonConfiguration { } $actual = Test-SPDistributedCacheHealth $poShMonConfiguration $headerKeyCount = 2 $actual.Keys.Count | Should Be 5 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be $headerKeyCount $actual.OutputValues[0].Server | Should Be 'Server1' $actual.OutputValues[0].Status | Should Be 'Online' $actual.OutputValues[0].Status | Should Be 'Online' $actual.OutputValues[0].Highlight.Count | Should Be 0 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be ($headerKeyCount+1) #$values1.ContainsKey("Server") | Should Be $true #$values1.ContainsKey("Status") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDistributedCacheMock]::new('Server1', 'Online') ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPDistributedCacheHealth $poShMonConfiguration -Verbose $output = $($actual = Test-SPDistributedCacheHealth $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 3 $output[0].ToString() | Should Be "Initiating 'Distributed Cache Status' Test..." $output[1].ToString() | Should Be "`tServer1 : Online" $output[2].ToString() | Should Be "Complete 'Distributed Cache Status' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDistributedCacheMock]::new('Server1', 'Online'), [SPDistributedCacheMock]::new('Server2', 'Offline') ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-SPDistributedCacheHealth $poShMonConfiguration $output = $($actual = Test-SPDistributedCacheHealth $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`tServer2 is listed as Offline" } It "Should not warn on all server are online" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDistributedCacheMock]::new('Server1', 'Online') ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPDistributedCacheHealth $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should warn on servers being offline" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDistributedCacheMock]::new('Server1', 'Online'), [SPDistributedCacheMock]::new('Server2', 'Offline') ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPDistributedCacheHealth $poShMonConfiguration -WarningAction SilentlyContinue Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues[0].Highlight.Count | Should Be 0 $actual.OutputValues[1].Highlight.Count | Should Be 1 $actual.OutputValues[1].Highlight[0] | Should Be 'Status' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-SPWindowsServiceState.Tests.ps1
Test-SPWindowsServiceState.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-SPWindowsServiceState" { InModuleScope PoShMon { class SPServiceInstanceMock { [object]$Status [object]$Service [object]$Server SPServiceInstanceMock ([string]$NewServerDisplayName, [string]$NewServiceName, [string]$NewStatusValue) { $this.Server = [pscustomobject]@{DisplayName=$NewServerDisplayName}; $this.Service = [pscustomobject]@{Name=$NewServiceName}; $this.Status = [pscustomobject]@{Value=$NewStatusValue}; } } It "Should return a matching output structure" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPServiceInstanceMock]::new('Server1', 'TheService', 'Online') ) } Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'NoIssuesFound' = $true 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 1 DisplayName'; 'Name' = 'Svc1'; 'Status' = "Running"; 'Highlight' = @() }, [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Running"; 'Highlight' = @() } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { OperatingSystem } $actual = Test-SPWindowsServiceState $poShMonConfiguration $headerKeyCount = 3 $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("GroupBy") | Should Be $true $actual.OutputValues[1].ServerName | Should Be 'Server1' $actual.OutputValues[1].DisplayName | Should Be 'Service 2 DisplayName' $actual.OutputValues[1].Name | Should Be 'Svc2' $actual.OutputValues[1].Status | Should Be 'Running' $actual.OutputValues[1].Highlight.Count | Should Be 0 #$values1 = $valuesGroup1.GroupOutputValues[0] #$values1.Keys.Count | Should Be ($headerKeyCount + 1) #$values1.ContainsKey("DisplayName") | Should Be $true #$values1.ContainsKey("Name") | Should Be $true #$values1.ContainsKey("Status") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPServiceInstanceMock]::new('Server1', 'TheService', 'Online') ) } Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'NoIssuesFound' = $true 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 1 DisplayName'; 'Name' = 'Svc1'; 'Status' = "Running"; 'Highlight' = @() }, [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Running"; 'Highlight' = @() } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { OperatingSystem } $actual = Test-SPWindowsServiceState $poShMonConfiguration -Verbose $output = $($actual = Test-SPWindowsServiceState $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Initiating 'Windows Service State' Test..." $output[1].ToString() | Should Be "`tGetting SharePoint service list..." $output[2].ToString() | Should Be "`tGetting state of services per server..." $output[3].ToString() | Should Be "Complete 'Windows Service State' Test, Issues Found: No" } It "Should fail for any service in the wrong state" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPServiceInstanceMock]::new('Server1', 'TheService', 'Online') ) } Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { return @( @{ 'NoIssuesFound' = $false 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Stopped"; 'Highlight' = @('Status') } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { OperatingSystem } $actual = Test-SPWindowsServiceState $poShMonConfiguration $actual.NoIssuesFound | Should Be $false Assert-VerifiableMocks } It "Should test for services discovered" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPServiceInstanceMock]::new('Server1', 'TheService', 'Online') ) } Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { if (!$Services.Contains('TheService')) { throw "Service Not Found" } return @( @{ 'NoIssuesFound' = $false 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Stopped"; 'Highlight' = @('Status') } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { OperatingSystem } $actual = Test-SPWindowsServiceState $poShMonConfiguration $actual.NoIssuesFound | Should Be $false Assert-VerifiableMocks } It "Should skip any service specified discovered" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPServiceInstanceMock]::new('Server1', 'TheService', 'Online') ) } Mock -CommandName Test-ServiceStatePartial -ModuleName PoShMon -Verifiable -MockWith { if (!$Services.Contains('TheService')) { throw "Service Not Found" } if ($Services.Contains('SPWriterV4')) { throw "SPWriterV4 Should be skipped!" } return @( @{ 'NoIssuesFound' = $false 'GroupOutputValues' = @( [pscustomobject]@{ 'ServerName' = 'Server1' 'DisplayName' = 'Service 2 DisplayName'; 'Name' = 'Svc2'; 'Status' = "Stopped"; 'Highlight' = @('Status') } ) } ) } $poShMonConfiguration = New-PoShMonConfiguration { OperatingSystem -WindowsServicesToSkip 'SPWriterV4' } $actual = Test-SPWindowsServiceState $poShMonConfiguration $actual.NoIssuesFound | Should Be $false Assert-VerifiableMocks } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-SPUPSSyncHealth.Tests.ps1
Test-SPUPSSyncHealth.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-SPUPSSyncHealth" { InModuleScope PoShMon { class UpsServiceInstanceMock { [object]$Server UpsServiceInstanceMock ([string]$NewServerDisplayName) { $this.Server = [pscustomobject]@{DisplayName=$NewServerDisplayName}; } } class FimRunHistoryItemMock { [string]$RunStatus [string]$RunStatusReturnValue [string]$RunStartTime FimRunHistoryItemMock ([string]$NewRunStatus, [string]$NewRunStartTime, [string]$NewRunStatusReturnValue) { $this.RunStatus = $NewRunStatus; $this.RunStartTime = $NewRunStartTime; $this.RunStatusReturnValue = $NewRunStatusReturnValue; } [object] RunDetails() { return [PSCustomObject]@{ "ReturnValue" = $this.RunStatusReturnValue } } } It "Should return a matching output structure" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [UpsServiceInstanceMock]::new("Server1") ) } Mock -CommandName Get-WmiObject -MockWith { $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{85098734-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1879</run-number> <run-profile-name>DS_DELTAIMPORT</run-profile-name> <security-id>domain\serviceacc</security-id> <step-details step-number="2" step-id="{0D16BE50-FB6A-4CDC-B528-59B41D3F41A3}"> <start-date>2017-01-04 23:00:55.253</start-date> <end-date>2017-01-04 23:00:58.987</end-date> <step-result>stopped-connectivity</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>failed-search</connection-result><server>DC01.ab.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:58.473</date><server>DC01.ab.company.com:389</server></incident><incident><connection-result>failed-search</connection-result><date>2017-01-04 23:00:58.957</date><server>DC01.ab.company.com:389</server><cd-error><error-code>8453</error-code> <error-literal>Replication access was denied.</error-literal> <server-error-detail>00002105: LdapErr: DSID-adcv, comment: Error processing control, data 0, v1db1</server-error-detail> </cd-error></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{874BEB73-FFF1-4C43-9836-26D8AACE454E}"> <start-date>2017-01-04 23:00:35.380</start-date> <end-date>2017-01-04 23:00:55.223</end-date> <step-result>success</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=za,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>success</connection-result><server>dc.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:35.410</date><server>dc.company.com:389</server></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> <filtered-objects>46</filtered-objects> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">3</stage-add> <stage-update detail="true">27</stage-update> <stage-rename detail="true">2</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' return [FimRunHistoryItemMock]::new('not so good', (Get-Date).ToString(), $xml) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPUPSSyncHealth $poShMonConfiguration -WarningAction SilentlyContinue $headerKeyCount = 4 $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("HeaderUrl") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be $headerKeyCount $actual.OutputValues[1].ManagementAgent.Count | Should Be 0 $actual.OutputValues[1].RunProfile.Count | Should Be 0 $actual.OutputValues[1].RunStartTime.Count | Should Be 0 $actual.OutputValues[1].ErrorDetail.Count | Should Be 0 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be $headerKeyCount #$values1.ContainsKey("ManagementAgent") | Should Be $true #$values1.ContainsKey("RunProfile") | Should Be $true #$values1.ContainsKey("RunStartTime") | Should Be $true #$values1.ContainsKey("ErrorDetail") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Invoke-RemoteCommand -Verifiable -ModuleName PoShMon -MockWith { return @( [UpsServiceInstanceMock]::new("Server1") ) } Mock -CommandName Get-WmiObject -Verifiable -MockWith { $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{12345678-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1882</run-number> <run-profile-name>DS_DELTASYNC</run-profile-name> <security-id>Domain\ServiceAccount</security-id> <step-details step-number="2" step-id="{12345678-A92D-4691-8C41-4526906B3307}"> <start-date>2017-01-04 23:05:00.303</start-date> <end-date>2017-01-04 23:05:04.490</end-date> <step-result>success</step-result> <step-description> <step-type type="apply-rules"> <apply-rules-subtype>apply-pending</apply-rules-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">1023</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{12345678-E482-45D4-863A-DF382E82ED45}"> <start-date>2017-01-04 23:04:33.303</start-date> <end-date>2017-01-04 23:04:59.977</end-date> <step-result>success</step-result> <step-description> <step-type type="apply-rules"> <apply-rules-subtype>apply-pending</apply-rules-subtype> </step-type> <partition>DC=cd,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <outbound-flow-counters ma="MOSS-UserProfile" ma-id="{12345678-4E0B-44DA-AF5F-62D4D99B2FBC}"> <provisioned-add-flow detail="true">3</provisioned-add-flow> <connector-flow detail="true">23</connector-flow> </outbound-flow-counters> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">3</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">4235</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">23</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">17</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' return [FimRunHistoryItemMock]::new('success', (Get-Date).ToString(), $xml) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPUPSSyncHealth $poShMonConfiguration -Verbose $output = $($actual = Test-SPUPSSyncHealth $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Getting UPS Service App..." $output[1].ToString() | Should Be "Initiating 'User Profile Sync State' Test..." $output[2].ToString() | Should Be "`tGetting SharePoint service list to locate UPS Sync server..." $output[3].ToString() | Should Be "Complete 'User Profile Sync State' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [UpsServiceInstanceMock]::new("Server1") ) } Mock -CommandName Get-WmiObject -MockWith { $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{85098734-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1879</run-number> <run-profile-name>DS_DELTAIMPORT</run-profile-name> <security-id>domain\serviceacc</security-id> <step-details step-number="2" step-id="{0D16BE50-FB6A-4CDC-B528-59B41D3F41A3}"> <start-date>2017-01-04 23:00:55.253</start-date> <end-date>2017-01-04 23:00:58.987</end-date> <step-result>stopped-connectivity</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>failed-search</connection-result><server>DC01.ab.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:58.473</date><server>DC01.ab.company.com:389</server></incident><incident><connection-result>failed-search</connection-result><date>2017-01-04 23:00:58.957</date><server>DC01.ab.company.com:389</server><cd-error><error-code>8453</error-code> <error-literal>Replication access was denied.</error-literal> <server-error-detail>00002105: LdapErr: DSID-adcv, comment: Error processing control, data 0, v1db1</server-error-detail> </cd-error></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{874BEB73-FFF1-4C43-9836-26D8AACE454E}"> <start-date>2017-01-04 23:00:35.380</start-date> <end-date>2017-01-04 23:00:55.223</end-date> <step-result>success</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=za,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>success</connection-result><server>dc.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:35.410</date><server>dc.company.com:389</server></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> <filtered-objects>46</filtered-objects> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">3</stage-add> <stage-update detail="true">27</stage-update> <stage-rename detail="true">2</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' return [FimRunHistoryItemMock]::new('not so good', (Get-Date).ToString(), $xml) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPUPSSyncHealth $poShMonConfiguration $output = $($actual = Test-SPUPSSyncHealth $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString().Substring(0, 97) | Should Be "`tStep 2 has status of stopped-connectivity : <connection-result>failed-search</connection-result>" } It "Should not warn on no failed Jobs" { Mock -CommandName Invoke-RemoteCommand -Verifiable -ModuleName PoShMon -MockWith { return @( [UpsServiceInstanceMock]::new("Server1") ) } Mock -CommandName Get-WmiObject -Verifiable -MockWith { $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{12345678-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1882</run-number> <run-profile-name>DS_DELTASYNC</run-profile-name> <security-id>Domain\ServiceAccount</security-id> <step-details step-number="2" step-id="{12345678-A92D-4691-8C41-4526906B3307}"> <start-date>2017-01-04 23:05:00.303</start-date> <end-date>2017-01-04 23:05:04.490</end-date> <step-result>success</step-result> <step-description> <step-type type="apply-rules"> <apply-rules-subtype>apply-pending</apply-rules-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">1023</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{12345678-E482-45D4-863A-DF382E82ED45}"> <start-date>2017-01-04 23:04:33.303</start-date> <end-date>2017-01-04 23:04:59.977</end-date> <step-result>success</step-result> <step-description> <step-type type="apply-rules"> <apply-rules-subtype>apply-pending</apply-rules-subtype> </step-type> <partition>DC=cd,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <outbound-flow-counters ma="MOSS-UserProfile" ma-id="{12345678-4E0B-44DA-AF5F-62D4D99B2FBC}"> <provisioned-add-flow detail="true">3</provisioned-add-flow> <connector-flow detail="true">23</connector-flow> </outbound-flow-counters> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">3</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">4235</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">23</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">17</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' return [FimRunHistoryItemMock]::new('success', (Get-Date).ToString(), $xml) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPUPSSyncHealth $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $true } It "Should warn on any failed Jobs" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [UpsServiceInstanceMock]::new("Server1") ) } Mock -CommandName Get-WmiObject -MockWith { $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{85098734-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1879</run-number> <run-profile-name>DS_DELTAIMPORT</run-profile-name> <security-id>domain\serviceacc</security-id> <step-details step-number="2" step-id="{0D16BE50-FB6A-4CDC-B528-59B41D3F41A3}"> <start-date>2017-01-04 23:00:55.253</start-date> <end-date>2017-01-04 23:00:58.987</end-date> <step-result>stopped-connectivity</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>failed-search</connection-result><server>DC01.ab.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:58.473</date><server>DC01.ab.company.com:389</server></incident><incident><connection-result>failed-search</connection-result><date>2017-01-04 23:00:58.957</date><server>DC01.ab.company.com:389</server><cd-error><error-code>8453</error-code> <error-literal>Replication access was denied.</error-literal> <server-error-detail>00002105: LdapErr: DSID-adcv, comment: Error processing control, data 0, v1db1</server-error-detail> </cd-error></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{874BEB73-FFF1-4C43-9836-26D8AACE454E}"> <start-date>2017-01-04 23:00:35.380</start-date> <end-date>2017-01-04 23:00:55.223</end-date> <step-result>success</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=za,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>success</connection-result><server>dc.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:35.410</date><server>dc.company.com:389</server></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> <filtered-objects>46</filtered-objects> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">3</stage-add> <stage-update detail="true">27</stage-update> <stage-rename detail="true">2</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' return [FimRunHistoryItemMock]::new('not so good', (Get-Date).ToString(), $xml) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPUPSSyncHealth $poShMonConfiguration -WarningAction SilentlyContinue Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Count | Should Be 1 } It "Should return all failed Jobs" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [UpsServiceInstanceMock]::new("Server1") ) } Mock -CommandName Get-WmiObject -MockWith { $jobs = @() $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{12345678-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1882</run-number> <run-profile-name>DS_DELTASYNC</run-profile-name> <security-id>Domain\ServiceAccount</security-id> <step-details step-number="2" step-id="{12345678-A92D-4691-8C41-4526906B3307}"> <start-date>2017-01-04 23:05:00.303</start-date> <end-date>2017-01-04 23:05:04.490</end-date> <step-result>success</step-result> <step-description> <step-type type="apply-rules"> <apply-rules-subtype>apply-pending</apply-rules-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">1023</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{12345678-E482-45D4-863A-DF382E82ED45}"> <start-date>2017-01-04 23:04:33.303</start-date> <end-date>2017-01-04 23:04:59.977</end-date> <step-result>success</step-result> <step-description> <step-type type="apply-rules"> <apply-rules-subtype>apply-pending</apply-rules-subtype> </step-type> <partition>DC=cd,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <outbound-flow-counters ma="MOSS-UserProfile" ma-id="{12345678-4E0B-44DA-AF5F-62D4D99B2FBC}"> <provisioned-add-flow detail="true">3</provisioned-add-flow> <connector-flow detail="true">23</connector-flow> </outbound-flow-counters> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">3</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">4235</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">23</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">17</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' $jobs += [FimRunHistoryItemMock]::new('success', (Get-Date).ToString(), $xml) $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{85098734-66BC-4938-8122-C5F585F463D0}</ma-id> <ma-name>MOSSAD-company</ma-name> <run-number>1879</run-number> <run-profile-name>DS_DELTAIMPORT</run-profile-name> <security-id>domain\serviceacc</security-id> <step-details step-number="2" step-id="{0D16BE50-FB6A-4CDC-B528-59B41D3F41A3}"> <start-date>2017-01-04 23:00:55.253</start-date> <end-date>2017-01-04 23:00:58.987</end-date> <step-result>stopped-connectivity</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=ab,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>failed-search</connection-result><server>DC01.ab.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:58.473</date><server>DC01.ab.company.com:389</server></incident><incident><connection-result>failed-search</connection-result><date>2017-01-04 23:00:58.957</date><server>DC01.ab.company.com:389</server><cd-error><error-code>8453</error-code> <error-literal>Replication access was denied.</error-literal> <server-error-detail>00002105: LdapErr: DSID-adcv, comment: Error processing control, data 0, v1db1</server-error-detail> </cd-error></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> <step-details step-number="1" step-id="{874BEB73-FFF1-4C43-9836-26D8AACE454E}"> <start-date>2017-01-04 23:00:35.380</start-date> <end-date>2017-01-04 23:00:55.223</end-date> <step-result>success</step-result> <step-description> <step-type type="delta-import"> <import-subtype>to-cs</import-subtype> </step-type> <partition>DC=za,DC=company,DC=com</partition> <custom-data> <adma-step-data><batch-size>100</batch-size><page-size>500</page-size><time-limit>120</time-limit></adma-step-data> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> <connection-result>success</connection-result><server>dc.company.com:389</server><connection-log><incident><connection-result>success</connection-result><date>2017-01-04 23:00:35.410</date><server>dc.company.com:389</server></incident></connection-log> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> <filtered-objects>46</filtered-objects> </ma-discovery-counters> <synchronization-errors/> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">3</stage-add> <stage-update detail="true">27</stage-update> <stage-rename detail="true">2</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">0</export-add> <export-update detail="true">0</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">0</export-failure> </export-counters> </step-details> </run-details> </run-history>' $jobs += [FimRunHistoryItemMock]::new('not so good', (Get-Date).ToString(), $xml) $xml = '<?xml version="1.0" encoding="utf-16"?> <run-history> <run-details> <ma-id>{FB0D00E1-4E0B-44DA-AF5F-62D4D99B2FBC}</ma-id> <ma-name>MOSS-UserProfile</ma-name> <run-number>2590</run-number> <run-profile-name>MOSS_EXPORT_a9061a90-5fb2-485e-90e8-4019c5c1f9ce</run-profile-name> <security-id>domain\serviceacc</security-id> <step-details step-number="1" step-id="{E0446E50-FF59-4691-9EC0-F9BD3D564F4A}"> <start-date>2017-01-04 23:05:05.367</start-date> <end-date>2017-01-04 23:06:06.677</end-date> <step-result>completed-export-errors</step-result> <step-description> <step-type type="export"> </step-type> <partition>default</partition> <custom-data> <run-config><input-file /><timeout>0</timeout></run-config> </custom-data> </step-description> <current-export-step-counter>0</current-export-step-counter> <last-successful-export-step-counter>0</last-successful-export-step-counter> <ma-connection> </ma-connection> <ma-discovery-errors> </ma-discovery-errors> <ma-discovery-counters> </ma-discovery-counters> <synchronization-errors><export-error cs-guid="{12345678-DF83-E611-8CE8-00505689546C}" dn="MVID=67d2da90-0c2a-e411-a2e8-0050568e45d6"> <date-occurred>2017-01-04 23:06:02.006</date-occurred> <first-occurred>2016-09-26 12:02:16.987</first-occurred> <retry-count>77</retry-count> <error-type>ma-extension-error</error-type> <cd-error> <error-code>0x80230703</error-code><error-literal>System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---&gt; System.AggregateException: One or more errors occurred. ---&gt; Microsoft.Office.Server.UserProfiles.PropertyInvalidFormatException: Invalid URL Format: Invalid format for a URL. ---&gt; System.UriFormatException: Invalid URI : The format of the URI could not be determined. at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) at Microsoft.Office.Server.UserProfiles.UserProfileGlobal.ValidatedUrl(Object value) --- End of inner exception stack trace --- at Microsoft.Office.Server.UserProfiles.UserProfileGlobal.ValidatedUrl(Object value) at Microsoft.Office.Server.UserProfiles.MemberGroup.set_Url(String value) at Microsoft.Office.Server.UserProfiles.MemberGroup.BulkPropertiesUpdate(Int64 importExportId, Hashtable properties, String sourceReference) at Microsoft.Office.Server.UserProfiles.ProfileImportExportService.&lt;&gt;c__DisplayClass26.&lt;UpdateWithProfileChangeData&gt;b__24(Int32 idx) at System.Threading.Tasks.Parallel.&lt;&gt;c__DisplayClassf`1.&lt;ForWorker&gt;b__c() at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask) at System.Threading.Tasks.Task.&lt;&gt;c__DisplayClass11.&lt;ExecuteSelfReplicating&gt;b__10(Object param0) --- End of inner exception stack trace --- at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait() at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func `1 localInit, Action`1 localFinally) at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body) at Microsoft.Office.Server.UserProfiles.ProfileImportExportService.UpdateWithProfileChangeData(Int64 importExportId, ProfileChangeData[] profileChangeData) --- End of inner exception stack trace --- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Microsoft.Office.Server.WebServiceDirectProxy.WebMethodInfo.Invoke(Object webServiceInstance, Object[] args) at Microsoft.Office.Server.WebServiceDirectProxy.Invoke(String methodName, Object[] args) at Microsoft.Office.Server.UserProfiles.ManagementAgent.ProfileImportExportDirect.UpdateWithProfileChangeData(Int64 importExportId, ProfileChangeData[] profileChangeData) at Microsoft.Office.Server.UserProfiles.ManagementAgent.ProfileImportExportExtension.Microsoft.MetadirectoryServices.IMAExtensibleCallExport.ExportEntry(ModificationType modificationType, Str ing[] changedAttributes, CSEntry csentry) </error-literal> </cd-error> </export-error> </synchronization-errors> <mv-retry-errors/> <staging-counters> <stage-no-change detail="false">0</stage-no-change> <stage-add detail="true">0</stage-add> <stage-update detail="true">0</stage-update> <stage-rename detail="true">0</stage-rename> <stage-delete detail="true">0</stage-delete> <stage-delete-add detail="true">0</stage-delete-add> <stage-failure detail="true">0</stage-failure> </staging-counters> <inbound-flow-counters> <disconnector-filtered detail="true">0</disconnector-filtered> <disconnector-joined-no-flow detail="true">0</disconnector-joined-no-flow> <disconnector-joined-flow detail="true">0</disconnector-joined-flow> <disconnector-joined-remove-mv detail="true">0</disconnector-joined-remove-mv> <disconnector-projected-no-flow detail="true">0</disconnector-projected-no-flow> <disconnector-projected-flow detail="true">0</disconnector-projected-flow> <disconnector-projected-remove-mv detail="true">0</disconnector-projected-remove-mv> <disconnector-remains detail="false">0</disconnector-remains> <connector-filtered-remove-mv detail="true">0</connector-filtered-remove-mv> <connector-filtered-leave-mv detail="true">0</connector-filtered-leave-mv> <connector-flow detail="true">0</connector-flow> <connector-flow-remove-mv detail="true">0</connector-flow-remove-mv> <connector-no-flow detail="true">0</connector-no-flow> <connector-delete-remove-mv detail="true">0</connector-delete-remove-mv> <connector-delete-leave-mv detail="true">0</connector-delete-leave-mv> <connector-delete-add-processed detail="true">0</connector-delete-add-processed> <flow-failure detail="true">0</flow-failure> </inbound-flow-counters> <export-counters> <export-add detail="true">3</export-add> <export-update detail="true">23</export-update> <export-rename detail="true">0</export-rename> <export-delete detail="true">0</export-delete> <export-delete-add detail="true">0</export-delete-add> <export-failure detail="true">1</export-failure> </export-counters> </step-details> </run-details> </run-history>' $jobs += [FimRunHistoryItemMock]::new('failed again', (Get-Date).ToString(), $xml) return $jobs } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPUPSSyncHealth $poShMonConfiguration -WarningAction SilentlyContinue Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Count | Should Be 2 } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-SPSearchHealth.Tests.ps1
Test-SPSearchHealth.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-SPSearchHealth" { InModuleScope PoShMon { class SearchItemsMock { [object[]]$SearchComponentStates [object[]]$ComponentTopology SearchItemsMock () { } AddComponentWithState([string]$name, [string]$serverName, [string]$state) { $this.SearchComponentStates += [PSCustomObject]@{ Name = $name; State = $state } $this.ComponentTopology += [PSCustomObject]@{ Name = $name; ServerName = $serverName} } } It "Should return a matching output structure" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { $searchItemsMock = [SearchItemsMock]::new() $searchItemsMock.AddComponentWithState("Component1", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component2", "Server1", "Active") return $searchItemsMock } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPSearchHealth $poShMonConfiguration $headerKeyCount = 3 $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("HeaderUrl") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be $headerKeyCount $actual.OutputValues[1].ServerName | Should Be 'Server1' $actual.OutputValues[1].ComponentName | Should Be 'Component2' $actual.OutputValues[1].State | Should Be 'Active' $actual.OutputValues[1].Highlight.Count | Should Be 0 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be ($headerKeyCount + 1) #$values1.ContainsKey("ComponentName") | Should Be $true #$values1.ContainsKey("ServerName") | Should Be $true #$values1.ContainsKey("State") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { $searchItemsMock = [SearchItemsMock]::new() $searchItemsMock.AddComponentWithState("Component1", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component2", "Server1", "Active") return $searchItemsMock } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPSearchHealth $poShMonConfiguration -Verbose $output = $($actual = Test-SPSearchHealth $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 5 $output[0].ToString() | Should Be "Getting Search Service App..." $output[1].ToString() | Should Be "Initiating 'Search Status' Test..." $output[2].ToString() | Should Be "`tComponent1 is in the following state: Active" $output[3].ToString() | Should Be "`tComponent2 is in the following state: Active" $output[4].ToString() | Should Be "Complete 'Search Status' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { $searchItemsMock = [SearchItemsMock]::new() $searchItemsMock.AddComponentWithState("Component1", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component2", "Server1", "InActive") return $searchItemsMock } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPSearchHealth $poShMonConfiguration $output = $($actual = Test-SPSearchHealth $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`tComponent2 is not listed as 'Active'. State: InActive" } It "Should return an output for each component" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { $searchItemsMock = [SearchItemsMock]::new() $searchItemsMock.AddComponentWithState("Component1", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component2", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component3", "Server2", "Active") return $searchItemsMock } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPSearchHealth $poShMonConfiguration $actual.OutputValues.Count | Should Be 3 } It "Should not warn on all Active components" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { $searchItemsMock = [SearchItemsMock]::new() $searchItemsMock.AddComponentWithState("Component1", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component2", "Server1", "Active") return $searchItemsMock } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPSearchHealth $poShMonConfiguration $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should warn on at least one InActive components" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { $searchItemsMock = [SearchItemsMock]::new() $searchItemsMock.AddComponentWithState("Component1", "Server1", "Active") $searchItemsMock.AddComponentWithState("Component2", "Server1", "InActive") return $searchItemsMock } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPSearchHealth $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues[1].Highlight.Count | Should Be 1 $actual.OutputValues[1].Highlight[0] | Should Be 'State' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-SPJobHealth.Tests.ps1
Test-SPJobHealth.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Test-SPJobHealth" { InModuleScope PoShMon { class SPJobHealthMock { [string]$JobDefinitionTitle [string]$EndTime [string]$ServerName [string]$WebApplicationName [string]$ErrorMessage SPJobHealthMock ([string]$NewJobDefinitionTitle, [string]$NewEndTime, [string]$NewServerName, [string]$NewWebApplicationName, [string]$NewErrorMessage) { $this.JobDefinitionTitle = $NewJobDefinitionTitle; $this.EndTime = $NewEndTime; $this.ServerName = $NewServerName; $this.WebApplicationName = $NewWebApplicationName; $this.ErrorMessage = $NewErrorMessage; } } It "Should return a matching output structure" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [SPJobHealthMock]::new('Job 123', [datetime]::new(2017, 1, 1, 10, 15, 0).ToString(), "Server1", "Web App1", "Something went wrong...") ) } $poShMonConfiguration = New-PoShMonConfiguration { } $actual = Test-SPJobHealth $poShMonConfiguration $headerKeyCount = 4 $actual.Keys.Count | Should Be 6 $actual.ContainsKey("NoIssuesFound") | Should Be $true $actual.ContainsKey("OutputHeaders") | Should Be $true $actual.ContainsKey("OutputValues") | Should Be $true $actual.ContainsKey("SectionHeader") | Should Be $true $actual.ContainsKey("ElapsedTime") | Should Be $true $actual.ContainsKey("HeaderUrl") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be $headerKeyCount $actual.OutputValues[0].JobDefinitionTitle | Should Be 'Job 123' $actual.OutputValues[0].EndTime | Should Be ([datetime]::new(2017, 1, 1, 10, 15, 0)).ToString() $actual.OutputValues[0].ServerName | Should Be "Server1" #$actual.OutputValues[0].WebApplicationName | Should Be "Web App1" $actual.OutputValues[0].ErrorMessage | Should Be "Something went wrong..." #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be $headerKeyCount #$values1.ContainsKey("JobDefinitionTitle") | Should Be $true #$values1.ContainsKey("EndTime") | Should Be $true #$values1.ContainsKey("ServerName") | Should Be $true #$values1.ContainsKey("WebApplicationName") | Should Be $true #$values1.ContainsKey("ErrorMessage") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( ) } $poShMonConfiguration = New-PoShMonConfiguration { } $actual = Test-SPJobHealth $poShMonConfiguration -Verbose $output = $($actual = Test-SPJobHealth $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 2 $output[0].ToString() | Should Be "Initiating 'Failing Timer Jobs' Test..." $output[1].ToString() | Should Be "Complete 'Failing Timer Jobs' Test, Issues Found: No" } It "Should not warn on no failed Jobs" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPJobHealth $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $true } It "Should write the expected Warning output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { $date = Get-Date -Year 2017 -Month 1 -Day 1 -Hour 9 -Minute 30 -Second 15 return @( [SPJobHealthMock]::new('Job 123', $date, "Server1", "Web App1", "Something went wrong..."), [SPJobHealthMock]::new('Job 456', $date.AddMinutes(-1), "Server1", "Web App1", "Something went wrong...") ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPJobHealth $poShMonConfiguration $output = $($actual = Test-SPJobHealth $poShMonConfiguration) 3>&1 $output.Count | Should Be 2 $output[0].ToString() | Should Be "`tJob 123 at 01/01/2017 09:30:15 on Server1 for Web App1 : Something went wrong..." $output[1].ToString() | Should Be "`tJob 456 at 01/01/2017 09:29:15 on Server1 for Web App1 : Something went wrong..." } It "Should warn on any failed Jobs" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPJobHealthMock]::new('Job 123', (get-date).AddMinutes(-145), "Server1", "Web App1", "Something went wrong...") ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPJobHealth $poShMonConfiguration -WarningAction SilentlyContinue Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Count | Should Be 1 } It "Should return all failed Jobs" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPJobHealthMock]::new('Job 123', (get-date).AddMinutes(-145), "Server1", "Web App1", "Something went wrong..."), [SPJobHealthMock]::new('Job 456', (get-date).AddMinutes(-145), "Server1", "Web App1", "Something went wrong...") ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPJobHealth $poShMonConfiguration -WarningAction SilentlyContinue Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Count | Should Be 2 $actual.OutputValues[0].JobDefinitionTitle | Should Be 'Job 123' $actual.OutputValues[1].JobDefinitionTitle | Should Be 'Job 456' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Resolve-HighCPUWhileSearchRunning.Tests.ps1
Resolve-HighCPUWhileSearchRunning.Tests.ps1
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve Remove-Module PoShMon -ErrorAction SilentlyContinue Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1") Describe "Resolve-HighCPUWhileSearchRunning" { InModuleScope PoShMon { class ContentSourceMock { [string]$Name [string]$CrawlState ContentSourceMock ([string]$NewName, [string]$NewCrawlState) { $this.Name = $NewName; $this.CrawlState = $NewCrawlState; } } class SearchComponentMock { [string]$Name [string]$ServerName SearchComponentMock ([string]$NewName, [string]$NewServerName) { $this.Name = $NewName; $this.ServerName = $NewServerName; } } It "Should not change output for non-Search activity" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { $contentSources = @( [ContentSourceMock]::new("ContentSource1", "Idle") ) $componentTopology = @( [SearchComponentMock]::new("IndexComponent1", "Svr123") [SearchComponentMock]::new("QueryProcessingComponent1", "Svr123") ) return @{ "ContentSources" = $contentSources; "ComponentTopology" = $componentTopology } } $poShMonConfiguration = New-PoShMonConfiguration {} $testMonitoringOutput = @( @{ "SectionHeader" = "Server CPU Load Review" "OutputHeaders" =[ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ServerName" = "Svr123" "CPULoad" = 5 "Highlight" = @() }, @{ "ServerName" = "Svr456" "CPULoad" = 99 "Highlight" = @("CPULoad") } ) } @{ "SectionHeader" = "Another Test Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Component" = 123 "State" = "State 1" }, @{ "Component" = 456 "State" = "State 2" } ) } ) $actual = Resolve-HighCPUWhileSearchRunning $poShMonConfiguration $testMonitoringOutput Assert-VerifiableMocks $testMonitoringOutput.Count | Should Be 2 $testMonitoringOutput[0].OutputValues[1].Highlight[0] | Should Be "CPULoad" } It "Should not change output for Search Query activity" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { $contentSources = @( [ContentSourceMock]::new("ContentSource1", "Idle") ) $componentTopology = @( [SearchComponentMock]::new("IndexComponent1", "Svr123") [SearchComponentMock]::new("QueryProcessingComponent1", "Svr456") ) return @{ "ContentSources" = $contentSources; "ComponentTopology" = $componentTopology } } $poShMonConfiguration = New-PoShMonConfiguration {} $testMonitoringOutput = @( @{ "SectionHeader" = "Server CPU Load Review" "OutputHeaders" =[ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ServerName" = "Svr123" "CPULoad" = 5 "Highlight" = @() }, @{ "ServerName" = "Svr456" "CPULoad" = 99 "Highlight" = @("CPULoad") } ) } @{ "SectionHeader" = "Another Test Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Component" = 123 "State" = "State 1" }, @{ "Component" = 456 "State" = "State 2" } ) } ) $actual = Resolve-HighCPUWhileSearchRunning $poShMonConfiguration $testMonitoringOutput Assert-VerifiableMocks $testMonitoringOutput.Count | Should Be 2 $testMonitoringOutput[0].OutputValues[1].Highlight[0] | Should Be "CPULoad" } It "Should change output for non-Query Search activity" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { $contentSources = @( [ContentSourceMock]::new("ContentSource1", "Idle") ) $componentTopology = @( [SearchComponentMock]::new("IndexComponent1", "Svr456") [SearchComponentMock]::new("QueryProcessingComponent1", "Svr123") ) return @{ "ContentSources" = $contentSources; "ComponentTopology" = $componentTopology } } $poShMonConfiguration = New-PoShMonConfiguration {} $testMonitoringOutput = @( @{ "SectionHeader" = "Server CPU Load Review" "OutputHeaders" =[ordered]@{ 'ServerName' = 'Server Name'; 'CPULoad' = 'CPU Load (%)' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "ServerName" = "Svr123" "CPULoad" = 5 "Highlight" = @() }, @{ "ServerName" = "Svr456" "CPULoad" = 99 "Highlight" = @("CPULoad") } ) } @{ "SectionHeader" = "Another Test Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Component" = 123 "State" = "State 1" }, @{ "Component" = 456 "State" = "State 2" } ) } ) $actual = Resolve-HighCPUWhileSearchRunning $poShMonConfiguration $testMonitoringOutput Assert-VerifiableMocks $testMonitoringOutput.Count | Should Be 2 $testMonitoringOutput[0].OutputValues[1].Highlight.Count | Should Be 0 $testMonitoringOutput[0].NoIssuesFound | Should Be $true } } }