full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-FarmHealth.Tests.ps1
Test-FarmHealth.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") class SPFarmMock { [string]$Name [string]$BuildVersion [string]$Status [bool]$NeedsUpgrade SPFarmMock ([string]$NewName, [string]$NewBuildVersion, [string]$NewStatus, [bool]$NewNeedsUpgrade) { $this.Name = $NewName; $this.BuildVersion = $NewBuildVersion; $this.Status = $NewStatus; $this.NeedsUpgrade = $NewNeedsUpgrade; } } <# Can't get these to run on my workstation - PoSh Remoting issues on this machine that I don't want to deal with now Describe "Test-FarmHealth" { It "Should return a matching output structure" { Mock -CommandName Invoke-Command -MockWith { return [SPFarmMock]::new("SP_Config", "1.2.3", "Online", $false) } $actual = Test-FarmHealth $null $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 $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 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.SharePoint/Test-SPServerStatus.Tests.ps1
Test-SPServerStatus.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-SPServerStatus" { InModuleScope PoShMon { class SPServerMock { [string]$DisplayName [string]$Status [bool]$NeedsUpgrade [string]$Role SPServerMock ([string]$NewDisplayName, [string]$NewStatus, [bool]$NewNeedsUpgrade, [string]$NewRole) { $this.DisplayName = $NewDisplayName $this.Status = $NewStatus $this.NeedsUpgrade = $NewNeedsUpgrade $this.Role = $NewRole } } It "Should return a matching output structure" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { return [SPServerMock]::new($ServerName, 'Online', $false, 'Application') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2' } $actual = Test-SPServerStatus $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[1].ServerName | Should Be 'Server2' $actual.OutputValues[1].Role | Should Be 'Application' $actual.OutputValues[1].NeedsUpgrade | Should Be 'No' $actual.OutputValues[1].Status | Should Be 'Online' $actual.OutputValues[1].Highlight.Count | Should Be 0 #$values1 = $actual.OutputValues[0] #$values1.Keys.Count | Should Be ($headerKeyCount + 1) #$values1.ContainsKey("ServerName") | Should Be $true #$values1.ContainsKey("Role") | Should Be $true #$values1.ContainsKey("NeedsUpgrade") | Should Be $true #$values1.ContainsKey("Status") | Should Be $true #$values1.ContainsKey("Highlight") | Should Be $true } It "Should write the expected Verbose output" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { return [SPServerMock]::new($ServerName, 'Online', $false, 'Application') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2' } $actual = Test-SPServerStatus $poShMonConfiguration -Verbose $output = $($actual = Test-SPServerStatus $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Initiating 'Farm Server Status' Test..." $output[1].ToString() | Should Be "`tServer1 : Online : False" $output[2].ToString() | Should Be "`tServer2 : Online : False" $output[3].ToString() | Should Be "Complete 'Farm Server Status' Test, Issues Found: No" } It "Should write the expected Warning output" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { $needsUpgrade = if ($ServerName -eq 'Server2') { $true } else { $false } $online = if ($ServerName -eq 'Server3') { 'Offline' } else { 'Online' } return [SPServerMock]::new($ServerName, $online, $needsUpgrade, 'Application') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2','Server3' } $actual = Test-SPServerStatus $poShMonConfiguration $output = $($actual = Test-SPServerStatus $poShMonConfiguration) 3>&1 $output.Count | Should Be 2 $output[0].ToString() | Should Be "`tServer2 is listed as Needing Upgrade" $output[1].ToString() | Should Be "`tServer3 is not listed as Online. Status: Offline" } It "Should return an output for each Server" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { return [SPServerMock]::new($ServerName, 'Online', $false, 'Application') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2' } $actual = Test-SPServerStatus $poShMonConfiguration $actual.OutputValues.Count | Should Be 2 } It "Should warn on any component needing upgrade" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { $needsUpgrade = if ($ServerName -eq 'Server1') { $false } else { $true } return [SPServerMock]::new($ServerName, 'Online', $needsUpgrade, 'Application') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2' } $actual = Test-SPServerStatus $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues[0].Highlight.Count | Should Be 0 $actual.OutputValues[1].Highlight.Count | Should Be 1 $actual.OutputValues[1].Highlight[0] | Should Be 'NeedsUpgrade' } It "Should warn on any component not being Online" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { $status = if ($ServerName -eq 'Server1') { 'Online' } else { 'Something Else' } return [SPServerMock]::new($ServerName, $status, $false, 'TheRole') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2' } $actual = Test-SPServerStatus $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 1 $actual.OutputValues[0].Highlight.Count | Should Be 0 $actual.OutputValues[1].Highlight.Count | Should Be 1 $actual.OutputValues[1].Highlight[0] | Should Be 'Status' } It "Should warn on any component not being Online and needing upgrade" { Mock -CommandName Get-SPServerForRemoteServer -ModuleName PoShMon -MockWith { $status = if ($ServerName -eq 'Server1') { 'Online' } else { 'Something Else' } $needsUpgrade = if ($ServerName -eq 'Server1') { $false } else { $true } return [SPServerMock]::new($ServerName, $status, $needsUpgrade, 'TheRole') } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1','Server2' } $actual = Test-SPServerStatus $poShMonConfiguration -WarningAction SilentlyContinue $actual.NoIssuesFound | Should Be $false $actual.OutputValues.Highlight.Count | Should Be 2 $actual.OutputValues[0].Highlight.Count | Should Be 0 $actual.OutputValues[1].Highlight.Count | Should Be 2 $actual.OutputValues[1].Highlight[0] | Should Be 'NeedsUpgrade' $actual.OutputValues[1].Highlight[1] | Should Be 'Status' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Unit/PoShMon.Monitoring.SharePoint/Test-SPDatabaseHealth.Tests.ps1
Test-SPDatabaseHealth.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-SPDatabaseHealth" { InModuleScope PoShMon { class SPDatabaseMock { [string]$DisplayName [string]$ApplicationName [bool]$NeedsUpgrade [UInt64]$DiskSizeRequired SPDatabaseMock ([string]$NewDisplayName, [string]$NewApplicationName, [bool]$NewNeedsUpgrade, [UInt64]$NewDiskSizeRequired) { $this.DisplayName = $NewDisplayName; $this.ApplicationName = $NewApplicationName; $this.NeedsUpgrade = $NewNeedsUpgrade; $this.DiskSizeRequired = $NewDiskSizeRequired; } } It "Should return a matching output structure" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -MockWith { return @( [SPDatabaseMock]::new('Database1', 'Application1', $false, [UInt64]50GB) ) } $poShMonConfiguration = New-PoShMonConfiguration { } $actual = Test-SPDatabaseHealth $poShMonConfiguration $headerKeyCount = 3 $actual.Keys.Count | Should Be 7 $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("LinkColumn") | Should Be $true $actual.ContainsKey("HeaderUrl") | Should Be $true $headers = $actual.OutputHeaders $headers.Keys.Count | Should Be $headerKeyCount $values1 = $actual.OutputValues[0] $actual.OutputValues[0].DatabaseName | Should Be 'Database1' $actual.OutputValues[0].NeedsUpgrade | Should Be 'No' $actual.OutputValues[0].Size | Should Be '50.00' $actual.OutputValues[0].Highlight.Count | Should Be 0 #$values1.Keys.Count | Should Be ($headerKeyCount+1) #$values1.ContainsKey("DatabaseName") | Should Be $true #$values1.ContainsKey("NeedsUpgrade") | Should Be $true #$values1.ContainsKey("Size") | 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 @( [SPDatabaseMock]::new('Database1', 'Application1', $false, [UInt64]50GB), [SPDatabaseMock]::new('Database2', 'Application1', $false, [UInt64]4GB) ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPDatabaseHealth $poShMonConfiguration -Verbose $output = $($actual = Test-SPDatabaseHealth $poShMonConfiguration -Verbose) 4>&1 $output.Count | Should Be 4 $output[0].ToString() | Should Be "Initiating 'Database Status' Test..." $output[1].ToString() | Should Be "`tDatabase1 : No : 50.00 GB" $output[2].ToString() | Should Be "`tDatabase2 : No : 4.00 GB" $output[3].ToString() | Should Be "Complete 'Database Status' Test, Issues Found: No" Assert-VerifiableMocks } It "Should write the expected Warning output" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDatabaseMock]::new('Database1', 'Application1', $false, [UInt64]50GB), [SPDatabaseMock]::new('Database2', 'Application1', $true, [UInt64]4GB) ) } $poShMonConfiguration = New-PoShMonConfiguration { General -ServerNames 'Server1' OperatingSystem } $actual = Test-SPDatabaseHealth $poShMonConfiguration $output = $($actual = Test-SPDatabaseHealth $poShMonConfiguration) 3>&1 $output.Count | Should Be 1 $output[0].ToString() | Should Be "`tDatabase2 (Application1) is listed as Needing Upgrade" } It "Should not warn on databases that are all fine" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDatabaseMock]::new('Database1', 'Application1', $false, [UInt64]50GB), [SPDatabaseMock]::new('Database2', 'Application1', $false, [UInt64]4GB) ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPDatabaseHealth $poShMonConfiguration Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $true $actual.OutputValues.Highlight.Count | Should Be 0 } It "Should warn on databases that are need upgrade" { Mock -CommandName Invoke-RemoteCommand -ModuleName PoShMon -Verifiable -MockWith { return @( [SPDatabaseMock]::new('Database1', 'Application1', $false, [UInt64]50GB), [SPDatabaseMock]::new('Database2', 'Application1', $true, [UInt64]4GB) ) } $poShMonConfiguration = New-PoShMonConfiguration {} $actual = Test-SPDatabaseHealth $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 'NeedsUpgrade' } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.Notifications/Send-RepairNotifications.Tests.ps1
Send-RepairNotifications.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" Describe "Send-RepairNotifications" { It "Should send notifications to the specified channels (email, Pushbullet, O365 Teams)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi" } } $repairOutput = @( @{ "SectionHeader" = "Repair 1" "RepairResult" = "Something Important Was Done" } ) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -Verifiable -MockWith { return } $actual = Send-RepairNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $repairOutput -Verbose Assert-VerifiableMocks } It "Should send notifications to ONLY the specified channels (email, Pushbullet, O365 Teams)" { #$o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" } } $repairOutput = @( @{ "SectionHeader" = "Repair 1" "RepairResult" = "Something Important Was Done" } ) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -MockWith { throw "Should not get here..." } $actual = Send-RepairNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $repairOutput -Verbose Assert-VerifiableMocks } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.Notifications/Send-MonitoringNotifications.Tests.ps1
Send-MonitoringNotifications.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" Describe "Send-MonitoringNotifications" { InModuleScope PoShMon { Mock -CommandName Get-Module -Verifiable -MockWith { return @( [pscustomobject]@{ Version = "1.2.3" } ) } It "Should send notifications to the specified channels (email, Pushbullet, O365 Teams)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi" } } $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)) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -Verifiable -MockWith { return } $actual = Send-MonitoringNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks "All" $testMonitoringOutput $totalElapsedTime Assert-VerifiableMocks } It "Should send notifications to ONLY the specified channels (email, Pushbullet, O365 Teams)" { #$o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" } } $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)) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } $actual = Send-MonitoringNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks "All" $testMonitoringOutput $totalElapsedTime Assert-VerifiableMocks } It "Should mark failures as Critical" { #$o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When OnlyOnFailure { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" } } $testMonitoringOutput = @( @{ "SectionHeader" = "Grouped Test With A Long Name" "OutputHeaders" = @{ 'EventID' = 'Event ID'; 'Message' ='Message' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @() } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @() } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } -ParameterFilter { $Critical -eq $true } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } -ParameterFilter { $Critical -eq $true } $actual = Send-MonitoringNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $poShMonConfiguration.Notifications.When $testMonitoringOutput $totalElapsedTime Assert-VerifiableMocks } It "Should mark non-failures as NOT Critical" { #$o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When OnlyOnFailure { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" } } $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" = @() } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $true "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @() } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } -ParameterFilter { $Critical -eq $false } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } -ParameterFilter { $Critical -eq $false } $actual = Send-MonitoringNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $poShMonConfiguration.Notifications.When $testMonitoringOutput $totalElapsedTime Assert-VerifiableMocks } It "Should mark failures as NOT Critical when 'All' set" { #$o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'APPServer1' ` -ConfigurationName SpFarmPosh ` -SkipVersionUpdateCheck ` -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests' Notifications -When All { Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com" Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID" } } $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" = @() } @{ "SectionHeader" = "Ungrouped Test" "OutputHeaders" = @{ 'ComponentName' = 'Component'; 'State' = 'State' } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @() } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { return } -ParameterFilter { $Critical -eq $false } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { return } -ParameterFilter { $Critical -eq $false } $actual = Send-MonitoringNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $poShMonConfiguration.Notifications.When $testMonitoringOutput $totalElapsedTime Assert-VerifiableMocks } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.Notifications/Initialize-Notifications.Tests.ps1
Initialize-Notifications.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 "Initialize-Notifications" { It "Should return a the correct html for given test output" -Skip { <#$poShMonConfiguration = @{ TypeName = 'PoShMon.Configuration' General = @{ TypeName = "PoShMon.ConfigurationItems.General" EnvironmentName = "SharePoint" TestsToSkip = 'SkippedTest1','SkippedTest2' } Notifications = @( @{ TypeName = "PoShMon.ConfigurationItems.NotificationCollection-All" Sinks = @{ TypeName = 'PoShMon.ConfigurationItems.Notifications.Email' ToAddress = "testTo@email.com" FromAddress = "testFrom@email.com" } When = "All" } ) }#> Mock -CommandName Send-MailMessage -Verifiable -MockWith { return } $poShMonConfiguration = New-PoShMonConfiguration { General -EnvironmentName "SharePoint" -PrimaryServerName "Server1" -TestsToSkip 'SkippedTest1','SkippedTest2' Notifications -When All { Email -ToAddress "testTo@email.com" -FromAddress "testFrom@email.com" -SmtpServer "EXCHANGE.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" = @( @{ "Component" = 123 "State" = "State 1" }, @{ "Component" = 456 "State" = "State 2" } ) } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-5)) $actual = Initialize-Notifications $poShMonConfiguration $testMonitoringOutput $totalElapsedTime -Verbose } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/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 invoke OS monitoring" { $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 } } Describe "Invoke-OSMonitoring2" { It "Should work with a minimal configuration" -Skip { $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 } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.SelfHealing.Core/Repair-Environment.Tests.ps1
Repair-Environment.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") #. (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Dummy-Repair.ps1") #. (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Dummy-Repair2.ps1") Describe "Repair-Environment" { It "Should send notifications of repairs" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'Core' ` -PrimaryServerName 'Svr1' 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" } } $monitoringOutput = [System.Collections.ArrayList]@( @{ "SectionHeader" = "AMonitoringTest" "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" } ) } ) $RepairScripts = @( (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Dummy-Repair.ps1") ) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon] Core Repair Results (1 Repairs(s) Performed)" $Body | Should Be '<head><title>Core Repairs Report</title></head><body><h1>Core Repairs Report</h1><p><h1>Mock Repair</h1><table border="1"><tbody><tr><td>Some repair message</td></tr></tbody></table></body>' return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Mock Repair : Repair performed`r`n" return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Mock Repair : Repair performed`r`n" return } $actual = Repair-Environment $poShMonConfiguration $monitoringOutput $RepairScripts -Verbose Assert-VerifiableMocks } It "Should send notifications of exceptions in repairs" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'Core' ` -PrimaryServerName 'Svr1' 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" } } $monitoringOutput = [System.Collections.ArrayList]@( @{ "SectionHeader" = "AMonitoringTest" "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" } ) } ) $RepairScripts = @( (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Failing-Repair.ps1") ) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon] Core Repair Results (1 Repairs(s) Performed)" $Body | Should Be '<head><title>Core Repairs Report</title></head><body><h1>Core Repairs Report</h1><p><h1>Failing-Repair</h1><table border="1"><tbody><tr><td>An Exception Occurred</td></tr><tr><td>System.Management.Automation.RuntimeException: Something</td></tr></tbody></table></body>' return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Failing-Repair : (Exception occurred)`r`n" return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Failing-Repair : (Exception occurred)`r`n" return } $actual = Repair-Environment $poShMonConfiguration $monitoringOutput $RepairScripts -Verbose Assert-VerifiableMocks } It "Should send notifications of each repair performed" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'Core' ` -PrimaryServerName 'Svr1' 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" } } $monitoringOutput = @( @{ "SectionHeader" = "AMonitoringTest" "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" } ) } ) $RepairScripts = @( (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Dummy-Repair.ps1") (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Dummy-Repair2.ps1") ) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon] Core Repair Results (2 Repairs(s) Performed)" $Body | Should Be '<head><title>Core Repairs Report</title></head><body><h1>Core Repairs Report</h1><p><h1>Mock Repair</h1><table border="1"><tbody><tr><td>Some repair message</td></tr></tbody></table><p><h1>Another Mock Repair</h1><table border="1"><tbody><tr><td>Another repair message</td></tr></tbody></table></body>' return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Mock Repair : Repair performed`r`nAnother Mock Repair : Repair performed`r`n" return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Mock Repair : Repair performed`r`nAnother Mock Repair : Repair performed`r`n" return } $actual = Repair-Environment $poShMonConfiguration $monitoringOutput $RepairScripts -Verbose Assert-VerifiableMocks } It "Should send notifications of exceptions in repairs as well as successful repairs" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'Core' ` -PrimaryServerName 'Svr1' 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" } } $monitoringOutput = @( @{ "SectionHeader" = "AMonitoringTest" "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" } ) } ) $RepairScripts = @( (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Failing-Repair.ps1") (Join-Path $rootPath -ChildPath "Tests\CI\Integration\PoShMon.SelfHealing.Core\Dummy-Repair2.ps1") ) Mock -CommandName Send-PoShMonEmail -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon] Core Repair Results (2 Repairs(s) Performed)" $Body | Should Be '<head><title>Core Repairs Report</title></head><body><h1>Core Repairs Report</h1><p><h1>Failing-Repair</h1><table border="1"><tbody><tr><td>An Exception Occurred</td></tr><tr><td>System.Management.Automation.RuntimeException: something</td></tr></tbody></table><p><h1>Another Mock Repair</h1><table border="1"><tbody><tr><td>Another repair message</td></tr></tbody></table></body>' return } Mock -CommandName Send-PushbulletMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Failing-Repair : (Exception occurred)`r`nAnother Mock Repair : Repair performed`r`n" return } Mock -CommandName Send-O365TeamsMessage -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose $Subject Write-Verbose $Body $Subject | Should Be "[PoshMon Core Repair Results]`r`n" $Body | Should Be "Failing-Repair : (Exception occurred)`r`nAnother Mock Repair : Repair performed`r`n" return } $actual = Repair-Environment $poShMonConfiguration $monitoringOutput $RepairScripts -Verbose Assert-VerifiableMocks } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.SelfHealing.Core/Dummy-Repair2.ps1
Dummy-Repair2.ps1
Function Dummy-Repair2 { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$PoShMonOutputValues ) return @{ "SectionHeader" = "Another Mock Repair" "RepairResult" = "Another repair message" } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.SelfHealing.Core/Failing-Repair.ps1
Failing-Repair.ps1
Function Failing-Repair { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$PoShMonOutputValues ) throw "Something" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.SelfHealing.Core/Dummy-Repair.ps1
Dummy-Repair.ps1
Function Dummy-Repair { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$PoShMonOutputValues ) return @{ "SectionHeader" = "Mock Repair" "RepairResult" = "Some repair message" } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.Notifications.Email/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" { InModuleScope PoShMon { Mock -CommandName Get-Module -Verifiable -MockWith { return @( [pscustomobject]@{ Version = "1.2.3" } ) } It "Should return a the correct html for given test output" -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)) "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 = '<head><title></title></head><body style="font-family: verdana; font-size: 12px;"><table width="100%" style="border-collapse: collapse; "><tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr><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><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 10px; padding-left: 20px">SharePoint Environment</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: lightgray; padding-top: 20px;"><div style="width:100%; background-color: #FFFFFF;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3"><thead><tr><th align="left" style="border: 1px solid CCCCCC; background-color: #1D6097;" colspan="2"><h2 style="font-size: 16px; color: #FFFFFF">Grouped Test (60.00 Seconds)</h2></th></tr></thead><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="2">Server 1</th></tr></thead><tbody><tr><td style="padding-left: 25px">&nbsp;</td><td><table style="border-collapse: collapse;" cellpadding="3"><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Message</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Event ID</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">Message 1</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">123</td></tr><tr style="background-color: #e1e3e8"><td valign="top" style="border: 1px solid #CCCCCC;" align="left">Message 2</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">456</td></tr></tbody></table></td></tr></tbody><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="2">Server 2</th></tr></thead><tbody><tr><td style="padding-left: 25px">&nbsp;</td><td><table style="border-collapse: collapse;" cellpadding="3"><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Message</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Event ID</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">Message 3</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">789</td></tr></tbody></table></td></tr></tbody></table></div><br/><div style="width:100%; background-color: #FFFFFF;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3"><thead><tr><th align="left" style="border: 1px solid CCCCCC; background-color: #1D6097;" colspan="2"><h2 style="font-size: 16px; color: #FFFFFF">Ungrouped Test (60.00 Seconds)</h2></th></tr></thead><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">State</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Component</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">State 1</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">123</td></tr><tr style="background-color: #e1e3e8"><td valign="top" style="border: 1px solid #CCCCCC;" align="left">State 2</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">456</td></tr></tbody></table></div><br/></td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 20px"><b>Skipped Tests:</b> SPServerStatus, WindowsServiceState, SPFailingTimerJobs, SPDatabaseHealth, SPSearchHealth, SPDistributedCacheHealth, WebTests<br/><b>Total Elapsed Time (Seconds):</b> 180.00 (3.00 Minutes)</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #1D6097; color: #FFFFFF; padding: 20px" align="center">PoShMon Version ' + $currentVersion + ' (Version check skipped)</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr></table><br/></body>' $actual = New-EmailBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime $actual | Should Be $expected } It "Should return a the correct html for given test output [if the output structure changes]" { $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)) $expected = '<head><title></title></head><body style="font-family: verdana; font-size: 12px;"><table width="100%" style="border-collapse: collapse; "><tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr><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><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 10px; padding-left: 20px">SharePoint Environment</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: lightgray; padding-top: 20px;"><div style="width:100%; background-color: #FFFFFF;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3"><thead><tr><th align="left" style="border: 1px solid CCCCCC; background-color: #1D6097;" colspan="1"><h2 style="font-size: 16px; color: #FFFFFF">Grouped Test (60.00 Seconds)</h2><th align="right" style="border: 1px solid CCCCCC; background-color: #1D6097;"></th></tr></thead><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="2">Server 1</th></tr></thead><tbody><tr><td style="padding-left: 25px">&nbsp;</td><td><table style="border-collapse: collapse;" cellpadding="3"><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Message</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Event ID</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">Message 1</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">123</td></tr><tr style="background-color: #e1e3e8"><td valign="top" style="border: 1px solid #CCCCCC;" align="left">Message 2</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">456</td></tr></tbody></table></td></tr></tbody><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #1D6097; color: #FFFFFF" colspan="2">Server 2</th></tr></thead><tbody><tr><td style="padding-left: 25px">&nbsp;</td><td><table style="border-collapse: collapse;" cellpadding="3"><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Message</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Event ID</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">Message 3</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">789</td></tr></tbody></table></td></tr></tbody></table></div><br/><div style="width:100%; background-color: #FFFFFF;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3"><thead><tr><th align="left" style="border: 1px solid CCCCCC; background-color: #1D6097;" colspan="1"><h2 style="font-size: 16px; color: #FFFFFF">Ungrouped Test (60.00 Seconds)</h2><th align="right" style="border: 1px solid CCCCCC; background-color: #1D6097;"></th></tr></thead><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">State</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Component</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">State 1</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">123</td></tr><tr style="background-color: #e1e3e8"><td valign="top" style="border: 1px solid #CCCCCC;" align="left">State 2</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">456</td></tr></tbody></table></div><br/></td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 20px"><b>Skipped Tests:</b> SPServerStatus, WindowsServiceState, SPFailingTimerJobs, SPDatabaseHealth, SPSearchHealth, SPDistributedCacheHealth, WebTests<br/><b>Total Elapsed Time (Seconds):</b> 180.00 (3.00 Minutes)</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #1D6097; color: #FFFFFF; padding: 20px" align="center">PoShMon Version 1.2.3 (Version check skipped)</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr></table><br/></body>' $actual = New-EmailBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime $actual | Should Be $expected } It "Should return a the correct html if an exception occurs in a test" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -PrimaryServerName 'Server1' ` -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" = @( [PSCustomObject]@{ "ComponentName" = 123 "State" = "State 1" }, [PSCustomObject]@{ "ComponentName" = 456 "State" = "State 2" } ) }, @{ "SectionHeader" = "Test2 - Failed" "NoIssuesFound" = $false "Exception" = [Exception]::new("Something went wrong") } ) $totalElapsedTime = (Get-Date).Subtract((Get-Date).AddMinutes(-3)) $expected = '<head><title></title></head><body style="font-family: verdana; font-size: 12px;"><table width="100%" style="border-collapse: collapse; "><tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr><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><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 10px; padding-left: 20px">SharePoint Environment</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: lightgray; padding-top: 20px;"><div style="width:100%; background-color: #FFFFFF;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3"><thead><tr><th align="left" style="border: 1px solid CCCCCC; background-color: #1D6097;" colspan="1"><h2 style="font-size: 16px; color: #FFFFFF">Test1 (60.00 Seconds)</h2><th align="right" style="border: 1px solid CCCCCC; background-color: #1D6097;"></th></tr></thead><thead><tr><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">State</th><th align="left" style="border: 1px solid #CCCCCC; background-color: #C7DAE9; color: #126AB0">Component</th></tr></thead><tbody><tr style=""><td valign="top" style="border: 1px solid #CCCCCC;" align="left">State 1</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">123</td></tr><tr style="background-color: #e1e3e8"><td valign="top" style="border: 1px solid #CCCCCC;" align="left">State 2</td><td valign="top" style="border: 1px solid #CCCCCC;" align="right">456</td></tr></tbody></table></div><br/><div style="width:100%; background-color: #FFFFFF;"><table style="border-collapse: collapse; min-width: 500px; " cellpadding="3"><thead><tr><th align="left" style="border: 1px solid CCCCCC; background-color: #1D6097;" colspan="-1"><h2 style="font-size: 16px; color: #FFFFFF">Test2 - Failed</h2><th align="right" style="border: 1px solid CCCCCC; background-color: #1D6097;"></th></tr></thead><tbody><tr><td style="background-color: #FCCFC5">An Exception Occurred: System.Exception: Something went wrong</td></tr></tbody></table></div><br/></td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #000000; color: #FFFFFF; padding: 20px"><b>Skipped Tests:</b> SPServerStatus, WindowsServiceState, SPFailingTimerJobs, SPDatabaseHealth, SPSearchHealth, SPDistributedCacheHealth, WebTests<br/><b>Total Elapsed Time (Seconds):</b> 180.00 (3.00 Minutes)</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td style="background-color: lightgray">&nbsp;</td><td style="background-color: #1D6097; color: #FFFFFF; padding: 20px" align="center">PoShMon Version 1.2.3 (Version check skipped)</td><td style="background-color: lightgray">&nbsp;</td></tr><tr><td colspan="3" style="background-color: lightgray">&nbsp;</td></tr></table><br/></body>' $actual = New-EmailBody $poShMonConfiguration "All" $testMonitoringOutput $totalElapsedTime $actual | Should Be $expected } } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/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") 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; } } <# Describe "Test-Website" { It "Should return a matching output structure" { Mock -CommandName Invoke-WebRequest -MockWith { return [WebRequestMock]::new(200, "OK", $testContent) } Mock -CommandName Invoke-RemoteWebRequest -MockWith { return [RemoteWebRequestMock]::new(200, "OK", $testContent, $serverName) } $actual = Test-WebSite -SiteUrl 'abc' -TextToLocate $testContent -ServerNames $serverName 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 $headers.ContainsKey("ServerName") | Should Be $true $headers.ContainsKey("StatusCode") | Should Be $true $headers.ContainsKey("Outcome") | Should Be $true $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 test directly and on each server" { Mock -CommandName Invoke-WebRequest -Verifiable -MockWith { return [WebRequestMock]::new('200', 'OK', '<html>Test Content</html>') } Mock -CommandName Invoke-RemoteWebRequest -Verifiable -MockWith { return [RemoteWebRequestMock]::new('200', 'OK', '<html>Test Content</html>', $ServerName) } $actual = Test-WebSite -SiteUrl 'https://www.mywebsite.test' -TextToLocate 'Test content' -ServerNames 'Server1','Server2' 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 -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) } } $actual = Test-WebSite -SiteUrl 'https://www.mywebsite.test' -TextToLocate 'Test content' -ServerNames 'Server1','Server2' 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 -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) } } $actual = Test-WebSite -SiteUrl 'https://www.mywebsite.test' -TextToLocate 'Test Content' -ServerNames 'Server1','Server2' Assert-VerifiableMocks $actual.NoIssuesFound | Should Be $true $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/Integration/PoShMon.Monitoring.Core/Invoke-MonitoringCore.Tests.ps1
Invoke-MonitoringCore.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-MonitoringCore" { It "Should invoke core monitoring (non-farm)" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'Core' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'AppServer01' ` -ConfigurationName SpFarmPosh 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 Get-ServersInSPFarm -ModuleName PoShMon -Verifiable -MockWith { # return "Server1","Server2","Server3" #} 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 "Final Output Received:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } #Mock -CommandName Get-PSSession -Verifiable -MockWith { # return $null #} $actual = Invoke-MonitoringCore $poShMonConfiguration -TestList "Test1","Test2" -Verbose Assert-VerifiableMocks } It "Should send a notification for an exception OUTSIDE the tests" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'AppServer01' ` -ConfigurationName SpFarmPosh 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 Get-ServersInSPFarm -ModuleName PoShMon -Verifiable -MockWith { throw "Fake Exception" } Mock -CommandName Initialize-Notifications -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose "Final Output Received:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } Mock -CommandName Send-ExceptionNotifications -ModuleName PoShMon -Verifiable -MockWith { return $null } Invoke-MonitoringCore $poShMonConfiguration -TestList "Test1","Test2" -FarmDiscoveryFunctionName 'Get-ServersInSPFarm' Assert-VerifiableMocks } } Describe "Invoke-MonitoringCore (New Scope)" { It "Should NOT send a notification for an exception INSIDE the tests" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'AppServer01' ` -ConfigurationName SpFarmPosh 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 Initialize-Notifications -ModuleName PoShMon -Verifiable -MockWith { Write-Verbose "Final Output Received:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } Mock -CommandName Test-SPServerStatus -ModuleName PoShMon -Verifiable -MockWith { return @{ "SectionHeader" = "SPServerStatus Mock" "OutputHeaders" = @{ 'Item1' = 'Item 1'; } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Item1" = 123 "State" = "State 1" } ) } } Mock -CommandName Test-SPJobHealth -ModuleName PoShMon -Verifiable -MockWith { <#return @{ "SectionHeader" = "SPFailingTimerJobs Mock" "OutputHeaders" = @{ 'Item1' = 'Item 1'; } "NoIssuesFound" = $false "ElapsedTime" = (Get-Date).Subtract((Get-Date).AddMinutes(-1)) "OutputValues" = @( @{ "Item1" = 123 "State" = "State 1" } ) }#> throw "something" } #Mock -CommandName Get-PSSession -Verifiable -MockWith { # return $null #} Mock -CommandName Send-ExceptionNotifications -ModuleName PoShMon -MockWith { throw "Should not get here" } $actual = Invoke-MonitoringCore $poShMonConfiguration -TestList "SPServerStatus","SPJobHealth" Assert-VerifiableMocks $actual[1].Exception.Message | Should Be "something" } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Tests/CI/Integration/PoShMon.Monitoring.SharePoint/Invoke-SPMonitoring.Tests.ps1
Invoke-SPMonitoring.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-SPMonitoring" { It "Should invoke SP monitoring" { $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 60 ` -PrimaryServerName 'AppServer01' ` -ConfigurationName SpFarmPosh ` -TestsToSkip 'SPServerStatus','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth' 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 Get-ServersInSPFarm -ModuleName PoShMon -Verifiable -MockWith { return "Server1","Server2","Server3" } 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 "Final Output Received:" $TestOutputValues | % { Write-Verbose "`t$($_.SectionHeader)" } return } #Mock -CommandName Get-PSSession -Verifiable -MockWith { # return $null #} $actual = Invoke-SPMonitoring $poShMonConfiguration -Verbose Assert-VerifiableMocks } }
PowerShellCorpus/PowerShellGallery/xDefender/0.2.0.0/Examples/ExampleScript.ps1
ExampleScript.ps1
configuration Defender { Import-DscResource -ModuleName xDefender node Localhost { xMpPreference Test1 { Name = 'MyPreferences1' CheckForSignaturesBeforeRunningScan = $True HighThreatDefaultAction = 'Clean' } } } Defender -OutputPath 'c:\DSC_Defender\' Start-DscConfiguration -Wait -Force -Path 'c:\DSC_Defender\' -ComputerName localhost -Verbose
PowerShellCorpus/PowerShellGallery/xDefender/0.2.0.0/Examples/xDefender_CreateScript.ps1
xDefender_CreateScript.ps1
$modules = 'C:\Program Files\WindowsPowerShell\Modules\' $modulename = 'xDefender' $Description = 'The xDefender allows you to configure Windows Defender preferences.' if (!(test-path (join-path $modules $modulename))) { $modulefolder = mkdir (join-path $modules $modulename) $examplesFolder = mkdir (join-path $moduleFolder 'Examples') New-ModuleManifest -Path (join-path $modulefolder "$modulename.psd1") -Guid $([system.guid]::newguid().guid) -Author 'PowerShell DSC' -CompanyName 'Microsoft Corporation' -Copyright '2015' -ModuleVersion '0.1.0.0' -Description $Description -PowerShellVersion '4.0' $standard = @{ModuleName = $modulename ClassVersion = '0.1.0.0' Path = $modules } $Resources = @() $Resource = @{Name = 'xMpPreference'; Param = @()} $Resource.Param += New-xDscResourceProperty -Name Name -Type String -Attribute Key -Description 'Provide the text string to uniquely identify this group of settings' $Resource.Param += New-xDscResourceProperty -Name ExclusionPath -Type String[] -Attribute Write -Description 'Specifies an array of file paths to exclude from scheduled and real-time scanning. You can specify a folder to exclude all the files under the folder.' $Resource.Param += New-xDscResourceProperty -Name ExclusionExtension -Type String[] -Attribute Write -Description 'Specifies an array of file name extensions, such as obj or lib, to exclude from scheduled, custom, and real-time scanning.' $Resource.Param += New-xDscResourceProperty -Name ExclusionProcess -Type String[] -Attribute Write -Description 'Specifies an array of processes, as paths to process images. The cmdlet excludes any files opened by the processes that you specify from scheduled and real-time scanning. Specifying this parameter excludes files opened by executable programs only. The cmdlet does not exclude the processes themselves. To exclude a process, specify it by using the ExclusionPath parameter.' $Resource.Param += New-xDscResourceProperty -Name RealTimeScanDirection -Type String -Attribute Write -ValidateSet 'Both','Incoming','Outgoing' -Description 'Specifies scanning configuration for incoming and outgoing files on NTFS volumes. Specify a value for this parameter to enhance performance on servers which have a large number of file transfers, but need scanning for either incoming or outgoing files. Evaluate this configuration based on the server role. For non-NTFS volumes, Windows Defender performs full monitoring of file and program activity.' $Resource.Param += New-xDscResourceProperty -Name QuarantinePurgeItemsAfterDelay -Type uint32 -Attribute Write -Description 'Specifies the number of days to keep items in the Quarantine folder. If you specify a value of zero or do not specify a value for this parameter, items stay in the Quarantine folder indefinitely.' $Resource.Param += New-xDscResourceProperty -Name RemediationScheduleDay -Type String -Attribute Write -ValidateSet 'Everyday','Never','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday' -Description 'Specifies the day of the week on which to perform a scheduled full scan in order to complete remediation. Alternatively, specify everyday for this full scan or never. The default value is Never. If you specify a value of Never or do not specify a value, Windows Defender performs a scheduled full scan to complete remediation by using a default frequency.' $Resource.Param += New-xDscResourceProperty -Name RemediationScheduleTime -Type DateTime -Attribute Write -Description 'Specifies the time of day, as the number of minutes after midnight, to perform a scheduled scan. The time refers to the local time on the computer. If you do not specify a value for this parameter, a scheduled scan runs at the default time of two hours after midnight.' $Resource.Param += New-xDscResourceProperty -Name ReportingAdditionalActionTimeOut -Type uint32 -Attribute Write -Description 'Specifies the number of minutes before a detection in the additional action state changes to the cleared state.' $Resource.Param += New-xDscResourceProperty -Name ReportingNonCriticalTimeOut -Type uint32 -Attribute Write -Description 'Specifies the number of minutes before a detection in the non-critically failed state changes to the cleared state.' $Resource.Param += New-xDscResourceProperty -Name ReportingCriticalFailureTimeOut -Type uint32 -Attribute Write -Description 'Specifies the number of minutes before a detection in the critically failed state changes to either the additional action state or the cleared state.' $Resource.Param += New-xDscResourceProperty -Name ScanAvgCPULoadFactor -Type uint32 -Attribute Write -Description 'Specifies the maxium percentage CPU usage for a scan. The acceptable values for this parameter are: integers from 5 through 100, and the value 0, which disables CPU throttling. Windows Defender does not exceed the percentage of CPU usage that you specify. The default value is 50.' $Resource.Param += New-xDscResourceProperty -Name CheckForSignaturesBeforeRunningScan -Type boolean -Attribute Write -Description 'Indicates whether to check for new virus and spyware definitions before Windows Defender runs a scan. If you specify a value of $True, Windows Defender checks for new definitions. If you specify $False or do not specify a value, the scan begins with existing definitions. This value applies to scheduled scans and to scans that you start from the command line, but it does not affect scans that you start from the user interface.' $Resource.Param += New-xDscResourceProperty -Name ScanPurgeItemsAfterDelay -Type uint32 -Attribute Write -Description 'Specifies the number of days to keep items in the scan history folder. After this time, Windows Defender removes the items. If you specify a value of zero, Windows Defender does not remove items. If you do not specify a value, Windows Defender removes items from the scan history folder after the default length of time, which is 30 days.' $Resource.Param += New-xDscResourceProperty -Name ScanOnlyIfIdleEnabled -Type boolean -Attribute Write -Description 'Indicates whether to start scheduled scans only when the computer is not in use. If you specify a value of $True or do not specify a value, Windows Defender runs schedules scans when the computer is on, but not in use.' $Resource.Param += New-xDscResourceProperty -Name ScanParameters -Type String -Attribute Write -ValidateSet 'FullSCan','QuickScan' -Description 'Specifies the scan type to use during a scheduled scan. If you do not specify this parameter, Windows Defender uses the default value of quick scan.' $Resource.Param += New-xDscResourceProperty -Name ScanScheduleDay -Type String -Attribute Write -ValidateSet 'Everyday','Never','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday' -Description 'Specifies the day of the week on which to perform a scheduled scan. Alternatively, specify everyday for a scheduled scan or never. If you specify a value of Never or do not specify a value, Windows Defender performs a scheduled scan by using a default frequency.' $Resource.Param += New-xDscResourceProperty -Name ScanScheduleQuickScanTime -Type DateTime -Attribute Write -Description 'Specifies the time of day, as the number of minutes after midnight, to perform a scheduled quick scan. The time refers to the local time on the computer. If you do not specify a value for this parameter, a scheduled quick scan runs at the time specified by the ScanScheduleTime parameter. That parameter has a default time of two hours after midnight.' $Resource.Param += New-xDscResourceProperty -Name ScanScheduleTime -Type DateTime -Attribute Write -Description 'Specifies the time of day, as the number of minutes after midnight, to perform a scheduled scan. The time refers to the local time on the computer. If you do not specify a value for this parameter, a scheduled scan runs at a default time of two hours after midnight.' $Resource.Param += New-xDscResourceProperty -Name SignatureFirstAuGracePeriod -Type uint32 -Attribute Write -Description 'Specifies a grace period, in minutes, for the definition. If a definition successfully updates within this period, Windows Defender abandons any service initiated updates. This parameter overrides the value of the CheckForSignaturesBeforeRunningScan parameter.' $Resource.Param += New-xDscResourceProperty -Name SignatureAuGracePeriod -Type uint32 -Attribute Write -Description 'Specifies a grace period, in minutes, for the definition. If a definition successfully updates within this period, Windows Defender abandons any service initiated updates.' $Resource.Param += New-xDscResourceProperty -Name SignatureDefinitionUpdateFileSharesSources -Type String -Attribute Write -Description 'Specifies file-share sources for definition updates. Specify sources as a bracketed sequence of Universal Naming Convention (UNC) locations, separated by the pipeline symbol. If you specify a value for this parameter, Windows Defender attempts to connect to the shares in the order that you specify. After Windows Defender updates a definition, it stops attempting to connect to shares on the list. If you do not specify a value for this parameter, the list is empty.' $Resource.Param += New-xDscResourceProperty -Name SignatureDisableUpdateOnStartupWithoutEngine -Type boolean -Attribute Write -Description 'Indicates whether to initiate definition updates even if no antimalware engine is present. If you specify a value of $True or do not specify a value, Windows Defender initiates definition updates on startup. If you specify a value of $False, and if no antimalware engine is present, Windows Defender does not initiate definition updates on startup.' $Resource.Param += New-xDscResourceProperty -Name SignatureFallbackOrder -Type String -Attribute Write -Description 'Specifies the order in which to contact different definition update sources. Specify the types of update sources in the order in which you want Windows Defender to contact them, enclosed in braces and separated by the pipeline symbol.' $Resource.Param += New-xDscResourceProperty -Name SignatureScheduleDay -Type String -Attribute Write -ValidateSet 'Everyday','Never','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday' -Description 'Specifies the day of the week on which to check for definition updates. Alternatively, specify everyday for a scheduled scan or never. If you specify a value of Never or do not specify a value, Windows Defender checks for definition updates by using a default frequency.' $Resource.Param += New-xDscResourceProperty -Name SignatureScheduleTime -Type DateTime -Attribute Write -Description 'Specifies the time of day, as the number of minutes after midnight, to check for definition updates. The time refers to the local time on the computer. If you do not specify a value for this parameter, Windows Defender checks for definition updates at the default time of 15 minutes before the scheduled scan time.' $Resource.Param += New-xDscResourceProperty -Name SignatureUpdateCatchupInterval -Type uint32 -Attribute Write -Description 'Specifies the number of days after which Windows Defender requires a catch-up definition update. If you do not specify a value for this parameter, Windows Defender requires a catch-up definition update after the default value of one day.' $Resource.Param += New-xDscResourceProperty -Name SignatureUpdateInterval -Type uint32 -Attribute Write -Description 'Specifies the interval, in hours, at which to check for definition updates. The acceptable values for this parameter are: integers from 1 through 24. If you do not specify a value for this parameter, Windows Defender checks at the default interval. You can use this parameter instead of the SignatureScheduleDay parameter and SignatureScheduleTime parameter. ' $Resource.Param += New-xDscResourceProperty -Name MAPSReporting -Type String -Attribute Write -ValidateSet 'Advanced','Basic','Disabled' -Description 'Specifies the type of membership in Microsoft Active Protection Service. Microsoft Active Protection Service is an online community that helps you choose how to respond to potential threats. The community also helps prevent the spread of new malicious software. If you join this community, you can choose to automatically send basic or additional information about detected software. Additional information helps Microsoft create new definitions. In some instances, personal information might unintentionally be sent to Microsoft. However, Microsoft will not use this information to identify you or contact you.' $Resource.Param += New-xDscResourceProperty -Name DisablePrivacyMode -Type boolean -Attribute Write -Description 'Indicates whether to disable privacy mode. Privacy mode prevents users, other than administrators, from displaying threat history.' $Resource.Param += New-xDscResourceProperty -Name RandomizeScheduleTaskTimes -Type boolean -Attribute Write -Description 'Indicates whether to select a random time for the scheduled start and scheduled update for definitions. If you specify a value of $True or do not specify a value, scheduled tasks begin within 30 minutes, before or after, the scheduled time. If you randomize the start times, it can distribute the impact of scanning. For example, if several virtual machines share the same host, randomized start times prevents all the hosts from starting the scheduled tasks at the same time.' $Resource.Param += New-xDscResourceProperty -Name DisableBehaviorMonitoring -Type boolean -Attribute Write -Description 'Indicates whether to enable behavior monitoring. If you specify a value of $True or do not specify a value, Windows Defender enables behavior monitoring' $Resource.Param += New-xDscResourceProperty -Name DisableIntrusionPreventionSystem -Type boolean -Attribute Write -Description 'Indicates whether to configure network protection against exploitation of known vulnerabilities. If you specify a value of $True or do not specify a value, network protection is enabled' $Resource.Param += New-xDscResourceProperty -Name DisableIOAVProtection -Type boolean -Attribute Write -Description 'Indicates whether Windows Defender scans all downloaded files and attachments. If you specify a value of $True or do not specify a value, scanning downloaded files and attachments is enabled. ' $Resource.Param += New-xDscResourceProperty -Name DisableRealtimeMonitoring -Type boolean -Attribute Write -Description 'Indicates whether to use real-time protection. If you specify a value of $True or do not specify a value, Windows Defender uses real-time protection. We recommend that you enable Windows Defender to use real-time protection.' $Resource.Param += New-xDscResourceProperty -Name DisableScriptScanning -Type boolean -Attribute Write -Description 'Specifies whether to disable the scanning of scripts during malware scans.' $Resource.Param += New-xDscResourceProperty -Name DisableArchiveScanning -Type boolean -Attribute Write -Description 'Indicates whether to scan archive files, such as .zip and .cab files, for malicious and unwanted software. If you specify a value of $True or do not specify a value, Windows Defender scans archive files.' $Resource.Param += New-xDscResourceProperty -Name DisableAutoExclusions -Type boolean -Attribute Write -Description 'Indicates whether to disable the Automatic Exclusions feature for the server.' $Resource.Param += New-xDscResourceProperty -Name DisableCatchupFullScan -Type boolean -Attribute Write -Description 'Indicates whether Windows Defender runs catch-up scans for scheduled full scans. A computer can miss a scheduled scan, usually because the computer is turned off at the scheduled time. If you specify a value of $True, after the computer misses two scheduled full scans, Windows Defender runs a catch-up scan the next time someone logs on to the computer. If you specify a value of $False or do not specify a value, the computer does not run catch-up scans for scheduled full scans.' $Resource.Param += New-xDscResourceProperty -Name DisableCatchupQuickScan -Type boolean -Attribute Write -Description 'Indicates whether Windows Defender runs catch-up scans for scheduled quick scans. A computer can miss a scheduled scan, usually because the computer is off at the scheduled time. If you specify a value of $True, after the computer misses two scheduled quick scans, Windows Defender runs a catch-up scan the next time someone logs onto the computer. If you specify a value of $False or do not specify a value, the computer does not run catch-up scans for scheduled quick scans. ' $Resource.Param += New-xDscResourceProperty -Name DisableEmailScanning -Type boolean -Attribute Write -Description 'Indicates whether Windows Defender parses the mailbox and mail files, according to their specific format, in order to analyze mail bodies and attachments. Windows Defender supports several formats, including .pst, .dbx, .mbx, .mime, and .binhex. If you specify a value of $True, Windows Defender performs email scanning. If you specify a value of $False or do not specify a value, Windows Defender does not perform email scanning. ' $Resource.Param += New-xDscResourceProperty -Name DisableRemovableDriveScanning -Type boolean -Attribute Write -Description 'Indicates whether to scan for malicious and unwanted software in removable drives, such as flash drives, during a full scan. If you specify a value of $True, Windows Defender scans removable drives during any type of scan. If you specify a value of $False or do not specify a value, Windows Defender does not scan removable drives during a full scan. Windows Defender can still scan removable drives during quick scans or custom scans.' $Resource.Param += New-xDscResourceProperty -Name DisableRestorePoint -Type boolean -Attribute Write -Description 'Indicates whether to disable scanning of restore points.' $Resource.Param += New-xDscResourceProperty -Name DisableScanningMappedNetworkDrivesForFullScan -Type boolean -Attribute Write -Description 'Indicates whether to scan mapped network drives. If you specify a value of $True, Windows Defender scans mapped network drives. If you specify a value of $False or do not specify a value, Windows Defender does not scan mapped network drives.' $Resource.Param += New-xDscResourceProperty -Name DisableScanningNetworkFiles -Type boolean -Attribute Write -Description 'Indicates whether to scan for network files. If you specify a value of $True, Windows Defender scans network files. If you specify a value of $False or do not specify a value, Windows Defender does not scan network files. We do not recommend that you scan network files.' $Resource.Param += New-xDscResourceProperty -Name UILockdown -Type boolean -Attribute Write -Description 'Indicates whether to disable UI lockdown mode. If you specify a value of $True, Windows Defender disables UI lockdown mode. If you specify $False or do not specify a value, UI lockdown mode is enabled.' $Resource.Param += New-xDscResourceProperty -Name ThreatIDDefaultAction_Ids -Type uint64 -Attribute Write -Description 'Specifies an array of the actions to take for the IDs specified by using the ThreatIDDefaultAction_Ids parameter.' $Resource.Param += New-xDscResourceProperty -Name ThreatIDDefaultAction_Actions -Type String -Attribute Write -ValidateSet 'Allow','Block','Clean','NoAction','Quarantine','Remove','UserDefined' -Description 'Specifies which automatic remediation action to take for an unknonwn level threat.' $Resource.Param += New-xDscResourceProperty -Name UnknownThreatDefaultAction -Type String -Attribute Write -ValidateSet 'Allow','Block','Clean','NoAction','Quarantine','Remove','UserDefined' -Description 'Specifies which automatic remediation action to take for a low level threat.' $Resource.Param += New-xDscResourceProperty -Name LowThreatDefaultAction -Type String -Attribute Write -ValidateSet 'Allow','Block','Clean','NoAction','Quarantine','Remove','UserDefined' -Description 'Specifies which automatic remediation action to take for a low level threat.' $Resource.Param += New-xDscResourceProperty -Name ModerateThreatDefaultAction -Type String -Attribute Write -ValidateSet 'Allow','Block','Clean','NoAction','Quarantine','Remove','UserDefined' -Description 'Specifies which automatic remediation action to take for a moderate level threat.' $Resource.Param += New-xDscResourceProperty -Name HighThreatDefaultAction -Type String -Attribute Write -ValidateSet 'Allow','Block','Clean','NoAction','Quarantine','Remove','UserDefined' -Description 'Specifies which automatic remediation action to take for a high level threat.' $Resource.Param += New-xDscResourceProperty -Name SevereThreatDefaultAction -Type String -Attribute Write -ValidateSet 'Allow','Block','Clean','NoAction','Quarantine','Remove','UserDefined' -Description 'Specifies which automatic remediation action to take for a severe level threat.' $Resource.Param += New-xDscResourceProperty -Name SubmitSamplesConsent -Type String -Attribute Write -ValidateSet 'Allways Prompt','Send safe samples automatically','Never send','Send all samples automatically' -Description 'Specifies how Windows Defender checks for user consent for certain samples. If consent has previously been granted, Windows Defender submits the samples. Otherwise, if the MAPSReporting parameter does not have a value of Disabled, Windows Defender prompts the user for consent.' New-xDscResource -Name MSFT_$($Resource.Name) -Property $Resource.Param -FriendlyName $Resource.Name @standard $Resources += $Resource } # Markdown Generator # This is experimental. Expected to become 100% efficient in future version. Import example from script, etc. $MD = @" <--AppVeyorBadge--> The **$ModuleName** module is a part of the Windows PowerShell Desired State Configuration (DSC) Resource Kit, which is a collection of DSC Resources. $Description, with simple declarative language. ## Installation To install **$ModuleName** module - If you are using WMF4 / PowerShell Version 4: Unzip the content under the $env:ProgramFiles\WindowsPowerShell\Modules folder - If you are using WMF5 Preview: From an elevated PowerShell session run "Install-Module $ModuleName" To confirm installation - Run Get-DSCResource to see that the resources listed above are among the DSC Resources displayed ## Contributing Please check out common DSC Resources [contributing guidelines](https://github.com/PowerShell/DscResource.Kit/blob/master/CONTRIBUTING.md). ## Resources "@ foreach ($r in $Resources) { $MD += @" **$($r.Name)** resource has following properties "@ foreach ($p in $r.Param) { $MD += @" - **$($p.Name)**: $($p.Description) "@ } } $MD += @" Versions -------- **0.1.0.0** Initial release with the following resources: foreach ($r in $Resources) { $MD += @" - $($r.Name) "@ @' Examples -------- ```powershell configuration Defender { Import-DscResource -ModuleName xDefender node Localhost { xMpPreference Test1 { Name = 'MyPreferences1' CheckForSignaturesBeforeRunningScan = $True HighThreatDefaultAction = 'Clean' } } } Defender -OutputPath 'c:\DSC_Defender\' Start-DscConfiguration -Wait -Force -Path 'c:\DSC_Defender\' -ComputerName localhost -Verbose ``` '@ $MD | Out-File "$moduleFolder\ReadMe.md" # Generate License File if (-not (Test-Path "$moduleFolder\License.txt")) { @' The MIT License (MIT) Copyright (c) 2015 Michael Greene Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. '@ | out-file -FilePath "$moduleFolder\LICENSE" } # Generate AppVeyor file if (-not (Test-Path "$moduleFolder\appveyor.yml")) { @' install: - cinst -y pester - git clone https://github.com/PowerShell/DscResource.Tests build: false test_script: - ps: | $testResultsFile = ".\TestsResults.xml" $res = Invoke-Pester -OutputFormat NUnitXml -OutputFile $testResultsFile -PassThru (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $testResultsFile)) if ($res.FailedCount -gt 0) { throw "$($res.FailedCount) tests failed." } on_finish: - ps: | $stagingDirectory = (Resolve-Path ..).Path $zipFile = Join-Path $stagingDirectory "$(Split-Path $pwd -Leaf).zip" Add-Type -assemblyname System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::CreateFromDirectory($pwd, $zipFile) @( # You can add other artifacts here (ls $zipFile) ) | % { Push-AppveyorArtifact $_.FullName } '@ | out-file -FilePath "$moduleFolder\appveyor.yml" }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/build.ps1
build.ps1
[cmdletbinding()] Param( [string]$ModuleFileName = 'Numbers.psm1' , [switch]$Major , [switch]$Minor , [switch]$LoadModule , [string]$description = 'Convert numbers to different number formats' ) END { write-verbose -message "ModuleFilename = $moduleFileName" Set-location -Path "$PSScriptRoot" -ErrorAction SilentlyContinue $F = $MyInvocation.InvocationName Write-Verbose -Message "$F - Starting build, getting files" $fileList = Get-ChildItem -Filter .\functions\*.ps1 | where name -NotLike "*Tests*" #$ModuleName = (Get-ChildItem -Path $ModuleFileName -ErrorAction SilentlyContinue).BaseName $ModuleName = $ModuleFileName.Split('.') | Select-Object -first 1 Write-Verbose -Message "$f - Modulename is $ModuleName" if([string]::IsNullOrEmpty($moduleName)) { write-warning -message "Modulename is null or empty" break } $ExportedFunctions = New-Object System.Collections.ArrayList $fileList | foreach { Write-Verbose -Message "$F - Function = $($_.BaseName) added" $null = $ExportedFunctions.Add($_.BaseName) } $ModuleLevelFunctions = $null foreach($function in $ModuleLevelFunctions) { Write-Verbose -Message "$f - Checking function $function" if($ExportedFunctions -contains $function) { write-verbose -Message "$f - Removing function $function from exportlist" $ExportedFunctions.Remove($function) } else { Write-Verbose -Message "$f - Exported functions does not contain $function" } } Write-Verbose -Message "$f - Constructing content of module file" [string]$ModuleFile = "" foreach($file in $fileList) { $filecontent = Get-Content -Path $file.FullName -Raw -Encoding UTF8 $filecontent = "$filecontent`n`n" $ModuleFile += $filecontent } [System.Version]$ver = $null if((Test-Path -Path $moduleFileName -ErrorAction SilentlyContinue) -eq $true) { Write-Verbose -Message "$f - Getting version info" Import-Module -Name ".\$ModuleName.psd1" -Verbose:$false $ver = (Get-Module $Modulename).Version Write-Verbose -Message "$f - Removing previous version of $ModuleFileName" Remove-Item -Path $ModuleFileName } function Get-NextVersion { [cmdletbinding()] [outputtype([System.Version])] Param( [System.Version]$CurrentVersion , [switch]$Major , [switch]$Minor ) [System.Version]$newVersion = $null $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" if($Major) { Write-Verbose -Message "$F - Bumping Major version" $build = $CurrentVersion.Build $ma = $CurrentVersion.Major + 1 $mi = $CurrentVersion.Minor } if($Minor) { Write-Verbose -Message "$f - Bumping Minor version" $build = $CurrentVersion.Build $ma = $CurrentVersion.Major $mi = $CurrentVersion.Minor + 1 } if($Minor -and $Major) { Write-Verbose -Message "$f - Bumping Major and Minor version" $build = $CurrentVersion.Build $ma = $CurrentVersion.Major + 1 $mi = $CurrentVersion.Minor + 1 } if(-not $Minor -and -not $Major) { Write-Verbose -Message "$f - Bumping build version" $build = $CurrentVersion.Build + 1 $ma = $CurrentVersion.Major $mi = $CurrentVersion.Minor } $newVersion = New-Object System.Version("$Ma.$Mi.$build.0") return $newVersion } if(-not $ver) { Write-Verbose -Message "$f - No previous version found, creating new version" $ver = New-Object System.Version("1.0.0.0") } if($Major) { $ver = Get-NextVersion -CurrentVersion $ver -Major } if($Minor) { $ver = Get-NextVersion -CurrentVersion $ver -Minor } if($Minor -and $Major) { $ver = Get-NextVersion -CurrentVersion $ver -Minor -Major } if(-not $Minor -and -not $Major) { Write-Verbose -Message "$f - Defaults to bump build version" $ver = Get-NextVersion -CurrentVersion $ver } $versionString = $ver.ToString() Write-Verbose -Message "$f - New version is $versionString" Write-Verbose -Message "$f - Writing contents to modulefile [$ModuleFileName]" #$ModuleFilePathName = Resolve-Path -Path .\ #Write-Verbose -Message "filepath $ModuleFilePathName" Set-Content -Path ".\$ModuleFileName" -Value $ModuleFile -Encoding UTF8 $ManifestName = "$((Get-ChildItem -Path $ModuleFileName -ErrorAction SilentlyContinue).BaseName).psd1" Write-Verbose -Message "$f - ManifestfileName is $ManifestName" if((Test-Path -Path $ManifestName -ErrorAction SilentlyContinue) -eq $true) { Write-Verbose -Message "$f - Removing previous version of $ManifestName" Remove-Item -Path $ManifestName } $FormatsToProcess = New-Object -TypeName System.Collections.ArrayList foreach($file in (Get-ChildItem -Path "$PSScriptRoot\formats")) { Write-Verbose -Message "Adding formats file $($file.FullName)" $null = $FormatsToProcess.Add($file.FullName) } Write-Verbose -Message "$f - Creating manifestfile" $newModuleManifest = @{ Path = "$PSScriptRoot\$ManifestName" Author = "Tore Grøneng @toregroneng tore@firstpoint.no" Copyright = "(c) 2015 Tore Grøneng @toregroneng tore@firstpoint.no" CompanyName = "Firstpoint AS" ModuleVersion = $ver.ToString() FunctionsToExport = $ExportedFunctions RootModule = "$ModuleFileName" Description = "$description" PowerShellVersion = "4.0" ProjectUri = "https://github.com/torgro/Numbers" FormatsToProcess = $FormatsToProcess.ToArray() } New-ModuleManifest @newModuleManifest Write-Verbose -Message "$f - Reading back content to convert to UTF8 (content management tracking)" Set-Content -Path $ManifestName -Value (Get-Content -Path $ManifestName -Raw) -Encoding UTF8 $Answer = "n" if(-not $LoadModule) { $Answer = Read-Host -Prompt "Load module $ModuleName? (Yes/No)" } if($Answer -eq "y" -or $Answer -eq "yes" -or $LoadModule) { Write-Verbose -Message "$f - Loading module" if(Test-Path -Path $ManifestName) { Import-Module $PSScriptRoot\$ManifestName } else { Write-Warning -Message "Modulefile $ManifestName not found, module not imported" } } else { Write-Verbose -Message "$f - Module not loaded" } Write-Verbose -Message "$f - END" }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Test-OddNumber.ps1
Test-OddNumber.ps1
function Test-OddNumber { <# .Synopsis Check if a number is odd. .DESCRIPTION This will return a boolean value indicating if the number is odd. .EXAMPLE PS C:\> Test-OddNumber -Number 13 True PS C:\> This check if the number 13 is an odd number. .EXAMPLE PS C:\> 13 | Test-OddNumber True PS C:\> This check if the number 13 is an odd number using the pipeline .INPUTS [int64] .OUTPUTS [bool] .NOTES NAME: Test-OddNumber AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [cmdletbinding()] [OutputType([bool])] Param( [Parameter(ValueFromPipeline)] [int64[]]$Number ) BEGIN {} PROCESS { foreach($int in $Number) { if($int % 2 -eq 0) { $false } else { $true } } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Get-HexNumber.ps1
Get-HexNumber.ps1
function Get-HexNumber { <# .Synopsis Converts an INT64 to a hex representation .DESCRIPTION This cmdlet takes a integer number as input and will return a string object with the hex representation of the integer value. It supports pipeline input. By default it will pad with a maximum of 3 zeros. You can override this with the NumberOfDigits parameter .EXAMPLE PS C:\> Get-HexNumber -Number 16 0x0010 PS C:\> This example converts the integer 16 to the hex representation .EXAMPLE PS C:\> 16 | Get-HexNumber 0x0010 PS C:\> This example converts the integer 16 to the hex representation using the pipeline .EXAMPLE PS C:\> 255 | Get-HexNumber -NumberOfDigits 8 0x000000FF PS C:\> This example converts the integer 255 to the hex representation using the pipeline and returns 8 digits .INPUTS [int64] .OUTPUTS [string] .NOTES NAME: Get-HexNumber AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [CmdletBinding()] [OutputType([string])] Param( [Parameter(ValueFromPipeLine)] [int64[]]$Number , [int]$NumberOfDigits = 4 ) BEGIN {} PROCESS { foreach($num in $Number) { "0x$($num.ToString("X$NumberOfDigits"))" } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Convert-Number.ps1
Convert-Number.ps1
function Convert-Number { <# .Synopsis Convert any integer number to Hex, binary or byte array .DESCRIPTION This cmdlet takes a integer number as input and will return a PSCustomobject with values for hex, binary, IsOddNumber and the byte array of the number. This cmdlet support pipeline input. .EXAMPLE PS C:\> Convert-Number -Number 16 Int : 16 Hex : 0x0010 Binary : 10000 Bytes : {16, 0, 0, 0...} OddNumber : False PS C:\> This example converts the integer 16 to Hex, Binary, a byte array and indicates if it is a OddNumber .EXAMPLE PS C:\> 16 | Convert-Number Int : 16 Hex : 0x0010 Binary : 10000 Bytes : {16, 0, 0, 0...} OddNumber : False PS C:\> This example converts the integer 16 to Hex, Binary, a byte array and indicates if it is a OddNumber using pipeline input. .INPUTS [int64] .OUTPUTS [PSCustomobject] .NOTES NAME: Convert-Number AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [CmdletBinding()] [OutputType([String])] Param( [Parameter(ValueFromPipeLine)] [int64[]]$Number ) BEGIN {} PROCESS { foreach($int in $Number) { $out = "" | Select-Object -Property Int, Hex, Binary, Bytes, OddNumber $out.Int = $int $out.Hex = Get-HexNumber -Number $int $out.Binary = Get-BinaryNumber -Number $int $out.Bytes = [System.BitConverter]::GetBytes($int) $out.OddNumber = Test-OddNumber -Number $int $out } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Get-BinaryNumber.ps1
Get-BinaryNumber.ps1
function Get-BinaryNumber { <# .Synopsis Converts an INT64 to a binary representation .DESCRIPTION This cmdlet takes a integer number as input and will return a string object with the binary representation of the integer value. It supports pipeline input. By default it will pad with a maximum of 3 zeros. You can override this with the NumberOfDigits parameter .EXAMPLE PS C:\> Get-BinaryNumber -Number 16 10000 PS C:\> This example converts the integer 16 to the binary representation .EXAMPLE PS C:\> 16 | Get-BinaryNumber 10000 PS C:\> This example converts the integer 16 to the binary representation using the pipeline .EXAMPLE PS C:\> 255 | Get-BinaryNumber -NumberOfDigits 10 0011111111 PS C:\> This example converts the integer 255 to the binary representation using the pipeline and returns 10 digits .INPUTS [int64] .OUTPUTS [string] .NOTES NAME: Get-BinaryNumber AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [CmdletBinding()] [OutputType([string])] Param( [Parameter(ValueFromPipeLine)] [int64[]]$Number , [int]$NumberOfDigits ) BEGIN { if(-not $PSBoundParameters.ContainsKey("NumberOfDigits")) { $NumberOfDigits = 4 } } PROCESS { foreach($num in $Number) { if($num -ge 0) { ([int64][System.Convert]::ToString("$num",2)).ToString("D$NumberOfDigits") } } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Get-IntFromHex.ps1
Get-IntFromHex.ps1
function Get-IntFromHex { <# .Synopsis Convert a hex value to an integer value .DESCRIPTION This cmdlet takes a string as input and will return an int64 object representing the hex value It supports pipeline input. .EXAMPLE PS C:\> Get-IntFromHex -HexValue 0x0010 16 PS C:\> This will convert the hex string '0x0010' to the decial value of 16 .EXAMPLE "0x0010" | Get-IntFromHex 16 PS C:\> This will convert the hex string '0x0010' to the decial value of 16 using the pipeline .EXAMPLE PS C:\> 1..16 | Get-HexNumber | Get-IntFromHex 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 PS C:\> This will convert the valuerange 1..16 to hex values and back again to decial values .INPUTS [string] .OUTPUTS [int64] .NOTES NAME: Get-IntFromHex AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [CmdletBinding()] [OutputType([int64])] Param( [Parameter(ValueFromPipeLine)] [string[]]$HexValue ) BEGIN {} PROCESS { foreach($string in $HexValue) { [System.Convert]::ToInt64($string,16) } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Get-IntFromBinary.ps1
Get-IntFromBinary.ps1
function Get-IntFromBinary { <# .Synopsis Convert a binary value to an integer value .DESCRIPTION This cmdlet takes a string as input and will return an int64 object representing the binary value It supports pipeline input. .EXAMPLE PS C:\> Get-IntFromBinary -BinaryValue 10000 16 PS C:\> This will convert the string '10000' to the decial value of 16 .EXAMPLE PS C:\> 10000 | Get-IntFromBinary 16 PS C:\> This will convert the string '10000' to the decial value of 16 using the pipeline .INPUTS [string] .OUTPUTS [int64] .NOTES NAME: Get-IntFromBinary AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [CmdletBinding()] [OutputType([int64])] Param( [Parameter(ValueFromPipeLine)] [string[]]$BinaryValue ) BEGIN {} PROCESS { foreach($string in $BinaryValue) { [System.Convert]::ToInt64($string,2) } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Functions/Get-IntFromByteArray.ps1
Get-IntFromByteArray.ps1
function Get-IntFromByteArray { <# .Synopsis Convert a byte array to an integer representation .DESCRIPTION This cmdlet takes an byte array as input and will return a int64 value. This cmdlet support pipeline input. .EXAMPLE PS C:\> $bytesArray = @(16,0,0,0,0,0,0,0) PS C:\> Get-IntFromByteArray -Bytes $bytesArray 16 PS C:\> This creates a new variable $bytesArray and converts it to a integer value .EXAMPLE PS C:\> $bytesArray = @(16,0,0,0,0,0,0,0) PS C:\> $bytesArray | Get-IntFromByteArray 16 PS C:\> This creates a new variable $bytesArray and converts it to a integer value using the pipeline .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES NAME: Get-IntFromByteArray AUTHOR: Tore Groneng tore@firstpoint.no @toregroneng tore.groneng@gmail.com LASTEDIT: Jul 2016 KEYWORDS: Convert, Hex, Binary, bytes HELP:OK .LINK https://github.com/torgro/Numbers #> [cmdletbinding()] [OutputType([int64])] Param( [Parameter(ValueFromPipeline)] [byte[]]$Bytes ) BEGIN { $arrayList = New-Object -TypeName System.Collections.ArrayList } PROCESS { if($PSBoundParameters.ContainsKey("Bytes")) { if($Bytes -is [array]) { $null = $arrayList.AddRange($Bytes) } else { $null = $arrayList.Add($Bytes) } } } END { if($arrayList.count -gt 0) { [System.BitConverter]::ToInt64($arrayList,0) } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Get-HexNumber.Tests.ps1
Get-HexNumber.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\functions\$sut" $PSBoundParameters.clear() Describe "Get-HexNumber" { Context "Parameter validation" { It "No parameters should NOT throw" { { Get-HexNumber } | Should not throw } It "String input should throw" { { Get-HexNumber -Number bla } | Should throw } } Context "Convertion tests" { $number = 0 It "Should Convert [$number] to [0x0000]" { Get-HexNumber -Number $number | Should belike "*0" } $number = 16 It "Should Convert [$number] to [0x0010]" { Get-HexNumber -Number $number | Should belike "*10" } It "Default length should be 6" { $hex = Get-HexNumber -Number $number $hex.length | should be 6 } $number = 255 $hex = Get-HexNumber -Number $number -NumberOfDigits 10 It "Should Convert [$number] to [0x00000000FF] when 10 digits are specified" { $hex | Should belike "*00000000FF" } It "Length should be 12" { $hex.length | Should be 12 } } Context "Convertion tests using pipline" { $number = 0 It "Should Convert [$number] to [0x0000]" { $number | Get-HexNumber | Should belike "*0" } $number = 16 It "Should Convert [$number] to [0x0010]" { $number | Get-HexNumber | Should belike "*10" } It "Default length should be 6" { $hex = $number | Get-HexNumber } $number = 255 $hex = $number | Get-HexNumber -NumberOfDigits 10 It "Should Convert [$number] to [0x00000000FF] when 10 digits are specified" { $hex | Should belike "*00000000FF" } It "Length should be 12" { $hex.length | Should be 12 } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Get-IntFromHex.Tests.ps1
Get-IntFromHex.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\functions\$sut" $PSBoundParameters.clear() Describe "Get-IntFromHex" { Context "Parameter validation" { It "No parameters should NOT throw" { { Get-IntFromHex } | Should not throw } It "None hex String input should throw" { { Get-IntFromHex -HexValue bla } | Should throw } } Context "Convertion tests" { $hex = "0x0000" $Expected = 0 It "Should Convert [$hex] to [$Expected]" { Get-IntFromHex -HexValue $hex | Should be $Expected } $hex = "0x0010" $Expected = 16 It "Should Convert [$hex] to [$Expected]" { Get-IntFromHex -HexValue $hex | Should be $Expected } $hex = "0x00000000FF" $Expected = 255 It "Should Convert [$hex] to[$Expected]" { Get-IntFromHex -HexValue $hex | Should be $Expected } } Context "Convertion tests using pipline" { $hex = "0x0000" $Expected = 0 It "Should Convert [$hex] to [$Expected]" { $hex | Get-IntFromHex | Should be $Expected } $hex = "0x0010" $Expected = 16 It "Should Convert [$hex] to [$Expected]" { $hex | Get-IntFromHex | Should be $Expected } $hex = "0x00000000FF" $Expected = 255 It "Should Convert [$hex] to[$Expected]" { $hex | Get-IntFromHex | Should be $Expected } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Get-IntFromByteArray.Tests.ps1
Get-IntFromByteArray.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\functions\$sut" $PSBoundParameters.clear() Describe "Get-IntFromByteArray" { Context "Parameter validation" { It "No parameters should NOT throw" { { Get-IntFromByteArray } | Should not throw } It "String input should throw" { { Get-IntFromByteArray -bytes bla } | Should throw } } Context "Logic validation" { $value = @(16,0,0,0,0,0,0,0) $expected = 16 It "Value from bytearray should be [$expected]" { Get-IntFromByteArray -bytes $value | should be $expected } } Context "Logic validation using pipeline" { $value = @(255,0,0,0,0,0,0,0) $expected = 255 It "Value from bytearray should be [$expected]" { $value | Get-IntFromByteArray | should be $expected } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Get-BinaryNumber.Tests.ps1
Get-BinaryNumber.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\functions\$sut" $PSBoundParameters.clear() Describe "Get-BinaryNumber" { Context "Parameter validation" { It "No parameters should NOT throw" { { Get-BinaryNumber } | Should not throw } It "String input should throw" { { Get-BinaryNumber -Number bla } | Should throw } } Context "Convertion tests" { $number = 0 It "Should Convert [$number] to [0000]" { Get-BinaryNumber -Number $number | Should belike "*0" } $number = 16 It "Should Convert [$number] to [10000]" { Get-BinaryNumber -Number $number | Should belike "*10000" } It "Default length should be 4" { $bin = Get-BinaryNumber -Number 7 $bin.length | should be 4 } $number = 255 $bin = Get-BinaryNumber -Number $number -NumberOfDigits 10 It "Should Convert [$number] to [0011111111] when 10 digits are specified" { $bin | Should belike "*11111111" } It "Length should be 10" { $bin.length | Should be 10 } } Context "Convertion tests using pipline" { $number = 0 It "Should Convert [$number] to [0000]" { $number | Get-BinaryNumber | Should belike "*0" } $number = 16 It "Should Convert [$number] to [10000]" { $number | Get-BinaryNumber | Should belike "*10000" } It "Default length should be 4" { $bin = 7 | Get-BinaryNumber $bin.length | should be 4 } $number = 255 $bin = $number | Get-BinaryNumber -NumberOfDigits 10 It "Should Convert [$number] to [0011111111] when 10 digits are specified" { $bin | Should belike "*11111111" } It "Length should be 10" { $bin.length | Should be 10 } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Test-OddNumber.Tests.ps1
Test-OddNumber.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\functions\$sut" $PSBoundParameters.clear() Describe "Test-OddNumber" { Context "Parameter validation" { It "No parameters should NOT throw" { { Test-OddNumber } | Should not throw } It "String input should throw" { { Test-OddNumber -HexValue bla } | Should throw } } Context "Logic validation" { $Expected = $false $value = 2 It "Value [$value] should return $Expected" { Test-OddNumber -Number $value | Should be $Expected } $Expected = $true $value = 13 It "Value [$value] should return $Expected" { Test-OddNumber -Number $value | Should be $Expected } } Context "Logic validation using pipeline" { $Expected = $false $value = 4 It "Value [$value] should return $Expected" { $value | Test-OddNumber | Should be $Expected } $Expected = $true $value = 133 It "Value [$value] should return $Expected" { $value | Test-OddNumber | Should be $Expected } } }
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Convert-Number.Tests.ps1
Convert-Number.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") #. "$here\functions\$sut" import-module "$here\Numbers.psd1" $PSBoundParameters.clear() Describe "Convert-Number" { Context "Parameter validation" { It "No parameters should NOT throw" { { Convert-Number } | Should not throw } It "String input should throw" { { Convert-Number -Number bla } | Should throw } } Context "Logic validation" { $value = 16 $expected = [PSCustomobject]@{ Hex = "0x0010" Binary = "10000" Int = 16 Bytes = @(16,0,0,0,0,0,0,0) OddNumber = $False } $Actual = Convert-Number -Number $value It "Should return a PSCustomobject" { $Actual | should BeOfType PSCustomobject } It "Should have an int value of $value" { $Actual.Int | should be $value } It "Should have an hex value of $($Expected.Hex)" { $Actual.Hex | Should be $Expected.Hex } It "Should have an bin value of $($Expected.Bin)" { $Actual.Bin | Should be $Expected.Bin } It "Should have an OddNumber value of $($Expected.OddNumber)" { $Actual.OddNumber | Should be $Expected.OddNumber } It "Should have an bytes value of $($Expected.Bytes)" { $Actual.Bytes | Should be $Expected.Bytes } } Context "Logic validation using pipeline" { $value = 16 $expected = [PSCustomobject]@{ Hex = "0x0010" Binary = "10000" Int = 16 Bytes = @(16,0,0,0,0,0,0,0) OddNumber = $False } $Actual = $value | Convert-Number It "Should return a PSCustomobject" { $Actual | should BeOfType PSCustomobject } It "Should have an int value of $value" { $Actual.Int | should be $value } It "Should have an hex value of $($Expected.Hex)" { $Actual.Hex | Should be $Expected.Hex } It "Should have an bin value of $($Expected.Bin)" { $Actual.Bin | Should be $Expected.Bin } It "Should have an OddNumber value of $($Expected.OddNumber)" { $Actual.OddNumber | Should be $Expected.OddNumber } It "Should have an bytes value of $($Expected.Bytes)" { $Actual.Bytes | Should be $Expected.Bytes } } } Remove-module Numbers
PowerShellCorpus/PowerShellGallery/Numbers/1.0.3.0/Tests/Get-IntFromBinary.Tests.ps1
Get-IntFromBinary.Tests.ps1
#cd C:\Users\Tore\Dropbox\SourceTreeRepros\Numbers -ErrorAction SilentlyContinue $here = Split-Path -Parent $MyInvocation.MyCommand.Path | split-path -parent $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\functions\$sut" $PSBoundParameters.clear() Describe "Get-IntFromBinary" { Context "Parameter validation" { It "No parameters should NOT throw" { { Get-IntFromBinary } | Should not throw } It "None binary String input should throw" { { Get-IntFromBinary -BinaryValue bla } | Should throw #Get-IntFromBin -BinaryValue bla } } Context "Convertion tests" { $bin = "0000" $Expected = 0 It "Should Convert [$bin] to [$Expected]" { Get-IntFromBinary -BinaryValue $bin | Should be $Expected } $bin = "10000" $Expected = 16 It "Should Convert [$bin] to [$Expected]" { Get-IntFromBinary -BinaryValue $bin | Should be $Expected } $bin = "11111111" $Expected = 255 It "Should Convert [$bin] to[$Expected]" { Get-IntFromBinary -BinaryValue $bin | Should be $Expected } } Context "Convertion tests using pipline" { $bin = "0000" $Expected = 0 It "Should Convert [$bin] to [$Expected]" { $bin | Get-IntFromBinary | Should be $Expected } $bin = "10000" $Expected = 16 It "Should Convert [$bin] to [$Expected]" { $bin | Get-IntFromBinary | Should be $Expected } $bin = "11111111" $Expected = 255 It "Should Convert [$bin] to[$Expected]" { $bin | Get-IntFromBinary | Should be $Expected } } }
PowerShellCorpus/PowerShellGallery/PSSQLite/1.0.3/New-SqliteConnection.ps1
New-SqliteConnection.ps1
function New-SQLiteConnection { <# .SYNOPSIS Creates a SQLiteConnection to a SQLite data source .DESCRIPTION Creates a SQLiteConnection to a SQLite data source .PARAMETER DataSource SQLite Data Source to connect to. .PARAMETER Password Specifies A Secure String password to use in the SQLite connection string. SECURITY NOTE: If you use the -Debug switch, the connectionstring including plain text password will be sent to the debug stream. .PARAMETER ReadOnly If specified, open SQLite data source as read only .PARAMETER Open We open the connection by default. You can use this parameter to create a connection without opening it. .OUTPUTS System.Data.SQLite.SQLiteConnection .EXAMPLE $Connection = New-SQLiteConnection -DataSource C:\NAMES.SQLite Invoke-SQLiteQuery -SQLiteConnection $Connection -query $Query # Connect to C:\NAMES.SQLite, invoke a query against it .EXAMPLE $Connection = New-SQLiteConnection -DataSource :MEMORY: Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" # Create a connection to a SQLite data source in memory # Create a table in the memory based datasource, verify it exists with PRAGMA STATS $Connection.Close() $Connection.Open() Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" #Close the connection, open it back up, verify that the ephemeral data no longer exists .LINK https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery .LINK Invoke-SQLiteQuery .FUNCTIONALITY SQL #> [cmdletbinding()] [OutputType([System.Data.SQLite.SQLiteConnection])] param( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, HelpMessage='SQL Server Instance required...' )] [Alias( 'Instance', 'Instances', 'ServerInstance', 'Server', 'Servers','cn','Path','File','FullName','Database' )] [ValidateNotNullOrEmpty()] [string[]] $DataSource, [Parameter( Position=2, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [System.Security.SecureString] $Password, [Parameter( Position=3, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Switch] $ReadOnly, [Parameter( Position=4, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [bool] $Open = $True ) Process { foreach($DataSRC in $DataSource) { if ($DataSRC -match ':MEMORY:' ) { $Database = $DataSRC } else { $Database = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DataSRC) } Write-Verbose "Querying Data Source '$Database'" [string]$ConnectionString = "Data Source=$Database;" if ($Password) { $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $ConnectionString += "Password=$PlainPassword;" } if($ReadOnly) { $ConnectionString += "Read Only=True;" } $conn = New-Object System.Data.SQLite.SQLiteConnection -ArgumentList $ConnectionString $conn.ParseViaFramework = $true #Allow UNC paths, thanks to Ray Alex! Write-Debug "ConnectionString $ConnectionString" if($Open) { Try { $conn.Open() } Catch { Write-Error $_ continue } } write-Verbose "Created SQLiteConnection:`n$($Conn | Out-String)" $Conn } } }
PowerShellCorpus/PowerShellGallery/PSSQLite/1.0.3/Invoke-SqliteBulkCopy.ps1
Invoke-SqliteBulkCopy.ps1
function Invoke-SQLiteBulkCopy { <# .SYNOPSIS Use a SQLite transaction to quickly insert data .DESCRIPTION Use a SQLite transaction to quickly insert data. If we run into any errors, we roll back the transaction. The data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. .PARAMETER DataSource Path to one ore more SQLite data sources to query .PARAMETER Force If specified, skip the confirm prompt .PARAMETER NotifyAfter The number of rows to fire the notification event after transferring. 0 means don't notify. Notifications hit the verbose stream (use -verbose to see them) .PARAMETER QueryTimeout Specifies the number of seconds before the queries time out. .PARAMETER SQLiteConnection An existing SQLiteConnection to use. We do not close this connection upon completed query. .PARAMETER ConflictClause The conflict clause to use in case a conflict occurs during insert. Valid values: Rollback, Abort, Fail, Ignore, Replace See https://www.sqlite.org/lang_conflict.html for more details .EXAMPLE # #Create a table Invoke-SqliteQuery -DataSource "C:\Names.SQLite" -Query "CREATE TABLE NAMES ( fullname VARCHAR(20) PRIMARY KEY, surname TEXT, givenname TEXT, BirthDate DATETIME)" #Build up some fake data to bulk insert, convert it to a datatable $DataTable = 1..10000 | %{ [pscustomobject]@{ fullname = "Name $_" surname = "Name" givenname = "$_" BirthDate = (Get-Date).Adddays(-$_) } } | Out-DataTable #Copy the data in within a single transaction (SQLite is faster this way) Invoke-SQLiteBulkCopy -DataTable $DataTable -DataSource $Database -Table Names -NotifyAfter 1000 -ConflictClause Ignore -Verbose .INPUTS System.Data.DataTable .OUTPUTS None Produces no output .NOTES This function borrows from: Chad Miller's Write-Datatable jbs534's Invoke-SQLBulkCopy Mike Shepard's Invoke-BulkCopy from SQLPSX .LINK https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery .LINK New-SQLiteConnection .LINK Invoke-SQLiteBulkCopy .LINK Out-DataTable .FUNCTIONALITY SQL #> [cmdletBinding( DefaultParameterSetName = 'Datasource', SupportsShouldProcess = $true, ConfirmImpact = 'High' )] param( [parameter( Position = 0, Mandatory = $true, ValueFromPipeline = $false, ValueFromPipelineByPropertyName= $false)] [System.Data.DataTable] $DataTable, [Parameter( ParameterSetName='Datasource', Position=1, Mandatory=$true, ValueFromRemainingArguments=$false, HelpMessage='SQLite Data Source required...' )] [Alias('Path','File','FullName','Database')] [validatescript({ #This should match memory, or the parent path should exist if ( $_ -match ":MEMORY:" -or (Test-Path $_) ) { $True } else { Throw "Invalid datasource '$_'.`nThis must match :MEMORY:, or must exist" } })] [string] $DataSource, [Parameter( ParameterSetName = 'Connection', Position=1, Mandatory=$true, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Alias( 'Connection', 'Conn' )] [System.Data.SQLite.SQLiteConnection] $SQLiteConnection, [parameter( Position=2, Mandatory = $true)] [string] $Table, [Parameter( Position=3, Mandatory=$false, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false)] [ValidateSet("Rollback","Abort","Fail","Ignore","Replace")] [string] $ConflictClause, [int] $NotifyAfter = 0, [switch] $Force, [Int32] $QueryTimeout = 600 ) Write-Verbose "Running Invoke-SQLiteBulkCopy with ParameterSet '$($PSCmdlet.ParameterSetName)'." Function CleanUp { [cmdletbinding()] param($conn, $com, $BoundParams) #Only dispose of the connection if we created it if($BoundParams.Keys -notcontains 'SQLiteConnection') { $conn.Close() $conn.Dispose() Write-Verbose "Closed connection" } $com.Dispose() } function Get-ParameterName { [CmdletBinding()] Param( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [string[]]$InputObject, [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$Regex = '(\W+)', [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$Separator = '_' ) Process{ $InputObject | ForEach-Object { if($_ -match $Regex){ $Groups = @($_ -split $Regex | Where-Object {$_}) for($i = 0; $i -lt $Groups.Count; $i++){ if($Groups[$i] -match $Regex){ $Groups[$i] = ($Groups[$i].ToCharArray() | ForEach-Object {[string][int]$_}) -join $Separator } } $Groups -join $Separator } else { $_ } } } } function New-SqliteBulkQuery { [CmdletBinding()] Param( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string]$Table, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string[]]$Columns, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string[]]$Parameters, [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$ConflictClause = '' ) Begin{ $EscapeSingleQuote = "'","''" $Delimeter = ", " $QueryTemplate = "INSERT{0} INTO {1} ({2}) VALUES ({3})" } Process{ $fmtConflictClause = if($ConflictClause){" OR $ConflictClause"} $fmtTable = "'{0}'" -f ($Table -replace $EscapeSingleQuote) $fmtColumns = ($Columns | ForEach-Object { "'{0}'" -f ($_ -replace $EscapeSingleQuote) }) -join $Delimeter $fmtParameters = ($Parameters | ForEach-Object { "@$_"}) -join $Delimeter $QueryTemplate -f $fmtConflictClause, $fmtTable, $fmtColumns, $fmtParameters } } #Connections if($PSBoundParameters.Keys -notcontains "SQLiteConnection") { if ($DataSource -match ':MEMORY:') { $Database = $DataSource } else { $Database = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DataSource) } $ConnectionString = "Data Source={0}" -f $Database $SQLiteConnection = New-Object System.Data.SQLite.SQLiteConnection -ArgumentList $ConnectionString $SQLiteConnection.ParseViaFramework = $true #Allow UNC paths, thanks to Ray Alex! } Write-Debug "ConnectionString $($SQLiteConnection.ConnectionString)" Try { if($SQLiteConnection.State -notlike "Open") { $SQLiteConnection.Open() } $Command = $SQLiteConnection.CreateCommand() $CommandTimeout = $QueryTimeout $Transaction = $SQLiteConnection.BeginTransaction() } Catch { Throw $_ } write-verbose "DATATABLE IS $($DataTable.gettype().fullname) with value $($Datatable | out-string)" $RowCount = $Datatable.Rows.Count Write-Verbose "Processing datatable with $RowCount rows" if ($Force -or $PSCmdlet.ShouldProcess("$($DataTable.Rows.Count) rows, with BoundParameters $($PSBoundParameters | Out-String)", "SQL Bulk Copy")) { #Get column info... [array]$Columns = $DataTable.Columns | Select-Object -ExpandProperty ColumnName $ColumnTypeHash = @{} $ColumnToParamHash = @{} $Index = 0 foreach($Col in $DataTable.Columns) { $Type = Switch -regex ($Col.DataType.FullName) { # I figure we create a hashtable, can act upon expected data when doing insert # Might be a better way to handle this... '^(|\ASystem\.)Boolean$' {"BOOLEAN"} #I know they're fake... '^(|\ASystem\.)Byte\[\]' {"BLOB"} '^(|\ASystem\.)Byte$' {"BLOB"} '^(|\ASystem\.)Datetime$' {"DATETIME"} '^(|\ASystem\.)Decimal$' {"REAL"} '^(|\ASystem\.)Double$' {"REAL"} '^(|\ASystem\.)Guid$' {"TEXT"} '^(|\ASystem\.)Int16$' {"INTEGER"} '^(|\ASystem\.)Int32$' {"INTEGER"} '^(|\ASystem\.)Int64$' {"INTEGER"} '^(|\ASystem\.)UInt16$' {"INTEGER"} '^(|\ASystem\.)UInt32$' {"INTEGER"} '^(|\ASystem\.)UInt64$' {"INTEGER"} '^(|\ASystem\.)Single$' {"REAL"} '^(|\ASystem\.)String$' {"TEXT"} Default {"BLOB"} #Let SQLite handle the rest... } #We ref columns by their index, so add that... $ColumnTypeHash.Add($Index,$Type) # Parameter names can only be alphanumeric: https://www.sqlite.org/c3ref/bind_blob.html # So we have to replace all non-alphanumeric chars in column name to use it as parameter later. # This builds hashtable to correlate column name with parameter name. $ColumnToParamHash.Add($Col.ColumnName, (Get-ParameterName $Col.ColumnName)) $Index++ } #Build up the query if ($PSBoundParameters.ContainsKey('ConflictClause')) { $Command.CommandText = New-SqliteBulkQuery -Table $Table -Columns $ColumnToParamHash.Keys -Parameters $ColumnToParamHash.Values -ConflictClause $ConflictClause } else { $Command.CommandText = New-SqliteBulkQuery -Table $Table -Columns $ColumnToParamHash.Keys -Parameters $ColumnToParamHash.Values } foreach ($Column in $Columns) { $param = New-Object System.Data.SQLite.SqLiteParameter $ColumnToParamHash[$Column] [void]$Command.Parameters.Add($param) } for ($RowNumber = 0; $RowNumber -lt $RowCount; $RowNumber++) { $row = $Datatable.Rows[$RowNumber] for($col = 0; $col -lt $Columns.count; $col++) { # Depending on the type of thid column, quote it # For dates, convert it to a string SQLite will recognize switch ($ColumnTypeHash[$col]) { "BOOLEAN" { $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = [int][boolean]$row[$col] } "DATETIME" { Try { $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = $row[$col].ToString("yyyy-MM-dd HH:mm:ss") } Catch { $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = $row[$col] } } Default { $Command.Parameters[$ColumnToParamHash[$Columns[$col]]].Value = $row[$col] } } } #We have the query, execute! Try { [void]$Command.ExecuteNonQuery() } Catch { #Minimal testing for this rollback... Write-Verbose "Rolling back due to error:`n$_" $Transaction.Rollback() #Clean up and throw an error CleanUp -conn $SQLiteConnection -com $Command -BoundParams $PSBoundParameters Throw "Rolled back due to error:`n$_" } if($NotifyAfter -gt 0 -and $($RowNumber % $NotifyAfter) -eq 0) { Write-Verbose "Processed $($RowNumber + 1) records" } } } #Commit the transaction and clean up the connection $Transaction.Commit() CleanUp -conn $SQLiteConnection -com $Command -BoundParams $PSBoundParameters }
PowerShellCorpus/PowerShellGallery/PSSQLite/1.0.3/Invoke-SqliteQuery.ps1
Invoke-SqliteQuery.ps1
function Invoke-SqliteQuery { <# .SYNOPSIS Runs a SQL script against a SQLite database. .DESCRIPTION Runs a SQL script against a SQLite database. Paramaterized queries are supported. Help details below borrowed from Invoke-Sqlcmd, may be inaccurate here. .PARAMETER DataSource Path to one or more SQLite data sources to query .PARAMETER Query Specifies a query to be run. .PARAMETER InputFile Specifies a file to be used as the query input to Invoke-SqliteQuery. Specify the full path to the file. .PARAMETER QueryTimeout Specifies the number of seconds before the queries time out. .PARAMETER As Specifies output type - DataSet, DataTable, array of DataRow, PSObject or Single Value PSObject output introduces overhead but adds flexibility for working with results: http://powershell.org/wp/forums/topic/dealing-with-dbnull/ .PARAMETER SqlParameters Hashtable of parameters for parameterized SQL queries. http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/ Limited support for conversions to SQLite friendly formats is supported. For example, if you pass in a .NET DateTime, we convert it to a string that SQLite will recognize as a datetime Example: -Query "SELECT ServerName FROM tblServerInfo WHERE ServerName LIKE @ServerName" -SqlParameters @{"ServerName = "c-is-hyperv-1"} .PARAMETER SQLiteConnection An existing SQLiteConnection to use. We do not close this connection upon completed query. .PARAMETER AppendDataSource If specified, append the SQLite data source path to PSObject or DataRow output .INPUTS DataSource You can pipe DataSource paths to Invoke-SQLiteQuery. The query will execute against each Data Source. .OUTPUTS As PSObject: System.Management.Automation.PSCustomObject As DataRow: System.Data.DataRow As DataTable: System.Data.DataTable As DataSet: System.Data.DataTableCollectionSystem.Data.DataSet As SingleValue: Dependent on data type in first column. .EXAMPLE # # First, we create a database and a table $Query = "CREATE TABLE NAMES (fullname VARCHAR(20) PRIMARY KEY, surname TEXT, givenname TEXT, BirthDate DATETIME)" $Database = "C:\Names.SQLite" Invoke-SqliteQuery -Query $Query -DataSource $Database # We have a database, and a table, let's view the table info Invoke-SqliteQuery -DataSource $Database -Query "PRAGMA table_info(NAMES)" cid name type notnull dflt_value pk --- ---- ---- ------- ---------- -- 0 fullname VARCHAR(20) 0 1 1 surname TEXT 0 0 2 givenname TEXT 0 0 3 BirthDate DATETIME 0 0 # Insert some data, use parameters for the fullname and birthdate $query = "INSERT INTO NAMES (fullname, surname, givenname, birthdate) VALUES (@full, 'Cookie', 'Monster', @BD)" Invoke-SqliteQuery -DataSource $Database -Query $query -SqlParameters @{ full = "Cookie Monster" BD = (get-date).addyears(-3) } # Check to see if we inserted the data: Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM NAMES" fullname surname givenname BirthDate -------- ------- --------- --------- Cookie Monster Cookie Monster 3/14/2012 12:27:13 PM # Insert another entry with too many characters in the fullname. # Illustrate that SQLite data types may be misleading: Invoke-SqliteQuery -DataSource $Database -Query $query -SqlParameters @{ full = "Cookie Monster$('!' * 20)" BD = (get-date).addyears(-3) } Invoke-SqliteQuery -DataSource $Database -Query "SELECT * FROM NAMES" fullname surname givenname BirthDate -------- ------- --------- --------- Cookie Monster Cookie Monster 3/14/2012 12:27:13 PM Cookie Monster![...]! Cookie Monster 3/14/2012 12:29:32 PM .EXAMPLE Invoke-SqliteQuery -DataSource C:\NAMES.SQLite -Query "SELECT * FROM NAMES" -AppendDataSource fullname surname givenname BirthDate Database -------- ------- --------- --------- -------- Cookie Monster Cookie Monster 3/14/2012 12:55:55 PM C:\Names.SQLite # Append Database column (path) to each result .EXAMPLE Invoke-SqliteQuery -DataSource C:\Names.SQLite -InputFile C:\Query.sql # Invoke SQL from an input file .EXAMPLE $Connection = New-SQLiteConnection -DataSource :MEMORY: Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" # Execute a query against an existing SQLiteConnection # Create a connection to a SQLite data source in memory # Create a table in the memory based datasource, verify it exists with PRAGMA STATS .EXAMPLE $Connection = New-SQLiteConnection -DataSource :MEMORY: Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID) VALUES (2);" # We now have two entries, only one has a fullname. Despite this, the following command returns both; very un-PowerShell! Invoke-SqliteQuery -SQLiteConnection $Connection -Query "SELECT * FROM OrdersToNames" -As DataRow | Where{$_.fullname} OrderID fullname ------- -------- 1 Cookie Monster 2 # Using the default -As PSObject, we can get PowerShell-esque behavior: Invoke-SqliteQuery -SQLiteConnection $Connection -Query "SELECT * FROM OrdersToNames" | Where{$_.fullname} OrderID fullname ------- -------- 1 Cookie Monster .LINK https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery .LINK New-SQLiteConnection .LINK Invoke-SQLiteBulkCopy .LINK Out-DataTable .LINK https://www.sqlite.org/datatype3.html .LINK https://www.sqlite.org/lang.html .LINK http://www.sqlite.org/pragma.html .FUNCTIONALITY SQL #> [CmdletBinding( DefaultParameterSetName='Src-Que' )] [OutputType([System.Management.Automation.PSCustomObject],[System.Data.DataRow],[System.Data.DataTable],[System.Data.DataTableCollection],[System.Data.DataSet])] param( [Parameter( ParameterSetName='Src-Que', Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, HelpMessage='SQLite Data Source required...' )] [Parameter( ParameterSetName='Src-Fil', Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, HelpMessage='SQLite Data Source required...' )] [Alias('Path','File','FullName','Database')] [validatescript({ #This should match memory, or the parent path should exist $Parent = Split-Path $_ -Parent if( $_ -match ":MEMORY:|^WHAT$" -or ( $Parent -and (Test-Path $Parent)) ){ $True } else { Throw "Invalid datasource '$_'.`nThis must match :MEMORY:, or '$Parent' must exist" } })] [string[]] $DataSource, [Parameter( ParameterSetName='Src-Que', Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Parameter( ParameterSetName='Con-Que', Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [string] $Query, [Parameter( ParameterSetName='Src-Fil', Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Parameter( ParameterSetName='Con-Fil', Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [ValidateScript({ Test-Path $_ })] [string] $InputFile, [Parameter( Position=2, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Int32] $QueryTimeout=600, [Parameter( Position=3, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [ValidateSet("DataSet", "DataTable", "DataRow","PSObject","SingleValue")] [string] $As="PSObject", [Parameter( Position=4, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [System.Collections.IDictionary] $SqlParameters, [Parameter( Position=5, Mandatory=$false )] [switch] $AppendDataSource, [Parameter( Position=6, Mandatory=$false )] [validatescript({Test-Path $_ })] [string]$AssemblyPath = $SQLiteAssembly, [Parameter( ParameterSetName = 'Con-Que', Position=7, Mandatory=$true, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Parameter( ParameterSetName = 'Con-Fil', Position=7, Mandatory=$true, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Alias( 'Connection', 'Conn' )] [System.Data.SQLite.SQLiteConnection] $SQLiteConnection ) Begin { #Assembly, should already be covered by psm1 Try { [void][System.Data.SQLite.SQLiteConnection] } Catch { if( -not ($Library = Add-Type -path $SQLiteAssembly -PassThru -ErrorAction stop) ) { Throw "This module requires the ADO.NET driver for SQLite:`n`thttp://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki" } } if ($PSBoundParameters.ContainsKey('InputFile')) { $filePath = $(Resolve-Path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") Write-Verbose "Extracted query from [$InputFile]" } Write-Verbose "Running Invoke-SQLiteQuery with ParameterSet '$($PSCmdlet.ParameterSetName)'. Performing query '$Query'" If($As -eq "PSObject") { #This code scrubs DBNulls. Props to Dave Wyatt $cSharp = @' using System; using System.Data; using System.Management.Automation; public class DBNullScrubber { public static PSObject DataRowToPSObject(DataRow row) { PSObject psObject = new PSObject(); if (row != null && (row.RowState & DataRowState.Detached) != DataRowState.Detached) { foreach (DataColumn column in row.Table.Columns) { Object value = null; if (!row.IsNull(column)) { value = row[column]; } psObject.Properties.Add(new PSNoteProperty(column.ColumnName, value)); } } return psObject; } } '@ Try { Add-Type -TypeDefinition $cSharp -ReferencedAssemblies 'System.Data','System.Xml' -ErrorAction stop } Catch { If(-not $_.ToString() -like "*The type name 'DBNullScrubber' already exists*") { Write-Warning "Could not load DBNullScrubber. Defaulting to DataRow output: $_" $As = "Datarow" } } } #Handle existing connections if($PSBoundParameters.Keys -contains "SQLiteConnection") { if($SQLiteConnection.State -notlike "Open") { Try { $SQLiteConnection.Open() } Catch { Throw $_ } } if($SQLiteConnection.state -notlike "Open") { Throw "SQLiteConnection is not open:`n$($SQLiteConnection | Out-String)" } $DataSource = @("WHAT") } } Process { foreach($DB in $DataSource) { if($PSBoundParameters.Keys -contains "SQLiteConnection") { $Conn = $SQLiteConnection } else { # Resolve the path entered for the database to a proper path name. # This accounts for a variaty of possible ways to provide a path, but # in the end the connection string needs a fully qualified file path. if ($DB -match ":MEMORY:") { $Database = $DB } else { $Database = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DB) } if(Test-Path $Database) { Write-Verbose "Querying existing Data Source '$Database'" } else { Write-Verbose "Creating andn querying Data Source '$Database'" } $ConnectionString = "Data Source={0}" -f $Database $conn = New-Object System.Data.SQLite.SQLiteConnection -ArgumentList $ConnectionString $conn.ParseViaFramework = $true #Allow UNC paths, thanks to Ray Alex! Write-Debug "ConnectionString $ConnectionString" Try { $conn.Open() } Catch { Write-Error $_ continue } } $cmd = $Conn.CreateCommand() $cmd.CommandText = $Query $cmd.CommandTimeout = $QueryTimeout if ($SqlParameters -ne $null) { $SqlParameters.GetEnumerator() | ForEach-Object { If ($_.Value -ne $null) { if($_.Value -is [datetime]) { $_.Value = $_.Value.ToString("yyyy-MM-dd HH:mm:ss") } $cmd.Parameters.AddWithValue("@$($_.Key)", $_.Value) } Else { $cmd.Parameters.AddWithValue("@$($_.Key)", [DBNull]::Value) } } > $null } $ds = New-Object system.Data.DataSet $da = New-Object System.Data.SQLite.SQLiteDataAdapter($cmd) Try { [void]$da.fill($ds) if($PSBoundParameters.Keys -notcontains "SQLiteConnection") { $conn.Close() } $cmd.Dispose() } Catch { $Err = $_ if($PSBoundParameters.Keys -notcontains "SQLiteConnection") { $conn.Close() } switch ($ErrorActionPreference.tostring()) { {'SilentlyContinue','Ignore' -contains $_} {} 'Stop' { Throw $Err } 'Continue' { Write-Error $Err} Default { Write-Error $Err} } } if($AppendDataSource) { #Basics from Chad Miller $Column = New-Object Data.DataColumn $Column.ColumnName = "Datasource" $ds.Tables[0].Columns.Add($Column) Try { #Someone better at regular expression, feel free to tackle this $Conn.ConnectionString -match "Data Source=(?<DataSource>.*);" $Datasrc = $Matches.DataSource.split(";")[0] } Catch { $Datasrc = $DB } Foreach($row in $ds.Tables[0]) { $row.Datasource = $Datasrc } } switch ($As) { 'DataSet' { $ds } 'DataTable' { $ds.Tables } 'DataRow' { $ds.Tables[0] } 'PSObject' { #Scrub DBNulls - Provides convenient results you can use comparisons with #Introduces overhead (e.g. ~2000 rows w/ ~80 columns went from .15 Seconds to .65 Seconds - depending on your data could be much more!) foreach ($row in $ds.Tables[0].Rows) { [DBNullScrubber]::DataRowToPSObject($row) } } 'SingleValue' { $ds.Tables[0] | Select-Object -ExpandProperty $ds.Tables[0].Columns[0].ColumnName } } } } }
PowerShellCorpus/PowerShellGallery/PSSQLite/1.0.3/Out-DataTable.ps1
Out-DataTable.ps1
function Out-DataTable { <# .SYNOPSIS Creates a DataTable for an object .DESCRIPTION Creates a DataTable based on an object's properties. .PARAMETER InputObject One or more objects to convert into a DataTable .PARAMETER NonNullable A list of columns to set disable AllowDBNull on .INPUTS Object Any object can be piped to Out-DataTable .OUTPUTS System.Data.DataTable .EXAMPLE $dt = Get-psdrive | Out-DataTable # This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable .EXAMPLE Get-Process | Select Name, CPU | Out-DataTable | Invoke-SQLBulkCopy -ServerInstance $SQLInstance -Database $Database -Table $SQLTable -force -verbose # Get a list of processes and their CPU, create a datatable, bulk import that data .NOTES Adapted from script by Marc van Orsouw and function from Chad Miller Version History v1.0 - Chad Miller - Initial Release v1.1 - Chad Miller - Fixed Issue with Properties v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0 v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties v1.4 - Chad Miller - Corrected issue with DBNull v1.5 - Chad Miller - Updated example v1.6 - Chad Miller - Added column datatype logic with default to string v1.7 - Chad Miller - Fixed issue with IsArray v1.8 - ramblingcookiemonster - Removed if($Value) logic. This would not catch empty strings, zero, $false and other non-null items - Added perhaps pointless error handling .LINK https://github.com/RamblingCookieMonster/PowerShell .LINK Invoke-SQLBulkCopy .LINK Invoke-Sqlcmd2 .LINK New-SQLConnection .FUNCTIONALITY SQL #> [CmdletBinding()] [OutputType([System.Data.DataTable])] param( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject, [string[]]$NonNullable = @() ) Begin { $dt = New-Object Data.datatable $First = $true function Get-ODTType { param($type) $types = @( 'System.Boolean', 'System.Byte[]', 'System.Byte', 'System.Char', 'System.Datetime', 'System.Decimal', 'System.Double', 'System.Guid', 'System.Int16', 'System.Int32', 'System.Int64', 'System.Single', 'System.UInt16', 'System.UInt32', 'System.UInt64') if ( $types -contains $type ) { Write-Output "$type" } else { Write-Output 'System.String' } } #Get-Type } Process { foreach ($Object in $InputObject) { $DR = $DT.NewRow() foreach ($Property in $Object.PsObject.Properties) { $Name = $Property.Name $Value = $Property.Value #RCM: what if the first property is not reflective of all the properties? Unlikely, but... if ($First) { $Col = New-Object Data.DataColumn $Col.ColumnName = $Name #If it's not DBNull or Null, get the type if ($Value -isnot [System.DBNull] -and $Value -ne $null) { $Col.DataType = [System.Type]::GetType( $(Get-ODTType $property.TypeNameOfValue) ) } #Set it to nonnullable if specified if ($NonNullable -contains $Name ) { $col.AllowDBNull = $false } try { $DT.Columns.Add($Col) } catch { Write-Error "Could not add column $($Col | Out-String) for property '$Name' with value '$Value' and type '$($Value.GetType().FullName)':`n$_" } } Try { #Handle arrays and nulls if ($property.GetType().IsArray) { $DR.Item($Name) = $Value | ConvertTo-XML -As String -NoTypeInformation -Depth 1 } elseif($Value -eq $null) { $DR.Item($Name) = [DBNull]::Value } else { $DR.Item($Name) = $Value } } Catch { Write-Error "Could not add property '$Name' with value '$Value' and type '$($Value.GetType().FullName)'" continue } #Did we get a null or dbnull for a non-nullable item? let the user know. if($NonNullable -contains $Name -and ($Value -is [System.DBNull] -or $Value -eq $null)) { write-verbose "NonNullable property '$Name' with null value found: $($object | out-string)" } } Try { $DT.Rows.Add($DR) } Catch { Write-Error "Failed to add row '$($DR | Out-String)':`n$_" } $First = $false } } End { Write-Output @(,$dt) } } #Out-DataTable
PowerShellCorpus/PowerShellGallery/AwsDscToolkit/0.5.0.0/Examples/AwsDscToolkit.Examples.ps1
AwsDscToolkit.Examples.ps1
#--- Module Setup ---# # Install the AWS DSC Toolkit from the PowerShellGallery Install-Module AwsDscToolkit Import-Module AwsDscToolkit # Set your AWS credentials in the default profile $AwsAccessKey = 'MyAccessKey' $AwsSecretKey = 'MySecretKey' Set-AWSCredentials -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -StoreAs 'default' # Set your default AWS region $AwsRegion = 'us-west-2' Set-DefaultAWSRegion -Region $AwsRegion # Log in to AzureRm Add-AzureRmAccount #--- Register a New EC2 Instance ---# # Create a valid security group or supply the name of an exisitng one $securityGroupName = 'MySecurityGroup' New-EC2SecurityGroup -GroupName $securityGroupName -Description 'Security group for registration to Azure Automation' # Create a valid IAM instance profile for a new instance $instanceProfileName = 'MyInstanceProfile' $instanceProfile = Set-IAMInstanceProfileForRegistration -Name $instanceProfileName # OR # Test that an existing IAM instance profile is valid to register a new instance Test-IAMInstanceProfileForRegistration -Name $instanceProfileName # AND # Modify an existing IAM instance profile to be valid to register a new instance Set-IAMInstanceProfileForRegistration -Name $instanceProfileName # Get the image id of the Amazon Machine Image (AMI) to use - By default the cmdlet will create a VM with the most recent version of 'WINDOWS_2012R2_BASE' $imageName = 'WINDOWS_2012R2_BASE' $imageId = $(Get-EC2ImageByName -Name $imageName).ImageId # Choose an instance type - By default the cmdlet will create a t2.micro instance. $instanceType = 't2.micro' # Register a new instance $keyPairName = 'MyKeyPair' $azureAutomationAccountName = 'MyAzureAutomationAccount' Register-EC2Instance ` -AzureAutomationAccount $azureAutomationAccountName ` -New ` -ImageId $imageId ` -KeyName $keyPairName ` -SecurityGroup $securityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName #--- Register an Existing EC2 Instance ---# # Test if the instance can be registered $existingInstanceId = 'MyExistingInstanceId' Test-EC2InstanceRegistration -InstanceId $existingInstanceId -Verbose # Test that the existing IAM instance profile is valid to register an existing instance $existingInstanceProfileName = 'MyExistingInstanceProfile' Test-IAMInstanceProfileForRegistration -Name $existingInstanceProfileName -ExistingInstance # AND # Modify an existing IAM instance profile to be valid to register an existing instance Set-IAMInstanceProfileForRegistration -Name $existingInstanceProfileName -ExistingInstance # Register an existing instance $azureAutomationAccountName = 'MyAzureAutomationAccount' $existingInstanceId = 'MyExistingInstanceId' Register-EC2Instance -AzureAutomationAccount $azureAutomationAccountName -InstanceId $existingInstanceId #--- Check if an EC2 Instance is Registered ---# $azureAutomationAccountName = 'MyAzureAutomation' $registeredInstanceId = 'MyRegisteredInstanceId' Test-EC2InstanceRegistration -AzureAutomationAccount $azureAutomationAccountName -InstanceId $registeredInstanceId
PowerShellCorpus/PowerShellGallery/AwsDscToolkit/0.5.0.0/Tests/AwsDscToolkit.Tests.ps1
AwsDscToolkit.Tests.ps1
[CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$AwsAccessKey, [Parameter(Mandatory = $true)] [string]$AwsSecretKey, [Parameter(Mandatory = $true)] [string]$AzureAutomationAccount, [string]$AzureAutomationResourceGroup, [string]$AwsRegion = 'us-west-2', [string]$ExtensionVersion = '0.1.0.0' ) $ErrorActionPreference = 'stop' Set-StrictMode -Version latest # $PSScriptRoot is not defined in 2.0 if (-not (Test-Path variable:PSScriptRoot) -or -not $PSScriptRoot) { $PSScriptRoot = [System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Path) } # Check for Azure login try { AzureRM.Profile\Get-AzureRmContext | Out-Null } catch { AzureRM.Profile\Add-AzureRmAccount | Out-Null } function Write-VerboseWithDate { [CmdletBinding()] param ( [string]$Message ) Write-Verbose "$(Get-Date) $Message" } # Retrieves the Azure Automation resource group for an Azure Automation account function Get-AzureAutomationResourceGroup { param ( [Parameter(Mandatory = $true)] $AzureAutomationAccountName ) $accounts = AzureRM.Automation\Get-AzureRmAutomationAccount $matchingAccounts = @() foreach ($account in $accounts) { if ($account.AutomationAccountName -eq $AzureAutomationAccountName) { $matchingAccounts += $account } } if ($matchingAccounts.Count -eq 0) { throw "Azure Automation account $AzureAutomationAccountName not found." } elseif ($matchingAccounts.Count -gt 1) { throw "Multiple Azure Automation accounts found with the name $AzureAutomationAccountName. Please specify AzureAutomationResourceGroup." } return $matchingAccounts[0].ResourceGroupName } # If an Azure Automation resource group was not provided, find the resource group for the given account if (-not $AzureAutomationResourceGroup) { Write-VerboseWithDate "Retrieving Azure Automation resource group for account $AzureAutomationAccount..." $AzureAutomationResourceGroup = Get-AzureAutomationResourceGroup -AzureAutomationAccountName $AzureAutomationAccount } $testPrefix = 'AwsDscToolkitTest' $testInstanceProfileName = $testPrefix + 'InstanceProfile' $originalKeyPolicies = @{} $keyPolicyName = $testPrefix + 'KeyPolicy' function Set-IAMInstanceProfileKeyAccess { [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory = $true)] [string]$RoleArn, [string]$KeyId ) # Give new custom instance profile access to encryption keys $keyPolicyInsert = @" , { "Sid": "Allow use of the key", "Effect": "Allow", "Principal": { "AWS": "$RoleArn" }, "Action": [ "kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt", "kms:GenerateDataKey*", "kms:DescribeKey" ], "Resource": "*" } ] } "@ if (-not $KeyId) { $keys = @() $keys += Get-KMSKeys -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion if (-not $keys -or $keys.Count -eq 0) { throw "This AWS account does not have any AWS encryption keys." } $KeyId = $keys[0].KeyId } $keyPolicies = @() $keyPolicies += Get-KMSKeyPolicies -KeyId $KeyId -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion if ($keyPolicies -and $keyPolicies.Count -gt 0) { $keyPolicyName = $keyPolicies[0] } $keyPolicy = Get-KMSKeyPolicy -KeyId $KeyId -PolicyName $keyPolicyName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion if (-not ($originalKeyPolicies.Keys -contains $keyId)) { $originalKeyPolicies[$keyId] = $keyPolicy } $modifiedKeyPolicy = $keyPolicy.Remove($keyPolicy.LastIndexOf(']'), $keyPolicy.Length - $keyPolicy.LastIndexOf(']')) + $keyPolicyInsert if ($PSCmdlet.ShouldProcess($KeyId)) { Write-KMSKeyPolicy -KeyId $KeyId -PolicyName $keyPolicyName -Policy $modifiedKeyPolicy -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } function Reset-IAMInstanceProfileKeyAccess { [CmdletBinding(SupportsShouldProcess=$true)] param ( [string]$KeyId ) if (-not $originalKeyPolicies.Keys -contains $KeyId) { throw "Policy for encryption key $KeyId has not been modified." } elseif (-not $originalKeyPolicies[$KeyId]) { throw "Original key policy is null." } $keyPolicies = @() $keyPolicies += Get-KMSKeyPolicies -KeyId $keyId -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion if ($keyPolicies -and $keyPolicies.Count -gt 0) { $keyPolicyName = $keyPolicies[0] } # Reset the encryption key policy if ($PSCmdlet.ShouldProcess($KeyId)) { Write-KMSKeyPolicy -KeyId $KeyId -PolicyName $keyPolicyName -Policy $originalKeyPolicies[$KeyId] -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } function Remove-IAMInstanceProfileAndRole { [CmdletBinding()] param( [Parameter(Mandatory = $true)] $InstanceProfile ) $instanceRoles = $InstanceProfile.Roles foreach ($instanceRole in $instanceRoles) { Remove-IAMRoleFromInstanceProfile -InstanceProfileName $InstanceProfile.InstanceProfileName -RoleName $instanceRole.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion -Force | Out-Null $attachedPolicies = Get-IAMAttachedRolePolicies -RoleName $instanceRole.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion foreach ($attachedPolicy in $attachedPolicies) { Unregister-IAMRolePolicy -PolicyArn $attachedPolicy.PolicyArn -RoleName $instanceRole.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } $inlinePolicies = Get-IAMRolePolicies -RoleName $instanceRole.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion foreach ($inlinePolicy in $inlinePolicies) { Remove-IAMRolePolicy -RoleName $instanceRole.RoleName -PolicyName $inlinePolicy -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion -Force | Out-Null } Remove-IAMRole -RoleName $instanceRole.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion -Force | Out-Null } Remove-IAMInstanceProfile -InstanceProfileName $InstanceProfile.InstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion -Force | Out-Null } function Save-IAMInstanceProfileKeyAccess { param () $keys = @() $keys += AWSPowershell\Get-KMSKeys -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion if (-not $keys -or $keys.Count -eq 0) { throw "This AWS account does not have any AWS encryption keys." } $keyId = $keys[0].KeyId $keyPolicies = @() $keyPolicies += Get-KMSKeyPolicies -KeyId $keyId -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion if ($keyPolicies -and $keyPolicies.Count -gt 0) { $keyPolicyName = $keyPolicies[0] } $keyPolicy = Get-KMSKeyPolicy -KeyId $keyId -PolicyName $keyPolicyName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion $originalKeyPolicies[$keyId] = $keyPolicy return $keyId } function New-IAMInstanceProfileForRegistrationInline { [CmdletBinding(SupportsShouldProcess=$true)] param ( [Parameter(Mandatory = $true)] [string]$InstanceProfileName, [string]$RoleName, [string]$KeyId ) $roleTrustPolicyDocument = '{ "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole" } }' $rolePolicyDocument = '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ssm:DescribeAssociation", "ssm:GetDocument", "ssm:ListAssociations", "ssm:UpdateAssociationStatus", "ssm:UpdateInstanceInformation" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "ec2messages:AcknowledgeMessage", "ec2messages:DeleteMessage", "ec2messages:FailMessage", "ec2messages:GetEndpoint", "ec2messages:GetMessages", "ec2messages:SendReply" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "cloudwatch:PutMetricData" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "ec2:DescribeInstanceStatus" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "ds:CreateComputer", "ds:DescribeDirectories" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogGroups", "logs:DescribeLogStreams", "logs:PutLogEvents" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads" ], "Resource": "*" } ] }' if (-not $RoleName) { $RoleName = $InstanceProfileName } # Create a new custom instance profile Write-VerboseWithDate "Creating new IAM instance profile..." $instanceProfile = New-IAMInstanceProfile -InstanceProfileName $InstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion Write-VerboseWithDate "Creating new IAM role..." $role = New-IAMRole -RoleName $RoleName -AssumeRolePolicyDocument $roleTrustPolicyDocument -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion Write-VerboseWithDate "Adding IAM role to IAM instance profile..." Add-IAMRoleToInstanceProfile -InstanceProfileName $instanceProfile.InstanceProfileName -RoleName $role.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null Write-VerboseWithDate "Writing IAM role policy..." if ($PSCmdlet.ShouldProcess($role.RoleName)) { AWSPowershell\Write-IAMRolePolicy -PolicyDocument $rolePolicyDocument -PolicyName 'AllowRunCommand' -RoleName $role.RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } Write-VerboseWithDate "Waiting for 10 seconds while permissions propogate..." Start-Sleep -Seconds 10 Write-VerboseWithDate "Retrieving current IAM instance profile..." $instanceProfile = Get-IAMInstanceProfile -InstanceProfileName $InstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion $role = Get-IAMRole -RoleName $RoleName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion while (-not $instanceProfile -or -not $instanceProfile.Roles -or -not ($instanceProfile.Roles | Where-Object { $_.Arn -eq $role.Arn })) { Write-VerboseWithDate "IAM instance profile needs more time. Waiting 5 seconds..." Start-Sleep -Seconds 5 $instanceProfile = Get-IAMInstanceProfile -InstanceProfileName $InstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion } Set-IAMInstanceProfileKeyAccess -RoleArn $role.Arn -KeyId $KeyId return $instanceProfile } function Get-EC2InstanceAzureAutomationId { param ( [Parameter(Mandatory = $true)] [string]$InstanceId ) $instanceReservation = AWSPowershell\Get-EC2Instance $InstanceId -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion Write-VerboseWithDate "Checking for instance registration..." # Check if the instance's IP address matches an IP address in the Azure Automation account's DSC nodes Write-VerboseWithDate "Retrieving AWS VM IP address..." $vmIpAddress = $instanceReservation.Instances[0].PrivateIpAddress Write-VerboseWithDate "Retrieving Azure Automation DSC nodes..." $dscNodes = AzureRM.Automation\Get-AzureRmAutomationDscNode -ResourceGroupName $AzureAutomationResourceGroup -AutomationAccountName $AzureAutomationAccount Write-VerboseWithDate "Checking instance IP address against DSC nodes..." foreach ($dscNode in $dscNodes) { if ($dscNode.IpAddress.Split(';')[0] -eq $vmIpAddress) { Write-VerboseWithDate "Instance is registered." return $dscNode.Id } } return $null } function Invoke-WaitForEC2InstanceState { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$InstanceId, [Parameter(Mandatory = $true)] [string]$DesiredState, [Parameter(Mandatory = $true)] [string]$AccessKey, [Parameter(Mandatory = $true)] [string]$SecretKey, [Parameter(Mandatory = $true)] [string]$Region ) $instance = AWSPowershell\Get-EC2Instance $InstanceId -AccessKey $AccessKey -SecretKey $SecretKey -Region $Region # Wait until the instance is in the desired state while ($instance.RunningInstance.State.Name -ne $DesiredState) { Write-VerboseWithDate "Instance state is $($instance.RunningInstance.State.Name). Waiting for 10 seconds..." Start-Sleep -Seconds 10 $instance = AWSPowershell\Get-EC2Instance $InstanceId -AccessKey $AccessKey -SecretKey $SecretKey -Region $Region } Write-VerboseWithDate "Instance state is $($instance.RunningInstance.State.Name)." } function Invoke-WaitForEC2InstanceStatus { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$InstanceId, [Parameter(Mandatory = $true)] [string]$DesiredStatus ) $instanceStatus = AWSPowershell\Get-EC2InstanceStatus $InstanceId -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion # Wait until the instance has the desired status while ($instanceStatus.Status.Status.Value -ne $DesiredStatus) { Write-VerboseWithDate "Instance status is $($instanceStatus.Status.Status.Value). Waiting for 30 seconds..." Start-Sleep -Seconds 30 $instanceStatus = AWSPowershell\Get-EC2InstanceStatus $InstanceId -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion } Write-VerboseWithDate "Instance status is $($instanceStatus.Status.Status.Value)." } function Invoke-WaitForEC2InstanceRegistered { param ( [Parameter(Mandatory = $true)] [string]$InstanceId, [int]$TimeoutMins = 10 ) $status = [EC2InstanceRegistrationStatus]::ReadyToRegister $startTime = Get-Date $runningTime = (Get-Date) - (Get-Date) while ($status -ne [EC2InstanceRegistrationStatus]::Registered -and $runningTime.Minutes -lt $TimeoutMins) { Write-VerboseWithDate "Registration not found. Waiting 30 seconds..." Start-Sleep -Seconds 30 $status = Test-EC2InstanceRegistration ` -AzureAutomationResourceGroup $AzureAutomationResourceGroup ` -AzureAutomationAccount $AzureAutomationAccount ` -InstanceId $instanceId ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $currentTime = Get-Date $runningTime = $currentTime - $startTime } return $status } Describe 'IAMInstanceProfileForRegistration' { It 'Should create a new valid IAM Instance Profile (New Instance)' { $keyId = Save-IAMInstanceProfileKeyAccess try { $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $testInstanceProfileName ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion ` -KeyId $keyId try { $testResult = Test-IAMInstanceProfileForRegistration ` -Name $instanceProfile.InstanceProfileName ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $testResult | Should Be $true } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $instanceProfile } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } It 'Should create a new valid IAM Instance Profile (Existing Instance)' { $keyId = Save-IAMInstanceProfileKeyAccess try { $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $testInstanceProfileName ` -ExistingInstance ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion ` -KeyId $keyId try { $testResult = Test-IAMInstanceProfileForRegistration ` -Name $instanceProfile.InstanceProfileName ` -ExistingInstance ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $testResult | Should Be $true } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $instanceProfile } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } It 'Should modify an existing IAM Instance Profile (New Instance)' { $keyId = Save-IAMInstanceProfileKeyAccess try { $instanceProfile = New-IAMInstanceProfile -InstanceProfileName $testInstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion # Wait for the profile to be available outside IAM Start-Sleep -Seconds 10 try { $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $testInstanceProfileName ` -KeyId $keyId ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $testResult = Test-IAMInstanceProfileForRegistration ` -Name $instanceProfile.InstanceProfileName ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $testResult | Should Be $true } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $instanceProfile } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } It 'Should modify an existing IAM Instance Profile (Existing Instance)' { $keyId = Save-IAMInstanceProfileKeyAccess try { $instanceProfile = New-IAMInstanceProfile -InstanceProfileName $testInstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion # Wait for the profile to be available outside IAM Start-Sleep -Seconds 10 try { $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $testInstanceProfileName ` -ExistingInstance ` -KeyId $keyId ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $testResult = Test-IAMInstanceProfileForRegistration ` -Name $instanceProfile.InstanceProfileName ` -ExistingInstance ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $testResult | Should Be $true } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $instanceProfile } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } } $instanceType = 't2.micro' $imageName = 'WINDOWS_2012R2_BASE' $imageId = (AWSPowershell\Get-EC2ImageByName -Name $imageName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion).ImageId $testSecurityGroupName = $testPrefix + 'SecurityGroup' $testSecurityGroupDescription = 'Security group for AWS DSC Toolkit tests.' AWSPowershell\New-EC2SecurityGroup ` -GroupName $testSecurityGroupName ` -Description $testSecurityGroupDescription ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion ` | Out-Null try { Describe 'Test-EC2InstanceRegistration' { $invalidInstanceId = 'fakeId' $invalidAwsProfile = 'fakeProfileName' # Error Tests It 'Should throw an error when invalid AWS credentials profile specified' { {Test-EC2InstanceRegistration -InstanceId $invalidInstanceId -AwsProfile $invalidAwsProfile} ` | Should Throw "No AWS credentials" } It 'Should throw an error when no AWS region specified or in defaults' { $savedRegion = Get-DefaultAwsRegion Clear-DefaultAwsRegion {Test-EC2InstanceRegistration -InstanceId $invalidInstanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey} ` | Should Throw "No default AWS region. Please specify an AWS region or follow the guide here to set your default region: http://docs.aws.amazon.com/powershell/latest/userguide/pstools-installing-specifying-region.html" if ($savedRegion) { Set-DefaultAwsRegion $savedRegion } } It 'Should throw an error when invalid instance id specified' { {Test-EC2InstanceRegistration -InstanceId $invalidInstanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey -AwsRegion $AwsRegion} ` | Should Throw 'Invalid id: "' + $invalidInstanceId + '"' } # Negative Tests It 'Should return CannotRegister when instance does not have an IAM role' { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { $testResult = Test-EC2InstanceRegistration -InstanceId $instanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey -AwsRegion $AwsRegion $testResult | Should Be ([EC2InstanceRegistrationStatus]::CannotRegister) } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } $instanceProfile = New-IAMInstanceProfile -InstanceProfileName $testInstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion $roleTrustPolicyDocument = '{ "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole" } }' $instanceRole = New-IAMRole ` -RoleName $testInstanceProfileName ` -AssumeRolePolicyDocument $roleTrustPolicyDocument ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion Add-IAMRoleToInstanceProfile ` -InstanceProfileName $instanceProfile.InstanceProfileName ` -RoleName $instanceRole.RoleName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion ` | Out-Null # Wait for instance profile to propogate outside IAM Start-Sleep -Seconds 10 $instanceProfile = Get-IAMInstanceProfile -InstanceProfileName $instanceProfile.InstanceProfileName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion try { It 'Should return NotReadyToRegister when instance role does not have access to an encryption key' { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { $testResult = Test-EC2InstanceRegistration -InstanceId $instanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey -AwsRegion $AwsRegion $testResult | Should Be ([EC2InstanceRegistrationStatus]::NotReadyToRegister) } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } $keyId = Save-IAMInstanceProfileKeyAccess try { $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $instanceProfile.InstanceProfileName ` -KeyId $keyId ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion It 'Should return NotReadyToRegister when instance does not have the correct IAM role permissions to use Run Command' { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { $testResult = Test-EC2InstanceRegistration -InstanceId $instanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey -AwsRegion $AwsRegion $testResult | Should Be ([EC2InstanceRegistrationStatus]::NotReadyToRegister) } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } # Positive Tests $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $instanceProfile.InstanceProfileName ` -KeyId $keyId ` -ExistingInstance ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion It 'Should return ReadyToRegister for instance with AWS managed role policy' { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { $testResult = Test-EC2InstanceRegistration -InstanceId $instanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey -AwsRegion $AwsRegion $testResult | Should Be ([EC2InstanceRegistrationStatus]::ReadyToRegister) } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $instanceProfile } It 'Should return ReadyToRegister for instance with inline role policy' { $keyId = Save-IAMInstanceProfileKeyAccess try { $inlineInstanceProfile = New-IAMInstanceProfileForRegistrationInline -InstanceProfileName $testInstanceProfileName -KeyId $keyId try { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $inlineInstanceProfile.InstanceProfileName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { $testResult = Test-EC2InstanceRegistration -InstanceId $instanceId -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey -AwsRegion $AwsRegion $testResult | Should Be ([EC2InstanceRegistrationStatus]::ReadyToRegister) } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $inlineInstanceProfile } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } } Describe 'Register-EC2Instance' { $invalidInstanceId = 'fakeId' $invalidAwsProfile = 'fakeProfileName' # Error tests It 'Should throw an error when invalid AWS credentials profile specified' { {Register-EC2Instance -AzureAutomationAccount $AzureAutomationAccount -AzureAutomationResourceGroup $AzureAutomationResourceGroup -New -AwsProfile $invalidAwsProfile} ` | Should Throw "No AWS credentials" } It 'Should throw an error when no AWS region specified or in defaults' { $savedRegion = Get-DefaultAwsRegion Clear-DefaultAwsRegion {Register-EC2Instance -AzureAutomationAccount $AzureAutomationAccount -AzureAutomationResourceGroup $AzureAutomationResourceGroup -New -AwsAccessKey $AwsAccessKey -AwsSecretKey $AwsSecretKey} ` | Should Throw "No default AWS region. Please specify an AWS region or follow the guide here to set your default region: http://docs.aws.amazon.com/powershell/latest/userguide/pstools-installing-specifying-region.html" if ($savedRegion) { Set-DefaultAwsRegion $savedRegion } } It 'Should throw an error when both instance id and new flag specified' { {Register-EC2Instance -AzureAutomationAccount $AzureAutomationAccount -AzureAutomationResourceGroup $AzureAutomationResourceGroup -InstanceId $invalidInstanceId -New} ` | Should Throw 'Cannot register an existing instance and a new instance at the same time.' } It 'Should throw an error when neither instance id nor new flag specified' { {Register-EC2Instance -AzureAutomationAccount $AzureAutomationAccount -AzureAutomationResourceGroup $AzureAutomationResourceGroup} ` | Should Throw 'Either the new flag or an existing instance id must be specified.' } # Positive tests $keyId = Save-IAMInstanceProfileKeyAccess try { $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $testInstanceProfileName ` -KeyId $keyId ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion try { It 'Should register a new instance' { $instanceReservation = Register-EC2Instance ` -AzureAutomationResourceGroup $AzureAutomationResourceGroup ` -AzureAutomationAccount $AzureAutomationAccount ` -New ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName ` -DscBootstrapperVersion $ExtensionVersion ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { Invoke-WaitForEC2InstanceState -InstanceId $instanceId -DesiredState 'running' -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion Invoke-WaitForEC2InstanceStatus -InstanceId $instanceId -DesiredStatus 'ok' $status = Invoke-WaitForEC2InstanceRegistered -InstanceId $instanceId $status | Should Be ([EC2InstanceRegistrationStatus]::Registered) $azureAutomationId = Get-EC2InstanceAzureAutomationId -InstanceId $instanceId if ($azureAutomationId) { Unregister-AzureRmAutomationDscNode ` -ResourceGroupName $AzureAutomationResourceGroup ` -AutomationAccountName $AzureAutomationAccount ` -Id $azureAutomationId ` -Force ` | Out-Null } } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } $instanceProfile = Set-IAMInstanceProfileForRegistration ` -Name $testInstanceProfileName ` -KeyId $keyId ` -ExistingInstance ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion It 'Should register an existing instance' { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { Invoke-WaitForEC2InstanceState -InstanceId $instanceId -DesiredState 'running' -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion Invoke-WaitForEC2InstanceStatus -InstanceId $instanceId -DesiredStatus 'ok' $instanceReservation = Register-EC2Instance ` -AzureAutomationResourceGroup $AzureAutomationResourceGroup ` -AzureAutomationAccount $AzureAutomationAccount ` -InstanceId $instanceId ` -DscBootstrapperVersion $ExtensionVersion ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion $status = Invoke-WaitForEC2InstanceRegistered -InstanceId $instanceId $status | Should Be ([EC2InstanceRegistrationStatus]::Registered) $azureAutomationId = Get-EC2InstanceAzureAutomationId -InstanceId $instanceId if ($azureAutomationId) { Unregister-AzureRmAutomationDscNode ` -ResourceGroupName $AzureAutomationResourceGroup ` -AutomationAccountName $AzureAutomationAccount ` -Id $azureAutomationId ` -Force ` | Out-Null } } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } It 'Should be able to pipe between Register-EC2Instance and Test-EC2InstanceRegistration' { $instanceReservation = New-EC2Instance ` -ImageId $imageId ` -SecurityGroup $testSecurityGroupName ` -InstanceType $instanceType ` -InstanceProfile_Name $instanceProfile.InstanceProfileName ` -AccessKey $AwsAccessKey ` -SecretKey $AwsSecretKey ` -Region $AwsRegion $instanceId = $instanceReservation.Instances[0].InstanceId try { Invoke-WaitForEC2InstanceState -InstanceId $instanceId -DesiredState 'running' -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion Invoke-WaitForEC2InstanceStatus -InstanceId $instanceId -DesiredStatus 'ok' Register-EC2Instance ` -AzureAutomationResourceGroup $AzureAutomationResourceGroup ` -AzureAutomationAccount $AzureAutomationAccount ` -InstanceId $instanceId ` -DscBootstrapperVersion $ExtensionVersion ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion ` | Test-EC2InstanceRegistration ` -AzureAutomationAccount $AzureAutomationAccount ` -AzureAutomationResourceGroup $AzureAutomationResourceGroup ` -AwsAccessKey $AwsAccessKey ` -AwsSecretKey $AwsSecretKey ` -AwsRegion $AwsRegion ` | Should Be ([EC2InstanceRegistrationStatus]::ReadyToRegister) $status = Invoke-WaitForEC2InstanceRegistered -InstanceId $instanceId $status | Should Be ([EC2InstanceRegistrationStatus]::Registered) $azureAutomationId = Get-EC2InstanceAzureAutomationId -InstanceId $instanceId if ($azureAutomationId) { Unregister-AzureRmAutomationDscNode ` -ResourceGroupName $AzureAutomationResourceGroup ` -AutomationAccountName $AzureAutomationAccount ` -Id $azureAutomationId ` -Force ` | Out-Null } } finally { Stop-EC2Instance -Instance $instanceId -Terminate -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion | Out-Null } } } finally { Remove-IAMInstanceProfileAndRole -InstanceProfile $instanceProfile } } finally { Reset-IAMInstanceProfileKeyAccess -KeyId $keyId } } } finally { # Wait for all instances to terminate before removing security group Start-Sleep -Seconds 60 Remove-EC2SecurityGroup -GroupName $testSecurityGroupName -AccessKey $AwsAccessKey -SecretKey $AwsSecretKey -Region $AwsRegion -Force }
PowerShellCorpus/PowerShellGallery/PoshTwit/0.1.6/PoshTwit-postbuild.ps1
PoshTwit-postbuild.ps1
Import-Module -Name $PSscriptRoot\PoshTwit.psd1; $NuGetApiKey = Read-Host -Prompt 'NuGet API Key'; Publish-Module -Path $PSScriptRoot -NuGetApiKey $NuGetApiKey; Set-PoshTwitToken; Publish-Tweet -Tweet Testing -Verbose;
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchActiveSyncVirtualDirectory.Integration.Tests.ps1
MSFT_xExchActiveSyncVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchActiveSyncVirtualDirectory\MSFT_xExchActiveSyncVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } if ($null -eq $Global:WebCertAuthInstalled) { $webCertAuth = Get-WindowsFeature -Name Web-Cert-Auth if ($webCertAuth.InstallState -ne "Installed") { $Global:WebCertAuthInstalled = $false Write-Verbose "Web-Cert-Auth is not installed. Skipping certificate based authentication tests." } else { $Global:WebCertAuthInstalled = $true } } if ($Global:WebCertAuthInstalled -eq $true) { #Get the thumbprint to use for ActiveSync Cert Based Auth if ($null -eq $Global:CBACertThumbprint) { $Global:CBACertThumbprint = Read-Host -Prompt "Enter the thumbprint of an Exchange certificate to use when enabling Certificate Based Authentication" } } Describe "Test Setting Properties with xExchActiveSyncVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $Global:ShellCredentials AutoCertBasedAuth = $false AutoCertBasedAuthThumbprint = '' BasicAuthEnabled = $true ClientCertAuth = 'Ignore' CompressionEnabled = $false ExternalUrl = "https://$($Global:ServerFqdn)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($Global:ServerFqdn)/Microsoft-Server-ActiveSync" WindowsAuthEnabled = $false } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\Microsoft-Server-ActiveSync (Default Web Site)" BasicAuthEnabled = $true ClientCertAuth = 'Ignore' CompressionEnabled = $false ExternalUrl = "https://$($Global:ServerFqdn)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($Global:ServerFqdn)/Microsoft-Server-ActiveSync" WindowsAuthEnabled = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams.ExternalUrl = '' $testParams.InternalUrl = '' $expectedGetResults.ExternalUrl = $null $expectedGetResults.InternalUrl = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try with empty URL's" -ExpectedGetResults $expectedGetResults if ($Global:WebCertAuthInstalled -eq $true) { $testParams.AutoCertBasedAuth = $true $testParams.AutoCertBasedAuthThumbprint = $Global:CBACertThumbprint $testParams.ClientCertAuth = 'Required' $expectedGetResults.ClientCertAuth = 'Required' Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try enabling certificate based authentication" -ExpectedGetResults $expectedGetResults } #Set Authentication values back to default $testParams = @{ Identity = "$($env:COMPUTERNAME)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthEnabled = $false ClientCertAuth = 'Ignore' WindowsAuthEnabled = $true } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\Microsoft-Server-ActiveSync (Default Web Site)" BasicAuthEnabled = $false ClientCertAuth = 'Ignore' WindowsAuthEnabled = $true } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Reset authentication to default" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchMaintenanceMode.Integration.Tests.ps1
MSFT_xExchMaintenanceMode.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. ###This module also requires that this server is a member of a DAG" Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMaintenanceMode\MSFT_xExchMaintenanceMode.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 function Test-ServerIsOutOfMaintenanceMode { [CmdletBinding()] param() Context "Do additional Get-TargetResource verification after taking server out of maintenance mode" { [Hashtable]$getResult = Get-TargetResource @testParams -Verbose It 'ActiveComponentCount is greater than 0' { $getResult.ActiveComponentCount -gt 0 | Should Be $true } #Verify that all components in the following list are Active. This list comes from an Exchange 2013 CU9 machine with both the CAS and MBX roles. [string[]]$expectedActiveComponentsList = "ServerWideOffline","HubTransport","FrontendTransport","Monitoring","RecoveryActionsEnabled","AutoDiscoverProxy","ActiveSyncProxy","EcpProxy","EwsProxy","ImapProxy","OabProxy","OwaProxy","PopProxy","PushNotificationsProxy","RpsProxy","RwsProxy","RpcProxy","UMCallRouter","XropProxy","HttpProxyAvailabilityGroup","MapiProxy","EdgeTransport","HighAvailability","SharedCache" foreach ($expectedActiveComponent in $expectedActiveComponentsList) { It "Component $($expectedActiveComponent) should be Active" { $getResult.ActiveComponentsList.Contains($expectedActiveComponent) | Should Be $true } } $status = $null $status = Get-MailboxDatabaseCopyStatus -Server $env:COMPUTERNAME | Where-Object {$_.Status -eq "Mounted"} It 'Databases were failed back' { ($null -ne $status) | Should Be $true } } } function EnsureOutOfMaintenanceMode { [CmdletBinding()] param ( [System.Boolean] $WaitBetweenTests = $true ) Write-Verbose "Ensuring server is out of maintenance mode" #Put server in maintenance mode $testParams = @{ Enabled = $false Credential = $Global:ShellCredentials AdditionalComponentsToActivate = "AutoDiscoverProxy","ActiveSyncProxy","EcpProxy","EwsProxy","ImapProxy","OabProxy","OwaProxy","PopProxy","PushNotificationsProxy","RpsProxy","RwsProxy","RpcProxy","UMCallRouter","XropProxy","HttpProxyAvailabilityGroup","MapiProxy","EdgeTransport","HighAvailability","SharedCache" MovePreferredDatabasesBack = $true } Set-TargetResource @testParams -Verbose $inMM = Test-TargetResource @testParams -Verbose if ($inMM -eq $false) { throw "Failed to take server out of maintenance mode" } elseif ($WaitBetweenTests -eq $true) { WaitBetweenTests -Verbose } } function WaitBetweenTests { [CmdletBinding()] param([int]$SleepSeconds = 60) Write-Verbose "Sleeping $($SleepSeconds) between tests." Start-Sleep -Seconds $SleepSeconds } #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Make sure server is a DAG member if ($null -eq $Global:IsDagMember) { GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "Get-MailboxServer","Get-MailboxDatabaseCopyStatus","Get-MailboxDatabase" $mbxServer = Get-MailboxServer $env:COMPUTERNAME [boolean]$Global:IsDagMember = !([string]::IsNullOrEmpty($mbxServer.DatabaseAvailabilityGroup)) } if ($Global:IsDagMember -eq $false) { Write-Verbose "Tests in this file require that this server be a member of a Database Availability Group" return } #Make sure server only has replicated DB's if ($null -eq $Global:HasNonReplicationDBs) { $nonReplicatedDBs = Get-MailboxDatabase -Server $env:COMPUTERNAME -ErrorAction SilentlyContinue | Where-Object {$_.ReplicationType -like "None"} if ($null -ne $nonReplicatedDBs) { $Global:HasNonReplicationDBs = $true } } if ($Global:HasNonReplicationDBs -eq $true) { Write-Verbose "Tests in this file require that all databases on this server must have copies on other DAG members." return } #Get Domain Controller if ($null -eq $Global:DomainController) { [string]$Global:DomainController = Read-Host -Prompt "Enter Domain Controller to use for DC tests" } Write-Verbose "Ensuring server is out of maintenance mode before beginning tests" EnsureOutOfMaintenanceMode Describe "Test Putting a Server in and out of Maintenance Mode" { #Put server in maintenance mode $testParams = @{ Enabled = $true Credential = $Global:ShellCredentials AdditionalComponentsToActivate = "AutoDiscoverProxy","ActiveSyncProxy","EcpProxy","EwsProxy","ImapProxy","OabProxy","OwaProxy","PopProxy","PushNotificationsProxy","RpsProxy","RwsProxy","RpcProxy","UMCallRouter","XropProxy","HttpProxyAvailabilityGroup","MapiProxy","EdgeTransport","HighAvailability","SharedCache" MovePreferredDatabasesBack = $true } $expectedGetResults = @{ Enabled = $true ActiveComponentCount = 2 #Monitoring and RecoveryActionsEnabled should still be Active after this ActiveDBCount = 0 ActiveUMCallCount = 0 ClusterState = "Paused" QueuedMessageCount = 0 } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Put server in maintenance mode" -ExpectedGetResults $expectedGetResults WaitBetweenTests -Verbose #Take server out of maintenance mode $testParams.Enabled = $false $expectedGetResults = @{ Enabled = $false ClusterState = "Up" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Take server out of maintenance mode" -ExpectedGetResults $expectedGetResults Test-ServerIsOutOfMaintenanceMode WaitBetweenTests -Verbose #Test passing in UpgradedServerVersion that is lower than the current server version $testParams = @{ Enabled = $true Credential = $Global:ShellCredentials MovePreferredDatabasesBack = $true UpgradedServerVersion = "15.0.0.0" } $expectedGetResults = @{ Enabled = $false ClusterState = "Up" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try to put server in maintenance mode using UpgradedServerVersion of an older server." -ExpectedGetResults $expectedGetResults WaitBetweenTests -Verbose #Test using Domain Controller switch to put server in maintenance mode $testParams = @{ Enabled = $true Credential = $Global:ShellCredentials MovePreferredDatabasesBack = $true DomainController = $Global:DomainController } $expectedGetResults = @{ Enabled = $true ActiveComponentCount = 2 #Monitoring and RecoveryActionsEnabled should still be Active after this ActiveDBCount = 0 ActiveUMCallCount = 0 ClusterState = "Paused" QueuedMessageCount = 0 } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Put server in maintenance mode using Domain Controller switch" -ExpectedGetResults $expectedGetResults WaitBetweenTests -Verbose #Test using Domain Controller switch to take server out of maintenance mode $testParams.Enabled = $false $expectedGetResults = @{ Enabled = $false ClusterState = "Up" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Take server out of maintenance mode using Domain Controller switch" -ExpectedGetResults $expectedGetResults Test-ServerIsOutOfMaintenanceMode WaitBetweenTests -Verbose #Test SetInactiveComponentsFromAnyRequesterToActive Parameter #First put the server in maintenance mode $testParams = @{ Enabled = $true Credential = $Global:ShellCredentials AdditionalComponentsToActivate = "AutoDiscoverProxy","ActiveSyncProxy","EcpProxy","EwsProxy","ImapProxy","OabProxy","OwaProxy","PopProxy","PushNotificationsProxy","RpsProxy","RwsProxy","RpcProxy","UMCallRouter","XropProxy","HttpProxyAvailabilityGroup","MapiProxy","EdgeTransport","HighAvailability","SharedCache" MovePreferredDatabasesBack = $true SetInactiveComponentsFromAnyRequesterToActive = $false } Set-TargetResource @testParams -Verbose $testResults = Test-TargetResource @testParams -Verbose It 'Server should be in maintenance mode' { $testResults | Should Be $true } if ($testResults -eq $true) { #Manually set a component to Inactive as the HealthApi Set-ServerComponentState -Identity $env:COMPUTERNAME -Component "ImapProxy" -State "Inactive" -Requester "HealthApi" #Do a failed attempt to take server out of maintenance mode $testParams.Enabled = $false Set-TargetResource @testParams -Verbose $testResults = Test-TargetResource @testParams -Verbose It 'Test should fail' { $testResults | Should Be $false } #Now set SetInactiveComponentsFromAnyRequesterToActive to true and try again. This should succeed $testParams.SetInactiveComponentsFromAnyRequesterToActive = $true Set-TargetResource @testParams -Verbose $testResults = Test-TargetResource @testParams -Verbose It 'Test should succeed' { $testResults | Should Be $true } } } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchEcpVirtualDirectory.Integration.Tests.ps1
MSFT_xExchEcpVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchEcpVirtualDirectory\MSFT_xExchEcpVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchEcpVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\ecp (Default Web Site)" Credential = $Global:ShellCredentials #AdfsAuthentication = $false #Don't test AdfsAuthentication changes in dedicated ECP tests, as they have to be done to OWA at the same time BasicAuthentication = $true DigestAuthentication = $false ExternalUrl = "https://$($Global:ServerFqdn)/ecp" FormsAuthentication = $true InternalUrl = "https://$($Global:ServerFqdn)/ecp" WindowsAuthentication = $false } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\ecp (Default Web Site)" BasicAuthentication = $true DigestAuthentication = $false ExternalUrl = "https://$($Global:ServerFqdn)/ecp" FormsAuthentication = $true InternalUrl = "https://$($Global:ServerFqdn)/ecp" WindowsAuthentication = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams = @{ Identity = "$($env:COMPUTERNAME)\ecp (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $false DigestAuthentication = $true ExternalUrl = '' FormsAuthentication = $false InternalUrl = '' WindowsAuthentication = $true } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\ecp (Default Web Site)" BasicAuthentication = $false DigestAuthentication = $true ExternalUrl = $null FormsAuthentication = $false InternalUrl = $null WindowsAuthentication = $true } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try with the opposite of each property value" -ExpectedGetResults $expectedGetResults #Set Authentication values back to default $testParams = @{ Identity = "$($env:COMPUTERNAME)\ecp (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $true DigestAuthentication = $false FormsAuthentication = $true WindowsAuthentication = $false } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\ecp (Default Web Site)" BasicAuthentication = $true DigestAuthentication = $false FormsAuthentication = $true WindowsAuthentication = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Reset authentication to default" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchMailboxServer.Integration.Tests.ps1
MSFT_xExchMailboxServer.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxServer\MSFT_xExchMailboxServer.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Test Setting Properties with xExchMailboxServer" { $serverVersion = GetExchangeVersion #Make sure DB activation is not blocked $testParams = @{ Identity = $env:COMPUTERNAME Credential = $Global:ShellCredentials AutoDatabaseMountDial = 'BestAvailability' CalendarRepairIntervalEndWindow = '15' CalendarRepairLogDirectorySizeLimit = '1GB' CalendarRepairLogEnabled = $false CalendarRepairLogFileAgeLimit = '30.00:00:00' CalendarRepairLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Calendar Repair DSC' CalendarRepairLogSubjectLoggingEnabled = $false CalendarRepairMissingItemFixDisabled = $true CalendarRepairMode = 'ValidateOnly' DatabaseCopyActivationDisabledAndMoveNow = $false DatabaseCopyAutoActivationPolicy = 'Unrestricted' FolderLogForManagedFoldersEnabled = $true ForceGroupMetricsGeneration = $true IsExcludedFromProvisioning = $true JournalingLogForManagedFoldersEnabled = $true LogDirectorySizeLimitForManagedFolders = '10GB' LogFileAgeLimitForManagedFolders = '7.00:00:00' LogFileSizeLimitForManagedFolders = '15MB' LogPathForManagedFolders = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Managed Folder Assistant DSC' MAPIEncryptionRequired = $true MaximumActiveDatabases = '36' MaximumPreferredActiveDatabases = '24' RetentionLogForManagedFoldersEnabled = $false SharingPolicySchedule = 'Sun.11:30 PM-Mon.1:30 AM' SubjectLogForManagedFoldersEnabled = $true } $expectedGetResults = @{ Identity = $env:COMPUTERNAME AutoDatabaseMountDial = 'BestAvailability' CalendarRepairIntervalEndWindow = '15' CalendarRepairLogDirectorySizeLimit = '1GB' CalendarRepairLogEnabled = $false CalendarRepairLogFileAgeLimit = '30.00:00:00' CalendarRepairLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Calendar Repair DSC' CalendarRepairLogSubjectLoggingEnabled = $false CalendarRepairMissingItemFixDisabled = $true CalendarRepairMode = 'ValidateOnly' DatabaseCopyActivationDisabledAndMoveNow = $false DatabaseCopyAutoActivationPolicy = 'Unrestricted' FolderLogForManagedFoldersEnabled = $true ForceGroupMetricsGeneration = $true IsExcludedFromProvisioning = $true JournalingLogForManagedFoldersEnabled = $true LogDirectorySizeLimitForManagedFolders = '10GB' LogFileAgeLimitForManagedFolders = '7.00:00:00' LogFileSizeLimitForManagedFolders = '15MB' LogPathForManagedFolders = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Managed Folder Assistant DSC' MAPIEncryptionRequired = $true MaximumActiveDatabases = '36' MaximumPreferredActiveDatabases = '24' RetentionLogForManagedFoldersEnabled = $false SharingPolicySchedule = 'Sun.11:30 PM-Mon.1:30 AM' SubjectLogForManagedFoldersEnabled = $true } if ($serverVersion -eq "2016") { $testParams.Add("WacDiscoveryEndpoint", "") $expectedGetResults.Add("WacDiscoveryEndpoint", "") } if ($serverVersion -eq "2013") { $testParams.Add('CalendarRepairWorkCycle', '2.00:00:00') $expectedGetResults.Add('CalendarRepairWorkCycle', '2.00:00:00') $testParams.Add('CalendarRepairWorkCycleCheckpoint', '2.00:00:00') $expectedGetResults.Add('CalendarRepairWorkCycleCheckpoint', '2.00:00:00') $testParams.Add('MailboxProcessorWorkCycle', '2.00:00:00') $expectedGetResults.Add('MailboxProcessorWorkCycle', '2.00:00:00') $testParams.Add('ManagedFolderAssistantSchedule', 'Sun.11:30 PM-Mon.1:30 AM') $expectedGetResults.Add('ManagedFolderAssistantSchedule', 'Sun.11:30 PM-Mon.1:30 AM') $testParams.Add('ManagedFolderWorkCycle', '2.00:00:00') $expectedGetResults.Add('ManagedFolderWorkCycle', '2.00:00:00') $testParams.Add('ManagedFolderWorkCycleCheckpoint', '2.00:00:00') $expectedGetResults.Add('ManagedFolderWorkCycleCheckpoint', '2.00:00:00') $testParams.Add('OABGeneratorWorkCycle', '10:00:00') $expectedGetResults.Add('OABGeneratorWorkCycle', '10:00:00') $testParams.Add('OABGeneratorWorkCycleCheckpoint', '10:00:00') $expectedGetResults.Add('OABGeneratorWorkCycleCheckpoint', '10:00:00') $testParams.Add('PublicFolderWorkCycle', '2.00:00:00') $expectedGetResults.Add('PublicFolderWorkCycle', '2.00:00:00') $testParams.Add('PublicFolderWorkCycleCheckpoint', '2.00:00:00') $expectedGetResults.Add('PublicFolderWorkCycleCheckpoint', '2.00:00:00') $testParams.Add('SharingPolicyWorkCycle', '2.00:00:00') $expectedGetResults.Add('SharingPolicyWorkCycle', '2.00:00:00') $testParams.Add('SharingPolicyWorkCycleCheckpoint', '2.00:00:00') $expectedGetResults.Add('SharingPolicyWorkCycleCheckpoint', '2.00:00:00') $testParams.Add('SharingSyncWorkCycle', '05:00:00') $expectedGetResults.Add('SharingSyncWorkCycle', '05:00:00') $testParams.Add('SharingSyncWorkCycleCheckpoint', '05:00:00') $expectedGetResults.Add('SharingSyncWorkCycleCheckpoint', '05:00:00') $testParams.Add('SiteMailboxWorkCycle', '05:00:00') $expectedGetResults.Add('SiteMailboxWorkCycle', '05:00:00') $testParams.Add('SiteMailboxWorkCycleCheckpoint', '05:00:00') $expectedGetResults.Add('SiteMailboxWorkCycleCheckpoint', '05:00:00') $testParams.Add('TopNWorkCycle', '10.00:00:00') $expectedGetResults.Add('TopNWorkCycle', '10.00:00:00') $testParams.Add('TopNWorkCycleCheckpoint', '2.00:00:00') $expectedGetResults.Add('TopNWorkCycleCheckpoint', '2.00:00:00') $testParams.Add('UMReportingWorkCycle', '2.00:00:00') $expectedGetResults.Add('UMReportingWorkCycle', '2.00:00:00') $testParams.Add('UMReportingWorkCycleCheckpoint', '2.00:00:00') $expectedGetResults.Add('UMReportingWorkCycleCheckpoint', '2.00:00:00') } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set non-default values for all properties" -ExpectedGetResults $expectedGetResults #Block DB activation $testParams.DatabaseCopyActivationDisabledAndMoveNow = $true $testParams.DatabaseCopyAutoActivationPolicy = "Blocked" $testParams.MaximumActiveDatabases = "24" $testParams.MaximumPreferredActiveDatabases = "12" $expectedGetResults.DatabaseCopyActivationDisabledAndMoveNow = $true $expectedGetResults.DatabaseCopyAutoActivationPolicy = "Blocked" $expectedGetResults.MaximumActiveDatabases = "24" $expectedGetResults.MaximumPreferredActiveDatabases = "12" if ($serverVersion -eq "2016") { $testParams["WacDiscoveryEndpoint"] = "https://localhost/hosting/discovery" $expectedGetResults["WacDiscoveryEndpoint"] = "https://localhost/hosting/discovery" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Block DB Activation, Set WacDiscoveryEndpoint, and modify MaxDBValues" -ExpectedGetResults $expectedGetResults #Make sure DB activation is not blocked $testParams = @{ Identity = $env:COMPUTERNAME Credential = $Global:ShellCredentials AutoDatabaseMountDial = 'GoodAvailability' CalendarRepairLogDirectorySizeLimit = '500MB' CalendarRepairLogEnabled = $true CalendarRepairLogFileAgeLimit = '10.00:00:00' CalendarRepairLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Calendar Repair' CalendarRepairLogSubjectLoggingEnabled = $true CalendarRepairMissingItemFixDisabled = $false CalendarRepairMode = 'RepairAndValidate' DatabaseCopyActivationDisabledAndMoveNow = $false DatabaseCopyAutoActivationPolicy = 'Unrestricted' FolderLogForManagedFoldersEnabled = $false ForceGroupMetricsGeneration = $false IsExcludedFromProvisioning = $false JournalingLogForManagedFoldersEnabled = $false LogDirectorySizeLimitForManagedFolders = 'Unlimited' LogFileAgeLimitForManagedFolders = '00:00:00' LogFileSizeLimitForManagedFolders = '10MB' LogPathForManagedFolders = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Managed Folder Assistant' MAPIEncryptionRequired = $false MaximumActiveDatabases = '' MaximumPreferredActiveDatabases = '' RetentionLogForManagedFoldersEnabled = $false SharingPolicySchedule = $null SubjectLogForManagedFoldersEnabled = $false } $expectedGetResults = @{ Identity = $env:COMPUTERNAME AutoDatabaseMountDial = 'GoodAvailability' CalendarRepairLogDirectorySizeLimit = '500MB' CalendarRepairLogEnabled = $true CalendarRepairLogFileAgeLimit = '10.00:00:00' CalendarRepairLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Calendar Repair' CalendarRepairLogSubjectLoggingEnabled = $true CalendarRepairMissingItemFixDisabled = $false CalendarRepairMode = 'RepairAndValidate' DatabaseCopyActivationDisabledAndMoveNow = $false DatabaseCopyAutoActivationPolicy = 'Unrestricted' FolderLogForManagedFoldersEnabled = $false ForceGroupMetricsGeneration = $false IsExcludedFromProvisioning = $false JournalingLogForManagedFoldersEnabled = $false LogDirectorySizeLimitForManagedFolders = 'Unlimited' LogFileAgeLimitForManagedFolders = '00:00:00' LogFileSizeLimitForManagedFolders = '10MB' LogPathForManagedFolders = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\Managed Folder Assistant' MAPIEncryptionRequired = $false MaximumActiveDatabases = $null MaximumPreferredActiveDatabases = $null RetentionLogForManagedFoldersEnabled = $false SubjectLogForManagedFoldersEnabled = $false } if ($serverVersion -eq "2016") { $testParams["CalendarRepairIntervalEndWindow"] = '7' $expectedGetResults["CalendarRepairIntervalEndWindow"] = '7' $testParams["WacDiscoveryEndpoint"] = "" $expectedGetResults["WacDiscoveryEndpoint"] = "" } if ($serverVersion -eq "2013") { $testParams["CalendarRepairIntervalEndWindow"] = '30' $expectedGetResults["CalendarRepairIntervalEndWindow"] = '30' $testParams["CalendarRepairWorkCycle"] = '1.00:00:00' $expectedGetResults["CalendarRepairWorkCycle"] = '1.00:00:00' $testParams["CalendarRepairWorkCycleCheckpoint"] = '1.00:00:00' $expectedGetResults["CalendarRepairWorkCycleCheckpoint"] = '1.00:00:00' $testParams["MailboxProcessorWorkCycle"] = '1.00:00:00' $expectedGetResults["MailboxProcessorWorkCycle"] = '1.00:00:00' $testParams["ManagedFolderAssistantSchedule"] = $null $expectedGetResults["ManagedFolderAssistantSchedule"] = $null $testParams["ManagedFolderWorkCycle"] = '1.00:00:00' $expectedGetResults["ManagedFolderWorkCycle"] = '1.00:00:00' $testParams["ManagedFolderWorkCycleCheckpoint"] = '1.00:00:00' $expectedGetResults["ManagedFolderWorkCycleCheckpoint"] = '1.00:00:00' $testParams["OABGeneratorWorkCycle"] = '08:00:00' $expectedGetResults["OABGeneratorWorkCycle"] = '08:00:00' $testParams["OABGeneratorWorkCycleCheckpoint"] = '01:00:00' $expectedGetResults["OABGeneratorWorkCycleCheckpoint"] = '01:00:00' $testParams["PublicFolderWorkCycle"] = '1.00:00:00' $expectedGetResults["PublicFolderWorkCycle"] = '1.00:00:00' $testParams["PublicFolderWorkCycleCheckpoint"] = '1.00:00:00' $expectedGetResults["PublicFolderWorkCycleCheckpoint"] = '1.00:00:00' $testParams["SharingPolicyWorkCycle"] = '1.00:00:00' $expectedGetResults["SharingPolicyWorkCycle"] = '1.00:00:00' $testParams["SharingSyncWorkCycleCheckpoint"] = '1.00:00:00' $expectedGetResults["SharingSyncWorkCycleCheckpoint"] = '1.00:00:00' $testParams["SiteMailboxWorkCycle"] = '06:00:00' $expectedGetResults["SiteMailboxWorkCycle"] = '06:00:00' $testParams["SiteMailboxWorkCycleCheckpoint"] = '06:00:00' $expectedGetResults["SiteMailboxWorkCycleCheckpoint"] = '06:00:00' $testParams["TopNWorkCycle"] = '7.00:00:00' $expectedGetResults["TopNWorkCycle"] = '7.00:00:00' $testParams["TopNWorkCycleCheckpoint"] = '1.00:00:00' $expectedGetResults["TopNWorkCycleCheckpoint"] = '1.00:00:00' $testParams["UMReportingWorkCycle"] = '1.00:00:00' $expectedGetResults["UMReportingWorkCycle"] = '1.00:00:00' $testParams["UMReportingWorkCycleCheckpoint"] = '1.00:00:00' $expectedGetResults["UMReportingWorkCycleCheckpoint"] = '1.00:00:00' } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Reset values to default" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.SharingPolicySchedule -GetResultParameterName "SharingPolicySchedule" -ContextLabel "Verify SharingPolicySchedule" -ItLabel "SharingPolicySchedule should be empty" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchWebServicesVirtualDirectory.Integration.Tests.ps1
MSFT_xExchWebServicesVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchWebServicesVirtualDirectory\MSFT_xExchWebServicesVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchWebServicesVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\EWS (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $false CertificateAuthentication = $false DigestAuthentication = $false ExternalUrl = "http://$($Global:ServerFqdn)/ews/exchange.asmx" InternalNLBBypassUrl = "http://$($Global:ServerFqdn)/ews/exchange.asmx" InternalUrl = "http://$($Global:ServerFqdn)/ews/exchange.asmx" OAuthAuthentication = $false WindowsAuthentication = $true WSSecurityAuthentication = $true } $expectedGetResults = @{ BasicAuthentication = $false CertificateAuthentication = $null DigestAuthentication = $false ExternalUrl = "http://$($Global:ServerFqdn)/ews/exchange.asmx" InternalNLBBypassUrl = "http://$($Global:ServerFqdn)/ews/exchange.asmx" InternalUrl = "http://$($Global:ServerFqdn)/ews/exchange.asmx" OAuthAuthentication = $false WindowsAuthentication = $true WSSecurityAuthentication = $true } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams.ExternalUrl = '' $testParams.InternalUrl = '' $expectedGetResults.ExternalUrl = $null $expectedGetResults.InternalUrl = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try with empty URL's" -ExpectedGetResults $expectedGetResults #Set Authentication values back to default $testParams = @{ Identity = "$($env:COMPUTERNAME)\EWS (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $false DigestAuthentication = $false OAuthAuthentication = $true WindowsAuthentication = $true WSSecurityAuthentication = $true } $expectedGetResults = @{ BasicAuthentication = $false DigestAuthentication = $false OAuthAuthentication = $true WindowsAuthentication = $true WSSecurityAuthentication = $true } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Reset authentication to default" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchOwaVirtualDirectory.Integration.Tests.ps1
MSFT_xExchOwaVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchOwaVirtualDirectory\MSFT_xExchOwaVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } #Get the thumbprint to use for Lync integration if ($null -eq $Global:IMCertThumbprint) { $Global:IMCertThumbprint = Read-Host -Prompt "Enter the thumbprint of an Exchange certificate to use when enabling Lync integration" } Describe "Test Setting Properties with xExchOwaVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\owa (Default Web Site)" Credential = $Global:ShellCredentials #AdfsAuthentication = $false #Don't test AdfsAuthentication changes in dedicated OWA tests, as they have to be done to ECP at the same time BasicAuthentication = $true ChangePasswordEnabled = $true DigestAuthentication = $false ExternalUrl = "https://$($Global:ServerFqdn)/owa" FormsAuthentication = $true InstantMessagingEnabled = $false InstantMessagingCertificateThumbprint = '' InstantMessagingServerName = '' InstantMessagingType = 'None' InternalUrl = "https://$($Global:ServerFqdn)/owa" LogonPagePublicPrivateSelectionEnabled = $true LogonPageLightSelectionEnabled = $true WindowsAuthentication = $false LogonFormat = 'PrincipalName' DefaultDomain = 'contoso.local' } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\owa (Default Web Site)" BasicAuthentication = $true ChangePasswordEnabled = $true DigestAuthentication = $false ExternalUrl = "https://$($Global:ServerFqdn)/owa" FormsAuthentication = $true InstantMessagingEnabled = $false InstantMessagingCertificateThumbprint = '' InstantMessagingServerName = '' InstantMessagingType = 'None' InternalUrl = "https://$($Global:ServerFqdn)/owa" LogonPagePublicPrivateSelectionEnabled = $true LogonPageLightSelectionEnabled = $true WindowsAuthentication = $false LogonFormat = 'PrincipalName' DefaultDomain = 'contoso.local' } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams = @{ Identity = "$($env:COMPUTERNAME)\owa (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $false ChangePasswordEnabled = $false DigestAuthentication = $true ExternalUrl = '' FormsAuthentication = $false InstantMessagingEnabled = $true InstantMessagingCertificateThumbprint = $Global:IMCertThumbprint InstantMessagingServerName = $env:COMPUTERNAME InstantMessagingType = 'Ocs' InternalUrl = '' LogonPagePublicPrivateSelectionEnabled = $false LogonPageLightSelectionEnabled = $false WindowsAuthentication = $true LogonFormat = 'FullDomain' DefaultDomain = '' } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\owa (Default Web Site)" BasicAuthentication = $false ChangePasswordEnabled = $false DigestAuthentication = $true ExternalUrl = $null FormsAuthentication = $false InstantMessagingEnabled = $true InstantMessagingCertificateThumbprint = $Global:IMCertThumbprint InstantMessagingServerName = $env:COMPUTERNAME InstantMessagingType = 'Ocs' InternalUrl = $null LogonPagePublicPrivateSelectionEnabled = $false LogonPageLightSelectionEnabled = $false WindowsAuthentication = $true LogonFormat = 'FullDomain' DefaultDomain = '' } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try with the opposite of each property value" -ExpectedGetResults $expectedGetResults #Set Authentication values back to default $testParams = @{ Identity = "$($env:COMPUTERNAME)\owa (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $true DigestAuthentication = $false FormsAuthentication = $true WindowsAuthentication = $false } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\owa (Default Web Site)" BasicAuthentication = $true DigestAuthentication = $false FormsAuthentication = $true WindowsAuthentication = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Reset authentication to default" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchUMService.Integration.Tests.ps1
MSFT_xExchUMService.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchUMService\MSFT_xExchUMService.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete $testUMDPName = "UMDP (DSC Test)" if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Check if the test UM Dial Plan exists, and if not, create it GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "*-UMDialPlan" if ($null -eq (Get-UMDialPlan -Identity $testUMDPName -ErrorAction SilentlyContinue)) { Write-Verbose "Test UM Dial Plan does not exist. Creating UM Dial Plan with name '$testUMDPName'." $testUMDP = New-UMDialPlan -Name $testUMDPName -URIType SipName -CountryOrRegionCode 1 -NumberOfDigitsInExtension 10 if ($null -eq $testUMDP) { throw "Failed to create test UM Dial Plan." } } Describe "Test Setting Properties with xExchUMService" { $testParams = @{ Identity = $env:COMPUTERNAME Credential = $Global:ShellCredentials UMStartupMode = "TLS" DialPlans = @() } $expectedGetResults = @{ Identity = $env:COMPUTERNAME UMStartupMode = "TLS" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.DialPlans -GetResultParameterName "DialPlans" -ContextLabel "Verify DialPlans" -ItLabel "DialPlans should be empty" $testParams.UMStartupMode = "Dual" $testParams.DialPlans = @($testUMDPName) $expectedGetResults.UMStartupMode = "Dual" $expectedGetResults.DialPlans = @($testUMDPName) Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Change some parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.DialPlans -GetResultParameterName "DialPlans" -ContextLabel "Verify DialPlans" -ItLabel "DialPlans should contain a value" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/xExchangeConfigHelper.Unit.Tests.ps1
xExchangeConfigHelper.Unit.Tests.ps1
Import-Module $PSScriptRoot\..\Examples\HelperScripts\ExchangeConfigHelper.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Performs common tests against the specified MailboxDatabases.csv file function Test-MailboxDatabasesCsv { [CmdletBinding()] param([string]$MailboxDatabasesCsvPath, [string]$ServerNameInCsv, [Hashtable]$DbNameReplacements, [string]$ContextLabel) Context $ContextLabel { $dbList = $null $dbList = DBListFromMailboxDatabasesCsv -MailboxDatabasesCsvPath $MailboxDatabasesCsvPath -ServerNameInCsv $ServerNameInCsv -DbNameReplacements $DbNameReplacements It "DB List Should Not Be Null" { ($null -ne $dbList) | Should Be $true } if ($null -ne $dbList) { It "DB List Should Contain Ten Members" { ($dbList.Count -eq 10) | Should Be $true } It "DBFilePath Should Not Be Null Or Empty" { ([string]::IsNullOrEmpty($dbList[0].DBFilePath)) | Should Be $false } } } } [string]$mailboxDatabasesCsv66 = "$($PSScriptRoot)\Data\MailboxDatabases v6.6.csv" [string]$mailboxDatabasesCsv = "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.FullName)\Examples\ConfigureDatabases-FromCalculator\CalculatorAndScripts\MailboxDatabases.csv" [string]$serverNameInCsv = 'SRV-nn-01' [Hashtable]$dbNameReplacements = @{"-nn-" = "-01-"} Describe "Test DBListFromMailboxDatabasesCsv" { Test-MailboxDatabasesCsv -MailboxDatabasesCsvPath $mailboxDatabasesCsv66 -ServerNameInCsv $serverNameInCsv -DbNameReplacements $dbNameReplacements -ContextLabel 'Test MailboxDatabases.csv v6.6' Test-MailboxDatabasesCsv -MailboxDatabasesCsvPath $mailboxDatabasesCsv -ServerNameInCsv $serverNameInCsv -DbNameReplacements $dbNameReplacements -ContextLabel 'Test MailboxDatabases.csv Current' }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchClientAccessServer.Integration.Tests.ps1
MSFT_xExchClientAccessServer.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchClientAccessServer\MSFT_xExchClientAccessServer.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchClientAccessServer" { #Do standard URL and scope tests $testParams = @{ Identity = $env:COMPUTERNAME Credential = $Global:ShellCredentials AutoDiscoverServiceInternalUri = "https://$($Global:ServerFqdn)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = 'Site1' } $expectedGetResults = @{ Identity = $env:COMPUTERNAME AutoDiscoverServiceInternalUri = "https://$($Global:ServerFqdn)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = 'Site1' } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set autod url and site scope" -ExpectedGetResults $expectedGetResults #Now set the URL to empty $testParams.AutoDiscoverServiceInternalUri = '' $expectedGetResults.AutoDiscoverServiceInternalUri = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set url to empty" -ExpectedGetResults $expectedGetResults #Now try multiple sites in the site scope $testParams.AutoDiscoverSiteScope = 'Site1','Site2' $expectedGetResults = @{} Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set site scope to multi value" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.AutoDiscoverSiteScope -GetResultParameterName "AutoDiscoverSiteScope" -ContextLabel "Verify AutoDiscoverSiteScope" -ItLabel "AutoDiscoverSiteScope should contain two values" #Now set the site scope to $null $testParams.AutoDiscoverSiteScope = $null $expectedGetResults = @{} Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set site scope to null" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.AutoDiscoverSiteScope -GetResultParameterName "AutoDiscoverSiteScope" -ContextLabel "Verify AutoDiscoverSiteScope" -ItLabel "AutoDiscoverSiteScope should be empty" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchReceiveConnector.Integration.Tests.ps1
MSFT_xExchReceiveConnector.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchReceiveConnector\MSFT_xExchReceiveConnector.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Set and modify a Receive Connector" { #Set configuration with default values $testParams = @{ Identity = "$($env:computername)\AnonymousRelay $($env:computername)" Credential = $Global:ShellCredentials Ensure = 'Present' ExtendedRightAllowEntries = $(New-CimInstance -ClassName MSFT_KeyValuePair -Namespace root/microsoft/Windows/DesiredStateConfiguration -Property @{Key = 'NT AUTHORITY\ANONYMOUS LOGON'; ` Value = 'Ms-Exch-SMTP-Accept-Any-Recipient,ms-Exch-Bypass-Anti-Spam'} -ClientOnly) AdvertiseClientSettings = $false AuthMechanism = 'Tls', 'ExternalAuthoritative' Banner = '220 Pester' BareLinefeedRejectionEnabled = $false BinaryMimeEnabled = $true Bindings = "192.168.0.100:25" ChunkingEnabled = $true Comment = 'Connector for relaying' ConnectionInactivityTimeout = '00:05:00' ConnectionTimeout = '00:10:00' DefaultDomain = '' #DomainController = '' DeliveryStatusNotificationEnabled = $true DomainSecureEnabled = $false EightBitMimeEnabled = $true EnableAuthGSSAPI = $false Enabled = $true EnhancedStatusCodesEnabled = $true ExtendedProtectionPolicy = 'none' Fqdn = "$($env:computername).pester.com" LongAddressesEnabled = $false MaxAcknowledgementDelay = '00:00:00' MaxHeaderSize = '128KB' MaxHopCount = '60' MaxInboundConnection = '5000' MaxInboundConnectionPercentagePerSource = '100' MaxInboundConnectionPerSource = '50' MaxLocalHopCount = '12' MaxLogonFailures = '3' MaxMessageSize = '35MB' MaxProtocolErrors = '5' MaxRecipientsPerMessage = '5000' MessageRateLimit = 'Unlimited' MessageRateSource = 'IPAddress' OrarEnabled = $false PermissionGroups = 'AnonymousUsers','ExchangeServers' PipeliningEnabled = $true ProtocolLoggingLevel = 'Verbose' RemoteIPRanges = '192.16.7.99' RequireEHLODomain = $false RequireTLS = $false ServiceDiscoveryFqdn = '' SizeEnabled = 'EnabledwithoutValue' SuppressXAnonymousTls = $false TarpitInterval = '00:00:00' TlsCertificateName = $null TlsDomainCapabilities = 'contoso.com:AcceptOorgProtocol' TransportRole = 'FrontendTransport' Usage = 'Custom' } $expectedGetResults = @{ ExtendedRightAllowEntries = "NT AUTHORITY\ANONYMOUS LOGON=Ms-Exch-SMTP-Accept-Any-Recipient,ms-Exch-Bypass-Anti-Spam" AdvertiseClientSettings = $false AuthMechanism = 'Tls', 'ExternalAuthoritative' Banner = '220 Pester' BareLinefeedRejectionEnabled = $false BinaryMimeEnabled = $true Bindings = "192.168.0.100:25" ChunkingEnabled = $true Comment = 'Connector for relaying' ConnectionInactivityTimeout = '00:05:00' ConnectionTimeout = '00:10:00' DefaultDomain = $null #DomainController = '' DeliveryStatusNotificationEnabled = $true DomainSecureEnabled = $false EightBitMimeEnabled = $true EnableAuthGSSAPI = $false Enabled = $true EnhancedStatusCodesEnabled = $true ExtendedProtectionPolicy = 'none' Fqdn = "$($env:computername).pester.com" LongAddressesEnabled = $false MaxAcknowledgementDelay = '00:00:00' MaxHeaderSize = '128KB' MaxHopCount = '60' MaxInboundConnection = '5000' MaxInboundConnectionPercentagePerSource = '100' MaxInboundConnectionPerSource = '50' MaxLocalHopCount = '12' MaxLogonFailures = '3' MaxMessageSize = '35MB' MaxProtocolErrors = '5' MaxRecipientsPerMessage = '5000' MessageRateLimit = 'Unlimited' MessageRateSource = 'IPAddress' OrarEnabled = $false PermissionGroups = 'AnonymousUsers','ExchangeServers','Custom' PipeliningEnabled = $true ProtocolLoggingLevel = 'Verbose' RemoteIPRanges = '192.16.7.99' RequireEHLODomain = $false RequireTLS = $false ServiceDiscoveryFqdn = $null SizeEnabled = 'EnabledwithoutValue' SuppressXAnonymousTls = $false TarpitInterval = '00:00:00' TlsCertificateName = $null TlsDomainCapabilities = 'contoso.com:AcceptOorgProtocol' TransportRole = 'FrontendTransport' } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Create Receive Connector" -ExpectedGetResults $expectedGetResults #modify configuration $testParams.ExtendedRightDenyEntries = $(New-CimInstance -ClassName MSFT_KeyValuePair -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{Key = 'Domain Users'; Value = 'ms-Exch-Bypass-Anti-Spam'} -ClientOnly) $expectedGetResults.ExtendedRightDenyEntries = "Domain Users=ms-Exch-Bypass-Anti-Spam" Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Modify Receive Connector" -ExpectedGetResults $expectedGetResults #modify configuration $testParams.Ensure = 'Absent' $expectedGetResults = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Remove Receive Connector" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchTransportService.Integration.Tests.ps1
MSFT_xExchTransportService.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchTransportService\MSFT_xExchTransportService.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Set and modify Transport Service configuration" { #Set configuration with default values $testParams = @{ Identity = $env:computername Credential = $Global:ShellCredentials AllowServiceRestart = $true ActiveUserStatisticsLogMaxAge = '30.00:00:00' ActiveUserStatisticsLogMaxDirectorySize = '250MB' ActiveUserStatisticsLogMaxFileSize = '10MB' ActiveUserStatisticsLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ActiveUsersStats' AgentLogEnabled = $true AgentLogMaxAge = '7.00:00:00' AgentLogMaxDirectorySize = '250MB' AgentLogMaxFileSize = '10MB' AgentLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\AgentLog' ConnectivityLogEnabled = $true ConnectivityLogMaxAge = '30.00:00:00' ConnectivityLogMaxDirectorySize = '1000MB' ConnectivityLogMaxFileSize = '10MB' ConnectivityLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\Connectivity' ContentConversionTracingEnabled = $false DelayNotificationTimeout = '04:00:00' DnsLogEnabled = $false DnsLogMaxAge = '7.00:00:00' DnsLogMaxDirectorySize = '100 MB' DnsLogMaxFileSize = '10 MB' DnsLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\DNS' ExternalDNSAdapterEnabled = $true ExternalDNSAdapterGuid = '00000000-0000-0000-0000-000000000000' ExternalDNSProtocolOption = 'any' ExternalDNSServers = '' ExternalIPAddress = '' InternalDNSAdapterEnabled = $true InternalDNSAdapterGuid = '00000000-0000-0000-0000-000000000000' InternalDNSProtocolOption = 'any' InternalDNSServers = '' IntraOrgConnectorProtocolLoggingLevel = 'none' IntraOrgConnectorSmtpMaxMessagesPerConnection = '20' IrmLogEnabled = $true IrmLogMaxAge = '30.00:00:00' IrmLogMaxDirectorySize = '250MB' IrmLogMaxFileSize = '10MB' IrmLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\IRMLogs' MaxConcurrentMailboxDeliveries = '20' MaxConcurrentMailboxSubmissions = '20' MaxConnectionRatePerMinute = '1200' MaxOutboundConnections = '1000' MaxPerDomainOutboundConnections = '20' MessageExpirationTimeout = '2.00:00:00' MessageRetryInterval = '00:15:00' MessageTrackingLogEnabled = $true MessageTrackingLogMaxAge = '30.00:00:00' MessageTrackingLogMaxDirectorySize = '1000MB' MessageTrackingLogMaxFileSize = '10 MB' MessageTrackingLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\MessageTracking' MessageTrackingLogSubjectLoggingEnabled = $true OutboundConnectionFailureRetryInterval = '00:10:00' PickupDirectoryMaxHeaderSize = '64 KB' PickupDirectoryMaxMessagesPerMinute = '100' PickupDirectoryMaxRecipientsPerMessage = '100' PickupDirectoryPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Pickup' PipelineTracingEnabled = $false PipelineTracingPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\PipelineTracing' PipelineTracingSenderAddress = '' PoisonMessageDetectionEnabled = $true PoisonThreshold = '2' QueueLogMaxAge = '7.00:00:00' QueueLogMaxDirectorySize = '200MB' QueueLogMaxFileSize = '10MB' QueueLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\QueueViewer' QueueMaxIdleTime = '00:03:00' ReceiveProtocolLogMaxAge = '30.00:00:00' ReceiveProtocolLogMaxDirectorySize = '250MB' ReceiveProtocolLogMaxFileSize = '10 MB' ReceiveProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpReceive' RecipientValidationCacheEnabled = $false ReplayDirectoryPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Replay' RootDropDirectoryPath = '' RoutingTableLogMaxAge = '7.00:00:00' RoutingTableLogMaxDirectorySize = '50 MB' RoutingTableLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\Routing' SendProtocolLogMaxAge = '30.00:00:00' SendProtocolLogMaxDirectorySize = '250MB' SendProtocolLogMaxFileSize = '10MB' SendProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpSend' ServerStatisticsLogMaxAge = '30.00:00:00' ServerStatisticsLogMaxDirectorySize = '250MB' ServerStatisticsLogMaxFileSize = '10 MB' ServerStatisticsLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ServerStats' TransientFailureRetryCount = '6' TransientFailureRetryInterval = '00:05:00' UseDowngradedExchangeServerAuth = $false } $expectedGetResults = @{ ActiveUserStatisticsLogMaxAge = '30.00:00:00' ActiveUserStatisticsLogMaxDirectorySize = '250MB' ActiveUserStatisticsLogMaxFileSize = '10MB' ActiveUserStatisticsLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ActiveUsersStats' AgentLogEnabled = $true AgentLogMaxAge = '7.00:00:00' AgentLogMaxDirectorySize = '250MB' AgentLogMaxFileSize = '10MB' AgentLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\AgentLog' ConnectivityLogEnabled = $true ConnectivityLogMaxAge = '30.00:00:00' ConnectivityLogMaxDirectorySize = '1000MB' ConnectivityLogMaxFileSize = '10MB' ConnectivityLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\Connectivity' ContentConversionTracingEnabled = $false DelayNotificationTimeout = '04:00:00' DnsLogEnabled = $false DnsLogMaxAge = '7.00:00:00' DnsLogMaxDirectorySize = '100 MB' DnsLogMaxFileSize = '10 MB' DnsLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\DNS' ExternalDNSAdapterEnabled = $true ExternalDNSAdapterGuid = '00000000-0000-0000-0000-000000000000' ExternalDNSProtocolOption = 'any' ExternalDNSServers = $null ExternalIPAddress = $null InternalDNSAdapterEnabled = $true InternalDNSAdapterGuid = '00000000-0000-0000-0000-000000000000' InternalDNSProtocolOption = 'any' InternalDNSServers = $null IntraOrgConnectorProtocolLoggingLevel = 'none' IntraOrgConnectorSmtpMaxMessagesPerConnection = '20' IrmLogEnabled = $true IrmLogMaxAge = '30.00:00:00' IrmLogMaxDirectorySize = '250MB' IrmLogMaxFileSize = '10MB' IrmLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\Logging\IRMLogs' MaxConcurrentMailboxDeliveries = '20' MaxConcurrentMailboxSubmissions = '20' MaxConnectionRatePerMinute = '1200' MaxOutboundConnections = '1000' MaxPerDomainOutboundConnections = '20' MessageExpirationTimeout = '2.00:00:00' MessageRetryInterval = '00:15:00' MessageTrackingLogEnabled = $true MessageTrackingLogMaxAge = '30.00:00:00' MessageTrackingLogMaxDirectorySize = '1000MB' MessageTrackingLogMaxFileSize = '10 MB' MessageTrackingLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\MessageTracking' MessageTrackingLogSubjectLoggingEnabled = $true OutboundConnectionFailureRetryInterval = '00:10:00' PickupDirectoryMaxHeaderSize = '64 KB' PickupDirectoryMaxMessagesPerMinute = '100' PickupDirectoryMaxRecipientsPerMessage = '100' PickupDirectoryPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Pickup' PipelineTracingEnabled = $false PipelineTracingPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\PipelineTracing' PipelineTracingSenderAddress = $null PoisonMessageDetectionEnabled = $true PoisonThreshold = '2' QueueLogMaxAge = '7.00:00:00' QueueLogMaxDirectorySize = '200MB' QueueLogMaxFileSize = '10MB' QueueLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\QueueViewer' QueueMaxIdleTime = '00:03:00' ReceiveProtocolLogMaxAge = '30.00:00:00' ReceiveProtocolLogMaxDirectorySize = '250MB' ReceiveProtocolLogMaxFileSize = '10 MB' ReceiveProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpReceive' RecipientValidationCacheEnabled = $false ReplayDirectoryPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Replay' RootDropDirectoryPath = '' RoutingTableLogMaxAge = '7.00:00:00' RoutingTableLogMaxDirectorySize = '50 MB' RoutingTableLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\Routing' SendProtocolLogMaxAge = '30.00:00:00' SendProtocolLogMaxDirectorySize = '250 MB' SendProtocolLogMaxFileSize = '10MB' SendProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpSend' ServerStatisticsLogMaxAge = '30.00:00:00' ServerStatisticsLogMaxDirectorySize = '250MB' ServerStatisticsLogMaxFileSize = '10 MB' ServerStatisticsLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ServerStats' TransientFailureRetryCount = '6' TransientFailureRetryInterval = '00:05:00' UseDowngradedExchangeServerAuth = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set default Transport Service configuration" -ExpectedGetResults $expectedGetResults #modify configuration $testParams.InternalDNSServers = '192.168.1.10' $testParams.ExternalDNSServers = '10.1.1.10' $testParams.PipelineTracingSenderAddress = 'john.doe@contoso.com' $expectedGetResults.InternalDNSServers = '192.168.1.10' $expectedGetResults.ExternalDNSServers = '10.1.1.10' $expectedGetResults.PipelineTracingSenderAddress = 'john.doe@contoso.com' Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Modify Transport Service configuration" -ExpectedGetResults $expectedGetResults #modify configuration $testParams.InternalDNSServers = '' $testParams.ExternalDNSServers = '' $testParams.PipelineTracingSenderAddress = '' $expectedGetResults.InternalDNSServers = $null $expectedGetResults.ExternalDNSServers = $null $expectedGetResults.PipelineTracingSenderAddress = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Revert Transport Service configuration" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchOabVirtualDirectory.Integration.Tests.ps1
MSFT_xExchOabVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchOabVirtualDirectory\MSFT_xExchOabVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete $testOabName = "Offline Address Book (DSC Test)" if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } #Check if the test OAB exists, and if not, create it GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "*-OfflineAddressBook" if ($null -eq (Get-OfflineAddressBook -Identity $testOabName -ErrorAction SilentlyContinue)) { Write-Verbose "Test OAB does not exist. Creating OAB with name '$testOabName'." $testOab = New-OfflineAddressBook -Name $testOabName -AddressLists \ if ($null -eq $testOab) { throw "Failed to create test OAB." } } Describe "Test Setting Properties with xExchOabVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\OAB (Default Web Site)" Credential = $Global:ShellCredentials OABsToDistribute = $testOabName BasicAuthentication = $false ExtendedProtectionFlags = "Proxy","ProxyCoHosting" ExtendedProtectionSPNList = @() ExtendedProtectionTokenChecking = "Allow" InternalUrl = "http://$($Global:ServerFqdn)/OAB" ExternalUrl = "" RequireSSL = $false WindowsAuthentication = $true PollInterval = 481 } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\OAB (Default Web Site)" BasicAuthentication = $false ExtendedProtectionTokenChecking = "Allow" InternalUrl = "http://$($Global:ServerFqdn)/OAB" ExternalUrl = $null RequireSSL = $false WindowsAuthentication = $true PollInterval = 481 } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExtendedProtectionFlags -GetResultParameterName "ExtendedProtectionFlags" -ContextLabel "Verify ExtendedProtectionFlags" -ItLabel "ExtendedProtectionFlags should contain two values" Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExtendedProtectionSPNList -GetResultParameterName "ExtendedProtectionSPNList" -ContextLabel "Verify ExtendedProtectionSPNList" -ItLabel "ExtendedProtectionSPNList should be empty" Test-Array2ContainsArray1 -TestParams $testParams -DesiredArrayContents $testParams.OABsToDistribute -GetResultParameterName "OABsToDistribute" -ContextLabel "Verify OABsToDistribute" -ItLabel "OABsToDistribute contains an OAB" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchEventLogLevel.Integration.Tests.ps1
MSFT_xExchEventLogLevel.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchEventLogLevel\MSFT_xExchEventLogLevel.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Test Enabling and Disabling Event Log Levels" { #Set event log level to high $testParams = @{ Identity = "MSExchangeTransport\DSN" Level = "High" Credential = $Global:ShellCredentials } $expectedGetResults = @{ Level = "High" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set MSExchangeTransport\DSN to High" -ExpectedGetResults $expectedGetResults #Set event log level to lowest $testParams.Level = "Lowest" $expectedGetResults.Level = "Lowest" Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set MSExchangeTransport\DSN to Lowest" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchDatabaseAvailabilityGroup.Integration.Tests.ps1
MSFT_xExchDatabaseAvailabilityGroup.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. ###This module has the following additional requirements; ### * Requires that the ActiveDirectory module is installed ### * Requires that the DAG computer account has been precreated ### * Requires that the Failover-Clustering feature has been installed, and the machine has since been rebooted Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchDatabaseAvailabilityGroup\MSFT_xExchDatabaseAvailabilityGroup.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Removes the test DAG if it exists, and any associated databases function PrepTestDAG { [CmdletBinding()] param ( [string] $TestServerName1, [string] $TestServerName2, [string] $TestDAGName, [string] $TestDBName ) Write-Verbose "Cleaning up test DAG and related resources" $secondServerSpecified = (([String]::IsNullOrEmpty($TestServerName2)) -eq $false) GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "*-MailboxDatabase","*-DatabaseAvailabilityGroup","Remove-DatabaseAvailabilityGroupServer","Get-MailboxDatabaseCopyStatus","Remove-MailboxDatabaseCopy" $existingDB = Get-MailboxDatabase -Identity "$($TestDBName)" -Status -ErrorAction SilentlyContinue #First remove the test database copies if ($null -ne $existingDB) { Get-MailboxDatabaseCopyStatus -Identity "$($TestDBName)" | Where-Object {$existingDB.MountedOnServer.ToLower().Contains($_.MailboxServer.ToLower()) -eq $false} | Remove-MailboxDatabaseCopy -Confirm:$false } #Now remove the actual DB's Get-MailboxDatabase | Where-Object {$_.Name -like "$($TestDBName)"} | Remove-MailboxDatabase -Confirm:$false #Remove the files Get-ChildItem -LiteralPath "\\$($TestServerName1)\c`$\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue if ($secondServerSpecified) { Get-ChildItem -LiteralPath "\\$($TestServerName2)\c`$\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue } #Last remove the test DAG $dag = Get-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -ErrorAction SilentlyContinue if ($null -ne $dag) { Set-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -DatacenterActivationMode Off foreach ($server in $dag.Servers) { Remove-DatabaseAvailabilityGroupServer -MailboxServer "$($server.Name)" -Identity "$($TestDAGName)" -Confirm:$false } Remove-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -Confirm:$false } if ($null -ne (Get-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -ErrorAction SilentlyContinue)) { throw "Failed to remove test DAG" } #Disable the DAG computer account $compAccount = Get-ADComputer -Identity $TestDAGName -ErrorAction SilentlyContinue if ($null -ne $compAccount -and $compAccount.Enabled -eq $true) { $compAccount | Disable-ADAccount } Write-Verbose "Finished cleaning up test DAG and related resources" } $adModule = Get-Module -ListAvailable ActiveDirectory -ErrorAction SilentlyContinue if ($null -ne $adModule) { if ($null -eq $Global:DAGName) { $Global:DAGName = Read-Host -Prompt "Enter the name of the DAG to use for testing" } $compAccount = Get-ADComputer -Identity $Global:DAGName -ErrorAction SilentlyContinue if ($null -ne $compAccount) { #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete [string]$Global:TestDBName = "TestDAGDB1" if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } if ($null -eq $Global:SecondDAGMember) { $Global:SecondDAGMember = Read-Host -Prompt "Enter the host name of the second DAG member to use for testing, or press ENTER to skip." #If they didn't enter anything, set to an empty string so we don't prompt again on a re-run of the test if ($null -eq $Global:SecondDAGMember) { $Global:SecondDAGMember = "" } } while (([String]::IsNullOrEmpty($Global:Witness1))) { $Global:Witness1 = Read-Host -Prompt "Enter the FQDN of the first File Share Witness for testing" } #Allow for the second witness to not be specified if ($null -eq $Global:Witness2) { $Global:Witness2 = Read-Host -Prompt "Enter the FQDN of the second File Share Witness for testing, or press ENTER to skip." #If they didn't enter anything, set to an empty string so we don't prompt again on a re-run of the test if ($null -eq $Global:Witness2) { $Global:Witness2 = "" } } #Remove the existing DAG PrepTestDAG -TestServerName1 $env:COMPUTERNAME -TestServerName2 $Global:SecondDAGMember -TestDAGName $Global:DAGName -TestDBName $Global:TestDBName Describe "Test Creating and Modifying a DAG, adding DAG members, creating a DAG database, and adding database copies" { #Create a new DAG $dagTestParams = @{ Name = $Global:DAGName Credential = $Global:ShellCredentials AutoDagAutoReseedEnabled = $true AutoDagDatabaseCopiesPerDatabase = 2 AutoDagDatabaseCopiesPerVolume = 2 AutoDagDatabasesRootFolderPath = "C:\ExchangeDatabases" AutoDagDiskReclaimerEnabled = $true AutoDagTotalNumberOfServers = 2 AutoDagTotalNumberOfDatabases = 2 AutoDagVolumesRootFolderPath = "C:\ExchangeVolumes" DatabaseAvailabilityGroupIpAddresses = "192.168.1.99","192.168.2.99" DatacenterActivationMode = "DagOnly" ManualDagNetworkConfiguration = $true NetworkCompression = "Enabled" NetworkEncryption = "InterSubnetOnly" ReplayLagManagerEnabled = $true SkipDagValidation = $true WitnessDirectory = "C:\FSW" WitnessServer = $Global:Witness1 } #Skip checking DatacenterActivationMode until we have DAG members $dagExpectedGetResults = @{ Name = $Global:DAGName AutoDagAutoReseedEnabled = $true AutoDagDatabaseCopiesPerDatabase = 2 AutoDagDatabaseCopiesPerVolume = 2 AutoDagDatabasesRootFolderPath = "C:\ExchangeDatabases" AutoDagDiskReclaimerEnabled = $true AutoDagTotalNumberOfServers = 2 AutoDagTotalNumberOfDatabases = 2 AutoDagVolumesRootFolderPath = "C:\ExchangeVolumes" ManualDagNetworkConfiguration = $true NetworkCompression = "Enabled" NetworkEncryption = "InterSubnetOnly" ReplayLagManagerEnabled = $true WitnessDirectory = "C:\FSW" WitnessServer = $Global:Witness1 } if (!([String]::IsNullOrEmpty($Global:Witness2))) { $dagTestParams.Add("AlternateWitnessServer", $Global:Witness2) $dagTestParams.Add("AlternateWitnessDirectory", "C:\FSW") $dagExpectedGetResults.Add("AlternateWitnessServer", $Global:Witness2) $dagExpectedGetResults.Add("AlternateWitnessDirectory", "C:\FSW") } $serverVersion = GetExchangeVersion if ($serverVersion -eq "2016") { $dagTestParams.Add("FileSystem", "ReFS") $dagTestParams.Add("AutoDagAutoRedistributeEnabled", $true) $dagTestParams.Add("PreferenceMoveFrequency", "$(([System.Threading.Timeout]::InfiniteTimeSpan).ToString())") $dagExpectedGetResults.Add("FileSystem", "ReFS") $dagExpectedGetResults.Add("AutoDagAutoRedistributeEnabled", $true) $dagExpectedGetResults.Add("PreferenceMoveFrequency", "$(([System.Threading.Timeout]::InfiniteTimeSpan).ToString())") } Test-TargetResourceFunctionality -Params $dagTestParams -ContextLabel "Create the test DAG" -ExpectedGetResults $dagExpectedGetResults Test-ArrayContentsEqual -TestParams $dagTestParams -DesiredArrayContents $dagTestParams.DatabaseAvailabilityGroupIpAddresses -GetResultParameterName "DatabaseAvailabilityGroupIpAddresses" -ContextLabel "Verify DatabaseAvailabilityGroupIpAddresses" -ItLabel "DatabaseAvailabilityGroupIpAddresses should contain two values" #Add this server as a DAG member Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchDatabaseAvailabilityGroupMember\MSFT_xExchDatabaseAvailabilityGroupMember.psm1 $dagMemberTestParams = @{ MailboxServer = $env:COMPUTERNAME Credential = $Global:ShellCredentials DAGName = $Global:DAGName SkipDagValidation = $true } $dagMemberExpectedGetResults = @{ MailboxServer = $env:COMPUTERNAME DAGName = $Global:DAGName } Test-TargetResourceFunctionality -Params $dagMemberTestParams -ContextLabel "Add first member to the test DAG" -ExpectedGetResults $dagMemberExpectedGetResults #Do second DAG member tests if a second member was specified if (([String]::IsNullOrEmpty($Global:SecondDAGMember)) -eq $false) { #Add second DAG member $dagMemberTestParams = @{ MailboxServer = $Global:SecondDAGMember Credential = $Global:ShellCredentials DAGName = $Global:DAGName SkipDagValidation = $true } $dagMemberExpectedGetResults = @{ MailboxServer = $Global:SecondDAGMember DAGName = $Global:DAGName } Test-TargetResourceFunctionality -Params $dagMemberTestParams -ContextLabel "Add second member to the test DAG" -ExpectedGetResults $dagMemberExpectedGetResults #Test the DAG again, with props that only take effect once there are members Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchDatabaseAvailabilityGroup\MSFT_xExchDatabaseAvailabilityGroup.psm1 $dagExpectedGetResults.DatacenterActivationMode = "DagOnly" Test-TargetResourceFunctionality -Params $dagTestParams -ContextLabel "Set remaining props on the test DAG" -ExpectedGetResults $dagExpectedGetResults Test-ArrayContentsEqual -TestParams $dagTestParams -DesiredArrayContents $dagTestParams.DatabaseAvailabilityGroupIpAddresses -GetResultParameterName "DatabaseAvailabilityGroupIpAddresses" -ContextLabel "Verify DatabaseAvailabilityGroupIpAddresses" -ItLabel "DatabaseAvailabilityGroupIpAddresses should contain two values" #Create a new DAG database Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxDatabase\MSFT_xExchMailboxDatabase.psm1 $dagDBTestParams = @{ Name = $Global:TestDBName Credential = $Global:ShellCredentials AllowServiceRestart = $true DatabaseCopyCount = 2 EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)\$($Global:TestDBName).edb" LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)" Server = $env:COMPUTERNAME } $dagDBExpectedGetResults = @{ Name = $Global:TestDBName EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)\$($Global:TestDBName).edb" LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)" Server = $env:COMPUTERNAME } Test-TargetResourceFunctionality -Params $dagDBTestParams -ContextLabel "Create test database" -ExpectedGetResults $dagDBExpectedGetResults #Add DB Copy Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxDatabaseCopy\MSFT_xExchMailboxDatabaseCopy.psm1 $dagDBCopyTestParams = @{ Identity = $Global:TestDBName MailboxServer = $Global:SecondDAGMember Credential = $Global:ShellCredentials ActivationPreference = 2 } $dagDBCopyExpectedGetResults = @{ Identity = $Global:TestDBName MailboxServer = $Global:SecondDAGMember ActivationPreference = 2 } Test-TargetResourceFunctionality -Params $dagDBCopyTestParams -ContextLabel "Add a database copy" -ExpectedGetResults $dagDBCopyExpectedGetResults } } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." } } else { Write-Verbose "Tests in this file require that the computer account for the DAG is precreated" } } else { Write-Verbose "Tests in this file require that the ActiveDirectory module is installed. Run: Add-WindowsFeature RSAT-ADDS" }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchExchangeCertificate.Integration.Tests.ps1
MSFT_xExchExchangeCertificate.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] param () Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchExchangeCertificate\MSFT_xExchExchangeCertificate.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 function Test-ServicesInCertificate { [CmdletBinding()] param([Hashtable]$TestParams, [string]$ContextLabel) Context $ContextLabel { [Hashtable]$getResult = Get-TargetResource @TestParams It 'Certificate Services Check' { CompareCertServices -ServicesActual $getResult.Services -ServicesDesired $TestParams.Services -AllowExtraServices $TestParams.AllowExtraServices | Should Be $true } } } #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get required credentials to use for the test $certPassword = ConvertTo-SecureString "Password1" -AsPlainText -Force $certCredentials = New-Object System.Management.Automation.PSCredential ("admin", $certPassword) [string]$testCertThumbprint1 = "766358855A7361C6D99D4FB58903AB0833296B2A" [string]$testCertThumbprint2 = "4C14890860F4126A18560779B8AF8B818B900F5A" [string]$testCertPath1 = "$($PSScriptRoot)\Data\TestCert1.pfx" [string]$testCertPath2 = "$($PSScriptRoot)\Data\TestCert2.pfx" Describe "Test Installing, Enabling, and Removing Exchange Certificates" { #Test installing and enabling test cert 1 $testParams = @{ Thumbprint = $testCertThumbprint1 Credential = $Global:ShellCredentials Ensure = "Present" AllowExtraServices = $true CertCreds = $certCredentials CertFilePath = $testCertPath1 Services = "IIS","POP","IMAP","SMTP" } $expectedGetResults = @{ Thumbprint = $testCertThumbprint1 } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Install and Enable Test Certificate 1" -ExpectedGetResults $expectedGetResults Test-ServicesInCertificate -TestParams $testParams -ContextLabel 'Verify Services on Test Certificate 1' #Test installing and enabling test cert2 $testParams.Thumbprint = $testCertThumbprint2 $testParams.CertFilePath = $testCertPath2 $expectedGetResults.Thumbprint = $testCertThumbprint2 Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Install and Enable Test Certificate 2" -ExpectedGetResults $expectedGetResults Test-ServicesInCertificate -TestParams $testParams -ContextLabel 'Verify Services on Test Certificate 2' #Test removing test cert 1 $testParams.Thumbprint = $testCertThumbprint1 $testParams.Ensure = "Absent" $expectedGetResults = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Remove Test Certificate 1" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchPowershellVirtualDirectory.Integration.Tests.ps1
MSFT_xExchPowershellVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchPowershellVirtualDirectory\MSFT_xExchPowershellVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchPowershellVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\PowerShell (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $false CertificateAuthentication = $true ExternalUrl = "http://$($Global:ServerFqdn)/powershell" InternalUrl = "http://$($Global:ServerFqdn)/powershell" RequireSSL = $false WindowsAuthentication = $false } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\PowerShell (Default Web Site)" BasicAuthentication = $false CertificateAuthentication = $true ExternalUrl = "http://$($Global:ServerFqdn)/powershell" InternalUrl = "http://$($Global:ServerFqdn)/powershell" RequireSSL = $false WindowsAuthentication = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams.ExternalUrl = '' $testParams.InternalUrl = '' $expectedGetResults.ExternalUrl = $null $expectedGetResults.InternalUrl = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try with empty URL's" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchMailboxDatabase.Integration.Tests.ps1
MSFT_xExchMailboxDatabase.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxDatabase\MSFT_xExchMailboxDatabase.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Removes the test DAG if it exists, and any associated databases function PrepTestDB { [CmdletBinding()] param ( [string] $TestDBName ) Write-Verbose "Cleaning up test database" GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "*-MailboxDatabase" Get-MailboxDatabase | Where-Object {$_.Name -like "$($TestDBName)"} | Remove-MailboxDatabase -Confirm:$false Get-ChildItem -LiteralPath "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue if ($null -ne (Get-MailboxDatabase | Where-Object {$_.Name -like "$($TestDBName)"})) { throw "Failed to cleanup test database" } Write-Verbose "Finished cleaning up test database" } #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } $TestDBName = "Mailbox Database Test 123" PrepTestDB -TestDBName $TestDBName Describe "Test Creating a DB and Setting Properties with xExchMailboxDatabase" { $testParams = @{ Name = $TestDBName Credential = $Global:ShellCredentials Server = $env:COMPUTERNAME EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)\$($TestDBName).edb" LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" AllowServiceRestart = $true AutoDagExcludeFromMonitoring = $true BackgroundDatabaseMaintenance = $true CalendarLoggingQuota = "unlimited" CircularLoggingEnabled = $true DatabaseCopyCount = 1 DeletedItemRetention = "14.00:00:00" EventHistoryRetentionPeriod = "03:04:05" IndexEnabled = $true IsExcludedFromProvisioning = $false IsSuspendedFromProvisioning = $false MailboxRetention = "30.00:00:00" MountAtStartup = $true OfflineAddressBook = "Default Offline Address Book (Ex2013)" RetainDeletedItemsUntilBackup = $false IssueWarningQuota = "27 MB" ProhibitSendQuota = "1GB" ProhibitSendReceiveQuota = "1.5 GB" RecoverableItemsQuota = "uNlImItEd" RecoverableItemsWarningQuota = "1,000,448" } $expectedGetResults = @{ Name = $TestDBName Server = $env:COMPUTERNAME EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)\$($TestDBName).edb" LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" AutoDagExcludeFromMonitoring = $true BackgroundDatabaseMaintenance = $true CalendarLoggingQuota = "unlimited" CircularLoggingEnabled = $true DatabaseCopyCount = 1 DeletedItemRetention = "14.00:00:00" EventHistoryRetentionPeriod = "03:04:05" IndexEnabled = $true IsExcludedFromProvisioning = $false IsSuspendedFromProvisioning = $false MailboxRetention = "30.00:00:00" MountAtStartup = $true OfflineAddressBook = "\Default Offline Address Book (Ex2013)" RetainDeletedItemsUntilBackup = $false IssueWarningQuota = "27 MB" ProhibitSendQuota = "1GB" ProhibitSendReceiveQuota = "1.5 GB" RecoverableItemsQuota = "uNlImItEd" RecoverableItemsWarningQuota = "1,000,448" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Create Test Database" -ExpectedGetResults $expectedGetResults $testParams = @{ Name = $TestDBName Credential = $Global:ShellCredentials Server = $env:COMPUTERNAME EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)\$($TestDBName).edb" LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" AllowServiceRestart = $true AutoDagExcludeFromMonitoring = $true BackgroundDatabaseMaintenance = $true CalendarLoggingQuota = "30mb" CircularLoggingEnabled = $false DatabaseCopyCount = 1 DeletedItemRetention = "15.00:00:00" EventHistoryRetentionPeriod = "04:05:06" IndexEnabled = $false IsExcludedFromProvisioning = $true IsSuspendedFromProvisioning = $true MailboxRetention = "31.00:00:00" MountAtStartup = $false OfflineAddressBook = "Default Offline Address Book (Ex2013)" RetainDeletedItemsUntilBackup = $true IssueWarningQuota = "28 MB" ProhibitSendQuota = "2GB" ProhibitSendReceiveQuota = "2.5 GB" RecoverableItemsQuota = "2 GB" RecoverableItemsWarningQuota = "1.5 GB" } $expectedGetResults = @{ Name = $TestDBName Server = $env:COMPUTERNAME EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)\$($TestDBName).edb" LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" AutoDagExcludeFromMonitoring = $true BackgroundDatabaseMaintenance = $true CalendarLoggingQuota = "30mb" CircularLoggingEnabled = $false DatabaseCopyCount = 1 DeletedItemRetention = "15.00:00:00" EventHistoryRetentionPeriod = "04:05:06" IndexEnabled = $false IsExcludedFromProvisioning = $true IsSuspendedFromProvisioning = $true MailboxRetention = "31.00:00:00" MountAtStartup = $false OfflineAddressBook = "\Default Offline Address Book (Ex2013)" RetainDeletedItemsUntilBackup = $true IssueWarningQuota = "28 MB" ProhibitSendQuota = "2GB" ProhibitSendReceiveQuota = "2.5 GB" RecoverableItemsQuota = "2 GB" RecoverableItemsWarningQuota = "1.5 GB" } $serverVersion = GetExchangeVersion if ($serverVersion -eq "2016") { $testParams.Add("IsExcludedFromProvisioningReason", "Testing Excluding the Database") $expectedGetResults.Add("IsExcludedFromProvisioningReason", "Testing Excluding the Database") } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Change many DB properties" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/xExchangeCommon.Unit.Tests.ps1
xExchangeCommon.Unit.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Remove any existing Remote PowerShell sessions created by xExchange and verify they are gone function RemoveExistingPSSessions { Context 'Remove existing Remote PowerShell Session to Exchange' { RemoveExistingRemoteSession $Session = $null $Session = GetExistingExchangeSession It "Session Should Be Null" { $Session | Should BeNullOrEmpty } } } #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Test Exchange Remote PowerShell Functions" { #Remove any existing Remote PS Sessions to Exchange before getting started RemoveExistingPSSessions #Verify we can setup a new Remote PS Session to Exchange Context 'Establish new Remote PowerShell Session to Exchange' { GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "Get-ExchangeServer" $Session = $null $Session = GetExistingExchangeSession It "Session Should Not Be Null" { ($null -ne $Session) | Should Be $true } } #Remove sessions again before continuing RemoveExistingPSSessions #Simulate that setup is running (using notepad.exe), and try to establish a new session. This should fail Context 'Make sure PS session is not established when setup process is running' { Start-Process Notepad.exe $caughtException = $false try { GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "Get-ExchangeServer" -SetupProcessName "notepad" } catch { $caughtException = $true } It "GetRemoteExchangeSession Should Throw Exception" { $caughtException | Should Be $true } $Session = $null $Session = GetExistingExchangeSession It "Session Should Be Null" { ($null -eq $Session) | Should Be $true } } } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchMailboxTransportService.Integration.Tests.ps1
MSFT_xExchMailboxTransportService.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxTransportService\MSFT_xExchMailboxTransportService.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $global:ShellCredentials) { [PSCredential]$global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Set and modify Mailbox Transport Service configuration" { #Set configuration with default values $testParams = @{ Identity = $env:computername Credential = $global:ShellCredentials AllowServiceRestart = $true ConnectivityLogEnabled = $true ConnectivityLogMaxAge = '30.00:00:00' ConnectivityLogMaxDirectorySize = '1000MB' ConnectivityLogMaxFileSize = '10MB' ConnectivityLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\Connectivity' ContentConversionTracingEnabled = $false MaxConcurrentMailboxDeliveries = '20' MaxConcurrentMailboxSubmissions = '20' PipelineTracingEnabled = $false PipelineTracingPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\PipelineTracing' PipelineTracingSenderAddress = '' ReceiveProtocolLogMaxAge = '30.00:00:00' ReceiveProtocolLogMaxDirectorySize = '250MB' ReceiveProtocolLogMaxFileSize = '10 MB' ReceiveProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpReceive' SendProtocolLogMaxAge = '30.00:00:00' SendProtocolLogMaxDirectorySize = '250MB' SendProtocolLogMaxFileSize = '10MB' SendProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpSend' } $expectedGetResults = @{ ConnectivityLogEnabled = $true ConnectivityLogMaxAge = '30.00:00:00' ConnectivityLogMaxDirectorySize = '1000MB' ConnectivityLogMaxFileSize = '10MB' ConnectivityLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\Connectivity' ContentConversionTracingEnabled = $false MaxConcurrentMailboxDeliveries = '20' MaxConcurrentMailboxSubmissions = '20' PipelineTracingEnabled = $false PipelineTracingPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\PipelineTracing' PipelineTracingSenderAddress = $null ReceiveProtocolLogMaxAge = '30.00:00:00' ReceiveProtocolLogMaxDirectorySize = '250MB' ReceiveProtocolLogMaxFileSize = '10 MB' ReceiveProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpReceive' SendProtocolLogMaxAge = '30.00:00:00' SendProtocolLogMaxDirectorySize = '250 MB' SendProtocolLogMaxFileSize = '10MB' SendProtocolLogPath = 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\Hub\ProtocolLog\SmtpSend' } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set default Mailbox Transport Service configuration" -ExpectedGetResults $expectedGetResults #modify configuration $testParams.PipelineTracingSenderAddress = 'john.doe@contoso.com' $expectedGetResults.PipelineTracingSenderAddress = 'john.doe@contoso.com' Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Modify Mailbox Transport Service configuration" -ExpectedGetResults $expectedGetResults #modify configuration $testParams.PipelineTracingSenderAddress = '' $expectedGetResults.PipelineTracingSenderAddress = $null Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Revert Mailbox Transport Service configuration" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchPopSettings.Integration.Tests.ps1
MSFT_xExchPopSettings.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchPopSettings\MSFT_xExchPopSettings.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchPopSettings" { $testParams = @{ Server = $env:COMPUTERNAME Credential = $Global:ShellCredentials LoginType = "PlainTextLogin" ExternalConnectionSettings = @("$($Global:ServerFqdn):143:TLS") X509CertificateName = "$($Global:ServerFqdn)" } $expectedGetResults = @{ LoginType = "PlainTextLogin" X509CertificateName = "$($Global:ServerFqdn)" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExternalConnectionSettings -GetResultParameterName "ExternalConnectionSettings" -ContextLabel "Verify ExternalConnectionSettings" -ItLabel "ExternalConnectionSettings should contain a value" $testParams.LoginType = "SecureLogin" $testParams.ExternalConnectionSettings = @() $testParams.X509CertificateName = "" $expectedGetResults.LoginType = "SecureLogin" $expectedGetResults.X509CertificateName = "" Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Change some parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExternalConnectionSettings -GetResultParameterName "ExternalConnectionSettings" -ContextLabel "Verify ExternalConnectionSettings" -ItLabel "ExternalConnectionSettings should be empty" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchAntiMalwareScanning.Integration.Tests.ps1
MSFT_xExchAntiMalwareScanning.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchAntiMalwareScanning\MSFT_xExchAntiMalwareScanning.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Test Enabling and Disabling Malware Scanning" { #Test enabling with no restart of the service $testParams = @{ Enabled = $true Credential = $Global:ShellCredentials AllowServiceRestart = $false } $expectedGetResults = @{ Enabled = $true } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Enable Malware Scanning - No Restart" -ExpectedGetResults $expectedGetResults #Test disabling with no restart of the service $testParams.Enabled = $false $expectedGetResults.Enabled = $false Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Disable Malware Scanning - No Restart" -ExpectedGetResults $expectedGetResults #Test enabling with a restart of the service $testParams.Enabled = $true $testParams.AllowServiceRestart = $true $expectedGetResults.Enabled = $true Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Enable Malware Scanning - With Restart" -ExpectedGetResults $expectedGetResults #Test disabling with a restart of the service $testParams.Enabled = $false $expectedGetResults.Enabled = $false Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Disable Malware Scanning - With Restart" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchImapSettings.Integration.Tests.ps1
MSFT_xExchImapSettings.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchImapSettings\MSFT_xExchImapSettings.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchImapSettings" { $testParams = @{ Server = $env:COMPUTERNAME Credential = $Global:ShellCredentials LoginType = "PlainTextLogin" ExternalConnectionSettings = @("$($Global:ServerFqdn):143:TLS") X509CertificateName = "$($Global:ServerFqdn)" } $expectedGetResults = @{ LoginType = "PlainTextLogin" X509CertificateName = "$($Global:ServerFqdn)" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExternalConnectionSettings -GetResultParameterName "ExternalConnectionSettings" -ContextLabel "Verify ExternalConnectionSettings" -ItLabel "ExternalConnectionSettings should contain a value" $testParams.LoginType = "SecureLogin" $testParams.ExternalConnectionSettings = @() $testParams.X509CertificateName = "" $expectedGetResults.LoginType = "SecureLogin" $expectedGetResults.X509CertificateName = "" Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Change some parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExternalConnectionSettings -GetResultParameterName "ExternalConnectionSettings" -ContextLabel "Verify ExternalConnectionSettings" -ItLabel "ExternalConnectionSettings should be empty" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchExchangeServer.Integration.Tests.ps1
MSFT_xExchExchangeServer.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. ###This module has the following additional requirements; ### * Requires that the ActiveDirectory module is installed Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchExchangeServer\MSFT_xExchExchangeServer.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Sets props retrieved by Get-ExchangeServer back to their default values function PrepTestExchangeServer { [CmdletBinding()] param() Import-Module ActiveDirectory ClearServerADProp("msExchProductID") ClearServerADProp("msExchCustomerFeedbackEnabled") ClearServerADProp("msExchInternetWebProxy") #ClearServerADProp("msExchShadowDisplayName") } #Used to null out the specified Active Directory property of an Exchange Server function ClearServerADProp { [CmdletBinding()] param($prop) Get-ADObject -SearchBase "$($Global:ExchangeServerDN)" -Filter {ObjectClass -eq "msExchExchangeServer"} | Where-Object {$_.ObjectClass -eq "msExchExchangeServer"} | Set-ADObject -Clear "$($prop)" } function VerifyServerPrepped { [CmdletBinding()] param() Context "Server has had relevant properties nulled out for xExchExchangeServer tests" { [Hashtable]$getResult = Get-TargetResource @testParams -Verbose #It "CustomerFeedbackEnabled should be null" { # $getResult.CustomerFeedbackEnabled | Should Be $null #} It "InternetWebProxy should be empty" { [string]::IsNullOrEmpty($getResult.InternetWebProxy) | Should Be $true } It "ProductKey should be empty" { [string]::IsNullOrEmpty($getResult.ProductKey) | Should Be $true } } } $adModule = Get-Module -ListAvailable ActiveDirectory -ErrorAction SilentlyContinue if ($null -ne $adModule) { #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } if ($null -eq $Global:ExchangeServerDN) { GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "Get-ExchangeServer" $server = Get-ExchangeServer -Identity $env:COMPUTERNAME if ($null -ne $server) { $Global:ExchangeServerDN = $server.DistinguishedName } if ($null -eq $Global:ExchangeServerDN) { throw "Failed to determine distinguishedName of Exchange Server object" } } #Get the product key to use for testing if ($null -eq $Global:ProductKey) { $Global:ProductKey = Read-Host -Prompt "Enter the product key to license Exchange with" } Describe "Test Setting Properties with xExchExchangeServer" { #Create out initial test params $testParams = @{ Identity = $env:COMPUTERNAME Credential = $Global:ShellCredentials } #First prepare the server for tests PrepTestExchangeServer VerifyServerPrepped #Now do tests $testParams = @{ Identity = $env:COMPUTERNAME Credential = $Global:ShellCredentials InternetWebProxy = "http://someproxy.local/" ProductKey = $Global:ProductKey } $expectedGetResults = @{ Identity = $env:COMPUTERNAME InternetWebProxy = "http://someproxy.local/" ProductKey = "Licensed" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Standard xExchExchangeServer tests" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." } } else { Write-Verbose "Tests in this file require that the ActiveDirectory module is installed. Run: Add-WindowsFeature RSAT-ADDS" }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchOutlookAnywhere.Integration.Tests.ps1
MSFT_xExchOutlookAnywhere.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchOutlookAnywhere\MSFT_xExchOutlookAnywhere.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchOutlookAnywhere" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\Rpc (Default Web Site)" Credential = $Global:ShellCredentials ExtendedProtectionFlags = "Proxy","ProxyCoHosting" ExtendedProtectionSPNList = @() ExtendedProtectionTokenChecking = "Allow" ExternalClientAuthenticationMethod = "Ntlm" ExternalClientsRequireSsl = $true ExternalHostname = $Global:ServerFqdn IISAuthenticationMethods = "Basic","Ntlm","Negotiate" InternalClientAuthenticationMethod = "Negotiate" InternalHostname = $Global:ServerFqdn InternalClientsRequireSsl = $true SSLOffloading = $false } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\Rpc (Default Web Site)" ExtendedProtectionTokenChecking = "Allow" ExternalClientAuthenticationMethod = "Ntlm" ExternalClientsRequireSsl = $true ExternalHostname = $Global:ServerFqdn InternalClientAuthenticationMethod = "Negotiate" InternalHostname = $Global:ServerFqdn InternalClientsRequireSsl = $true SSLOffloading = $false } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExtendedProtectionFlags -GetResultParameterName "ExtendedProtectionFlags" -ContextLabel "Verify ExtendedProtectionFlags" -ItLabel "ExtendedProtectionFlags should contain two values" Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.ExtendedProtectionSPNList -GetResultParameterName "ExtendedProtectionSPNList" -ContextLabel "Verify ExtendedProtectionSPNList" -ItLabel "ExtendedProtectionSPNList should be empty" Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.IISAuthenticationMethods -GetResultParameterName "IISAuthenticationMethods" -ContextLabel "Verify IISAuthenticationMethods" -ItLabel "IISAuthenticationMethods should contain three values" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchMapiVirtualDirectory.Integration.Tests.ps1
MSFT_xExchMapiVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMapiVirtualDirectory\MSFT_xExchMapiVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } #Get the Server FQDN for using in URL's if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchMapiVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\mapi (Default Web Site)" Credential = $Global:ShellCredentials ExternalUrl = "https://$($Global:ServerFqdn)/mapi" IISAuthenticationMethods = "Ntlm", "Oauth", "Negotiate" InternalUrl = "https://$($Global:ServerFqdn)/mapi" } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\mapi (Default Web Site)" ExternalUrl = "https://$($Global:ServerFqdn)/mapi" InternalUrl = "https://$($Global:ServerFqdn)/mapi" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.IISAuthenticationMethods -GetResultParameterName "IISAuthenticationMethods" -ContextLabel "Verify IISAuthenticationMethods" -ItLabel "IISAuthenticationMethods should contain three values" $testParams = @{ Identity = "$($env:COMPUTERNAME)\mapi (Default Web Site)" Credential = $Global:ShellCredentials ExternalUrl = "" IISAuthenticationMethods = "Ntlm", "Negotiate" InternalUrl = "https://$($Global:ServerFqdn)/mapi" } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\mapi (Default Web Site)" ExternalUrl = $null InternalUrl = "https://$($Global:ServerFqdn)/mapi" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Try with different values" -ExpectedGetResults $expectedGetResults Test-ArrayContentsEqual -TestParams $testParams -DesiredArrayContents $testParams.IISAuthenticationMethods -GetResultParameterName "IISAuthenticationMethods" -ContextLabel "Verify IISAuthenticationMethods" -ItLabel "IISAuthenticationMethods should contain three values" } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchUMCallRouterSettings.Integration.Tests.ps1
MSFT_xExchUMCallRouterSettings.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchUMCallRouterSettings\MSFT_xExchUMCallRouterSettings.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } Describe "Test Setting Properties with xExchUMCallRouterSettings" { $testParams = @{ Server = $env:COMPUTERNAME Credential = $Global:ShellCredentials UMStartupMode = "TLS" } $expectedGetResults = @{ Server = $env:COMPUTERNAME UMStartupMode = "TLS" } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams.UMStartupMode = "Dual" $expectedGetResults.UMStartupMode = "Dual" Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Change some parameters" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Test/MSFT_xExchAutodiscoverVirtualDirectory.Integration.Tests.ps1
MSFT_xExchAutodiscoverVirtualDirectory.Integration.Tests.ps1
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user. Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchAutodiscoverVirtualDirectory\MSFT_xExchAutodiscoverVirtualDirectory.psm1 Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0 Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0 #Check if Exchange is installed on this machine. If not, we can't run tests [bool]$exchangeInstalled = IsSetupComplete if ($exchangeInstalled) { #Get required credentials to use for the test if ($null -eq $Global:ShellCredentials) { [PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange" } if ($null -eq $Global:ServerFqdn) { $Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName } Describe "Test Setting Properties with xExchAutodiscoverVirtualDirectory" { $testParams = @{ Identity = "$($env:COMPUTERNAME)\Autodiscover (Default Web Site)" Credential = $Global:ShellCredentials BasicAuthentication = $true DigestAuthentication = $false WindowsAuthentication = $true WSSecurityAuthentication = $true } $expectedGetResults = @{ Identity = "$($env:COMPUTERNAME)\Autodiscover (Default Web Site)" BasicAuthentication = $true DigestAuthentication = $false WindowsAuthentication = $true WSSecurityAuthentication = $true } Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Set standard parameters" -ExpectedGetResults $expectedGetResults $testParams.BasicAuthentication = $false $testParams.DigestAuthentication = $true $testParams.WindowsAuthentication = $false $testParams.WSSecurityAuthentication = $true $expectedGetResults.BasicAuthentication = $false $expectedGetResults.DigestAuthentication = $true $expectedGetResults.WindowsAuthentication = $false $expectedGetResults.WSSecurityAuthentication = $true Test-TargetResourceFunctionality -Params $testParams -ContextLabel "Change some parameters" -ExpectedGetResults $expectedGetResults } } else { Write-Verbose "Tests in this file require that Exchange is installed to be run." }
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureDatabases-FromCalculator/ConfigureDatabases-FromCalculator.ps1
ConfigureDatabases-FromCalculator.ps1
Configuration ConfigureDatabasesFromCalculator { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Import-Module "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.FullName)\HelperScripts\ExchangeConfigHelper.psm1" Node $AllNodes.NodeName { #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } #Load the primary and copy lists from the calculator files $primaryDbList = DBListFromMailboxDatabasesCsv ` -MailboxDatabasesCsvPath "$($PSScriptRoot)\CalculatorAndScripts\MailboxDatabases.csv" ` -ServerNameInCsv $Node.ServerNameInCsv ` -DbNameReplacements $Node.DbNameReplacements $copyDbList = DBListFromMailboxDatabaseCopiesCsv ` -MailboxDatabaseCopiesCsvPath "$($PSScriptRoot)\CalculatorAndScripts\MailboxDatabaseCopies.csv" ` -ServerNameInCsv $Node.ServerNameInCsv ` -DbNameReplacements $Node.DbNameReplacements #Create primary databases foreach ($DB in $primaryDbList) { $resourceId = "MDB:$($DB.Name)" #Need to define a unique ID for each database xExchMailboxDatabase $resourceId { Name = $DB.Name Credential = $ShellCreds EdbFilePath = $DB.DBFilePath LogFolderPath = $DB.LogFolderPath Server = $Node.NodeName CircularLoggingEnabled = $true DatabaseCopyCount = 4 IssueWarningQuota = "50176MB" ProhibitSendQuota = "51200MB" ProhibitSendReceiveQuota = "52224MB" AllowServiceRestart = $true } } #Create the copies foreach ($DB in $copyDbList) { $waitResourceId = "WaitForDB:$($DB.Name)" #Unique ID for the xExchWaitForMailboxDatabase resource $copyResourceId = "MDBCopy:$($DB.Name)" #Unique ID for the xExchMailboxDatabaseCopy resource #Need to wait for a primary copy to be created before we add a copy xExchWaitForMailboxDatabase $waitResourceId { Identity = $DB.Name Credential = $ShellCreds } xExchMailboxDatabaseCopy $copyResourceId { Identity = $DB.Name Credential = $ShellCreds MailboxServer = $Node.NodeName ActivationPreference = $DB.ActivationPreference ReplayLagTime = $DB.ReplayLagTime AllowServiceRestart = $true DependsOn = "[xExchWaitForMailboxDatabase]$($waitResourceId)" } } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example ConfigureDatabasesFromCalculator -ConfigurationData $PSScriptRoot\ConfigureDatabases-FromCalculator-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. Set-DscLocalConfigurationManager -Path .\ConfigureDatabasesFromCalculator -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\ConfigureDatabasesFromCalculator -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/QuickStartTemplate/QuickStartTemplate.ps1
QuickStartTemplate.ps1
Configuration QuickStartTemplate { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Used when passing credentials securely. This configures the thumbprint of the #cert that will be used to decrypt the creds LocalConfigurationManager { CertificateId = $Node.Thumbprint } } } #Get credentials if they haven't already been passed if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example QuickStartTemplate -ConfigurationData $PSScriptRoot\QuickStartTemplate-Config.psd1 -ShellCreds $ShellCreds
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/PostInstallationConfiguration/PostInstallationConfiguration.ps1
PostInstallationConfiguration.ps1
Configuration PostInstallationConfiguration { param ( [PSCredential]$ShellCreds, [PSCredential]$CertCreds ) Import-DscResource -Module xExchange #This script shows examples of how to utilize most resources in the xExchange module. #Where possible, configuration settings have been entered directly into this script. #That was done for all settings which will be common for every server being configured. #Settings which may be different, like for DAG's, CAS in different sites, or for individual #servers, are defined in EndToEndExample-Config.psd1. #This first section only configures a single DAG node, the first member of the DAG. #The first member of the DAG will be responsible for DAG creation and maintaining its configuration Node $AllNodes.Where{$_.Role -eq 'FirstDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Create the DAG xExchDatabaseAvailabilityGroup DAG { Name = $dagSettings.DAGName Credential = $ShellCreds AutoDagTotalNumberOfServers = $dagSettings.AutoDagTotalNumberOfServers AutoDagDatabaseCopiesPerVolume = $dagSettings.AutoDagDatabaseCopiesPerVolume AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DatacenterActivationMode = "DagOnly" DatabaseAvailabilityGroupIPAddresses = $dagSettings.DatabaseAvailabilityGroupIPAddresses ManualDagNetworkConfiguration = $dagSettings.ManualDagNetworkConfiguration ReplayLagManagerEnabled = $dagSettings.ReplayLagManagerEnabled SkipDagValidation = $true WitnessDirectory = 'C:\FSW' WitnessServer = $dagSettings.WitnessServer } #Add this server as member xExchDatabaseAvailabilityGroupMember DAGMember { MailboxServer = $Node.NodeName Credential = $ShellCreds DAGName = $dagSettings.DAGName SkipDagValidation = $true DependsOn = '[xExchDatabaseAvailabilityGroup]DAG' } #Create two new DAG Networks xExchDatabaseAvailabilityGroupNetwork DAGNet1 { Name = $dagSettings.DAGNet1NetworkName Credential = $ShellCreds DatabaseAvailabilityGroup = $dagSettings.DAGName Ensure = 'Present' ReplicationEnabled = $dagSettings.DAGNet1ReplicationEnabled Subnets = $dagSettings.DAGNet1Subnets DependsOn = '[xExchDatabaseAvailabilityGroupMember]DAGMember' #Can't do work on DAG networks until at least one member is in the DAG... } xExchDatabaseAvailabilityGroupNetwork DAGNet2 { Name = $dagSettings.DAGNet2NetworkName Credential = $ShellCreds DatabaseAvailabilityGroup = $dagSettings.DAGName Ensure = 'Present' ReplicationEnabled = $dagSettings.DAGNet2ReplicationEnabled Subnets = $dagSettings.DAGNet2Subnets DependsOn = '[xExchDatabaseAvailabilityGroupMember]DAGMember' #Can't do work on DAG networks until at least one member is in the DAG... } #Remove the original DAG Network xExchDatabaseAvailabilityGroupNetwork DAGNetOld { Name = $dagSettings.OldNetworkName Credential = $ShellCreds DatabaseAvailabilityGroup = $dagSettings.DAGName Ensure = 'Absent' DependsOn = '[xExchDatabaseAvailabilityGroupNetwork]DAGNet1','[xExchDatabaseAvailabilityGroupNetwork]DAGNet2' #Dont remove the old one until the new one is in place } } #Next we'll add the remaining nodes to the DAG Node $AllNodes.Where{$_.Role -eq 'AdditionalDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Can't join until the DAG exists... xExchWaitForDAG WaitForDAG { Identity = $dagSettings.DAGName Credential = $ShellCreds } xExchDatabaseAvailabilityGroupMember DAGMember { MailboxServer = $Node.NodeName Credential = $ShellCreds DAGName = $dagSettings.DAGName SkipDagValidation = $true DependsOn = '[xExchWaitForDAG]WaitForDAG' } } #This section will handle configuring all non-DAG specific settings, including CAS and MBX settings. Node $AllNodes.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node $casSettings = $ConfigurationData[$Node.CASId] #Look up and retrieve the CAS settings for this node #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } ###General server settings### #This section licenses the server xExchExchangeServer EXServer { Identity = $Node.NodeName Credential = $ShellCreds ProductKey = '12345-12345-12345-12345-12345' AllowServiceRestart = $true } #This imports a certificate .PFX that had been previously exported, and enabled services on it xExchExchangeCertificate Certificate { Thumbprint = $dagSettings.Thumbprint Credential = $ShellCreds Ensure = 'Present' AllowExtraServices = $dagSettings.AllowExtraServices CertCreds = $CertCreds CertFilePath = $dagSettings.CertFilePath Services = $dagSettings.Services } ###CAS specific settings### xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://$($casSettings.InternalNLBFqdn)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = $casSettings.AutoDiscoverSiteScope } #Install features that are required for xExchActiveSyncVirtualDirectory to do Auto Certification Based Authentication WindowsFeature WebClientAuth { Name = 'Web-Client-Auth' Ensure = 'Present' } WindowsFeature WebCertAuth { Name = 'Web-Cert-Auth' Ensure = 'Present' } #This example shows how to enable Certificate Based Authentication for ActiveSync xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds AutoCertBasedAuth = $true AutoCertBasedAuthThumbprint = $dagSettings.Thumbprint BasicAuthEnabled = $false ClientCertAuth = 'Required' ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/Microsoft-Server-ActiveSync" WindowsAuthEnabled = $false AllowServiceRestart = $true DependsOn = '[WindowsFeature]WebClientAuth','[WindowsFeature]WebCertAuth','[xExchExchangeCertificate]Certificate' #Can't configure CBA until we have a valid cert, and have required features } #Ensures forms based auth and configures URLs xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds BasicAuthentication = $true ExternalAuthenticationMethods = 'Fba' ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/ecp" FormsAuthentication = $true InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ecp" WindowsAuthentication = $false AllowServiceRestart = $true } #Configure URL's and for NTLM and negotiate auth xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/mapi" IISAuthenticationMethods = 'NTLM','Negotiate' InternalUrl = "https://$($casSettings.InternalNLBFqdn)/mapi" AllowServiceRestart = $true } #Configure URL's and add any OABs this vdir should distribute xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/oab" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/oab" OABsToDistribute = $casSettings.OABsToDistribute AllowServiceRestart = $true } #Configure URL's and auth settings xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalClientAuthenticationMethod = 'Ntlm' ExternalClientsRequireSSL = $true ExternalHostName = $casSettings.ExternalNLBFqdn IISAuthenticationMethods = 'Ntlm' InternalClientAuthenticationMethod = 'Ntlm' InternalClientsRequireSSL = $true InternalHostName = $casSettings.InternalNLBFqdn AllowServiceRestart = $true } #Ensures forms based auth and configures URLs and IM integration xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds BasicAuthentication = $true ExternalAuthenticationMethods = 'Fba' ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/owa" FormsAuthentication = $true InstantMessagingEnabled = $true InstantMessagingCertificateThumbprint = $dagSettings.Thumbprint InstantMessagingServerName = $casSettings.InstantMessagingServerName InstantMessagingType = 'Ocs' InternalUrl = "https://$($casSettings.InternalNLBFqdn)/owa" WindowsAuthentication = $false AllowServiceRestart = $true DependsOn = '[xExchExchangeCertificate]Certificate' #Can't configure the IM cert until it's valid } #Turn on Windows Integrated auth for remote powershell connections xExchPowerShellVirtualDirectory PSVdir { Identity = "$($Node.NodeName)\PowerShell (Default Web Site)" Credential = $ShellCreds WindowsAuthentication = $true AllowServiceRestart = $true } #Configure URL's xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/ews/exchange.asmx" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ews/exchange.asmx" AllowServiceRestart = $true } ###Transport specific settings### #Create a custom receive connector which could be used to receive SMTP mail from internal non-Exchange mail servers xExchReceiveConnector CustomConnector1 { Identity = "$($Node.NodeName)\Internal SMTP Servers to $($Node.NodeName)" Credential = $ShellCreds Ensure = 'Present' AuthMechanism = 'Tls','ExternalAuthoritative' Bindings = '0.0.0.0:25' MaxMessageSize = '25MB' PermissionGroups = 'AnonymousUsers','ExchangeServers' RemoteIPRanges = '192.168.1.101','192.168.1.102' TransportRole = 'FrontendTransport' Usage = 'Custom' } #Ensures that Exchange built in AntiMalware Scanning is enabled or disabled xExchAntiMalwareScanning AMS { Enabled = $true Credential = $ShellCreds } ###Mailbox Server settings### #Create database and volume mount points for AutoReseed xExchAutoMountPoint AMP { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = $Node.DiskToDBMap SpareVolumeCount = 1 VolumePrefix = 'EXVOL' } #Create primary databases foreach ($DB in $Node.PrimaryDBList.Values) { $resourceId = "MDB:$($DB.Name)" #Need to define a unique ID for each database xExchMailboxDatabase $resourceId { Name = $DB.Name Credential = $ShellCreds EdbFilePath = $DB.EdbFilePath LogFolderPath = $DB.LogFolderPath Server = $Node.NodeName CircularLoggingEnabled = $true DatabaseCopyCount = 4 DeletedItemRetention = '7.00:00:00' IssueWarningQuota = '5120MB' ProhibitSendQuota = '5300MB' ProhibitSendReceiveQuota = '5500MB' AllowServiceRestart = $true DependsOn = '[xExchAutoMountPoint]AMP' #Can"t create databases until the mount points exist } } #Create the copies foreach ($DB in $Node.CopyDBList.Values) { $waitResourceId = "WaitForDB:$($DB.Name)" #Unique ID for the xWaitForMailboxDatabase resource $copyResourceId = "MDBCopy:$($DB.Name)" #Unique ID for the xMailboxDatabaseCopy resource #Need to wait for a primary copy to be created before we add a copy xExchWaitForMailboxDatabase $waitResourceId { Identity = $DB.Name Credential = $ShellCreds } xExchMailboxDatabaseCopy $copyResourceId { Identity = $DB.Name Credential = $ShellCreds MailboxServer = $Node.NodeName ActivationPreference = $DB.ActivationPreference ReplayLagTime = $DB.ReplayLagTime AllowServiceRestart = $true DependsOn = "[xExchWaitForMailboxDatabase]$($waitResourceId)" } } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } if ($null -eq $CertCreds) { $CertCreds = Get-Credential -Message 'Enter credentials for importing the Exchange certificate' } ###Compiles the example PostInstallationConfiguration -ConfigurationData $PSScriptRoot\PostInstallationConfiguration-Config.psd1 -ShellCreds $ShellCreds -CertCreds $CertCreds ###Sets up LCM on target computers to decrypt credentials. Set-DscLocalConfigurationManager -Path .\PostInstallationConfiguration -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\PostInstallationConfiguration -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureAutoMountPoints-Manual/ConfigureAutoMountPoints-Manual.ps1
ConfigureAutoMountPoints-Manual.ps1
###See the following blog post for information on how to use this example: ###http://blogs.technet.com/b/mhendric/archive/2014/10/27/managing-exchange-2013-with-dsc-part-3-automating-mount-point-setup-and-maintenance-for-autoreseed.aspx Configuration ConfigureAutoMountPointsManual { Import-DscResource -Module xExchange Node $AllNodes.NodeName { xExchAutoMountPoint AMP { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = $Node.DiskToDBMap SpareVolumeCount = 1 VolumePrefix = 'EXVOL' } } } ###Compiles the example ConfigureAutoMountPointsManual -ConfigurationData $PSScriptRoot\ConfigureAutoMountPoints-Manual-Config.psd1 ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\ConfigureAutoMountPointsManual -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/CreateAndConfigureDAG/CreateAndConfigureDAG.ps1
CreateAndConfigureDAG.ps1
Configuration CreateAndConfigureDAG { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } } #This section only configures a single DAG node, the first member of the DAG. #The first member of the DAG will be responsible for DAG creation and maintaining its configuration Node $AllNodes.Where{$_.Role -eq 'FirstDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Create the DAG xExchDatabaseAvailabilityGroup DAG { Name = $dagSettings.DAGName Credential = $ShellCreds AutoDagTotalNumberOfServers = $dagSettings.AutoDagTotalNumberOfServers AutoDagDatabaseCopiesPerVolume = $dagSettings.AutoDagDatabaseCopiesPerVolume AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DatacenterActivationMode = "DagOnly" DatabaseAvailabilityGroupIPAddresses = $dagSettings.DatabaseAvailabilityGroupIPAddresses ManualDagNetworkConfiguration = $true ReplayLagManagerEnabled = $true SkipDagValidation = $true WitnessDirectory = 'C:\FSW' WitnessServer = $dagSettings.WitnessServer } #Add this server as member xExchDatabaseAvailabilityGroupMember DAGMember { MailboxServer = $Node.NodeName Credential = $ShellCreds DAGName = $dagSettings.DAGName SkipDagValidation = $true DependsOn = '[xExchDatabaseAvailabilityGroup]DAG' } #Create two new DAG Networks xExchDatabaseAvailabilityGroupNetwork DAGNet1 { Name = $dagSettings.DAGNet1NetworkName Credential = $ShellCreds DatabaseAvailabilityGroup = $dagSettings.DAGName Ensure = 'Present' ReplicationEnabled = $dagSettings.DAGNet1ReplicationEnabled Subnets = $dagSettings.DAGNet1Subnets DependsOn = '[xExchDatabaseAvailabilityGroupMember]DAGMember' #Can't do work on DAG networks until at least one member is in the DAG... } xExchDatabaseAvailabilityGroupNetwork DAGNet2 { Name = $dagSettings.DAGNet2NetworkName Credential = $ShellCreds DatabaseAvailabilityGroup = $dagSettings.DAGName Ensure = 'Present' ReplicationEnabled = $dagSettings.DAGNet2ReplicationEnabled Subnets = $dagSettings.DAGNet2Subnets DependsOn = '[xExchDatabaseAvailabilityGroupMember]DAGMember' #Can't do work on DAG networks until at least one member is in the DAG... } #Remove the original DAG Network xExchDatabaseAvailabilityGroupNetwork DAGNetOld { Name = $dagSettings.OldNetworkName Credential = $ShellCreds DatabaseAvailabilityGroup = $dagSettings.DAGName Ensure = 'Absent' DependsOn = '[xExchDatabaseAvailabilityGroupNetwork]DAGNet1','[xExchDatabaseAvailabilityGroupNetwork]DAGNet2' #Dont remove the old one until the new one is in place } } #Next we'll add the remaining nodes to the DAG Node $AllNodes.Where{$_.Role -eq 'AdditionalDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Can't join until the DAG exists... xExchWaitForDAG WaitForDAG { Identity = $dagSettings.DAGName Credential = $ShellCreds } xExchDatabaseAvailabilityGroupMember DAGMember { MailboxServer = $Node.NodeName Credential = $ShellCreds DAGName = $dagSettings.DAGName SkipDagValidation = $true DependsOn = '[xExchWaitForDAG]WaitForDAG' } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example CreateAndConfigureDAG -ConfigurationData $PSScriptRoot\CreateAndConfigureDAG-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. Set-DscLocalConfigurationManager -Path .\CreateAndConfigureDAG -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\CreateAndConfigureDAG -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/InstallExchange/InstallExchange.ps1
InstallExchange.ps1
Configuration InstallExchange { param ( [PSCredential]$Creds ) Import-DscResource -Module xExchange Import-DscResource -Module xPendingReboot Node $AllNodes.NodeName { LocalConfigurationManager { CertificateId = $Node.Thumbprint RebootNodeIfNeeded = $true } #Copy the Exchange setup files locally File ExchangeBinaries { Ensure = 'Present' Type = 'Directory' Recurse = $true SourcePath = '\\rras-1\Binaries\E15CU6' DestinationPath = 'C:\Binaries\E15CU6' } #Check if a reboot is needed before installing Exchange xPendingReboot BeforeExchangeInstall { Name = "BeforeExchangeInstall" DependsOn = '[File]ExchangeBinaries' } #Do the Exchange install xExchInstall InstallExchange { Path = "C:\Binaries\E15CU6\Setup.exe" Arguments = "/mode:Install /role:Mailbox,ClientAccess /Iacceptexchangeserverlicenseterms" Credential = $Creds DependsOn = '[xPendingReboot]BeforeExchangeInstall' } #See if a reboot is required after installing Exchange xPendingReboot AfterExchangeInstall { Name = "AfterExchangeInstall" DependsOn = '[xExchInstall]InstallExchange' } } } if ($null -eq $Creds) { $Creds = Get-Credential -Message "Enter credentials for establishing Remote Powershell sessions to Exchange" } ###Compiles the example InstallExchange -ConfigurationData $PSScriptRoot\InstallExchange-Config.psd1 -Creds $Creds ###Sets up LCM on target computers to decrypt credentials, and to allow reboot during resource execution Set-DscLocalConfigurationManager -Path .\InstallExchange -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\InstallExchange -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureAutoMountPoints-FromCalculator/ConfigureAutoMountPoints-FromCalculator.ps1
ConfigureAutoMountPoints-FromCalculator.ps1
###See the following blog post for information on how to use this example: ###http://blogs.technet.com/b/mhendric/archive/2014/10/27/managing-exchange-2013-with-dsc-part-3-automating-mount-point-setup-and-maintenance-for-autoreseed.aspx Configuration ConfigureAutoMountPointsFromCalculator { Import-DscResource -Module xExchange Import-Module "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.FullName)\HelperScripts\ExchangeConfigHelper.psm1" Node $AllNodes.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] $dbMap = DBMapFromServersCsv ` -ServersCsvPath "$($PSScriptRoot)\CalculatorAndScripts\Servers.csv" ` -ServerNameInCsv $Node.ServerNameInCsv ` -DbNameReplacements $dagSettings.DbNameReplacements xExchAutoMountPoint AMP { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = $dbMap SpareVolumeCount = 1 VolumePrefix = 'EXVOL' } } } ###Compiles the example ConfigureAutoMountPointsFromCalculator -ConfigurationData $PSScriptRoot\ConfigureAutoMountPoints-FromCalculator-Config.psd1 ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\ConfigureAutoMountPointsFromCalculator -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/WaitForADPrep/WaitForADPrep.ps1
WaitForADPrep.ps1
Configuration WaitForADPrep { param ( [PSCredential]$Creds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { LocalConfigurationManager { CertificateId = $Node.Thumbprint } xExchWaitForADPrep WaitForADPrep { Identity = "Doesn'tMatter" Credential = $Creds SchemaVersion = 15303 OrganizationVersion = 15965 DomainVersion = 13236 } } } if ($null -eq $Creds) { $Creds = Get-Credential -Message "Enter credentials for establishing Remote Powershell sessions to Exchange" } ###Compiles the example WaitForADPrep -ConfigurationData $PSScriptRoot\WaitForADPrep-Config.psd1 -Creds $Creds ###Sets up LCM on target computers to decrypt credentials, and to allow reboot during resource execution #Set-DscLocalConfigurationManager -Path .\WaitForADPrep -Verbose ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\WaitForADPrep -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/JetstressAutomation/1-InstallAndRunJetstress.ps1
1-InstallAndRunJetstress.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingCmdletAliases", "")] [CmdletBinding()] param() Configuration InstallAndRunJetstress { Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Create mount points for use with Jetstress. Here I prefer to use the same database names for ALL servers, #that way I can use the same JetstressConfig.xml for all of them. xExchAutoMountPoint AMPForJetstress { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = 'DB1,DB2,DB3,DB4','DB5,DB6,DB7,DB8' SpareVolumeCount = 0 VolumePrefix = 'EXVOL' CreateSubfolders = $true } #Copy the Jetstress install file File CopyJetstress { Ensure = 'Present' SourcePath = '\\rras-1\Jetstress\Jetstress.msi' DestinationPath = 'C:\Jetstress\Jetstress.msi' } #Install Jetstress Package InstallJetstress { Ensure = 'Present' Path = 'C:\Jetstress\Jetstress.msi' Name = 'Microsoft Exchange Jetstress 2013' ProductId = '75189587-0D84-4404-8F02-79C39728FA64' DependsOn = '[xExchAutoMountPoint]AMPForJetstress','[File]CopyJetstress' } #Copy required ESE DLL's to the Jetstress installation directory File CopyESEDlls { Ensure = 'Present' Type = 'Directory' Recurse = $true SourcePath = '\\rras-1\Jetstress\ESEDlls(CU7)' DestinationPath = 'C:\Program Files\Exchange Jetstress' DependsOn = '[Package]InstallJetstress' } #Copy JetstressConfig.xml to the Jetstress installation directory File CopyJetstressConfig { Ensure = 'Present' SourcePath = '\\rras-1\Jetstress\JetstressConfig.xml' DestinationPath = 'C:\Program Files\Exchange Jetstress\JetstressConfig.xml' DependsOn = '[Package]InstallJetstress' } #Run the Jetstress test, and evaluate the results xExchJetstress RunJetstress { Type = 'Performance' JetstressPath = 'C:\Program Files\Exchange Jetstress' JetstressParams = '/c "C:\Program Files\Exchange Jetstress\JetstressConfig.xml"' MinAchievedIOPS = 500 DependsOn = '[File]CopyESEDlls','[File]CopyJetstressConfig' } } } ###Compiles the example InstallAndRunJetstress -ConfigurationData $PSScriptRoot\Jetstress-Config.psd1 ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\InstallAndRunJetstress -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/JetstressAutomation/2-CleanupJetstress.ps1
2-CleanupJetstress.ps1
Configuration CleanupJetstress { Import-DscResource -Module xExchange Node $AllNodes.NodeName { LocalConfigurationManager { RebootNodeIfNeeded = $true } #Uninstall Jetstress from the computer Package UninstallJetstress { Ensure = 'Absent' Path = 'C:\Jetstress\Jetstress.msi' Name = 'Microsoft Exchange Jetstress 2013 - Uninstall' ProductId = '75189587-0D84-4404-8F02-79C39728FA64' } #Clean up Jetstress databases, mount points, and binaries xExchJetstressCleanup CleanupJetstress { JetstressPath = "C:\Program Files\Exchange Jetstress" ConfigFilePath = "C:\Program Files\Exchange Jetstress\JetstressConfig.xml" DeleteAssociatedMountPoints = $true OutputSaveLocation = "C:\JetstressOutput" RemoveBinaries = $true DependsOn = '[Package]UninstallJetstress' } } } ###Compiles the example CleanupJetstress -ConfigurationData $PSScriptRoot\Jetstress-Config.psd1 ###Sets up LCM on target computers to allow reboot during resource execution Set-DscLocalConfigurationManager -Path .\CleanupJetstress -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\CleanupJetstress -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureDatabases-Manual/ConfigureDatabases-Manual.ps1
ConfigureDatabases-Manual.ps1
Configuration ConfigureDatabasesManual { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } #Create primary databases foreach ($DB in $Node.PrimaryDBList.Values) { $resourceId = "MDB:$($DB.Name)" #Need to define a unique ID for each database xExchMailboxDatabase $resourceId { Name = $DB.Name Credential = $ShellCreds EdbFilePath = $DB.DBFilePath LogFolderPath = $DB.LogFolderPath Server = $Node.NodeName CircularLoggingEnabled = $true DatabaseCopyCount = 4 IssueWarningQuota = "50176MB" ProhibitSendQuota = "51200MB" ProhibitSendReceiveQuota = "52224MB" AllowServiceRestart = $true } } #Create the copies foreach ($DB in $Node.CopyDBList.Values) { $waitResourceId = "WaitForDB:$($DB.Name)" #Unique ID for the xExchWaitForMailboxDatabase resource $copyResourceId = "MDBCopy:$($DB.Name)" #Unique ID for the xExchMailboxDatabaseCopy resource #Need to wait for a primary copy to be created before we add a copy xExchWaitForMailboxDatabase $waitResourceId { Identity = $DB.Name Credential = $ShellCreds } xExchMailboxDatabaseCopy $copyResourceId { Identity = $DB.Name Credential = $ShellCreds MailboxServer = $Node.NodeName ActivationPreference = $DB.ActivationPreference ReplayLagTime = $DB.ReplayLagTime AllowServiceRestart = $true DependsOn = "[xExchWaitForMailboxDatabase]$($waitResourceId)" } } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example ConfigureDatabasesManual -ConfigurationData $PSScriptRoot\ConfigureDatabases-Manual-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. Set-DscLocalConfigurationManager -Path .\ConfigureDatabasesManual -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\ConfigureDatabasesManual -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureVirtualDirectories/ConfigureVirtualDirectories.ps1
ConfigureVirtualDirectories.ps1
Configuration ConfigureVirtualDirectories { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { $casSettings = $ConfigurationData[$Node.CASId] #Look up and retrieve the CAS settings for this node #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } ###CAS specific settings### xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://$($casSettings.InternalNLBFqdn)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = $casSettings.AutoDiscoverSiteScope } #Install features that are required for xExchActiveSyncVirtualDirectory to do Auto Certification Based Authentication WindowsFeature WebClientAuth { Name = 'Web-Client-Auth' Ensure = 'Present' } WindowsFeature WebCertAuth { Name = 'Web-Cert-Auth' Ensure = 'Present' } #This example shows how to enable Certificate Based Authentication for ActiveSync xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds AutoCertBasedAuth = $true AutoCertBasedAuthThumbprint = '49bef4b2e82599233154465323ebf96a12b60673' BasicAuthEnabled = $false ClientCertAuth = 'Required' ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/Microsoft-Server-ActiveSync" WindowsAuthEnabled = $false AllowServiceRestart = $true DependsOn = '[WindowsFeature]WebClientAuth','[WindowsFeature]WebCertAuth' #NOTE: If CBA is being configured, this should also be dependent on the cert whose thumbprint is being used. See EndToEndExample. } #Ensures forms based auth and configures URLs xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds BasicAuthentication = $true ExternalAuthenticationMethods = 'Fba' ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/ecp" FormsAuthentication = $true InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ecp" WindowsAuthentication = $false AllowServiceRestart = $true } #Configure URL's and for NTLM and negotiate auth xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/mapi" IISAuthenticationMethods = 'NTLM','Negotiate' InternalUrl = "https://$($casSettings.InternalNLBFqdn)/mapi" AllowServiceRestart = $true } #Configure URL's and add any OABs this vdir should distribute xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/oab" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/oab" OABsToDistribute = $casSettings.OABsToDistribute AllowServiceRestart = $true } #Configure URL's and auth settings xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalClientAuthenticationMethod = 'Ntlm' ExternalClientsRequireSSL = $true ExternalHostName = $casSettings.ExternalNLBFqdn IISAuthenticationMethods = 'Ntlm' InternalClientAuthenticationMethod = 'Ntlm' InternalClientsRequireSSL = $true InternalHostName = $casSettings.InternalNLBFqdn AllowServiceRestart = $true } #Ensures forms based auth and configures URLs and IM integration xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds BasicAuthentication = $true ExternalAuthenticationMethods = 'Fba' ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/owa" FormsAuthentication = $true InternalUrl = "https://$($casSettings.InternalNLBFqdn)/owa" WindowsAuthentication = $false AllowServiceRestart = $true } #Turn on Windows Integrated auth for remote powershell connections xExchPowerShellVirtualDirectory PSVdir { Identity = "$($Node.NodeName)\PowerShell (Default Web Site)" Credential = $ShellCreds WindowsAuthentication = $true AllowServiceRestart = $true } #Configure URL's xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/ews/exchange.asmx" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ews/exchange.asmx" AllowServiceRestart = $true } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example ConfigureVirtualDirectories -ConfigurationData $PSScriptRoot\ConfigureVirtualDirectories-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. Set-DscLocalConfigurationManager -Path .\ConfigureVirtualDirectories -Verbose ###Pushes configuration and waits for execution Start-DscConfiguration -Path .\ConfigureVirtualDirectories -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureNamespaces/RegionalNamespaces/RegionalNamespaces.ps1
RegionalNamespaces.ps1
Configuration RegionalNamespaces { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { $casSettings = $ConfigurationData[$Node.CASId] #Look up and retrieve the CAS settings for this node #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://$($casSettings.InternalNLBFqdn)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = $casSettings.AutoDiscoverSiteScope } xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/Microsoft-Server-ActiveSync" } xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/ecp" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ecp" } xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/mapi" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/mapi" IISAuthenticationMethods = "NTLM","Negotiate" #IISAuthenticationMethods is a required parameter for Set-MapiVirtualDirectory AllowServiceRestart = $true #Since we are changing the default auth method, we allow the app pool to be restarted right away so the change goes into effect immediately } xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/oab" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/oab" } xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalHostName = $casSettings.ExternalNLBFqdn ExternalClientAuthenticationMethod = 'Ntlm' #ExternalClientAuthenticationMethod is a required parameter for Set-OutlookAnywhere if ExternalHostName is specified ExternalClientsRequireSsl = $true #ExternalClientsRequireSsl is a required parameter for Set-OutlookAnywhere if ExternalHostName is specified InternalHostName = $casSettings.InternalNLBFqdn InternalClientAuthenticationMethod = 'Ntlm' #ExternalClientAuthenticationMethod is a required parameter for Set-OutlookAnywhere if InternalHostName is specified InternalClientsRequireSSL = $true #ExternalClientsRequireSsl is a required parameter for Set-OutlookAnywhere if InternalHostName is specified AllowServiceRestart = $true #Since we are changing the default auth method, we allow the app pool to be restarted right away so the change goes into effect immediately } xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/owa" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/owa" } xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettings.ExternalNLBFqdn)/ews/exchange.asmx" InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ews/exchange.asmx" } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example RegionalNamespaces -ConfigurationData $PSScriptRoot\RegionalNamespaces-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. #Set-DscLocalConfigurationManager -Path .\RegionalNamespaces -Verbose ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\RegionalNamespaces -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureNamespaces/InternetFacingSite/InternetFacingSite.ps1
InternetFacingSite.ps1
Configuration InternetFacingSite { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { $casSettings = $ConfigurationData[$Node.CASId] #Look up and retrieve the CAS settings for this node #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://$($casSettings.InternalNLBFqdn)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = $casSettings.AutoDiscoverSiteScope } xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds ExternalUrl = $casSettings.ExternalUrlActiveSync InternalUrl = "https://$($casSettings.InternalNLBFqdn)/Microsoft-Server-ActiveSync" } xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds ExternalUrl = $casSettings.ExternalUrlECP InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ecp" } xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = $casSettings.ExternalUrlMAPI InternalUrl = "https://$($casSettings.InternalNLBFqdn)/mapi" IISAuthenticationMethods = "NTLM","Negotiate" #IISAuthenticationMethods is a required parameter for Set-MapiVirtualDirectory AllowServiceRestart = $true #Since we are changing the default auth method, we allow the app pool to be restarted right away so the change goes into effect immediately } xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = $casSettings.ExternalUrlOAB InternalUrl = "https://$($casSettings.InternalNLBFqdn)/oab" } xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalHostName = $casSettings.ExternalUrlOA ExternalClientAuthenticationMethod = 'Ntlm' #ExternalClientAuthenticationMethod is a required parameter for Set-OutlookAnywhere if ExternalHostName is specified ExternalClientsRequireSsl = $true #ExternalClientsRequireSsl is a required parameter for Set-OutlookAnywhere if ExternalHostName is specified InternalHostName = $casSettings.InternalNLBFqdn InternalClientAuthenticationMethod = 'Ntlm' #ExternalClientAuthenticationMethod is a required parameter for Set-OutlookAnywhere if InternalHostName is specified InternalClientsRequireSSL = $true #ExternalClientsRequireSsl is a required parameter for Set-OutlookAnywhere if InternalHostName is specified AllowServiceRestart = $true #Since we are changing the default auth method, we allow the app pool to be restarted right away so the change goes into effect immediately } xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds ExternalUrl = $casSettings.ExternalUrlOWA InternalUrl = "https://$($casSettings.InternalNLBFqdn)/owa" } xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = $casSettings.ExternalUrlEWS InternalUrl = "https://$($casSettings.InternalNLBFqdn)/ews/exchange.asmx" } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example InternetFacingSite -ConfigurationData $PSScriptRoot\InternetFacingSite-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. #Set-DscLocalConfigurationManager -Path .\InternetFacingSite -Verbose ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\InternetFacingSite -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/ConfigureNamespaces/SingleNamespace/SingleNamespace.ps1
SingleNamespace.ps1
Configuration SingleNamespace { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Thumbprint of the certificate used to decrypt credentials on the target node LocalConfigurationManager { CertificateId = $Node.Thumbprint } xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://mail.mikelab.local/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = "Site1","Site2" } xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://mail.mikelab.local/Microsoft-Server-ActiveSync" InternalUrl = "https://mail.mikelab.local/Microsoft-Server-ActiveSync" } xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://mail.mikelab.local/ecp" InternalUrl = "https://mail.mikelab.local/ecp" } xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://mail.mikelab.local/mapi" InternalUrl = "https://mail.mikelab.local/mapi" IISAuthenticationMethods = "NTLM","Negotiate" #IISAuthenticationMethods is a required parameter for Set-MapiVirtualDirectory AllowServiceRestart = $true #Since we are changing the default auth method, we allow the app pool to be restarted right away so the change goes into effect immediately } xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://mail.mikelab.local/oab" InternalUrl = "https://mail.mikelab.local/oab" } xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalHostName = "mail.mikelab.local" ExternalClientAuthenticationMethod = 'Ntlm' #ExternalClientAuthenticationMethod is a required parameter for Set-OutlookAnywhere if ExternalHostName is specified ExternalClientsRequireSsl = $true #ExternalClientsRequireSsl is a required parameter for Set-OutlookAnywhere if ExternalHostName is specified InternalHostName = "mail.mikelab.local" InternalClientAuthenticationMethod = 'Ntlm' #ExternalClientAuthenticationMethod is a required parameter for Set-OutlookAnywhere if InternalHostName is specified InternalClientsRequireSSL = $true #ExternalClientsRequireSsl is a required parameter for Set-OutlookAnywhere if InternalHostName is specified AllowServiceRestart = $true #Since we are changing the default auth method, we allow the app pool to be restarted right away so the change goes into effect immediately } xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://mail.mikelab.local/owa" InternalUrl = "https://mail.mikelab.local/owa" } xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://mail.mikelab.local/ews/exchange.asmx" InternalUrl = "https://mail.mikelab.local/ews/exchange.asmx" } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example SingleNamespace -ConfigurationData $PSScriptRoot\SingleNamespace-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. #Set-DscLocalConfigurationManager -Path .\SingleNamespace -Verbose ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\SingleNamespace -Verbose -Wait
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/MaintenanceMode/MaintenanceModeStart.ps1
MaintenanceModeStart.ps1
Configuration MaintenanceModeStart { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { xExchMaintenanceMode EnterMaintenanceMode { Enabled = $true Credential = $ShellCreds } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example MaintenanceModeStart -ConfigurationData $PSScriptRoot\MaintenanceMode-Config.psd1 -ShellCreds $ShellCreds ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\MaintenanceModeStart -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/MaintenanceMode/MaintenanceModePrep.ps1
MaintenanceModePrep.ps1
Configuration MaintenanceModePrep { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { LocalConfigurationManager { CertificateId = $Node.Thumbprint ConfigurationMode = "ApplyOnly" #Set to ApplyOnly, as we probably don't want to continuously check our config during Maintenance } xExchMailboxServer SetMbxServerSite1 { Identity = $Node.NodeName #Use a different server Identity for each xExchMailboxServer resource to satisfy the Key requirement. Use HOSTNAME here. Credential = $ShellCreds DatabaseCopyAutoActivationPolicy = "Blocked" DomainController = $Node.Site1DC } xExchMailboxServer SetMbxServerSite2 { Identity = $Node.NodeFqdn #Use a different server Identity for each xExchMailboxServer resource to satisfy the Key requirement. Use FQDN here. Credential = $ShellCreds DatabaseCopyAutoActivationPolicy = "Blocked" DomainController = $Node.Site2DC } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example MaintenanceModePrep -ConfigurationData $PSScriptRoot\MaintenanceMode-Config.psd1 -ShellCreds $ShellCreds ###Sets up LCM on target computers to decrypt credentials. #Set-DscLocalConfigurationManager -Path .\MaintenanceModePrep -Verbose -ComputerName XXX ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\MaintenanceModePrep -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/MaintenanceMode/MaintenanceModeStop.ps1
MaintenanceModeStop.ps1
Configuration MaintenanceModeStop { param ( [PSCredential]$ShellCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { xExchMaintenanceMode ExitMaintenanceMode { Enabled = $false Credential = $ShellCreds AdditionalComponentsToActivate = "AutoDiscoverProxy","ActiveSyncProxy","EcpProxy","EwsProxy","ImapProxy","OabProxy","OwaProxy","PopProxy","PushNotificationsProxy","RpsProxy","RwsProxy","RpcProxy","UMCallRouter","XropProxy","HttpProxyAvailabilityGroup","MapiProxy","EdgeTransport","HighAvailability","SharedCache" MovePreferredDatabasesBack = $true SetInactiveComponentsFromAnyRequesterToActive = $true } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example MaintenanceModeStop -ConfigurationData $PSScriptRoot\MaintenanceMode-Config.psd1 -ShellCreds $ShellCreds ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\MaintenanceModeStop -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/1-ConfigureLCMForDeployment.ps1
1-ConfigureLCMForDeployment.ps1
Configuration ConfigureLCMForDeployment { Node $AllNodes.NodeName { LocalConfigurationManager { CertificateId = $Node.Thumbprint ConfigurationMode = "ApplyAndMonitor" RebootNodeIfNeeded = $true } } } ###Compiles the example ConfigureLCMForDeployment -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 ###Sets up LCM on target computers to decrypt credentials, and to allow reboot during resource execution #Set-DscLocalConfigurationManager -Path .\ConfigureLCMForDeployment -Verbose -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/8-ConfigureDatabaseCopies.ps1
8-ConfigureDatabaseCopies.ps1
Configuration ConfigureDatabaseCopies { param ( [PSCredential]$ShellCreds, [string]$NodeFilter = "*" ) #Import required DSC Modules Import-DscResource -Module xExchange #Import the helper module. It is used for importing the .CSV's created by the Server Role Requirements Calculator and using them to create mount points and databases Import-Module "$($PSScriptRoot)\ExchangeConfigHelper.psm1" #This section will handle configuring all non-DAG specific settings, including CAS and MBX settings. Node $AllNodes.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node ###Mailbox Server settings### $copyDbList = DBListFromMailboxDatabaseCopiesCsv -MailboxDatabaseCopiesCsvPath $Node.MailboxDatabaseCopiesCsvPath -ServerNameInCsv $Node.ServerNameInCsv -DbNameReplacements $dagSettings.DbNameReplacements #Create the copies foreach ($DB in $copyDbList) { $waitResourceId = "WaitForDB:$($DB.Name)" #Unique ID for the xWaitForMailboxDatabase resource $copyResourceId = "MDBCopy:$($DB.Name)" #Unique ID for the xMailboxDatabaseCopy resource #Need to wait for a primary copy to be created before we add a copy xExchWaitForMailboxDatabase $waitResourceId { Identity = $DB.Name Credential = $ShellCreds } xExchMailboxDatabaseCopy $copyResourceId { Identity = $DB.Name Credential = $ShellCreds MailboxServer = $Node.NodeName ActivationPreference = $DB.ActivationPreference ReplayLagTime = $DB.ReplayLagTime AllowServiceRestart = $false SeedingPostponed = $true DependsOn = "[xExchWaitForMailboxDatabase]$($waitResourceId)" } } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example ConfigureDatabaseCopies -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 -ShellCreds $ShellCreds -NodeFilter "*" ###Pushes configuration to specified computer #Start-DscConfiguration -Path .\ConfigureDatabaseCopies -Verbose -Wait -Credential $ShellCreds -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/6-ConfigureDAG.ps1
6-ConfigureDAG.ps1
Configuration ConfigureDAG { param ( [PSCredential]$ShellCreds ) #Import required DSC Modules Import-DscResource -Module xExchange #This first section only configures a single DAG node, the first member of the DAG. #The first member of the DAG will be responsible for DAG creation and maintaining its configuration Node $AllNodes.Where{$_.Role -eq 'FirstDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Create the DAG xExchDatabaseAvailabilityGroup DAG { Name = $dagSettings.DAGName Credential = $ShellCreds AutoDagTotalNumberOfServers = $dagSettings.AutoDagTotalNumberOfServers AutoDagDatabaseCopiesPerVolume = $dagSettings.AutoDagDatabaseCopiesPerVolume AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DatacenterActivationMode = "DagOnly" DatabaseAvailabilityGroupIPAddresses = $dagSettings.DatabaseAvailabilityGroupIPAddresses ManualDagNetworkConfiguration = $false ReplayLagManagerEnabled = $true SkipDagValidation = $true WitnessDirectory = 'C:\FSW' WitnessServer = $dagSettings.WitnessServer } #Add this server as member xExchDatabaseAvailabilityGroupMember DAGMember { MailboxServer = $Node.NodeName Credential = $ShellCreds DAGName = $dagSettings.DAGName SkipDagValidation = $true DependsOn = '[xExchDatabaseAvailabilityGroup]DAG' } } #Next we'll add the remaining nodes to the DAG Node $AllNodes.Where{$_.Role -eq 'AdditionalDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Can't join until the DAG exists... xExchWaitForDAG WaitForDAG { Identity = $dagSettings.DAGName Credential = $ShellCreds } xExchDatabaseAvailabilityGroupMember DAGMember { MailboxServer = $Node.NodeName Credential = $ShellCreds DAGName = $dagSettings.DAGName SkipDagValidation = $true DependsOn = '[xExchWaitForDAG]WaitForDAG' } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example ConfigureDAG -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 -ShellCreds $ShellCreds ###Pushes configuration to specified computer #Start-DscConfiguration -Path .\ConfigureDAG -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/3-CleanupJetstress.ps1
3-CleanupJetstress.ps1
Configuration CleanupJetstress { Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Uninstall Jetstress from the computer Package UninstallJetstress { Ensure = 'Absent' Path = 'C:\Binaries\Jetstress\Jetstress.msi' Name = 'Microsoft Exchange Jetstress 2013 - Uninstall' ProductId = '75189587-0D84-4404-8F02-79C39728FA64' } #Clean up Jetstress databases, mount points, and binaries xExchJetstressCleanup CleanupJetstress { JetstressPath = "C:\Program Files\Exchange Jetstress" ConfigFilePath = "C:\Program Files\Exchange Jetstress\JetstressConfig.xml" DeleteAssociatedMountPoints = $true OutputSaveLocation = "$($Node.FileServerBase)\JetstressOutput\$($Node.NodeName)" RemoveBinaries = $true DependsOn = '[Package]UninstallJetstress' } } } ###Compiles the example CleanupJetstress -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\CleanupJetstress -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/2-InstallAndRunJetstress.ps1
2-InstallAndRunJetstress.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingCmdletAliases", "")] [CmdletBinding()] param() Configuration InstallAndRunJetstress { param ( [PSCredential]$FileCopyCreds ) Import-DscResource -Module xExchange Node $AllNodes.NodeName { #Create mount points for use with Jetstress. Here I prefer to use the same database names for ALL servers, #that way I can use the same JetstressConfig.xml for all of them. xExchAutoMountPoint AMPForJetstress { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = $Node.JetstressDiskToDBMap SpareVolumeCount = 0 VolumePrefix = 'EXVOL' CreateSubfolders = $true } #Copy the Jetstress install file File CopyJetstress { Ensure = 'Present' SourcePath = "$($Node.FileServerBase)\Jetstress\Jetstress.msi" DestinationPath = 'C:\Binaries\Jetstress\Jetstress.msi' Credential = $FileCopyCreds } #Install Jetstress Package InstallJetstress { Ensure = 'Present' Path = 'C:\Binaries\Jetstress\Jetstress.msi' Name = 'Microsoft Exchange Jetstress 2013' ProductId = '75189587-0D84-4404-8F02-79C39728FA64' DependsOn = '[xExchAutoMountPoint]AMPForJetstress','[File]CopyJetstress' } #Copy required ESE DLL's to the Jetstress installation directory File CopyESEDlls { Ensure = 'Present' Type = 'Directory' Recurse = $true SourcePath = "$($Node.FileServerBase)\Jetstress\ESEDlls" DestinationPath = 'C:\Program Files\Exchange Jetstress' Credential = $FileCopyCreds DependsOn = '[Package]InstallJetstress' } #Copy JetstressConfig.xml to the Jetstress installation directory File CopyJetstressConfig { Ensure = 'Present' SourcePath = "$($Node.FileServerBase)\Jetstress\JetstressConfig.xml" DestinationPath = 'C:\Program Files\Exchange Jetstress\JetstressConfig.xml' Credential = $FileCopyCreds DependsOn = '[Package]InstallJetstress' } #Run the Jetstress test, and evaluate the results xExchJetstress RunJetstress { Type = 'Performance' JetstressPath = 'C:\Program Files\Exchange Jetstress' JetstressParams = '/c "C:\Program Files\Exchange Jetstress\JetstressConfig.xml"' MinAchievedIOPS = 100 DependsOn = '[File]CopyESEDlls','[File]CopyJetstressConfig' } } } if ($null -eq $FileCopyCreds) { $FileCopyCreds = Get-Credential -Message "Enter the credentials to copy Jetstress files from the file server" } ###Compiles the example InstallAndRunJetstress -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 -FileCopyCreds $FileCopyCreds ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\InstallAndRunJetstress -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/9-ConfigureLCMForContinuousChecking.ps1
9-ConfigureLCMForContinuousChecking.ps1
Configuration ConfigureLCMForContinuousChecking { Node $AllNodes.NodeName { LocalConfigurationManager { CertificateId = $Node.Thumbprint RebootNodeIfNeeded = $false ConfigurationMode = "ApplyAndAutoCorrect" ConfigurationModeFrequencyMins = 30 } } } if ($null -eq $RemoteServerCreds) { $RemoteServerCreds = Get-Credential -Message "Enter credentials for connecting to remote Exchange Server" } ###Compiles the example ConfigureLCMForContinuousChecking -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 ###Sets up LCM on target computers to decrypt credentials, and to allow reboot during resource execution #Set-DscLocalConfigurationManager -Path .\ConfigureLCMForContinuousChecking -Verbose -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/5-ConfigureServerSettings.ps1
5-ConfigureServerSettings.ps1
Configuration ConfigureServerSettings { param ( [PSCredential]$ShellCreds, [PSCredential]$CertCreds, [PSCredential]$FileCopyCreds ) #Import required DSC Modules Import-DscResource -Module xExchange Import-DscResource -Module xWebAdministration Node $AllNodes.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Get DAG settings for this node $casSettingsAll = $ConfigurationData.AllCAS #Get CAS settings for all sites $casSettingsPerSite = $ConfigurationData[$Node.CASId] #Get site specific CAS settings for this node #Copy an certificate .PFX that had been previously exported, import it, and enable services on it File CopyExchangeCert { Ensure = 'Present' SourcePath = "$($Node.FileServerBase)\Certificates\ExchangeCert.pfx" DestinationPath = 'C:\Binaries\Certificates\ExchangeCert.pfx' Credential = $FileCopyCreds } xExchExchangeCertificate Certificate { Thumbprint = $dagSettings.Thumbprint Credential = $ShellCreds Ensure = 'Present' AllowExtraServices = $true CertCreds = $CertCreds CertFilePath = 'C:\Binaries\Certificates\ExchangeCert.pfx' Services = 'IIS','POP','IMAP','SMTP' DependsOn = '[File]CopyExchangeCert' } ###CAS specific settings### #The following section shows how to configure commonly configured URL's on various virtual directories xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://$($casSettingsPerSite.InternalNamespace)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = $casSettingsPerSite.AutoDiscoverSiteScope } xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/Microsoft-Server-ActiveSync" } xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/ecp" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/ecp" } xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/mapi" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/mapi" IISAuthenticationMethods = 'Ntlm','OAuth','Negotiate' } xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/oab" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/oab" } xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalClientAuthenticationMethod = 'Negotiate' ExternalClientsRequireSSL = $true ExternalHostName = $casSettingsAll.ExternalNamespace IISAuthenticationMethods = 'Basic', 'Ntlm', 'Negotiate' InternalClientAuthenticationMethod = 'Ntlm' InternalClientsRequireSSL = $true InternalHostName = $casSettingsPerSite.InternalNamespace } #Configure OWA Lync Integration in the web.config xWebConfigKeyValue OWAIMCertificateThumbprint { WebsitePath = "IIS:\Sites\Exchange Back End\owa" ConfigSection = "AppSettings" Ensure = "Present" Key = "IMCertificateThumbprint" Value = $dagSettings.Thumbprint } xWebConfigKeyValue OWAIMServerName { WebsitePath = "IIS:\Sites\Exchange Back End\owa" ConfigSection = "AppSettings" Ensure = "Present" Key = "IMServerName" Value = $casSettingsPerSite.InstantMessagingServerName } #Sets OWA url's, and enables Lync integration on the OWA front end directory xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/owa" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/owa" InstantMessagingEnabled = $true InstantMessagingCertificateThumbprint = $dagSettings.Thumbprint InstantMessagingServerName = $casSettingsPerSite.InstantMessagingServerName InstantMessagingType = 'Ocs' DependsOn = '[xExchExchangeCertificate]Certificate' #Can't configure the IM cert until it's valid } xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/ews/exchange.asmx" InternalNLBBypassUrl = "https://$($Node.Fqdn)/ews/exchange.asmx" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/ews/exchange.asmx" } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } if ($null -eq $CertCreds) { $CertCreds = Get-Credential -Message 'Enter credentials for importing the Exchange certificate' } if ($null -eq $FileCopyCreds) { $FileCopyCreds = Get-Credential -Message 'Enter credentials for copying files from the file server' } ###Compiles the example ConfigureServerSettings -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 -ShellCreds $ShellCreds -CertCreds $CertCreds -FileCopyCreds $FileCopyCreds ###Pushes configuration to specified computer #Start-DscConfiguration -Path .\ConfigureServerSettings -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/4-InstallExchange.ps1
4-InstallExchange.ps1
Configuration InstallExchange { param ( [PSCredential]$InstallCreds, [PSCredential]$FileCopyCreds ) Import-DscResource -Module xExchange Import-DscResource -Module xPendingReboot Node $AllNodes.NodeName { #Copy the Exchange setup files locally File ExchangeBinaries { Ensure = 'Present' Type = 'Directory' Recurse = $true SourcePath = "$($Node.FileServerBase)\E2K13CU8" DestinationPath = 'C:\Binaries\E2K13CU8' Credential = $FileCopyCreds } #Check if a reboot is needed before installing Exchange xPendingReboot BeforeExchangeInstall { Name = "BeforeExchangeInstall" DependsOn = '[File]ExchangeBinaries' } #Do the Exchange install xExchInstall InstallExchange { Path = "C:\Binaries\E2K13CU8\Setup.exe" Arguments = "/mode:Install /role:Mailbox,ClientAccess /IAcceptExchangeServerLicenseTerms" Credential = $InstallCreds DependsOn = '[xPendingReboot]BeforeExchangeInstall' } #This section licenses the server xExchExchangeServer EXServer { Identity = $Node.NodeName Credential = $InstallCreds ProductKey = $Node.ProductKey AllowServiceRestart = $true DependsOn = '[xExchInstall]InstallExchange' } #See if a reboot is required after installing Exchange xPendingReboot AfterExchangeInstall { Name = "AfterExchangeInstall" DependsOn = '[xExchInstall]InstallExchange' } } } if ($null -eq $InstallCreds) { $InstallCreds = Get-Credential -Message "Enter credentials for Installing Exchange" } if ($null -eq $FileCopyCreds) { $FileCopyCreds = Get-Credential -Message "Enter credentials for copying Exchange setup files from the file server" } ###Compiles the example InstallExchange -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 -InstallCreds $InstallCreds -FileCopyCreds $FileCopyCreds ###Pushes configuration and waits for execution #Start-DscConfiguration -Path .\InstallExchange -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/7-ConfigurePrimaryDatabases.ps1
7-ConfigurePrimaryDatabases.ps1
Configuration ConfigurePrimaryDatabases { param ( [PSCredential]$ShellCreds ) #Import required DSC Modules Import-DscResource -Module xExchange #Import the helper module. It is used for importing the .CSV's created by the Server Role Requirements Calculator and using them to create mount points and databases Import-Module "$($PSScriptRoot)\ExchangeConfigHelper.psm1" #This section will handle configuring all non-DAG specific settings, including CAS and MBX settings. Node $AllNodes.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Get DAG settings for this node $casSettingsPerSite = $ConfigurationData[$Node.CASId] #Get site specific CAS settings for this node ###Mailbox Server settings### $dbMap = DBMapFromServersCsv -ServersCsvPath $Node.ServersCsvPath -ServerNameInCsv $Node.ServerNameInCsv -DbNameReplacements $dagSettings.DbNameReplacements $primaryDbList = DBListFromMailboxDatabasesCsv -MailboxDatabasesCsvPath $Node.MailboxDatabasesCsvPath -ServerNameInCsv $Node.ServerNameInCsv -DbNameReplacements $dagSettings.DbNameReplacements #Create all mount points on the server xExchAutoMountPoint AMP { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = $dbMap SpareVolumeCount = 1 VolumePrefix = 'EXVOL' } #Create primary databases foreach ($DB in $primaryDbList) { $resourceId = "MDB:$($DB.Name)" #Need to define a unique ID for each database xExchMailboxDatabase $resourceId { Name = $DB.Name Credential = $ShellCreds EdbFilePath = $DB.DBFilePath LogFolderPath = $DB.LogFolderPath Server = $Node.NodeName CircularLoggingEnabled = $true DatabaseCopyCount = $dagSettings.AutoDagDatabaseCopiesPerVolume OfflineAddressBook = $casSettingsPerSite.DefaultOAB SkipInitialDatabaseMount = $true DependsOn = '[xExchAutoMountPoint]AMP' #Can't create databases until the mount points exist } } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } ###Compiles the example ConfigurePrimaryDatabases -ConfigurationData $PSScriptRoot\ExchangeSettings-Prod.psd1 -ShellCreds $ShellCreds ###Pushes configuration to specified computer #Start-DscConfiguration -Path .\ConfigurePrimaryDatabases -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xExchange/1.15.0.0/Examples/EndToEndExample/10-OngoingConfiguration.ps1
10-OngoingConfiguration.ps1
Configuration OngoingConfiguration { param ( [PSCredential]$ShellCreds, [PSCredential]$CertCreds, [PSCredential]$FileCopyCreds ) #Import required DSC Modules Import-DscResource -Module xExchange Import-DscResource -Module xWebAdministration Node $AllNodes.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Get DAG settings for this node $casSettingsAll = $ConfigurationData.AllCAS #Get CAS settings for all sites $casSettingsPerSite = $ConfigurationData[$Node.CASId] #Get site specific CAS settings for this node #Copy an certificate .PFX that had been previously exported, import it, and enable services on it File CopyExchangeCert { Ensure = 'Present' SourcePath = "$($Node.FileServerBase)\Certificates\ExchangeCert.pfx" DestinationPath = 'C:\Binaries\Certificates\ExchangeCert.pfx' Credential = $FileCopyCreds } xExchExchangeCertificate Certificate { Thumbprint = $dagSettings.Thumbprint Credential = $ShellCreds Ensure = 'Present' AllowExtraServices = $true CertCreds = $CertCreds CertFilePath = 'C:\Binaries\Certificates\ExchangeCert.pfx' Services = 'IIS','POP','IMAP','SMTP' DependsOn = '[File]CopyExchangeCert' } ###CAS specific settings### #The following section shows how to configure commonly configured URL's on various virtual directories xExchClientAccessServer CAS { Identity = $Node.NodeName Credential = $ShellCreds AutoDiscoverServiceInternalUri = "https://$($casSettingsPerSite.InternalNamespace)/autodiscover/autodiscover.xml" AutoDiscoverSiteScope = $casSettingsPerSite.AutoDiscoverSiteScope } xExchActiveSyncVirtualDirectory ASVdir { Identity = "$($Node.NodeName)\Microsoft-Server-ActiveSync (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/Microsoft-Server-ActiveSync" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/Microsoft-Server-ActiveSync" } xExchEcpVirtualDirectory ECPVDir { Identity = "$($Node.NodeName)\ecp (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/ecp" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/ecp" } xExchMapiVirtualDirectory MAPIVdir { Identity = "$($Node.NodeName)\mapi (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/mapi" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/mapi" IISAuthenticationMethods = 'Ntlm','OAuth','Negotiate' } xExchOabVirtualDirectory OABVdir { Identity = "$($Node.NodeName)\OAB (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/oab" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/oab" } xExchOutlookAnywhere OAVdir { Identity = "$($Node.NodeName)\Rpc (Default Web Site)" Credential = $ShellCreds ExternalClientAuthenticationMethod = 'Negotiate' ExternalClientsRequireSSL = $true ExternalHostName = $casSettingsAll.ExternalNamespace IISAuthenticationMethods = 'Basic', 'Ntlm', 'Negotiate' InternalClientAuthenticationMethod = 'Ntlm' InternalClientsRequireSSL = $true InternalHostName = $casSettingsPerSite.InternalNamespace } #Configure OWA Lync Integration in the web.config xWebConfigKeyValue OWAIMCertificateThumbprint { WebsitePath = "IIS:\Sites\Exchange Back End\owa" ConfigSection = "AppSettings" Ensure = "Present" Key = "IMCertificateThumbprint" Value = $dagSettings.Thumbprint } xWebConfigKeyValue OWAIMServerName { WebsitePath = "IIS:\Sites\Exchange Back End\owa" ConfigSection = "AppSettings" Ensure = "Present" Key = "IMServerName" Value = $casSettingsPerSite.InstantMessagingServerName } #Sets OWA url's, and enables Lync integration on the OWA front end directory xExchOwaVirtualDirectory OWAVdir { Identity = "$($Node.NodeName)\owa (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/owa" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/owa" InstantMessagingEnabled = $true InstantMessagingCertificateThumbprint = $dagSettings.Thumbprint InstantMessagingServerName = $casSettingsPerSite.InstantMessagingServerName InstantMessagingType = 'Ocs' DependsOn = '[xExchExchangeCertificate]Certificate' #Can't configure the IM cert until it's valid } xExchWebServicesVirtualDirectory EWSVdir { Identity = "$($Node.NodeName)\EWS (Default Web Site)" Credential = $ShellCreds ExternalUrl = "https://$($casSettingsAll.ExternalNamespace)/ews/exchange.asmx" InternalNLBBypassUrl = "https://$($Node.Fqdn)/ews/exchange.asmx" InternalUrl = "https://$($casSettingsPerSite.InternalNamespace)/ews/exchange.asmx" } ###Mailbox Server settings### $dbMap = DBMapFromServersCsv -ServersCsvPath $Node.ServersCsvPath -ServerNameInCsv $Node.ServerNameInCsv -DbNameReplacements $dagSettings.DbNameReplacements $primaryDbList = DBListFromMailboxDatabasesCsv -MailboxDatabasesCsvPath $Node.MailboxDatabasesCsvPath -ServerNameInCsv $Node.ServerNameInCsv -DbNameReplacements $dagSettings.DbNameReplacements $copyDbList = DBListFromMailboxDatabaseCopiesCsv -MailboxDatabaseCopiesCsvPath $Node.MailboxDatabaseCopiesCsvPath -ServerNameInCsv $Node.ServerNameInCsv -DbNameReplacements $dagSettings.DbNameReplacements #Create all mount points on the server xExchAutoMountPoint AMP { Identity = $Node.NodeName AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DiskToDBMap = $dbMap SpareVolumeCount = 1 VolumePrefix = 'EXVOL' } #Create primary databases foreach ($DB in $primaryDbList) { $resourceId = "MDB:$($DB.Name)" #Need to define a unique ID for each database xExchMailboxDatabase $resourceId { Name = $DB.Name Credential = $ShellCreds EdbFilePath = $DB.DBFilePath LogFolderPath = $DB.LogFolderPath Server = $Node.NodeName CircularLoggingEnabled = $true DatabaseCopyCount = $dagSettings.AutoDagDatabaseCopiesPerVolume OfflineAddressBook = $casSettingsPerSite.DefaultOAB SkipInitialDatabaseMount = $true DependsOn = '[xExchAutoMountPoint]AMP' #Can't create databases until the mount points exist } } #Configure the copies foreach ($DB in $copyDbList) { $waitResourceId = "WaitForDB:$($DB.Name)" #Unique ID for the xWaitForMailboxDatabase resource $copyResourceId = "MDBCopy:$($DB.Name)" #Unique ID for the xMailboxDatabaseCopy resource #Need to wait for a primary copy to be created before we add a copy xExchWaitForMailboxDatabase $waitResourceId { Identity = $DB.Name Credential = $ShellCreds } xExchMailboxDatabaseCopy $copyResourceId { Identity = $DB.Name Credential = $ShellCreds MailboxServer = $Node.NodeName ActivationPreference = $DB.ActivationPreference #ReplayLagTime = $DB.ReplayLagTime #Note that ReplayLagTime is being excluded for the ongoing configuration so that it's easier to disable lags, if necessary AllowServiceRestart = $false DependsOn = "[xExchWaitForMailboxDatabase]$($waitResourceId)" } } } #This first section only configures a single DAG node, the first member of the DAG. #The first member of the DAG will be responsible for DAG creation and maintaining its configuration Node $AllNodes.Where{$_.Role -eq 'FirstDAGMember'}.NodeName { $dagSettings = $ConfigurationData[$Node.DAGId] #Look up and retrieve the DAG settings for this node #Create the DAG xExchDatabaseAvailabilityGroup DAG { Name = $dagSettings.DAGName Credential = $ShellCreds AutoDagTotalNumberOfServers = $dagSettings.AutoDagTotalNumberOfServers AutoDagDatabaseCopiesPerVolume = $dagSettings.AutoDagDatabaseCopiesPerVolume AutoDagDatabasesRootFolderPath = 'C:\ExchangeDatabases' AutoDagVolumesRootFolderPath = 'C:\ExchangeVolumes' DatacenterActivationMode = "DagOnly" DatabaseAvailabilityGroupIPAddresses = $dagSettings.DatabaseAvailabilityGroupIPAddresses ManualDagNetworkConfiguration = $false ReplayLagManagerEnabled = $true SkipDagValidation = $true WitnessDirectory = 'C:\FSW' WitnessServer = $dagSettings.WitnessServer } } } if ($null -eq $ShellCreds) { $ShellCreds = Get-Credential -Message 'Enter credentials for establishing Remote Powershell sessions to Exchange' } if ($null -eq $CertCreds) { $CertCreds = Get-Credential -Message 'Enter credentials for importing the Exchange certificate' } if ($null -eq $FileCopyCreds) { $FileCopyCreds = Get-Credential -Message 'Enter credentials for copying files from the file server' } ###Compiles the example OngoingConfiguration -ConfigurationData $PSScriptRoot\ExchangeSettings-Lab.psd1 -ShellCreds $ShellCreds -CertCreds $CertCreds -FileCopyCreds $FileCopyCreds ###Pushes configuration to specified computer #Start-DscConfiguration -Path .\OngoingConfiguration -Verbose -Wait -ComputerName XXX
PowerShellCorpus/PowerShellGallery/xIISMail/1.0.0.1/DSCResources/xIISMail/Test.ps1
Test.ps1
$Has = @{ SiteName = "hphsite"; DeliveryMethod = "PickupDirectoryFromIis" ; DefaultCredentials = $false; MailHost = "asdasda.xxxx"; From = "sdas@sdad.com" username = "asdads\asdasd" password = "123.com" PickupDirectoryLocation = "x:\asdasasd" } Test-iisxTargetResource @has -Verbose set-iisxTargetResource @has -Verbose Configuration xx { Import-DscResource -module admin* Node Localhost { xIISMail Mail { MailHost = "mail.hphr.com" DefaultCredentials = $true Port = 25 From = "isrvice@hpghr.com" DeliveryMethod = "network" sitename= "hphsite" } } } xx Start-DscConfiguration .\xx -Wait -Verbose -Force
PowerShellCorpus/PowerShellGallery/xIISMail/1.0.0.1/DSCResources/xIISMail/build.ps1
build.ps1
New-xDscResource -Name xIISMail -Property @( New-xDscResourceProperty -Name SiteName -Type String -Attribute Key New-xDscResourceProperty -Name MailHost -Type String -Attribute Write New-xDscResourceProperty -Name Username -Type String -Attribute Write New-xDscResourceProperty -Name Password -Type String -Attribute Write New-xDscResourceProperty -Name Port -Type Uint16 -Attribute Write New-xDscResourceProperty -Name DefaultCredentials -Type Boolean -Attribute Write New-xDscResourceProperty -Name DeliveryMethod -Type String -Attribute Key New-xDscResourceProperty -Name PickupDirectoryLocation -Type String -Attribute Write New-xDscResourceProperty -Name From -Type String -Attribute Write )
PowerShellCorpus/PowerShellGallery/WiscO365/1.0/HelperFunctions.ps1
HelperFunctions.ps1
#Module variables $moduleDataPath = "$env:LOCALAPPDATA\WindowsPowerShell\ModuleData\WiscO365" $credPath = "$moduleDataPath\Connections" $connectionsFile = "$moduleDataPath\Connections\connections.csv" $defaultEndpoint = "https://wiscmail.wisc.edu/domainadmin.json" Function Invoke-HelperO365Function ($body){ Try{ #Invoke the JSON command $result = Invoke-RestMethod -Method Default -Uri $Global:O365CurrentConnection.endpoint -WebSession $Global:O365Session -Credential $Global:O365CurrentConnection.cred -Body $body #Check if the command was successful If(!$result.mesg){return $result.result} ElseIf($result.mesg -like "Success*") {return $result.result} Else{Write-Error $result.mesg} } Catch{ #If an exception resulted, write the error ($_.ErrorDetails.Message | ConvertFrom-Json).error.result | Foreach{if($_ -eq 'authcheck failed'){Write-Error $_} Else {Write-Error $_}} } } Function Test-HelperO365Connection (){ If(!$Global:O365CurrentConnection){ Write-Error "The connection to the endpoint is not set. Please set the connection using the method Set-O365Connection." break } } Function Create-HelperO365ModuleData () { #Check if path exists If(!(Test-Path -Path "$moduleDataPath\Connections")){ Try{ New-Item "$moduleDataPath\Connections" -type directory -Force -ErrorAction Stop | Out-Null } Catch{ Write-Error $_ break } } #Check if path exists If(!(Test-Path -Path "$moduleDataPath\Old API Functions")){ Try{ New-Item "$moduleDataPath\Old API Functions" -type directory -Force -ErrorAction Stop | Out-Null } Catch{ Write-Error $_ break } } #Check if path exists If(!(Test-Path -Path "$moduleDataPath\Preferences")){ Try{ New-Item "$moduleDataPath\Preferences" -type directory -Force -ErrorAction Stop | Out-Null } Catch{ Write-Error $_ break } } #Check if path exists If(!(Test-Path -Path "$moduleDataPath\Preferences\Startup.txt")){ Try{ New-Item "$moduleDataPath\Preferences\Startup.txt" -type file -Force -ErrorAction Stop | Out-Null 1 | Out-File -FilePath "$moduleDataPath\Preferences\Startup.txt" -Force -ErrorAction Stop } Catch{ Write-Error $_ break } } } Function Show-HelperO365StartupMenu (){ $startupPath = "$moduleDataPath\Preferences\Startup.txt" Try{ $startupPreference = Get-Content $startupPath -ErrorAction SilentlyContinue } Catch{ Write-Error $_ } If($startupPreference -like "*1*"){ Write-Host "`n" Write-Host "`t Welcome to the WiscO365 PowerShell Module!" -ForegroundColor Cyan Write-Host "`n" Write-Host "`t`t To get information and help on this module, enter Get-O365Help." -ForegroundColor White Write-Host "`t`t To turn off this menu in future sessions, enter Set-O365StartupPreferences." -ForegroundColor White Write-Host "`n" } } Function Update-HelperO365InitialHelp () { Invoke-Expression "$PSScriptRoot\Update\psDoc-master\src\psDoc.ps1 -moduleName WiscO365 -outputDir $PSScriptRoot -fileName 'WiscO365 Initial Help.html'" } Create-HelperO365ModuleData Show-HelperO365StartupMenu #Check for the API Functions file If(Test-Path -Path "$moduleDataPath\APIFunctions.ps1"){ #If it exists, import the API Functions . "$moduleDataPath\APIFunctions.ps1" } Else{ #If it doesn't exist, import the function to get the other API functions . "$PSScriptRoot\Update\Get-O365DomainAdminDoc.ps1" }
PowerShellCorpus/PowerShellGallery/WiscO365/1.0/Update/Get-O365DomainAdminDoc.ps1
Get-O365DomainAdminDoc.ps1
<# .Synopsis Gets the documentation for the Domain Admin API, which is what you are viewing right now .OUTPUTS failure: undef success: JSON array with all Domain Admin API documentation .LINK https://wiscmail.wisc.edu/admin/index.php?action=domain-domainadmin_api #> Function Get-O365DomainAdminDoc{ [CmdletBinding()] Param ( # Domain name (e.g. bar.wisc.edu) [Parameter(Mandatory=$False,Position=0)] $domain = $Global:O365CurrentConnection.domain ) Begin{ #Check to ensure that a connection has been set. Test-HelperO365Connection } Process{ #Create hash table for JSON command $body = @{ "action" = "getDomainAdminDoc"; "domain" = "$domain" } #Invoke the function Invoke-HelperO365Function -body $body } }
PowerShellCorpus/PowerShellGallery/WiscO365/1.0/Update/UpdateAPIFunctions.ps1
UpdateAPIFunctions.ps1
param( #Defines the output location for the file [Parameter(Mandatory=$false,Position=0)] [string] $outputFile = "$moduleDataPath\New APIFunctions.ps1", #Defines if the alias is included [Parameter(Mandatory=$false,Position=1)] $includeAlias = $false ) $actionWordsPath = "$PSScriptRoot\actionWords.csv" $unallowedWords = Get-Content "$PSScriptRoot\unallowedWords.txt" If(Test-Path $outputFile){Remove-Item $outputFile -Force} $doc = Get-O365DomainAdminDoc -domain $Global:O365CurrentConnection.domain $methods = $doc.methods $methodNames = $methods | Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' Function Create-Function($methodName, $method, $outputFile, $actionWordsPath, $unallowedWords, $includeAlias){ $headers = Create-Headers -method $method -methodName $methodName -includeAlias $includeAlias $params = Create-Parameters -parameters $method.parameters $JSON = Create-JSON -parameters $method.parameters -methodName $methodName Add-Content $outputFile ` $headers Add-Content $outputFile ` " Param ( $params ) " Add-Content $outputFile ` " Begin{ #Check to ensure that a connection has been set. Test-HelperO365Connection } Process{ #Create hash table for JSON command `$body = @{ $JSON } " Add-Content $outputFile ` " #Invoke the function Invoke-HelperO365Function -body `$body } } " } Function Create-Headers($method, $methodName, $includeAlias){ $outputs = (Normalize-Outputs -outputs $method.return).trim() $names = Normalize-FunctionName -origName $methodName -actionWordsPath $actionWordsPath -unallowedWords $unallowedWords $normalizedName = $names.normalizedName $normalizedOriginalName = $names.normalizedOriginalName $originalName = $methodName $string = "" $string+= "<# .Synopsis $($method.purpose) .OUTPUTS $outputs .LINK https://wiscmail.wisc.edu/admin/index.php?action=domain-domainadmin_api #> Function $normalizedName{ [CmdletBinding()] " If($normalizedOriginalName){ $string+= " [Alias(`"$normalizedOriginalName`")] " } If($includeAlias){ $string+= " [Alias(`"$originalName`")] " } return $string } Function Create-Parameters($parameters){ $paramNames = $parameters | Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' $paramString = "" $i=0 $j=$paramNames.count Foreach($paramName in $paramNames){ $isRequired = ($parameters.$paramName.required -eq '1') if($paramName -eq "domain"){$isRequired = $false} if($parameters.$paramName.description -like "*|*") { $predefVals = $parameters.$paramName.description.Split("|") | % {"'$_'"} $predefVals = $predefVals -join "," } else {$predefVals = $null} $paramString += "`t`t" + "# " + "$($parameters.$paramName.description)" + "`n" $paramString += "`t`t" + "[Parameter(Mandatory=$" + "$isRequired,Position=$i)]" + "`n" $paramString += if($predefVals){"`t`t"+ "[ValidateSet($predefVals)]" + "`n"} $paramString += "`t`t" + "$" + "$paramName" $paramString += if($paramName -eq "domain"){" = `$Global:O365CurrentConnection.domain"} $paramString += if($i+1 -lt $j){",`n`n"} $i++ } return $paramString } Function Create-JSON($parameters, $methodName){ $paramNames = $parameters | Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' $JSONString = "" $JSONString += "`t`t`t" + '"action" = ' + '"' + $methodName + '";' + "`n" $i=0 $j=$paramNames.count Foreach ($paramName in $paramNames){ $JSONString += "`t`t`t" + '"' + $paramName + '"' + " = " + '"$' + $paramName + '"' $JSONString += if($i+1 -lt $j){";`n"} $i++ } return $JSONString } Function Normalize-FunctionName($origName, $actionWordsPath, $unallowedWords){ #Import the action words $actionWords = Import-Csv $actionWordsPath #Use PowerShell convention "Verb-Noun" $origVerb = $null $verb = $null $noun = $null #Find the verb $match = $false Foreach ($actionWord in $actionWords){ #Compare the method name to the pre-defined action words (verbs) If($origName -like "$($actionWord.originalVerb)*"){ $match = $true #Check if the original verb has an alternate approved verb (which means the original is unapproved) If($actionWord.approvedVerb){ #If so, the verb will be the alternate approved verb, not the original verb $verb = $actionWord.approvedVerb $origVerb = $actionWord.originalVerb } Else{ #Otherwise, the verb is the original verb $verb = $actionWord.originalVerb $origVerb = $actionWord.originalVerb } } } #If the original name isn't like any of the verbs in the list If(!$match){ #Separate at the first capital letter and remove all except the first word $verb = ($origName -creplace '([A-Z\W_]|\d+)(?<![a-z])',' $&') $verb = $verb.Substring(0, $verb.IndexOf(' ')) $origVerb = $verb #Add the verb to the list #Create an object to store the new verb information and add the values $newVerb = New-Object System.Object $newVerb | Add-Member -MemberType NoteProperty -Name "originalVerb" -Value $origVerb $newVerb | Add-Member -MemberType NoteProperty -Name "approvedVerb" -Value "" #Create an object for storing all the verbs and add the existing verbs $allVerbs = @() Foreach ($actionWord in $actionWords){ $allVerbs += $actionWord } #Add the new verb to the list $allVerbs += $newVerb #Export all verbs to the existing CSV file Try{ $allVerbs | Export-Csv -Path $actionWordsPath -NoTypeInformation -Force -ErrorAction SilentlyContinue } Catch{ Write-Error $_ } } #Trim the original word to get the noun $noun = $origName -replace $origVerb #Check for unallowed words in the noun. If present, at the beginning of the noun, trim them out. Foreach ($unallowedWord in $unallowedWords){ If($noun -like "$unallowedWord*"){ $noun = $noun -replace $unallowedWord } } #Check for special characters in the noun. If present, get rid of them, capitalize the next word, and combine. $noun = $noun -replace '[^a-zA-Z0-9]', ' ' $noun = $noun.Trim() if($noun -like '* *'){ $noun = (Get-Culture).TextInfo.ToTitleCase($noun) $noun = $noun.Replace(' ','') } #Capitalize the first letter of the verbs and noun if($verb) {$verb = $verb.substring(0,1).toupper()+$verb.substring(1)} if($origVerb) {$origVerb = $origVerb.substring(0,1).toupper()+$origVerb.substring(1)} if($noun) {$noun = $noun.substring(0,1).toupper()+$noun.substring(1)} #Create an object to store the names $names = New-Object System.Object #Combine to create the normalized name and add it to the names object $normalizedName = $verb + "-" + "O365" + $noun $names | Add-Member -MemberType NoteProperty -Name normalizedName -Value $normalizedName #If the verb was changed, create the normalized original name and add it to the names object If($verb -ne $origVerb){ $normalizedOriginalName = $origVerb + "-" + "O365" + $noun $names | Add-Member -MemberType NoteProperty -Name normalizedOriginalName -Value $normalizedOriginalName } return $names } Function Normalize-Outputs ($outputs){ $string = "" #Get the names of the outputs $outputNames = $outputs | Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' #Get the members of each of the outputs Foreach ($outputName in $outputNames){ $outputMembers = $outputs.$($outputName) #Check if the members have more members $outputSubMemberNames = $outputMembers | Get-Member -MemberType 'NoteProperty' | Select-Object -ExpandProperty 'Name' If($outputSubMemberNames){ $string += $tab + $outputName $string += "`n`t" $tab += "`t" $string += Normalize-Outputs -outputs $outputMembers } Else{ $string += $tab + $outputName + ": " + $outputMembers $string += "`n`t" } } return $string } Foreach ($methodName in $methodNames){ Create-Function -methodName $methodName -method $methods.$methodName -outputFile $outputFile -actionWordsPath $actionWordsPath -unallowedWords $unallowedWords -includeAlias $includeAlias }
PowerShellCorpus/PowerShellGallery/WiscO365/1.0/Update/psDoc-master/src/out-html-template.ps1
out-html-template.ps1
@" <!DOCTYPE html> <!-- <auto-generated> <synopsis> This code was generated by a tool. on: $(Get-Date) </synopsis> <description> If you'd like to regenerate the documentation, please open up powershell and run > .\psDoc.ps1 -moduleName NameOfYourModule If the documentation is incomplete, or eronious, please edit the comments at the top of the module method within it's respecive .ps1 file. </description> </auto-generated> --> <html lang="en"> <head> <title>$moduleName Module Documentation</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link href="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shCore.min.css" rel="stylesheet" charset="utf-8"> <link href="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/styles/shCoreDefault.min.css" rel="stylesheet" charset="utf-8"> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" charset="utf-8"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <style> .embedStyle { font-family: Arial,"Times New Roman; font-size: 14px; height: 1024px; width: 100%; } .gettingStarted { padding-left: 16px; padding-bottom: 12px; } .syntaxhighlighter { overflow-y: hidden !important; overflow-x: auto !important; } pre { min-height: 30px; } .navbar-nav { height: 100%; overflow-y: auto; } .form-group { padding-top: 12px; padding-left: 12px; padding-right: 12px; } .sidebar-nav .navbar-header { float: none; } .sidebar-nav .navbar li a { padding-top: 4px; padding-bottom: 4px; } @media (min-width: 768px) { .sidebar-nav .navbar .navbar-collapse { padding: 0; max-height: none; } .sidebar-nav .navbar ul { float: none; } .sidebar-nav .navbar ul:not { display: block; } .sidebar-nav .navbar li { float: none; display: block; } } </style> </head> <body> <script> function displayMessage(){ if(document.getElementById("message-id").style.display == 'block'){ document.getElementById("message-id").style.display = 'none'; document.getElementById("main-content-id").style.display = 'block'; document.getElementById("navbar-id").style.display = 'block'; document.getElementById("button-1").style.display = 'block'; document.getElementById("button-2").style.display = 'none'; }else{ document.getElementById("message-id").style.display = 'block'; document.getElementById("main-content-id").style.display = 'none'; document.getElementById("navbar-id").style.display = 'none'; document.getElementById("button-1").style.display = 'none'; document.getElementById("button-2").style.display = 'block'; } } </script> $docTitle <div class="container-fluid"> <div class="row-fluid"> <div class="col-lg-3 col-md-4 col-sm-5 col-xs-12" id="navbar-id"> <div class="sidebar-nav"> <div class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-navbar-collapse"> <span class="sr-only">Toggle</span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <span class="visible-xs navbar-brand">click menu to open</span> </div> <div class="navbar-collapse collapse sidebar-navbar-collapse"> <div class="form-group"> <input class="form-control" id="searchinput" type="search" placeholder="Filter..." /> </div> <ul class="nav navbar-nav list-group" id="searchList"> $extraNav "@ $progress = 0 $commandsHelp | % { Update-Progress $_.Name 'Navigation' $progress++ " <li class=`"nav-menu list-group-item`"><a href=`"#$($_.Name)`">$($_.Name)</a></li>" } @" </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="col-lg-9 col-md-8 col-sm-7 col-xs-12" id="main-content-id"> $extraBody "@ $progress = 0 $commandsHelp | % { Update-Progress $_.Name 'Documentation' $progress++ @" <div id=`"$(FixString($_.Name))`" class="toggle_container"> <div class="page-header"> <h2> $(FixString($_.Name)) </h2> "@ $syn = FixString($_.synopsis) if(!($syn).StartsWith($(FixString($_.Name)))){ @" <p>$syn</p> <p>$(FixString(($_.Description | out-string).Trim()) $true)</p> "@ } @" </div> "@ if (!($_.alias.Length -eq 0)) { @" <div class='panel panel-default'> <div class='panel-heading'> <h3 class='panel-title'> $($_.Name) Aliases </h3> </div> <div class='panel-body'> <ul> "@ $_.alias | % { @" <li>$($_.Name)</li> "@ } @" </ul> </div> </div> "@ } if (!($_.syntax | Out-String ).Trim().Contains('syntaxItem')) { @" <div> <h3> Syntax </h3> </div> <div class="panel panel-default"> <div class='panel-body'> <pre class="brush: ps">$(FixString($_.syntax | out-string))</pre> </div> </div> "@ } if($_.parameters){ @" <div> <h3> Parameters </h3> <table class="table table-striped table-bordered table-condensed visible-on"> <thead> <tr> <th>Name</th> <th class="visible-lg visible-md">Alias</th> <th>Description</th> <th class="visible-lg visible-md">Required?</th> <th class="visible-lg">Pipeline Input</th> <th class="visible-lg">Default Value</th> </tr> </thead> <tbody> "@ $_.parameters.parameter | % { @" <tr> <td><nobr>-$(FixString($_.Name))</nobr></td> <td class="visible-lg visible-md">$(FixString($_.Aliases))</td> <td>$(FixString(($_.Description | out-string).Trim()) $true)</td> <td class="visible-lg visible-md">$(FixString($_.Required))</td> <td class="visible-lg">$(FixString($_.PipelineInput))</td> <td class="visible-lg">$(FixString($_.DefaultValue))</td> </tr> "@ } @" </tbody> </table> </div> "@ } $inputTypes = $(FixString($_.inputTypes | out-string)) if ($inputTypes.Length -gt 0 -and -not $inputTypes.Contains('inputType')) { @" <div> <h3> Inputs </h3> <p>The input type is the type of the objects that you can pipe to the cmdlet.</p> <ul><li>$inputTypes</li></ul> </div> "@ } $returnValues = $(FixString -in ($_.returnValues | out-string) -includeBreaks $true) if ($returnValues.Length -gt 0 -and -not $returnValues.StartsWith("returnValue")) { @" <div> <h3> Outputs </h3> <p>The output type is the type of the objects that the cmdlet emits.</p> <ul><li>$returnValues</li></ul> </div> "@ } $notes = $(FixString($_.alertSet | out-string)) if ($notes.Trim().Length -gt 0) { @" <div class='panel panel-default'> <div class='panel-heading'> <h3 class='panel-title'> Note </h3> </div> <div class='panel-body'>$notes</div> </div> "@ } if(($_.examples | Out-String).Trim().Length -gt 0) { @" <div> <h3> Examples </h3> </div> <div class='panel panel-default'> <div class='panel-body'> "@ $_.examples.example | % { @" <strong>$(FixString($_.title.Trim(('-',' '))))</strong> <pre class="brush: ps">$(FixString($_.code | out-string ).Trim())</pre> <div>$(FixString($_.remarks | out-string ).Trim())</div> "@ } @" </div> </div> <p class='pull-right'><a onclick='document.body.scrollTop = document.documentElement.scrollTop = 0;' style='cursor: pointer;'>Top of page</a> "@ } if(($_.relatedLinks | Out-String).Trim().Length -gt 0) { @" <div> <h3> Links </h3> <div> <ul> "@ $_.links | % { @" <li class='$($_.cssClass)'><a href='$($_.link)' target='$($_.target)'>$($_.name)</a></li> "@ } @" </ul> </div> </div> "@ } @" </div> "@ } @" </div> </div> </div> $docFooter "@ @' <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js" charset="utf-8"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shCore.min.js" charset="utf-8"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/SyntaxHighlighter/3.0.83/scripts/shBrushPowerShell.min.js" charset="utf-8"></script> <script> $(document).ready(function() { $(".toggle_container").hide(); var previousId; if(location.hash) { var id = location.hash.slice(1); //Get rid of the # mark var elementToShow = $("#" + id); //Save local reference if(elementToShow.length) { //Check if the element exists elementToShow.slideToggle('fast'); //Show the element elementToShow.addClass("check_list_selected"); //Add class to element (the link) } previousId = id; } $('.nav-menu a, .psLink a').click(function() { $(".sidebar-navbar-collapse").collapse('hide'); $('.toggle_container').hide(); // Hide all var elem = $(this).prop("hash"); $(elem).toggle('fast'); // Show HREF/to/ID one history.pushState({}, '', $(this).attr("href")); window.scrollTo(0, 0); return false; }); SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.defaults['gutter'] = false; SyntaxHighlighter.all(); $('#searchList').btsListFilter('#searchinput', {itemChild: 'a', initial: false, resetOnBlur: true}); $(document).keyup(function( e ) { if(!$('#searchinput').is(':focus') && e.which >= 65 && e.which <= 90 ){ $('#searchinput').val(String.fromCharCode(e.keyCode)); $('#searchinput').focus(); } }); $(document).click(function() { $('#searchinput').blur(); }); }); </script> <!-- bootstrap-list-filter.min.js - removed as external resource and added as content --> <script> /* * bootstrap-list-filter v0.1.7 - 2015-03-30 * * Copyright 2015 Stefano Cudini * stefano.cudini@gmail.com * http://labs.easyblog.it/ * * Licensed under the MIT license. * * Demos: * http://labs.easyblog.it/bootstrap-list-filter/ * * Source: * git@github.com:stefanocudini/bootstrap-list-filter.git * */ !function(a){a.fn.btsListFilter=function(b,c){function d(a,b){return a.replace(/\{ *([\w_]+) *\}/g,function(a,c){return b[c]||""})}function e(a,b){var c;return b=b||300,function(){var d=this,e=arguments;clearTimeout(c),c=setTimeout(function(){a.apply(d,Array.prototype.slice.call(e))},b)}}var f,g=this,h=a(this),i=a(b),j=h;return c=a.extend({delay:300,minLength:1,initial:!0,eventKey:"keyup",resetOnBlur:!0,sourceData:null,sourceTmpl:'<a class="list-group-item" href="#"><span>{title}</span></a>',sourceNode:function(a){return d(c.sourceTmpl,a)},emptyNode:function(){return'<a class="list-group-item well" href="#"><span>No Results</span></a>'},itemEl:".list-group-item",itemChild:null,itemFilter:function(b,d){d=d&&d.replace(new RegExp("[({[^.$*+?\\]})]","g"),"");var e=a(b).text(),f=c.initial?"^":"",g=new RegExp(f+d,"i");return g.test(e)}},c),i.on(c.eventKey,e(function(){var b=a(this).val();c.itemEl&&(j=h.find(c.itemEl)),c.itemChild&&(j=j.find(c.itemChild));var d=j.filter(function(){return c.itemFilter.call(g,this,b)}),e=j.not(d);c.itemChild&&(d=d.parents(c.itemEl),e=e.parents(c.itemEl).hide()),""!==b&&b.length>=c.minLength?(d.show(),e.hide(),"function"===a.type(c.sourceData)?(d.hide(),e.hide(),f&&(a.isFunction(f.abort)?f.abort():a.isFunction(f.stop)&&f.stop()),f=c.sourceData.call(g,b,function(b){if(f=null,d.hide(),e.hide(),h.find(".bts-dynamic-item").remove(),b&&0!==b.length)for(var i in b)a(c.sourceNode.call(g,b[i])).addClass("bts-dynamic-item").appendTo(h);else a(c.emptyNode.call(g)).addClass("bts-dynamic-item").appendTo(h)})):0===d.length&&a(c.emptyNode.call(g)).addClass("bts-dynamic-item").appendTo(h)):(d.show(),e.show(),h.find(".bts-dynamic-item").remove())},c.delay)),c.resetOnBlur&&i.on("blur",function(){a(this).val("").trigger(c.eventKey)}),h}}(jQuery); </script> </body> </html> '@