full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Tests/Assert-ScriptString.Tests.ps1
Assert-ScriptString.Tests.ps1
$modulePath = Split-Path $PSScriptRoot -Parent $modulepath = Join-Path -Path $modulePath -ChildPath hashdata.psd1 Import-Module $modulePath #cd C:\Users\tore\Dropbox\SourceTreeRepros\HashData ; import-module .\HashData.psd1 Describe "Assert-ScriptString" { $asserted = "@{Test=1;date=new-date 636221878124518548}" $assertedObj = [scriptblock]::Create($asserted).invoke() Context "Validate output" { $actual = Assert-ScriptString -Data $asserted It "Should output an object" { $actual | Should Not Be $null } It "Should produce a hashtable" { $actual.GetType().Name | Should Be "Hashtable" } It "Should have a key [Test]" { $actual.ContainsKey("Test") | should be $true } It "Should have a key [Test] with value [$($assertedObj.Test)]" { $actual.Test | Should be $assertedObj.Test } It "Should be of type [$($assertedObj.Test.GetType().Name)]" { $actual.Test.GetType().Name | Should be $assertedObj.Test.GetType().Name } It "Should have a key [date]" { $actual.ContainsKey("Date") | Should be $true } It "Should have a key [Test] with value [$($assertedObj.Date.Ticks)]" { $actual.Date.Ticks | Should be $assertedObj.Date.Ticks } It "Should be of type [$($assertedObj.GetType().Name)]" { $actual.Date.GetType().Name | Should be $assertedObj.Date.GetType().Name } } Context "Test for restricted language" { $asserted = "@{Test=1;date=write-verbose 636221878124518548}" It "Should throw if string contains unapproved cmdlets" { { $asserted | Assert-ScriptString } | Should throw } It "Should not execute the scrip text if it contains unapproved cmdlets" { "Write-output 1" | Assert-ScriptString -ErrorAction SilentlyContinue | Should be $null } } } Remove-Module hashdata -ErrorAction SilentlyContinue
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/helpers/Connect-O365Skype.ps1
Connect-O365Skype.ps1
function Connect-O365Skype { PARAM ( [System.Management.Automation.PSCredential] $Credential ) try { Import-Module -Name SkypeOnlineConnector -DisableNameChecking -Force -ErrorAction Stop } catch { Write-Error -Message "The module 'SkypeOnlineConnector' was not found. A connection to Skype for Business will not be established" } $Option = New-PSSessionOption -IdleTimeout -1 $SkypeSession = New-CsOnlineSession -Credential $Credential -SessionOption $Option $ModuleName = 'SkypeForBusiness' $ModulePath = Join-Path $AppdataPath $ModuleName $null = Export-PSSession -Session $SkypeSession -OutputModule $ModulePath -AllowClobber -Force Import-Module $ModulePath -Global -DisableNameChecking }
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/helpers/Connect-O365Sharepoint.ps1
Connect-O365Sharepoint.ps1
function Connect-O365Sharepoint { PARAM ( [System.Management.Automation.PSCredential] $Credential, [string] $TenantName ) try { Import-Module -Name Microsoft.Online.Sharepoint.Powershell -DisableNameChecking -Force -ErrorAction Stop } catch { Write-Error -Message "The module 'Microsoft.Online.Sharepoint.Powershell' was not found. A connection to Sharepoint Online will not be established" } $Params = @{ Url = "https://$($PSBoundParameters.TenantName)-admin.sharepoint.com" Credential = $Credential WarningAction = 'SilentlyContinue' } Connect-SPOService @Params }
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/helpers/Connect-O365AzureAD.ps1
Connect-O365AzureAD.ps1
function Connect-O365AzureAD { <# .NOTES Currently supports the MSOnline module - should eventually support the AzureAD module as well, and will check to see which one is installed. If both, then AzureAD will be preferred. #> PARAM ( [System.Management.Automation.PSCredential] $Credential ) try { Import-Module -Name MSOnline -DisableNameChecking -Force -ErrorAction Stop } catch { Write-Error -Message "The module 'MSOnline' was not found. A connection to Azure Active Directory will not be established" } Import-Module -Name MSOnline -DisableNameChecking -Force Connect-MsolService -Credential $Credential }
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/helpers/Connect-O365Exchange.ps1
Connect-O365Exchange.ps1
function Connect-O365Exchange { PARAM ( [System.Management.Automation.PSCredential] $Credential ) $ExchParams = @{ ConfigurationName = 'microsoft.exchange' ConnectionUri = "https://$ExchComputerName/powershell-liveid/" Credential = $Credential Authentication = 'Basic' AllowRedirection = $true } $ExchSession = New-PSSession @ExchParams $ModuleName = 'ExchangeOnline' $ModulePath = Join-Path $AppdataPath $ModuleName $null = Export-PSSession -Session $ExchSession -OutputModule $ModulePath -AllowClobber -Force Import-Module $ModulePath -Global -DisableNameChecking }
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/helpers/Connect-O365Compliance.ps1
Connect-O365Compliance.ps1
function Connect-O365Compliance { PARAM ( [System.Management.Automation.PSCredential] $Credential ) $ComplianceParams = @{ ConfigurationName = 'Microsoft.Exchange' ConnectionUri = "https://$ComplianceComputerName/powershell-liveid/" Credential = $Credential Authentication = 'Basic' AllowRedirection = $true } $CCSession = New-PSSession @ComplianceParams $ModuleName = 'ComplianceCenter' $ModulePath = Join-Path $AppdataPath $ModuleName $null = Export-PSSession -Session $CCSession -OutputModule $ModulePath -AllowClobber -Force Import-Module $ModulePath -Global -DisableNameChecking -Prefix CC }
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/functions/Connect-O365.ps1
Connect-O365.ps1
function Connect-O365 { [CmdletBinding()] PARAM ( [parameter(Mandatory = $true)] [ValidateSet("AzureActiveDirectory","Exchange","ComplianceCenter","Sharepoint","Skype","*")] [string[]] $Services, [parameter(Mandatory = $true)] [System.Management.Automation.Credential()] [System.Management.Automation.PSCredential] $Credential ) DYNAMICPARAM { if ($PSBoundParameters.Services -contains "Sharepoint" -or $PSBoundParameters.Services -contains "*") { $Name = "TenantName" $ParamAttr = [System.Management.Automation.ParameterAttribute]::new() $ParamAttr.Mandatory = $true $Attributes = [Collections.ObjectModel.Collection[System.Attribute]]::new() $Attributes.Add($ParamAttr) $Parameter = [System.Management.Automation.RuntimeDefinedParameter]::new($Name, [string], $Attributes) $Dictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new() $Dictionary.Add($Name, $Parameter) $Dictionary } } BEGIN { if ($Services -eq "*") { $Services = $AllServices } } PROCESS { switch ($Services) { { $_ -contains "AzureActiveDirectory" } { Connect-O365AzureAD -Credential $Credential } { $_ -contains "Exchange" } { Connect-O365Exchange -Credential $Credential } { $_ -contains "Skype" } { Connect-O365Skype -Credential $Credential } { $_ -contains "Sharepoint" } { Connect-O365Sharepoint -Credential $Credential -TenantName $PSBoundParameters.TenantName } { $_ -contains "ComplianceCenter" } { Connect-O365Compliance -Credential $Credential } } } }
PowerShellCorpus/PowerShellGallery/O365Extensions/0.2.29/functions/Disconnect-O365.ps1
Disconnect-O365.ps1
function Disconnect-O365 { [CmdletBinding()] PARAM ( [parameter(Mandatory = $true)] [ValidateSet("AzureActiveDirectory","Exchange","ComplianceCenter","Sharepoint","Skype","*")] [string[]] $Services ) if ($Services -eq "*") { $Services = $AllServices } switch ($Services) { { $_ -contains "AzureActiveDirectory" } { # the MSOnline module does not support disconnection - we'll leave this for later when we add support for the AzureAD module } { $_ -contains "Exchange" } { Get-PSSession | Where-Object ComputerName -eq $ExchComputerName | Remove-PSSession Remove-Module -Name ExchangeOnline -ErrorAction SilentlyContinue } { $_ -contains "Skype" } { Get-PSSession | Where-Object ComputerName -Like "*$SkypeComputerName" | Remove-PSSession Remove-Module -Name SkypeForBusiness -ErrorAction SilentlyContinue } { $_ -contains "Sharepoint" } { try { Microsoft.Online.Sharepoint.PowerShell\Disconnect-SPOService -ErrorAction Stop } catch [System.InvalidOperationException] { } catch { Write-Error $_ } } { $_ -contains "ComplianceCenter" } { Get-PSSession | Where-Object ComputerName -eq 'ps.compliance.protection.outlook.com' | Remove-PSSession Remove-Module -Name ComplianceCenter -ErrorAction SilentlyContinue } } }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-FromMsi.ps1
Install-FromMsi.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Downloads an installs a MSI package. .Description Downloads a MSI package and silently installs it on the host. Any modifications to the system path are resolved after the installation. Additionally it can attempt to verify that the application installed correctly by calling it. .Parameter Name The name of the package. .Parameter Url The URL to download from. .Parameter NoVerify If set the installation is not verified by attempting to call an executable with the given name. .Parameter Options A list of options to pass in. #> Function Install-FromMsi { Param( [Parameter(Mandatory)] [string] $name, [Parameter(Mandatory)] [string] $url, [Parameter()] [switch] $noVerify = $false, [Parameter()] [string[]] $options = @() ) $installerPath = Join-Path ([System.IO.Path]::GetTempPath()) ('{0}.msi' -f $name); Write-Host ('Downloading {0} installer from {1} ..' -f $name, $url); (New-Object System.Net.WebClient).DownloadFile($url, $installerPath); Write-Host ('Downloaded {0} bytes' -f (Get-Item $installerPath).length); $args = @('/i', $installerPath, '/quiet', '/qn'); $args += $options; Write-Host ('Installing {0} ...' -f $name); Write-Host ('msiexec {0}' -f ($args -Join ' ')); Start-Process msiexec -Wait -ArgumentList $args; # Update path Update-ScriptPath; if (!$noVerify) { Write-Host ('Verifying {0} install ...' -f $name); $verifyCommand = (' {0} --version' -f $name); Write-Host $verifyCommand; Invoke-Expression $verifyCommand; } Write-Host ('Removing {0} installer ...' -f $name); Remove-Item $installerPath -Force; Write-Host ('{0} install complete.' -f $name); }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-VSBuildTools2015InstallationPath.ps1
Get-VSBuildTools2015InstallationPath.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location of a Visual Studio Build Tools 2015 installation. .Description Returns the default path for a Visual Studio Build Tools 2015 installation. The path should be tested before using. No error checking is performed. #> Function Get-VSBuildTools2015InstallationPath { return 'C:\Program Files (x86)\Microsoft Visual Studio 14.0'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Flex.ps1
Install-Flex.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs flex. .Description Downloads the specified release of flex and unzips it to the specified location on disk. Before installation `Register-SystemPath` should be used to add the install location to the system path. .Link Register-SystemPath .Parameter Version The version of flex to install. .Parameter InstallationPath The path to install at. .Example # Install 2.5.4a-1 Install-Flex -Version 2.5.4a-1 -InstallationPath C:\gnuwin32 #> Function Install-Flex { Param( [Parameter(Mandatory)] [string] $version, [Parameter(Mandatory)] [string] $installationPath ) $url = ('https://downloads.sourceforge.net/project/gnuwin32/flex/{0}/flex-{0}-bin.zip' -f $version); Install-FromArchive -Name 'flex' -Url $url -InstallationPath $installationPath; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Gperf.ps1
Install-Gperf.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs gperf. .Description Downloads the specified release of gperf and unzips it to the specified location on disk. Before installation `Register-SystemPath` should be used to add the install location to the system path. .Link Register-SystemPath .Parameter Version The version of gperf to install. .Parameter InstallationPath The path to install at. .Example # Install 3.0.1 Install-Gperf -Version 3.0.1 -InstallationPath C:\gnuwin32 #> Function Install-Gperf { Param( [Parameter(Mandatory)] [string] $version, [Parameter(Mandatory)] [string] $installationPath ) $url = ('https://downloads.sourceforge.net/project/gnuwin32/gperf/{0}/gperf-{0}-bin.zip' -f $version); Install-FromArchive -Name 'gperf' -Url $url -InstallationPath $installationPath; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Select-VSEnvironment.ps1
Select-VSEnvironment.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Selects and initializes the Visual Studio environment for use. .Description Initializes Visual Studio and Ninja builds. If a version is not specified it will search for a compatible environment. .Parameter Architecture The architecture to target. .Parameter Version The Visual Studio version to use. Either `vs2015` or `vs2017`. If not the value is not specified then the script will look for a compatible environment. #> Function Select-VSEnvironment { param( [ValidateSet('x86','amd64')] [string] $architecture = 'amd64', [ValidateSet('vs2015','vs2017')] [AllowNull()] [string] $version ) # Find version if not specified if (!$version) { if (Test-Path (Get-VSBuildTools2017InstallationPath)) { Write-Host 'Found VS2017 Build Tools'; $version = 'vs2017'; } elseif (Test-Path (Get-VSBuildTools2015InstallationPath)) { Write-Host 'Found VS2015 Build Tools'; $version = 'vs2015'; } else { Write-Error 'Could not find a compatible Visual Studio instance'; return; } } # Get vcvarsall.bat path $vcvars = $null; if ($version -eq 'vs2017') { $vcvars = Get-VSBuildTools2017VCVarsAllPath; } else { $vcvars = Get-VSBuildTools2015VCVarsAllPath; } Write-Host $vcvars; if (!(Test-Path $vcvars)) { Write-Error ('Could not find {0}' -f $vcvars); return; } Initialize-VSEnvironment -Architecture $architecture -Path $vcvars; # Initialize ninja $compilerExe = 'cl.exe'; $compilerPath = (Get-Command $compilerExe).Path; Write-Host ('Found compiler at {0}' -f $compilerPath); Initialize-NinjaEnvironment -CC $compilerPath -CXX $compilerPath; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-VSBuildTools2015.ps1
Install-VSBuildTools2015.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs Visual Studio Build Tools 2015. .Description Downloads VS Build Tools and installs it silently on the host. .Parameter InstallationPath The location to install to. #> Function Install-VSBuildTools2015 { Param( [Parameter()] [AllowNull()] [string] $installationPath ) $url = 'https://download.microsoft.com/download/5/f/7/5f7acaeb-8363-451f-9425-68a90f98b238/visualcppbuildtools_full.exe'; $options = @( '/NoRestart', '/Silent' ); if ($installationPath) { $options += ('/CustomInstallPath="{0}"' -f $installationPath); } Install-FromExe -Name 'VSBuildTools2015' -Url $url -Options $options -NoVerify; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-SourceCodeRelease.ps1
Get-SourceCodeRelease.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the source code for a project. .Parameter Name The name of the source code package. .Parameter Url The path to the source code release. .Parameter DestinationPath The location to expand the source code to. #> Function Get-SourceCodeRelease { Param( [Parameter(Mandatory)] [string] $name, [Parameter(Mandatory)] [string] $url, [Parameter(Mandatory)] [string] $destinationPath ) Write-Host ('Downloading {0} source code from {1} ...' -f $name, $url); $extension = [System.IO.Path]::GetExtension($url); $fileName = [System.IO.Path]::GetTempFileName() | Rename-Item -NewName { $_ -replace '.tmp$', $extension } -PassThru; (New-Object System.Net.WebClient).DownloadFile($url, $fileName); Write-Host ('Downloaded {0} bytes' -f (Get-Item $fileName).Length); Write-Host ('Unzipping {0} source code to {1} ...' -f $name, $destinationPath); Expand-SourceArchive -Path $fileName -DestinationPath $destinationPath; # Clean up temporary files Remove-Item $fileName -Force; Write-Host 'Complete'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-VSBuildTools2017InstallationPath.ps1
Get-VSBuildTools2017InstallationPath.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location of a Visual Studio Build Tools 2017 installation. .Description Interacts with Visual Studio Setup to find an instance of Visual Studio 2017. If not found the default path will be returned. The path should be tested before using. No error checking is performed. #> Function Get-VSBuildTools2017InstallationPath { $installs = Get-VSSetupInstance; foreach ($install in $installs) { if ($install.DisplayName -eq 'Visual Studio Build Tools 2017') { return $install.InstallationPath; } } # Return the default path return 'C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Bison.ps1
Install-Bison.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs bison. .Description Downloads the specified release of bison and unzips it to the specified location on disk. Before installation `Register-SystemPath` should be used to add the install location to the system path. .Link Register-SystemPath .Parameter Version The version of bison to install. .Parameter InstallationPath The path to install at. .Example # Install 2.4.1 Install-Bison -Version 2.4.1 -InstallationPath C:\gnuwin32 #> Function Install-Bison { Param( [Parameter(Mandatory)] [string] $version, [Parameter(Mandatory)] [string] $installationPath ) $url = ('https://downloads.sourceforge.net/project/gnuwin32/bison/{0}/bison-{0}-bin.zip' -f $version); Install-FromArchive -Name 'bison' -Url $url -InstallationPath $installationPath; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-VSBuildTools2015VCVarsAllPath.ps1
Get-VSBuildTools2015VCVarsAllPath.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the default location for `vcvarsall.bat` within Visual Studio Build Tools 2015. .Description Retrieves the location of a Visual Studio Build Tools 2015 install and appends the path to `vcvarsall.bat`. The path should be tested before attempting to call the executable. No error checking is performed. #> Function Get-VSBuildTools2015VCVarsAllPath { return (Join-Path (Get-VSBuildTools2015InstallationPath) 'VC\vcvarsall.bat'); }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Expand-SourceArchive.ps1
Expand-SourceArchive.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Expands a source code archive. .Description Recursively expands a source code archive and moves it to the destination path. Source code releases typically archive a folder. They may also use tar as well as compression. This script handles these cases. .Parameter Path The path to the archive. .Parameter DestinationPath The path to expand to. .Example Expand-SourceArchive -Path foo.tar.gz -DestinationPath C:\foo. #> Function Expand-SourceArchive { Param( [Parameter(Mandatory)] [string] $path, [Parameter(Mandatory)] [string] $destinationPath ) # Expand to a temporary directory $tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ([System.Guid]::NewGuid()); Expand-7Zip -ArchiveFileName $path -TargetPath $tempDir; # Look at the contents of the temporary directory to see if another file # should be expanded. # # This check is for tar.gz type archives. $contents = (Get-ChildItem $tempDir)[0]; $expandedPath = $contents.FullName; if ($contents -is [System.IO.DirectoryInfo]) { Move-Item -Path $expandedPath -Destination $destinationPath; } else { Expand-SourceArchive -Path $expandedPath -DestinationPath $destinationPath; } # Remove temporary directory and its contents Remove-Item $tempDir -Recurse -Force; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Git.ps1
Install-Git.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs Git for Windows. .Description Downloads the specified release of Git for Windows and installs it silently on the host. .Parameter Version The version of Git for Windows to install. .Parameter InstallationPath The location to install to. .Example # Install 2.12.1.1 Install-Git -Version 2.12.1.1 #> Function Install-Git { Param( [Parameter(Mandatory)] [string] $version, [Parameter()] [AllowNull()] [string] $installationPath ) $major, $minor, $patch, $build = $version.split('.'); $url = ('https://github.com/git-for-windows/git/releases/download/v{0}.{1}.{2}.windows.{3}/Git-{0}.{1}.{2}.{3}-64-bit.exe' -f $major, $minor, $patch, $build); $options = @( '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/NOCANCEL', '/SP-', '/COMPONENTS=Cmd' ); if ($installationPath) { $options += ('/DIR="{0}"' -f $installationPath); } Install-FromExe -Name 'git' -Url $url -Options $options; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-WebKitGitHubUrl.ps1
Get-WebKitGitHubUrl.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location of WebKit's GitHub mirror. #> Function Get-WebKitGitHubUrl { return 'https://github.com/WebKit/webkit.git'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Update-ScriptPath.ps1
Update-ScriptPath.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Updates the `env:PATH` variable to the current machine's value. .Description Updates the environment path for the script's execution. This is useful to run after any installers complete so any new system paths are present. #> Function Update-ScriptPath { $env:PATH = [Environment]::GetEnvironmentVariable('PATH', [EnvironmentVariableTarget]::Machine); }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-WebKitSVNSnapshotUrl.ps1
Get-WebKitSVNSnapshotUrl.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location of WebKit's SVN snapshot. #> Function Get-WebKitSVNSnapshotUrl { return 'http://nightly.webkit.org/files/WebKit-SVN-source.tar.bz2'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Initialize-VSEnvironment.ps1
Initialize-VSEnvironment.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Initializes the Visual Studio C++ environment. .Description Powershell wrapper for calling `vcvarsall.bat` and replicating the environment back to the powershell context. .Parameter Architecture The architecture to setup for. Either `x86` or `amd64`. .Parameter Path The path to `vcvarsall.bat` .Example # Initialize VC++ 2015 environment. Initialize-VSEnvironment -Architecture amd64 -Path (Get-VSBuildTools2015VCVarsAllPath) .Example # Initialize VC++ 2017 environment. Initialize-VSEnvironment -Architecture amd64 -Path (Get-VSBuildTools2017VCVarsAllPath) #> Function Initialize-VSEnvironment { Param( [Parameter(Mandatory)] [ValidateSet('x86','amd64')] [string] $architecture, [Parameter(Mandatory)] [string] $path ) if (!(Test-Path $path)) { Write-Error ('{0} path not found.'); return; } # Taken from https://www.safaribooksonline.com/library/view/windows-powershell-cookbook/9780596528492/ch01s09.html $tempFile = [IO.Path]::GetTempFileName(); # Store the output of cmd.exe. We also ask cmd.exe to output # the environment table after the batch file completes $call = ('"{0}" {1} && set > "{2}"' -f $path, $architecture, $tempFile); cmd /c $call; # Go through the environment variables in the temp file. # For each of them, set the variable in our local environment. Get-Content $tempFile | Foreach-Object { if($_ -match "^(.*?)=(.*)$") { Set-Content "env:\$($matches[1])" $matches[2] } } Remove-Item $tempFile; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-WebKitGitUrl.ps1
Get-WebKitGitUrl.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location of WebKit's git repository. #> Function Get-WebKitGitUrl { return 'git://git.webkit.org/WebKit.git'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Ruby.ps1
Install-Ruby.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs Ruby. .Description Downloads the specified release of Ruby and installs it silently on the host. .Parameter Version The version of Ruby to install. .Parameter InstallationPath The location to install to. .Example # Install 2.3.3 Install-Ruby -Version 2.3.3 #> Function Install-Ruby { Param( [Parameter(Mandatory)] [string] $version, [Parameter()] [AllowNull()] [string] $installationPath ) $url = ('https://dl.bintray.com/oneclick/rubyinstaller/rubyinstaller-{0}-x64.exe' -f $version); $options = @( '/verysilent', '/tasks="assocfiles,modpath"' ); if ($installationPath) { $options += ('/dir="{0}"' -f $installationPath); } Install-FromExe -Name 'ruby' -Url $url -Options $options; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Register-SystemPath.ps1
Register-SystemPath.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Registers a path on the host system. .Description Adds a path to the host system. This can be used when a developer dependency does not contain a Windows installer. .Parameter Path The path to add. .Example # Add ninja Register-Path -Path C:\ninja #> Function Register-SystemPath { Param( [Parameter(Mandatory)] [string] $path ) if (!([System.IO.Path]::IsPathRooted($path))) { Write-Error 'All system path values need to be absolute'; return; } Write-Host ('Adding {0} to the system path' -f $path); # Get current path from the registry $systemPathKey = 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment'; $systemPath = (Get-ItemProperty -Path $systemPathKey -Name PATH).Path; Write-Debug ('Current path {0}' -f $systemPath); # Create and store new path in the registry $updatedPath = ('{0};{1}' -f $systemPath, $path); Write-Debug ('Updating path to {0}' -f $updatedPath); Set-ItemProperty -Path $systemPathKey -Name PATH -Value $updatedPath; # Update script's environment Update-ScriptPath; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-VSBuildTools2017VCVarsAllPath.ps1
Get-VSBuildTools2017VCVarsAllPath.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location for `vcvarsall.bat` within Visual Studio Build Tools 2017. .Description Retrieves the location of a Visual Studio Build Tools 2017 install and appends the path to `vcvarsall.bat`. The path should be tested before attempting to call the executable. No error checking is performed. #> Function Get-VSBuildTools2017VCVarsAllPath { return (Join-Path (Get-VSBuildTools2017InstallationPath) 'VC\Auxiliary\Build\vcvarsall.bat'); }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-SVN.ps1
Install-SVN.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs TortoiseSVN. .Description Downloads the specified release of TortoiseSVN and installs it silently on the host. .Parameter Version The version of TortoiseSVN to install. .Parameter InstallationPath The location to install to. .Example # Install 1.9.5.27581 Install-SVN -Version 1.9.5.27581 #> Function Install-SVN { Param( [Parameter(Mandatory)] [string] $version, [Parameter()] [AllowNull()] [string] $installationPath ) $major, $minor, $patch, $build = $version.split('.'); $url = ('https://downloads.sourceforge.net/project/tortoisesvn/{0}.{1}.{2}/Application/TortoiseSVN-{0}.{1}.{2}.{3}-x64-svn-1.9.5.msi' -f $major, $minor, $patch, $build); $options = @( 'ADDLOCAL=CLI' ); if ($installationPath) { $options += ('INSTALLDIR="{0}"' -f $installationPath); } Install-FromMsi -Name 'svn' -Url $url -Options $options; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Initialize-NinjaEnvironment.ps1
Initialize-NinjaEnvironment.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Initializes the Ninja build environment. .Description Powershell command to set the environment variables expected for a Ninja build. .Parameter CC The path to the C compiler. .Parameter CXX The path to the C++ compiler. #> Function Initialize-NinjaEnvironment { Param( [Parameter(Mandatory)] [string] $cc, [Parameter(Mandatory)] [string] $cxx ) $env:CC = $cc; $env:CXX = $cxx; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Invoke-CMakeBuild.ps1
Invoke-CMakeBuild.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Invokes a CMake Build. .Description Powershell wrapper for calling a CMake build. .Parameter Path The path that contains the root CMakeLists.txt. .Parameter BuildPath The path to build at. .Parameter InstallationPath The root install path. .Parameter BuiltType The type of build to do. .Parameter Platform The platform to build for. .Parameter Options Additional CMake options for the build. #> Function Invoke-CMakeBuild { Param( [Parameter(Mandatory)] [string] $path, [Parameter(Mandatory)] [string] $buildPath, [Parameter(Mandatory)] [string] $installationPath, [Parameter(Mandatory)] [ValidateSet('Release','Debug')] [string] $buildType = 'Release', [ValidateSet('ninja','vs2015','vs2017')] [string] $generator = 'ninja', [Parameter()] [AllowNull()] [string] $platform, [Parameter()] [string[]] $options = @() ) # Select the generator $genArgs = @('-G') if ($generator -eq 'ninja') { $genArgs += 'Ninja'; } elseif ($generator -eq 'vs2015') { $genArgs += @('"Visual Studio 14 2015"', 'Win64'); } else { $genArgs += @('"Visual Studio 15 2017"', 'Win64'); } # Add all arguments if ($platform) { $genArgs += ('-DCMAKE_SYSTEM_NAME={0}' -f $platform); } $genArgs += ('-DCMAKE_BUILD_TYPE={0}' -f $buildType); $genArgs += ('-DCMAKE_INSTALL_PREFIX={0}' -f $installationPath); $genArgs += ('-DCMAKE_PREFIX_PATH={0}' -f $installationPath); $genArgs += $options; $genArgs += ('-B{0}' -f $buildPath); $genArgs += ('-H{0}' -f $path); # Create the generate call $genCall = ('cmake {0}' -f ($genArgs -Join ' ')); Write-Host $genCall; Invoke-Expression $genCall # Create the build call $buildArgs += @('--build', $buildPath, '--target install'); $buildCall = ('cmake {0}' -f ($buildArgs -Join ' ')); Write-Host $buildCall; Invoke-Expression $buildCall; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-CMake.ps1
Install-CMake.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs CMake. .Description Downloads the specified release of CMake and installs it silently on the host. .Parameter Version The version of CMake to install. .Parameter InstallationPath The location to install to. .Example # Install 3.7.2 Install-CMake -Version 3.7.2 #> Function Install-CMake { Param( [Parameter(Mandatory)] [string] $version, [Parameter()] [AllowNull()] [string] $installationPath ) $major, $minor, $patch = $version.split('.'); $url = ('https://cmake.org/files/v{0}.{1}/cmake-{2}-win64-x64.msi' -f $major, $minor, $version); $options = @( 'ADD_CMAKE_TO_PATH="System"' ); if ($installationPath) { $options += ('INSTALL_ROOT="{0}"' -f $installationPath); } Install-FromMsi -Name 'cmake' -Url $url -Options $options; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Perl.ps1
Install-Perl.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs Strawberry Perl. .Description Downloads the specified release of Perl and installs it silently on the host. .Parameter Version The version of Perl to install. .Parameter InstallationPath The location to install to. .Example # Install 5.24.1.1 Install-Perl -Version 5.24.1.1 #> Function Install-Perl { Param( [Parameter(Mandatory)] [string] $version, [Parameter()] [AllowNull()] [string] $installationPath ) $url = ('http://strawberryperl.com/download/{0}/strawberry-perl-{0}-64bit.msi' -f $version); $options = @(); if ($installationPath) { $options += ('INSTALLDIR="{0}"' -f $installationPath); } Install-FromMsi -Name 'perl' -Url $url -Options $options; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-VSBuildTools2017.ps1
Install-VSBuildTools2017.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs Visual Studio Build Tools 2017. .Description Downloads VS Build Tools and installs it silently on the host. .Parameter InstallationPath The location to install to. #> Function Install-VSBuildTools2017 { Param( [Parameter()] [AllowNull()] [string] $installationPath ) $url = 'https://download.microsoft.com/download/5/A/8/5A8B8314-CA70-4225-9AF0-9E957C9771F7/vs_BuildTools.exe'; $options = @( '--quiet', '--norestart', '--wait', '--add', 'Microsoft.VisualStudio.Workload.VCTools', '--includeOptional' ); if ($installationPath) { $options += @('--installPath', ('/dir="{0}"' -f $installationPath)); } Install-FromExe -Name 'VSBuildTools2017' -Url $url -Options $options -NoVerify; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Python.ps1
Install-Python.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs Python. .Description Downloads the specified release of Python and installs it silently on the host. Additionally PIP and Visual C++ for Python are installed. .Parameter Version The version of Python to install. .Parameter PipVersion The version of pip (Pip Installs Python) to install. .Parameter InstallationPath The location to install to. .Example # Install 2.7.13 and PIP 9.0.1 Install-Python -Version 2.7.13 -PipVersion #> Function Install-Python { Param( [Parameter(Mandatory)] [string] $version, [Parameter(Mandatory)] [string] $pipVersion, [Parameter()] [AllowNull()] [string] $installationPath ) $major, $minor, $patch = $version.split('.'); if ($major -ne '2') { Write-Error 'Only Python version 2.x is usable for WebKit development'; return; } $pythonUrl = ('https://www.python.org/ftp/python/{0}/python-{0}.amd64.msi' -f $version); $options = @( 'ALLUSERS=1', 'ADDLOCAL=DefaultFeature,Extensions,TclTk,Tools,PrependPath' ); if ($installationPath) { $options += ('TARGETDIR="{0}"' -f $installationPath); } Install-FromMsi -Name 'python' -Url $pythonUrl -Options $options; # Install PIP $pipInstall = ('pip=={0}' -f $pipVersion); Write-Host ('Installing {0} ...' -f $pipInstall); (New-Object System.Net.WebClient).DownloadFile('https://bootstrap.pypa.io/get-pip.py', 'get-pip.py'); python get-pip.py $pipInstall; Remove-Item get-pip.py -Force; # Install Visual Studio for Python 2.7 $vcForPythonUrl = 'https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi'; Install-FromMsi -Name 'VCForPython27' -Url $vcForPythonUrl -NoVerify; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-FromExe.ps1
Install-FromExe.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Downloads an installs a MSI package. .Description Downloads a MSI package and silently installs it on the host. Any modifications to the system path are resolved after the installation. Additionally it can attempt to verify that the application installed correctly by calling it. .Parameter Name The name of the package. .Parameter Url The URL to download from. .Parameter NoVerify If set the installation is not verified by attempting to call an executable with the given name. .Parameter Options A list of options to pass in. #> Function Install-FromExe { Param( [Parameter(Mandatory)] [string] $name, [Parameter(Mandatory)] [string] $url, [Parameter()] [switch] $noVerify = $false, [Parameter(Mandatory)] [string[]] $options = @() ) $installerPath = Join-Path ([System.IO.Path]::GetTempPath()) ('{0}.exe' -f $name); Write-Host ('Downloading {0} installer from {1} ..' -f $name, $url); (New-Object System.Net.WebClient).DownloadFile($url, $installerPath); Write-Host ('Downloaded {0} bytes' -f (Get-Item $installerPath).length); Write-Host ('Installing {0} ...' -f $name); Write-Host ('{0} {1}' -f $installerPath, ($options -Join ' ')); Start-Process $installerPath -Wait -ArgumentList $options; # Update path Update-ScriptPath; if (!$noVerify) { Write-Host ('Verifying {0} install ...' -f $name); $verifyCommand = (' {0} --version' -f $name); Write-Host $verifyCommand; Invoke-Expression $verifyCommand; } Write-Host ('Removing {0} installer ...' -f $name); Remove-Item $installerPath -Force; Write-Host ('{0} install complete.' -f $name); }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Get-WebKitSVNUrl.ps1
Get-WebKitSVNUrl.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Retrieves the location of WebKit's SVN repository. #> Function Get-WebKitSVNUrl { return 'https://svn.webkit.org/repository/webkit/trunk'; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-Ninja.ps1
Install-Ninja.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Installs the Ninja build system. .Description Downloads the specified release of Ninja and unzips it to the specified location on disk. Before installation `Register-SystemPath` should be used to add the install location to the system path. .Link Register-SystemPath .Parameter Version The version of Ninja to install. .Parameter InstallationPath The path to install at. .Example # Install 1.7.2 Install-Ninja -Version 1.7.2 -InstallationPath C:\Ninja #> Function Install-Ninja { Param( [Parameter(Mandatory)] [string] $version, [Parameter(Mandatory)] [string] $installationPath ) $url = ('https://github.com/ninja-build/ninja/releases/download/v{0}/ninja-win.zip' -f $version); Install-FromArchive -Name 'ninja' -Url $url -InstallationPath $installationPath; }
PowerShellCorpus/PowerShellGallery/WebKitDev/0.1.1/Functions/Install-FromArchive.ps1
Install-FromArchive.ps1
# Copyright (c) 2017, the WebKit for Windows project authors. Please see the # AUTHORS file for details. All rights reserved. Use of this source code is # governed by a BSD-style license that can be found in the LICENSE file. <# .Synopsis Downloads an installs a package from an archive format. .Description Downloads an archive of a package and installs it at the specified location. .Parameter Name The name of the package. .Parameter Url The URL to download from. .Parameter InstallationPath The path to install at. .Parameter NoVerify If set the installation is not verified by attempting to call an executable with the given name. .Parameter Options A list of options to pass in. #> Function Install-FromArchive { Param( [Parameter(Mandatory)] [string] $name, [Parameter(Mandatory)] [string] $url, [Parameter(Mandatory)] [string] $installationPath, [Parameter()] [switch] $noVerify = $false ) $extension = [System.IO.Path]::GetExtension($url); $archivePath = Join-Path ([System.IO.Path]::GetTempPath()) ('{0}.{1}' -f $name, $extension); Write-Host ('Downloading {0} package from {1} ..' -f $name, $url); (New-Object System.Net.WebClient).DownloadFile($url, $archivePath); Write-Host ('Downloaded {0} bytes' -f (Get-Item $archivePath).length); Write-Host ('Unzipping {0} package ...' -f $name); Expand-7Zip -ArchiveFileName $archivePath -TargetPath $installationPath; if (!$noVerify) { Write-Host ('Verifying {0} install ...' -f $name); $verifyCommand = (' {0} --version' -f $name); Write-Host $verifyCommand; Invoke-Expression $verifyCommand; } Write-Host ('Removing {0} package ...' -f $name); Remove-Item $archivePath -Force; Write-Host ('{0} install complete.' -f $name); }
PowerShellCorpus/PowerShellGallery/AzureRM.Billing/0.11.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; "Save-AzureRmProfile" = "Save-AzureRmContext"; "Select-AzureRmProfile" = "Import-AzureRmContext"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDApggZz05Qnk0e # yiuUwG/hQa3nA5NWg0bjPekKbmwN+aCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD # VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy # b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p # bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL # MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v # bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3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EfSZhAey3e6 # pCbfKp812qm8WOG4ryk9BilS1+wBtouJc2HWaXqEtrpakLtoXAlCL/MBQ70KiR20 # yxzZUh3skafTVEaSGzk00k+836GSIH5gWmXzIL+k5Hgm+xsLo5dV0snBOjhslRWY # afEFPQSRMZOxykUEw5NeaAkxdLz+8DciVxg+fjqGx+OqJzxndN+TpxDx5TdfTj1I # NNmal8Gqa9I2ygGBBs6ypYXZ6VbpPgUzrNyZGUf2mA== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Billing/0.13.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; "Save-AzureRmProfile" = "Save-AzureRmContext"; "Select-AzureRmProfile" = "Import-AzureRmContext"; "Resolve-Error" = "Resolve-AzureRmError"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkHgYJKoZIhvcNAQcCoIIkDzCCJAsCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCALJXjrzh47rcfU # 4UfdAQzeL9cnx2R84p1DABBXUFZ2oKCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACO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pbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD # b3Jwb3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIw # MTACEzMAAACwhumSIApd6vgAAAAAALAwFgQU08p1T3A05DDpAe4GnLPFNaCfYYow # DQYJKoZIhvcNAQELBQAEggEAv66cI5Pu3NucghKoXhEK30nj5pNIzud7WMrJAepi # /v7ld8zXE/PvVuWBfJseSDUZ7Ps45FgDhtw7J/Uqpb1xHH4wT2vPvvzywFsGtVzI # qUpDG+4YRA8lfoyXjPSzJxOc/aXX2ybc0AiUJeu6/iTZ8Vy1mYr63vNomS2bI6hG # Gy9tFW/j6ObVOwKK+6IvlubFTrI2svKv+u/G0O0VU/jml27SVt5Hac/0eQnsojaI # bd8DgpS6QJabpq+F3R49Hzgb22Hg6VQco95PVAfGYbForTmECLRJ2N77vmDyVUiO # /Y6WYNtD6iLfHZOw6aK40DHt2HVvXCiqfR8/rJPTVj75cQ== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/PSMarkdown/1.1/ConvertFrom-Markdown.ps1
ConvertFrom-Markdown.ps1
<# .Synopsis Converts a Markdown table to a PowerShell object. .Description The ConvertFrom-Markdown function converts a Markdown formatted table to a Powershell Object .EXAMPLE Get-Service | Select-Object Name, DisplayName, Status | ConvertTo-Markdown | ConvertFrom-Markdown This command gets the name, displayname and status of all the services on the system then converts it to a Markdown table format before converting it back to a Powershell object. .EXAMPLE Get-Process | Unique | Select-Object Name, Path, Company | ConvertTo-Markdown | ConvertFrom-Markdown This command gets the name, path and company of all the processes that are running on the computer with duplicates eliminated then converts it to a Markdown table format and then to Powershell object. .EXAMPLE ConvertTo-Markdown (Get-Service | Where-Object {$_.Status -eq "Running"} | Select-Object Name, DisplayName, Status) | ConvertFrom-Markdown This command displays the name, displayname and status of only the services that are currently running in Markdown table format before converting it back to a Powershell object. .EXAMPLE $mddata = ConvertTo-Markdown (Get-Alias | Select Name, DisplayName) ConvertFrom-Markdown $mddata The first command displays the name and displayname of all the aliases for the current session in Markdown table format. The second command converts the aliases in Markdown table format to a Powershell object. .EXAMPLE $date = Get-Date | ConvertTo-Markdown ConvertFrom-Markdown $date These commands converts a date object to Markdown table format and then to Powershell object. #> Function ConvertFrom-Markdown { [CmdletBinding()] [OutputType([PSObject])] Param ( [Parameter( Mandatory = $true, Position = 0, ValueFromPipeline = $true )] $InputObject ) Begin { $items = @() } Process { $mddata = $InputObject $data = $mddata | Where-Object {$_ -notmatch "--" } $items += $data } End { $object = $items -replace ' +', '' | ConvertFrom-Csv -Delimiter '|' $object } }
PowerShellCorpus/PowerShellGallery/PSMarkdown/1.1/ConvertTo-Markdown.ps1
ConvertTo-Markdown.ps1
<# .Synopsis Converts a PowerShell object to a Markdown table. .Description The ConvertTo-Markdown function converts a Powershell Object to a Markdown formatted table .EXAMPLE Get-Process | Where-Object {$_.mainWindowTitle} | Select-Object ID, Name, Path, Company | ConvertTo-Markdown This command gets all the processes that have a main window title, and it displays them in a Markdown table format with the process ID, Name, Path and Company. .EXAMPLE ConvertTo-Markdown (Get-Date) This command converts a date object to Markdown table format .EXAMPLE Get-Alias | Select Name, DisplayName | ConvertTo-Markdown This command displays the name and displayname of all the aliases for the current session in Markdown table format #> Function ConvertTo-Markdown { [CmdletBinding()] [OutputType([string])] Param ( [Parameter( Mandatory = $true, Position = 0, ValueFromPipeline = $true )] [PSObject[]]$InputObject ) Begin { $items = @() $columns = @{} } Process { ForEach($item in $InputObject) { $items += $item $item.PSObject.Properties | %{ if($_.Value -ne $null){ if(-not $columns.ContainsKey($_.Name) -or $columns[$_.Name] -lt $_.Value.ToString().Length) { $columns[$_.Name] = $_.Value.ToString().Length } } } } } End { ForEach($key in $($columns.Keys)) { $columns[$key] = [Math]::Max($columns[$key], $key.Length) } $header = @() ForEach($key in $columns.Keys) { $header += ('{0,-' + $columns[$key] + '}') -f $key } $header -join ' | ' $separator = @() ForEach($key in $columns.Keys) { $separator += '-' * $columns[$key] } $separator -join ' | ' ForEach($item in $items) { $values = @() ForEach($key in $columns.Keys) { $values += ('{0,-' + $columns[$key] + '}') -f $item.($key) } $values -join ' | ' } } }
PowerShellCorpus/PowerShellGallery/GoogleCloudBeta/1.0.0.5/AppendPsModulePath.ps1
AppendPsModulePath.ps1
# Copyright 2015-2016 Google Inc. All Rights Reserved. # Licensed under the Apache License Version 2.0. # # Appends the Cloud Tools for PowerShell module location to the registry's PSModulePath environment # variable param($installPath) # Let a user manually select a Cloud SDK install path $installPath = $installPath -or $args[0] # Find the Google Cloud SDK install path from the registry. if (-not $installPath) { $hklmPath = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" $hkcuPath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" if (Test-Path $hklmPath) { $installPath = Get-ItemPropertyValue $hklmPath InstallLocation } elseif (Test-Path $hkcuPath) { $installPath = Get-ItemPropertyValue $hkcuPath InstallLocation } else { Write-Error "Can not find Cloud SDK from the registry." return } } $installPath = $installPath -replace '"' # Registry values had quotes for some reason # The folder above where the PowerShell cmdlets are installed. PowerShell will crawl subfolders # looking for .psd1 files. (So it should find .\GoogleCloud\GoogleCloud.psd1.) $googlePowerShellPath = Join-Path $installPath "google-cloud-sdk\platform\PowerShell" if (-not (Test-Path $googlePowerShellPath)) { Write-Error "Can not find Google PowerShell. $googlePowerShellPath does not exist." return } # Get the value of the two registry keys that initialize the environment variable. $hklmLocation = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" $hklmValue = (Get-ItemProperty $hklmLocation).PSModulePath $hkcuLocation = "HKCU:\Environment" $hkcuValue = (Get-ItemProperty $hkcuLocation).PSModulePath $regValue = (($hklmValue, $hkcuValue | ?{$_}) -join ";") if(($regValue -split ";" -contains $googlePowerShellPath)) { Write-Warning "Path already exists." return } $wid = [Security.Principal.WindowsIdentity]::GetCurrent() $wip = New-Object Security.Principal.WindowsPrincipal $wid $isElevated = $wip.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) if ($isElevated -and (Test-Path $hklmPath)) { # If we are running as administrator, and the Cloud SDK is installed for all users, # append to the PSModluePath in the local machine registry location. Write-Verbose "Adding to registry key for all users." Push-Location $hklmLocation # Don't add a semicolon if $hklmValue is $null Set-ItemProperty . PSModulePath (($hklmValue, $googlePowerShellPath | ?{$_}) -join ";") } else { # If we are running as a local user, or Cloud SDK is installed for just the current user, # append to the PSModluePath in the current user registry location. Write-Verbose "Adding to registry key for user $env:UserName." Push-Location $hkcuLocation # Don't add a semicolon if $hkcuValue is $null Set-ItemProperty . PSModulePath (($hkcuValue, $googlePowerShellPath | ?{$_}) -join ";") } Write-Output (Get-ItemProperty . PSModulePath) Pop-Location
PowerShellCorpus/PowerShellGallery/GoogleCloudBeta/1.0.0.5/BootstrapCloudToolsForPowerShell.ps1
BootstrapCloudToolsForPowerShell.ps1
# Copyright 2015 Google Inc. All Rights Reserved. # Licensed under the Apache License Version 2.0. # # Bootstraps the Google Cloud cmdlets into the current PowerShell session. function Get-ScriptDirectory { $invocation = (Get-Variable MyInvocation -Scope 1).Value return Split-Path $invocation.MyCommand.Path } $modulePath = Join-Path (Get-ScriptDirectory) "GoogleCloud.psd1" Import-Module $modulePath $Env:UserProfile clear Write-Output "Google Cloud Tools for PowerShell"
PowerShellCorpus/PowerShellGallery/GoogleCloudBeta/1.0.0.5/PatchFromGcs.ps1
PatchFromGcs.ps1
# Copyright 2015-2016 Google Inc. All Rights Reserved. # Licensed under the Apache License Version 2.0. # # Updates Cloud Tools for PowerShell module to the latest found in # Google Cloud Storage bucket g-cloudsharp-unsignedbinaries. # Let a user manually select a Cloud SDK install path param($installPath) $installPath = $installPath -or $args[0] # Find the Google Cloud SDK install path from the registry. if (-not $installPath) { $hklmPath = "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" $hkcuPath = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Google Cloud SDK" if (Test-Path $hklmPath) { $installPath = Get-ItemPropertyValue $hklmPath InstallLocation } elseif (Test-Path $hkcuPath) { $installPath = Get-ItemPropertyValue $hkcuPath InstallLocation } else { Write-Error "Can not find Cloud SDK from the registry." return } } $installPath = $installPath -replace '"' # Registry values had quotes. This removes them. Push-Location (Join-Path $installPath "google-cloud-sdk\platform\PowerShell") $googlePowerShellPath = Resolve-Path "GoogleCloud" if (-not (Test-Path $googlePowerShellPath)) { Write-Error "Can not find Cloud Tools for PowerShell. '$googlePowerShellPath' does not exist." return } $pathToOldCmdlets = "GoogleCloudPowerShell-unpatched-backup" if (Test-Path $pathToOldCmdlets) { Remove-Item $pathToOldCmdlets -Recurse } Move-Item $googlePowerShellPath $pathToOldCmdlets Import-Module "$pathToOldCmdlets/GoogleCloud.psd1" $bucket = Get-GcsBucket g-cloudsharp-unsignedbinaries # Find objects in the powershell directory, and select one most recently created. $zipObject = Find-GcsObject $bucket -Prefix powershell | Sort TimeCreated -Descending | Select -First 1 $zipFileName = Split-Path $zipObject.Name -Leaf Write-Verbose "Saving new file to $zipFileName" Read-GcsObject $bucket $zipObject.Name -OutFile $zipFileName -Force $zipPath = Resolve-Path $zipFileName Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath, "$googlePowerShellPath\..") Pop-Location
PowerShellCorpus/PowerShellGallery/VMware.DeployAutomation/6.5.1.5299608/Initialize-VMware_DeployAutomation.ps1
Initialize-VMware_DeployAutomation.ps1
function global:Get-DeployCommand() { return (get-command -pssnapin VMware.DeployAutomation),(get-command Get-DeployMachineIdentity,Set-DeployMachineIdentity) } # # .SYNOPSIS # Set the value used to logically link an ESXi host in vCenter to a physical machine. # # .DESCRIPTION # The Set-DeployMachineIdentity function is used to logically link an ESXi host in vCenter to a physical machine that will be booted with AutoDeploy. Typically, AutoDeploy will keep track of the mapping between physical hosts and the hosts in vCenter. However, if the host was added to vCenter through other means, such as a disconnected add, then this function needs to be used to tell AutoDeploy about the mapping. # # The function takes two arguments, the host in vCenter and a string describing the machine identifier to use. The supported machine identifiers are the BIOS UUID and the MAC address of the network interface card that will be used to boot the machine. An automated way to retrieve machine identifiers is by listening for the "pxeBootNoImageRule" event that is sent by AutoDeploy when a machine tries to network boot and there are no matching image rules. # # Detail: The implementation is done using a custom attribute on the host in vCenter. This cmdlet and the getter are just powershell functions that call the existing PowerCLI cmdlets for manipulating custom attributes. # # .PARAMETER VMHost # The VMHost object or name of the host in vCenter that the identifier should be associated with. # # .PARAMETER Identifier # A string of the form "<type>=<value>" where the identifier types are "uuid" and "mac". The "uuid" type corresponds to the machine's BIOS UUID and the "mac" type corresponds to the MAC address of the network interface card that will be used to network boot. # # .EXAMPLE # C:\PS> Set-DeployMachineIdentity -VMHost (Get-VMHost h1) -Identifier "uuid=d5adcb43-fe5e-4034-9fa3-fd5afac1e0f1" # # Associate the host in vCenter named "h1" with the physical machine that has the BIOS UUID "d5adcb43-fe5e-4034-9fa3-fd5afac1e0f1". # # .LINK # Get-DeployMachineIdentity # function global:Set-DeployMachineIdentity($VMHost, $Identifier) { $identAttribute = Get-CustomAttribute -Name "AutoDeploy.MachineIdentity" if ($identAttribute) { if (! ($Identifier -match "^(uuid=[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}|mac=[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2})") ) { throw "Identifier is bad" } else { $anno = Set-Annotation -CustomAttribute $identAttribute -Entity $VMHost -Value $Identifier if(!$anno) { throw "Set-Annotation call failed" } } } else { throw "Cannot find AutoDeploy machine identity custom attribute" } } # # .SYNOPSIS # Return a string value that AutoDeploy uses to identify a particular physical machine # # .DESCRIPTION # Get the machine identifier used to logically link an ESXi host in vCenter to a physical machine. AutoDeploy can use this mapping for hosts that are manually added to vCenter by the user. The value will not be set for hosts automatically added by AutoDeploy. # # See the help for Set-DeployMachineIdentity for more details. # # .PARAMETER VMHost # The VMHost object or name of the host in vCenter that the identifier should be associated with. # # .EXAMPLE # C:\PS> Get-DeployMachineIdentity -VMHost (Get-VMHost h1) # # .LINK # Set-DeployMachineIdentity # function global:Get-DeployMachineIdentity($VMHost) { $identAttribute = Get-CustomAttribute -Name "AutoDeploy.MachineIdentity" if ($identAttribute) { $anno = Get-Annotation -CustomAttribute $identAttribute -Entity $VMHost if(!$anno) { throw "Get-Annotation call failed" } return $anno.Value } else { throw "Cannot find AutoDeploy machine identity custom attribute" } } # SIG # Begin signature block # MIIdVgYJKoZIhvcNAQcCoIIdRzCCHUMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUDJ2E4gsRwIGUIGTIC5QrV2KD # H72gghhpMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV # UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu # dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q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IJgdiHoZ9RX+29siIBh8IILRaRtjby6EJaZQu5cBRG3qZuBRqOV # iGWsmJMIwsucr4xf4TemfyC166+xcmdKegtVE/HDM3fkjS3aj79I4WYVyqeNhArl # /aiiOG90QKl3V26uJrIBQsZMi848umGzAaa2h783rWsy+FeLjNW5mBy7NMAXhuJR # P+UDAvyk/Jt0GmZW+GKXHTI72JOeYKzRbH3uyMpb60ys0LYY6mfLSNKDuLnx6h/H # 1mr4cSgClTud3eErSobqPUiM9vqjSHD5AmTHoYICCzCCAgcGCSqGSIb3DQEJBjGC # AfgwggH0AgEBMHIwXjELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENv # cnBvcmF0aW9uMTAwLgYDVQQDEydTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZp # Y2VzIENBIC0gRzICEA7P9DjI/r81bgTYapgbGlAwCQYFKw4DAhoFAKBdMBgGCSqG # SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDQwNDIyMzAz # MVowIwYJKoZIhvcNAQkEMRYEFHBTwtBQwVeJ/XnijdW3mgJ/BrcuMA0GCSqGSIb3 # DQEBAQUABIIBAEFwBQyuxJHDY0VRKJVi3GnnU4P+2Ig2OFp+HvkKl+bsac7PXwlu # 0mMN39vMPCwQA7At4JBtYPDuw4ynUVl++tnDWa05SNug2yzgjQjfOrcIHM5v447l # nP6TAQGq7/o/8GPDkda5NO+c2Lg0cI2pV56XjLjELfaezbIOqnPWc7dGISq3Mn01 # 5A7Q0N6c9LKuKmWYesROjKI4uvw7XJ2TRyVAKrgXIpYXQZ7CO0XqM28NHuqH7nKB # RLbLp8lRJGhOpBt6ao9AU9jdJl2MfNdqBloxY/RBhHi3IcptYXPfA1aGcpRlTJON # bUhCl1werbWbD3+vVOpTmxTVjDWbW2Sem8M= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/VMware.DeployAutomation/6.5.1.5299608/VMware.DeployAutomation.ps1
VMware.DeployAutomation.ps1
[VMware.VimAutomation.Sdk.Interop.V1.CoreServiceFactory]::CoreService.OnImportModule( "VMware.DeployAutomation", (Split-Path $script:MyInvocation.MyCommand.Path)); #set aliases set-alias Apply-ESXImageProfile Set-ESXImageProfileAssociation -Scope Global function global:Get-AutoDeployCommand([string] $Name = "*") { get-command -module VMware.DeployAutomation -Name $Name } # SIG # Begin signature block # MIIdVgYJKoZIhvcNAQcCoIIdRzCCHUMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUBs5MfwlxIfrju5rZAiHSwsJP # n3ugghhpMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV # UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu # dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q # WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC # i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhFpS+JzueZ5/6M4lc/PcaS3Er4 # ezPkeQr78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NT/1DxDghHegs6aOXZd89GRXTWe017FM1tdE61Xq # Haig1m6x3QdXmb+4/1wK/D4caw4pUm1rlq4/W2JzxHZmc6s5abgWn3OUZsO+p0NI # OJDpQoQDUo1W4GGf1sFQa8ewMugcCZv6h1IDoYICCzCCAgcGCSqGSIb3DQEJBjGC # AfgwggH0AgEBMHIwXjELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENv # cnBvcmF0aW9uMTAwLgYDVQQDEydTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZp # Y2VzIENBIC0gRzICEA7P9DjI/r81bgTYapgbGlAwCQYFKw4DAhoFAKBdMBgGCSqG # SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDQwNDIyMzAz # MVowIwYJKoZIhvcNAQkEMRYEFPauggLfDWLer6Xv4WENFlT8RiyIMA0GCSqGSIb3 # DQEBAQUABIIBAA8jlKpwsm/hKxp4lDhNsS0+tjF4dCuPaFnG+jDq0QfWVy0bsBHq # p1bLr7w1ie6nqVtakt8TrZ39TpkeF+n04mOchJFlEFYH56vylPs3NWhKBIaBZ6H/ # Gb+N6c+h/gDiufvMEW4H/5dlaoXXvZKauOpReJu5euJAaHUVwtdTv8kSREEPwDKN # 0N3kFak+LZiWhbVHIyzPaTNMdzLk3ugKoUl9b8iJKVoT+U4ONN3nTndkk4s5OO7W # PJHlBR3CnO9gChAHvYljaj3o3H+PoNj8YYMgEcFX0W9tRir8x74kNIzPyeyqedTI # h/KsaW5QW46SnjU72eSJG9GQMzyb0kMnbMA= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Crayon/1.0.11.16/init.ps1
init.ps1
$script:startTs = $null
PowerShellCorpus/PowerShellGallery/Crayon/1.0.11.16/functions/log.ps1
log.ps1
#$asm = [Reflection.Assembly]::LoadFile("$PSScriptRoot\..\lib\Crayons.dll") $p = new-object -type Crayons.Patterns.Pattern $p.Add("'(?<magenta>.*?)'", "quoted names") $p.Add("^(?<green>info):", "info log level") $p.Add("^(?<yellow>warn):", "warn log level") $p.Add("^(?<red>err) :", "error log level") $p.Add("^(?<cyan>verbose):", "verbose log level") $p.Add("(?<green>done|OK)", "done") $p.Add("(?<red>Error|Fail|Failed)", "done") $p.Add("(?<red>Error:.*)", "errors") $p.Add(":(?<cyan>[^\s.\\][^\s.]+)", "debug values") $global:logPattern = $p $global:logprefix = $null $global:lastprefix = $null $global:logtooutput = $false if ($global:timepreference -eq $null) { [System.Management.Automation.ActionPreference]$global:timepreference = [System.Management.Automation.ActionPreference]::SilentlyContinue } [Crayons.CrayonString]::EscapeChar = '`' [Crayons.Crayon]::Configure({ param($text, $color) write-host $text -NoNewline -ForegroundColor $color }, { param ($text) Write-Host $text }) $verboseBuffer = "" $verboseWriter = [Crayons.Crayon]::CreateWriter({ param($text, $color) $verboseBuffer += $text }, { param ($text) $verboseBuffer += $text Write-host $verboseBuffer $verbosebuffer = "" }) function _crayonwrite($message) { $cmessage = $p.Colorize($message) [Crayons.Crayon]::Write($cmessage) if ($logtooutput) { write-output $message } } function WithLogRedirect { param([ScriptBlock] $scriptblock) $old = $global:logtooutput try { $global:logtooutput = $true Invoke-Command $scriptblock } finally { $global:logtooutput = $old } } function Write-LogResult ([Parameter(ValueFromPipeline=$true)] $message) { Write-LogInfo $message } function Write-LogInfo ([Parameter(ValueFromPipeline=$true)] $message) { if (!($message -match "^info")) { $message = "info: " + $message } _crayonwrite($message) } function Write-LogWarn([Parameter(ValueFromPipeline=$true)] $message) { if (!($message -match "^warn")) { $message = "warn: " + $message } _crayonwrite($message) } function Write-LogError([Parameter(ValueFromPipeline=$true)] $message) { if (!($message -match "^err")) { $message = "err : " + $message } _crayonwrite($message) } function Write-LogVerbose([Parameter(ValueFromPipeline=$true)] $message, $verbref) { $VerbosePreference = $verbref if (!($message -match "^verbose")) { $message = "verbose: " + $message } #$message = $p.Colorize($message) #$message.WriteToConsole($verboseWriter) #$message.WriteToConsole() _crayonwrite($message) } function _Write-Logmessage([Parameter(ValueFromPipeline=$true)] $message, $prefix, $condition = $null) { if ($condition -ne $null) { if ($condition -eq [System.Management.Automation.ActionPreference]::SilentlyContinue ` -or $condition -eq [System.Management.Automation.ActionPreference]::Ignore) { return } } if ($prefix -ne $null) { if (!($message -match "^$prefix")) { $message = "$($prefix): " + $message } } #$message = $p.Colorize($message) #$message.WriteToConsole() _crayonwrite($message) } function Write-Logmessage([Parameter(ValueFromPipeline=$true)] $message, $prefix) { if ($prefix -eq $null) { if ($global:logprefix -ne $null) { $prefix = $global:logprefix } elseif ($global:lastprefix -ne $null) { $prefix = $global:lastprefix } } else { $global:lastprefix = $prefix } _Write-Logmessage $message $prefix } function Write-LogTime { [cmdletbinding()] param( [Parameter(ValueFromPipeline=$true)][scriptblock] $expression, [Alias("m")] [string]$message, [switch][bool] $detailed = $true ) $pref = $global:timepreference if ($VerbosePreference -ne "SilentlyContinue") { $pref = $VerbosePreference } if ($detailed) { _Write-Logmessage "$($message)..." -prefix "time" -condition $pref } $time = measure-command -Expression $expression _Write-Logmessage "$($message): '$($time.Tostring())'" -prefix "time" -condition $pref } function Write-LogProgress($activity, $status, $percentComplete, $id) { Write-Progress @PSBoundParameters write-host $activity : $status } function get-ElapsedTime([switch][bool]$reset) { if ($script:startTs -eq $null -or $reset) { $script:startTs = [DateTimeOffset]::Now $script:lastActivity = $null $script:lasttimestamp = $null } $now = [DateTimeOffset]::Now $elapsed = ($now - $script:startTs) return $elapsed } function get-loopTime() { $e = get-elapsedtime if ($script:lasttimestamp -eq $null) { $script:lasttimestamp = $script:startTs } $now = [DateTimeOffset]::Now $elapsed = ($now - $script:lasttimestamp) $script:lasttimestamp = $now return $elapsed } function get-ETA($percentComplete) { $elapsed = (get-elapsedtime).TotalMilliseconds if ($percentComplete -eq 0) { return [timespan]::MaxValue } $rate = $percentComplete / $elapsed $percleft = 100 - $percentComplete $msLeft = $percleft / $rate return [Timespan]::FromMilliseconds($msLeft) } function Write-ProgressReport($activity, $status, $collection, [switch][bool]$writeToHost, [switch][bool]$complete) { if ($script:lastActivity -ne $activity) { $script:activitystart = [DateTimeOffset]::Now $script:loopC = 0 } $script:lastActivity = $activity $script:loopC++ $c = $script:loopC if ($collection -ne $null) { $perc = ($c/[float]$collection.count * 100) $eta = get-eta $perc } else { $perc = 0 $eta = $null } if ($status -eq $null) { $status = "..." } $looptime = get-looptime $a = @{ Activity = "$activity $c/$($collection.count) Elapsed=$(get-elapsedtime) ETA=$eta Cur Speed=$(1/$($looptime.totalSeconds))/s AVG Speed=$($c/([DateTimeOffset]::Now - $script:activitystart).totalSeconds)/s" Status = $status } if ($complete) { $a += @{ Complete = $true } } else { $a += @{ PercentComplete = $perc } } write-progress @a if ($writeToHost) { $msg = "$activity : $status" if ($complete) { $msg += " DONE" } else { $msg += "($($perc)%)" } write-host $msg } } new-alias Log-Time Write-LogTime new-alias Log-Result Write-LogResult new-alias Log-Info Write-LogInfo new-alias Log-Error Write-LogError new-alias Log-Message Write-LogMessage new-alias Log-Verbose Write-LogVerbose new-alias Log-Progress Write-LogProgress new-alias Log-Warn Write-LogWarn new-alias Report-Progress Write-ProgressReport
PowerShellCorpus/PowerShellGallery/CompleteHipChat/1.0.1/functions/Get-HipChatRooms.ps1
Get-HipChatRooms.ps1
function Get-HipChatRooms { <# .SYNOPSIS Returns an array of HipChat rooms that the auth token has access to. .DESCRIPTION Returns an array of HipChat rooms that the auth token has access to. .LINK https://github.com/DaveStephens/PSHipchat .PARAMETER AuthToken Required. Your HipChat API token, that you can create here https://www.hipchat.com/account/api .PARAMETER MaxResults The maximum results that you want to see. Defaults to 100, limited to 1000 by the Hipchat API. .PARAMETER IncludePrivate Whether to include private rooms in the results. Defaults to true. .PARAMETER IncludeArchived Whether to include archived rooms in the results. Defaults to false. .PARAMETER ApiHost The URI of the HipChat api (default: api.hipchat.com) .PARAMETER TimeoutSecs Timeout of the HTTP call to the HipChat API. Defaults to 10 seconds. .EXAMPLE Get-HipChatRooms -AuthToken 1234abcd5678efgh -MaxResults 1000 #> [cmdletbinding()] param( [Parameter( Position = 0, Mandatory = $True )] [string]$AuthToken, [Parameter( Position = 1, Mandatory = $False )] [string]$MaxResults = 100, [Parameter( Position = 2, Mandatory = $False )] [string]$IncludePrivate = "true", [Parameter( Position = 3, Mandatory = $False )] [string]$IncludeArchived = "false", [Parameter( Position = 4, Mandatory = $False )] [string]$ApiHost = "api.hipchat.com", [Parameter( Position = 5, Mandatory = $False )] [string]$TimeoutSecs = 10 ) begin { $DebugPreference = "Continue" } process { try { $url = "https://$ApiHost/v2/room?max-results=$MaxResults&include-archived=$IncludeArchived&include-private=$IncludePrivate" Write-Verbose $url $headers = @{ "Authorization" = "Bearer $AuthToken" } $result = Invoke-RestMethod -Method Get -Uri $url -Headers $headers -TimeoutSec $TimeoutSecs -ContentType 'application/json' } catch { throw $_ } } end { return $result.items } }
PowerShellCorpus/PowerShellGallery/CompleteHipChat/1.0.1/functions/Send-HipChatMessage.ps1
Send-HipChatMessage.ps1
function Send-HipChatMessage { <# .SYNOPSIS Sends a message to a room in HipChat. .DESCRIPTION Sends a message to a room in HipChat. .LINK https://github.com/DaveStephens/PSHipchat .PARAMETER AuthToken Required. Your HipChat API token, created here https://www.hipchat.com/account/api .PARAMETER RoomID Required. The id of the room. .PARAMETER Message Required. The message body. 10,000 characters max. .PARAMETER Color The background color of the HipChat message. One of "yellow", "red", "green", "purple", "gray", or "random". Defaults to gray. .PARAMETER Notify Whether this message should trigger a user notification (change the tab color, play a sound, notify mobile phones, etc). Each recipient's notification preferences are taken into account. Defaults to false. .PARAMETER MessageFormat Determines how the message is treated by the HipChat server and rendered inside HipChat applications. More info at https://www.hipchat.com/docs/apiv2/method/send_room_notification. Valid values are html or text, defaults to 'text'. .PARAMETER ApiHost The URI of the HipChat api (default: api.hipchat.com). .PARAMETER TimeoutSecs Timeout of the HTTP call to the Hipchat API. Defaults to 10 seconds. .EXAMPLE Send-HipChatMessage -AuthToken 1234abcd5678efgh -RoomID 1234 -Message "All your base are belong to us." #> [cmdletbinding()] param( [Parameter( Position = 0, Mandatory = $True )] [string]$AuthToken, [Parameter( Position = 1, Mandatory = $True )] [string]$RoomID, [Parameter( Position = 2, Mandatory = $True )] [string]$Message, [Parameter( Position = 3, Mandatory = $False )] [string]$Color = "gray", [Parameter( Position = 4, Mandatory = $False )] [string]$Notify = "false", [Parameter( Position = 5, Mandatory = $False )] [string]$MessageFormat = "text", [Parameter( Position = 6, Mandatory = $False )] [string]$ApiHost = "api.hipchat.com", [Parameter( Position = 7, Mandatory = $False )] [string]$TimeoutSecs = 10 ) begin { $DebugPreference = "Continue" } process { try { $RoomID = [System.Uri]::EscapeDataString($RoomID) $url = "https://$ApiHost/v2/room/$RoomID/notification" Write-Verbose $url $headers = @{ "Authorization" = "Bearer $AuthToken" } $messageContent = @{ "color" = $Color "message_format" = $MessageFormat "notify" = $Notify "message" = $Message } $jsonMessage = ConvertTo-Json $messageContent Write-Verbose $jsonMessage $result = Invoke-RestMethod -Method Post -Uri $url -Headers $headers -TimeoutSec $TimeoutSecs -Body $jsonMessage -ContentType 'application/json' Write-Verbose $result } catch { throw $_ } } end { return $result } }
PowerShellCorpus/PowerShellGallery/NordTools/1.0.2/public/Install-NordVPN.ps1
Install-NordVPN.ps1
#Requires -RunAsAdministrator #Requires -Modules @{ModuleName="msi";ModuleVersion="3.2.3.1024"} $ErrorActionPreference = "Stop" Import-Module -Name "$(Split-Path $PSScriptRoot -Parent)\Private\Helpers.psm1" -DisableNameChecking function Install-NordVpn { <# .SYNOPSIS Installs NordVPN app .PARAMETER version Version of NordVPN app to install .PARAMETER paths Folder where to install .PARAMETER force Indicates if to remove existing NordVPN installation .PARAMETER displayLog Indicates if to display installation log .PARAMETER dontRun Indicates if to don't launch NordVPN after installation #> [CmdletBinding()] param( [string]$version, [string]$path, [switch]$force, [switch]$displayLog, [switch]$dontRun ) $existingInstallation = Get-MSIProductInfo -Name "NordVPN" if ($existingInstallation -ne $null) { Write-Host "Found existing installation of NordVPN $($existingInstallation.ProductVersion)" Write-Host "Product code $($existingInstallation.ProductCode)" Write-Host "Install location $($existingInstallation.InstallLocation)" if (!$force.IsPresent) { Write-Host "Exiting. Specify -force to force the installation." return } Write-Host "Removing existing installation" Uninstall-MSIProduct -ProductCode $existingInstallation.ProductCode } $source = "" if ($version) { $source = "http://downloads.nordvpn.com/apps/windows/NordVPN+Setup-$version.exe" } else { $source = "http://downloads.nordvpn.com/apps/windows/NordVPN beta setup.exe" } $destination = $null $result = $null $logFileName = [System.IO.Path]::GetRandomFileName() try { $destination = [System.IO.Path]::GetTempFileName() + ".exe" Write-Host "Downloading $version..." $response = Invoke-WebRequest $source -OutFile $destination Write-Host "Installing..." $result = RunInstaller -installerFile $destination -path $path -logFileName $logFileName } finally { if ($destination -and (Test-Path $destination)) { Remove-Item $destination -ErrorAction Ignore } } if ($displayLog.IsPresent) { DisplayLog $logFileName } if ($result.ExitCode -ne 0) { Write-Host "Failed to install NordVPN" -ForegroundColor Red return } $installation = Get-MSIProductInfo -Name "NordVPN" Write-Host "NordVPN $($installation.ProductVersion) has been successfully installed" -ForegroundColor Green if (!$dontRun.IsPresent) { Start-Process -FilePath (Join-Path $installation.InstallLocation "NordVPN.exe") } } function RunInstaller($installerFile, $path, $logFileName) { $installerArgs = @("/exenoui", "/qn", "/norestart") if ($path) { $installerArgs += "APPDIR=""$path""" } $installerArgs += "/li ""$logFileName""" # Can't use MSI cmdlets here because Advanced Installer exe packages are not supported $result = Execute-Command -path $installerFile -arguments $installerArgs return $result } function DisplayLog($fileName) { $logPath = Join-Path $env:TEMP $fileName Get-Content $logPath | Write-host }
PowerShellCorpus/PowerShellGallery/NordTools/1.0.2/public/Uninstall-NordVPN.ps1
Uninstall-NordVPN.ps1
#Requires -RunAsAdministrator #Requires -Modules @{ModuleName="msi";ModuleVersion="3.2.3.1024"} $ErrorActionPreference = "Stop" function Uninstall-NordVpn { <# .SYNOPSIS Uninstalls NordVpn app .PARAMETER displayLog Indicates if to display the uninstallation log file .PARAMETER cleanInstallDir Indicates if to clean leftovers after uninstallation #> [CmdletBinding()] param( [switch]$displayLog, [switch]$cleanInstallDir ) $existingInstallation = Get-MSIProductInfo -Name "NordVPN" if ($existingInstallation -eq $null) { Write-Host "Existing installation of NordVPN was not found." return } $installLocation = $existingInstallation.InstallLocation Write-Host "Found installation of NordVPN $($existingInstallation.ProductVersion)" Write-Host "Product code $($existingInstallation.ProductCode)" Write-Host "Install location $installLocation" Write-Host "Uninstalling..." $logFileName = [System.IO.Path]::GetTempFileName() $result = Uninstall-MSIProduct -ProductCode $existingInstallation.ProductCode -Log $logFileName if ($cleanInstallDir.IsPresent) { Write-Host "Cleaning install directory" Remove-Item $installLocation -Force -ErrorAction Ignore -Recurse } if ($displayLog.IsPresent) { Get-Content $logFileName | Write-Host } Write-Host "NordVPN has been successfully uninstalled" -ForegroundColor Green }
PowerShellCorpus/PowerShellGallery/PSPath/1.0.1/Update-Path.ps1
Update-Path.ps1
function Update-Path { $configuredPaths = [string[]] (& { foreach($path in & { (Get-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment').Path; (Get-ItemProperty 'HKCU:\Environment').Path; }) { if($path) { $path.Split(';') | % { if($_) { $_ } } } } }) $currentPaths = $env:Path.Split(';') $newPaths = [string[]] $configuredPaths | ? { -not ($currentPaths -contains $_) } foreach($path in $newPaths) { Write-Warning "Adding $path will be added to PATH." $env:Path = $env:Path + ';' + $path } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_SSLSettings_RequireCert.ps1
Sample_SSLSettings_RequireCert.ps1
configuration Sample_SSLSetting_RequireCert { param ( # Target nodes to apply the configuration [String[]]$NodeName = 'localhost' ) # Import the module that defines custom resources Import-DscResource -Module xWebAdministration Node $NodeName { SSLSettings SiteDefaults { Ensure = 'Present' Name = 'contoso.com' Bindings = @('Ssl', 'SslNegotiateCert', 'SslRequireCert') } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_IisLogging_Truncate.ps1
Sample_IisLogging_Truncate.ps1
configuration Sample_IisLogging_Truncate { param ( # Target nodes to apply the configuration [String[]]$NodeName = 'localhost' ) # Import the module that defines custom resources Import-DscResource -Module xWebAdministration Node $NodeName { IisLogging Logging { LogPath = 'C:\IISLogFiles' Logflags = @('Date','Time','ClientIP','UserName','ServerIP') LoglocalTimeRollover = $True LogTruncateSize = '2097152' LogFormat = 'W3C' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_Website_WithSSLFlags.ps1
Sample_Website_WithSSLFlags.ps1
configuration Sample_Website_NewWebsite { param ( # Target nodes to apply the configuration [String[]]$NodeName = 'localhost', # Name of the website to create [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$WebSiteName, # Source Path for Website content [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$SourcePath, # Destination path for Website content [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$DestinationPath ) # Import the module that defines custom resources Import-DscResource -Module xWebAdministration, PSDesiredStateConfiguration Node $NodeName { # Install the IIS role WindowsFeature IIS { Ensure = "Present" Name = "Web-Server" } # Install the ASP .NET 4.5 role WindowsFeature AspNet45 { Ensure = "Present" Name = "Web-Asp-Net45" } # Stop the default website Website DefaultSite { Ensure = "Present" Name = "Default Web Site" State = "Stopped" PhysicalPath = "C:\inetpub\wwwroot" DependsOn = "[WindowsFeature]IIS" } # Copy the website content File WebContent { Ensure = "Present" SourcePath = $SourcePath DestinationPath = $DestinationPath Recurse = $true Type = "Directory" DependsOn = "[WindowsFeature]AspNet45" } # Create the new Website # Have it set to the CertificateThumbprint # and set that the Server Name Indication is required Website NewWebsite { Ensure = "Present" Name = $WebSiteName State = "Started" PhysicalPath = $DestinationPath DependsOn = "[File]WebContent" BindingInfo = MSFT_WebBindingInformation { Protocol = 'https' Port = '443' CertificateStoreName = 'MY' CertificateThumbprint = 'BB84DE3EC423DDDE90C08AB3C5A828692089493C' HostName = $Website IPAddress = '*' SSLFlags = '1' } } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_Website_RemoveDefault.ps1
Sample_Website_RemoveDefault.ps1
configuration Sample_Website_StopDefault { param ( # Target nodes to apply the configuration [String[]]$NodeName = 'localhost' ) # Import the module that defines custom resources Import-DscResource -Module xWebAdministration, PSDesiredStateConfiguration Node $NodeName { # Install the IIS role WindowsFeature IIS { Ensure = 'Present' Name = 'Web-Server' } # Stop the default website Website DefaultSite { Ensure = 'Present' Name = 'Default Web Site' State = 'Stopped' PhysicalPath = 'C:\inetpub\wwwroot' DependsOn = '[WindowsFeature]IIS' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_Website_NewWebsiteFromConfigurationData.ps1
Sample_Website_NewWebsiteFromConfigurationData.ps1
Configuration Sample_Website_FromConfigurationData { # Import the module that defines custom resources Import-DscResource -Module xWebAdministration, PSDesiredStateConfiguration # Dynamically find the applicable nodes from configuration data Node $AllNodes.where{$_.Role -eq 'Web'}.NodeName { # Install the IIS role WindowsFeature IIS { Ensure = 'Present' Name = 'Web-Server' } # Install the ASP .NET 4.5 role WindowsFeature AspNet45 { Ensure = 'Present' Name = 'Web-Asp-Net45' } # Stop an existing website (set up in Sample_Website_Default) Website DefaultSite { Ensure = 'Present' Name = 'Default Web Site' State = 'Stopped' PhysicalPath = $Node.DefaultWebSitePath DependsOn = '[WindowsFeature]IIS' } # Copy the website content File WebContent { Ensure = 'Present' SourcePath = $Node.SourcePath DestinationPath = $Node.DestinationPath Recurse = $true Type = 'Directory' DependsOn = '[WindowsFeature]AspNet45' } # Create a new website Website BakeryWebSite { Ensure = 'Present' Name = $Node.WebsiteName State = 'Started' PhysicalPath = $Node.DestinationPath DependsOn = '[File]WebContent' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_IisLogging_Rollover.ps1
Sample_IisLogging_Rollover.ps1
configuration Sample_IisLogging_Rollover { param ( # Target nodes to apply the configuration [String[]]$NodeName = 'localhost' ) # Import the module that defines custom resources Import-DscResource -Module xWebAdministration Node $NodeName { IisLogging Logging { LogPath = 'C:\IISLogFiles' Logflags = @('Date','Time','ClientIP','UserName','ServerIP') LoglocalTimeRollover = $true LogPeriod = 'Hourly' LogFormat = 'W3C' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Examples/Sample_Website_NewWebsite.ps1
Sample_Website_NewWebsite.ps1
configuration Sample_Website_NewWebsite { param ( # Target nodes to apply the configuration [String[]]$NodeName = 'localhost', # Name of the website to create [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$WebSiteName, # Source Path for Website content [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$SourcePath, # Destination path for Website content [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$DestinationPath ) # Import the module that defines custom resources Import-DscResource -Module xWebAdministration, PSDesiredStateConfiguration Node $NodeName { # Install the IIS role WindowsFeature IIS { Ensure = 'Present' Name = 'Web-Server' } # Install the ASP .NET 4.5 role WindowsFeature AspNet45 { Ensure = 'Present' Name = 'Web-Asp-Net45' } # Stop the default website Website DefaultSite { Ensure = 'Present' Name = 'Default Web Site' State = 'Stopped' PhysicalPath = 'C:\inetpub\wwwroot' DependsOn = '[WindowsFeature]IIS' } # Copy the website content File WebContent { Ensure = 'Present' SourcePath = $SourcePath DestinationPath = $DestinationPath Recurse = $true Type = 'Directory' DependsOn = '[WindowsFeature]AspNet45' } # Create the new Website Website NewWebsite { Ensure = 'Present' Name = $WebSiteName State = 'Started' PhysicalPath = $DestinationPath DependsOn = '[File]WebContent' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Unit/MSFT_SslSettings.Tests.ps1
MSFT_SslSettings.Tests.ps1
$script:DSCModuleName = 'WebAdministrationDsc' $script:DSCResourceName = 'MSFT_SslSettings' #region HEADER $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'Tests\MockWebAdministrationWindowsFeature.psm1') $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Unit #endregion # Begin Testing try { #region Pester Tests InModuleScope $DSCResourceName { Describe "$script:DSCResourceName\Test-TargetResource" { Context 'Ensure is Present and SSLSettings is Present' { Mock Get-TargetResource -Verifiable {return @{ Name = 'Test' Bindings = @('Ssl') Ensure = 'Present' }} $result = Test-TargetResource -Name 'Test' -Ensure 'Present' -Bindings 'Ssl' Assert-VerifiableMocks It 'should return true' { $result | should be $true } } Context 'Ensure is Absent and SslSettings is Absent' { Mock Get-TargetResource {return @{ Name = 'Test' Bindings = @('Ssl') Ensure = 'Absent' }} $result = Test-TargetResource -Name 'Test' -Ensure 'Absent' -Bindings 'Ssl' Assert-VerifiableMocks It 'should return true' { $result | should be $true } } Context 'Ensure is Present and SslSettings is Absent' { Mock Get-TargetResource {return @{ Name = 'Test' Bindings = @('Ssl') Ensure = 'Absent' }} $result = Test-TargetResource -Name 'Test' -Ensure 'Present' -Bindings 'Ssl' Assert-VerifiableMocks It 'should return true' { $result | should be $false } } } Describe "$script:DSCResourceName\Get-TargetResource" { Context 'Command finds SSL Settings' { Mock Assert-Module -Verifiable {} Mock Get-WebConfigurationProperty -Verifiable { return 'Ssl' } $result = Get-TargetResource -Name 'Name' -Bindings 'Ssl' $expected = @{ Name = 'Name' Bindings = 'Ssl' Ensure = 'Present' } Assert-VerifiableMocks It 'should return the correct bindings' { $result.Bindings | should be $expected.Bindings } It 'should return the correct ensure' { $result.Ensure | Should Be $expected.Ensure } } Context 'Command does not find Ssl Settings' { Mock Assert-Module -Verifiable {} Mock Get-WebConfigurationProperty -Verifiable { return $false } $result = Get-TargetResource -Name 'Name' -Bindings 'Ssl' $expected = @{ Name = 'Name' Bindings = 'Ssl' Ensure = 'Absent' } Assert-VerifiableMocks It 'should return the correct bindings' { $result.Bindings | should be $expected.Bindings } It 'should return the correct ensure' { $result.Ensure | Should Be $expected.Ensure } } } Describe "$script:DSCResourceName\Set-TargetResource" { Context 'SSL Bindings set to none' { Mock Assert-Module -Verifiable { } Mock Set-WebConfigurationProperty -Verifiable {} $result = (Set-TargetResource -Name 'Name' -Bindings '' -Ensure 'Present' -Verbose) 4>&1 # Check that the LocalizedData message from the Set-TargetResource is correct $resultMessage = $LocalizedData.SettingSSLConfig -f 'Name', '' Assert-VerifiableMocks It 'should return the correct string' { $result | Should Be $resultMessage } } Context 'Ssl Bindings set to Ssl' { Mock Assert-Module -Verifiable { } Mock Set-WebConfigurationProperty -Verifiable {} $result = (Set-TargetResource -Name 'Name' -Bindings 'Ssl' -Ensure 'Present' -Verbose) 4>&1 # Check that the LocalizedData message from the Set-TargetResource is correct $resultMessage = $LocalizedData.SettingSSLConfig -f 'Name', 'Ssl' Assert-VerifiableMocks It 'should return the correct string' { $result | Should Be $resultMessage } } Context 'Ssl Bindings set to Ssl,SslNegotiateCert,SslRequireCert' { Mock Assert-Module -Verifiable {} Mock Set-WebConfigurationProperty -Verifiable {} $result = (Set-TargetResource -Name 'Name' -Bindings @('Ssl','SslNegotiateCert','SslRequireCert') -Ensure 'Present' -Verbose) 4>&1 # Check that the LocalizedData message from the Set-TargetResource is correct $resultMessage = $LocalizedData.SettingSSLConfig -f 'Name', 'Ssl,SslNegotiateCert,SslRequireCert' Assert-VerifiableMocks It 'should return the correct string' { $result | Should Be $resultMessage } } } } } finally { Restore-TestEnvironment -TestEnvironment $TestEnvironment }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Unit/MSFT_IisLogging.tests.ps1
MSFT_IisLogging.tests.ps1
$script:DSCModuleName = 'WebAdministrationDsc' $script:DSCResourceName = 'MSFT_IisLogging' # Unit Test Template Version: 1.1.0 $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'Tests\MockWebAdministrationWindowsFeature.psm1') $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Unit #endregion HEADER # Begin Testing try { #region Pester Tests InModuleScope $script:DSCResourceName { $MockLogParameters = @{ LogPath = 'C:\MockLogLocation' LogFlags = 'Date','Time','ClientIP','UserName','ServerIP' LogPeriod = 'Hourly' LogTruncateSize = '2097152' LoglocalTimeRollover = $true LogFormat = 'W3C' } $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' logFormat = 'W3C' period = 'Daily' truncateSize = '1048576' localTimeRollover = 'False' } Describe "$script:DSCResourceName\Assert-Module" { Context 'WebAdminstration module is not installed' { Mock -ModuleName Helper -CommandName Get-Module -MockWith { return $null } It 'should throw an error' { { Assert-Module } | Should Throw } } } Describe "$script:DSCResourceName\Get-TargetResource" { Context 'Correct hashtable is returned' { Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Assert-Module -MockWith {} $result = Get-TargetResource -LogPath $MockLogParameters.LogPath It 'should call Get-WebConfiguration once' { Assert-MockCalled -CommandName Get-WebConfiguration -Exactly 1 } It 'should return LogPath' { $Result.LogPath | Should Be $MockLogOutput.directory } It 'should return LogFlags' { $Result.LogFlags | Should Be $MockLogOutput.logExtFileFlags } It 'should return LogPeriod' { $Result.LogPeriod | Should Be $MockLogOutput.period } It 'should return LogTruncateSize' { $Result.LogTruncateSize | Should Be $MockLogOutput.truncateSize } It 'should return LoglocalTimeRollover' { $Result.LoglocalTimeRollover | Should Be $MockLogOutput.localTimeRollover } It 'should return LogFormat' { $Result.LogFormat | Should Be $MockLogOutput.logFormat } } } Describe "$script:DSCResourceName\Test-TargetResource" { Mock -CommandName Assert-Module -MockWith {} Context 'All settings are correct'{ $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return true' { $result | Should be $true } } Context 'All Settings are incorrect' { Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } Context 'Check LogPath should return false' { $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } Context 'Check LogFlags should return false' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } Context 'Check LogPeriod should return false' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = 'Daily' truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } Context 'Check LogTruncateSize should return false' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = '1048576' localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } Context 'Check LoglocalTimeRollover should return false' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = 'False' logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } Context 'Check LogFormat should return false' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = 'IIS' } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Test-TargetResource @MockLogParameters It 'Should return false' { $result | Should be $false } } } Describe "$script:DSCResourceName\Set-TargetResource" { Mock -CommandName Assert-Module -MockWith {} Context 'All Settings are incorrect' { $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' logFormat = 'IIS' period = 'Daily' truncateSize = '1048576' localTimeRollover = 'False' } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 8 } } Context 'LogPath is incorrect' { $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 1 } } Context 'LogFlags are incorrect' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 2 } } Context 'LogPeriod is incorrect' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = 'Daily' truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 1 } } Context 'LogTruncateSize is incorrect' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = '1048576' localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 2 } } Context 'LoglocalTimeRollover is incorrect' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = 'False' logFormat = $MockLogParameters.LogFormat } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 1 } } Context 'LogFormat is incorrect' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover logFormat = 'IIS' } Mock -CommandName Test-Path -MockWith { return $true } Mock -CommandName Get-WebConfiguration ` -MockWith { return $MockLogOutput } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } Mock -CommandName Set-WebConfigurationProperty $result = Set-TargetResource @MockLogParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 1 } } } Describe "$script:DSCResourceName\Compare-LogFlags" { Context 'Returns false when LogFlags are incorrect' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = @('Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus') logFormat = 'W3C' period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Compare-LogFlags $MockLogParameters.LogFlags It 'Should return false' { $result | Should be $false } } Context 'Returns true when LogFlags are correct' { $MockLogOutput = @{ directory = $MockLogParameters.LogPath logExtFileFlags = $MockLogParameters.LogFlags logFormat = 'W3C' period = $MockLogParameters.LogPeriod truncateSize = $MockLogParameters.LogTruncateSize localTimeRollover = $MockLogParameters.LoglocalTimeRollover } Mock -CommandName Get-WebConfigurationProperty ` -MockWith { return $MockLogOutput.logExtFileFlags } $result = Compare-LogFlags $MockLogParameters.LogFlags It 'Should return true' { $result | Should be $true } } } } #endregion } finally { Restore-TestEnvironment -TestEnvironment $TestEnvironment }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Unit/MSFT_Website.Tests.ps1
MSFT_Website.Tests.ps1
$script:DSCModuleName = 'WebAdministrationDsc' $script:DSCResourceName = 'MSFT_Website' #region HEADER $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'Tests\MockWebAdministrationWindowsFeature.psm1') $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Unit #endregion # Begin Testing try { #region Pester Tests InModuleScope -ModuleName $script:DSCResourceName -ScriptBlock { Describe "$script:DSCResourceName\Assert-Module" { Context 'WebAdminstration module is not installed' { Mock -ModuleName Helper -CommandName Get-Module -MockWith { return $null } It 'should throw an error' { { Assert-Module } | Should Throw } } } Describe "how $script:DSCResourceName\Get-TargetResource responds" { $MockWebBinding = @( @{ bindingInformation = '*:443:web01.contoso.com' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'WebHosting' sslFlags = '1' } ) $MockPreloadAndAutostartProviders = @( @{ preloadEnabled = 'True' ServiceAutoStartProvider = 'MockServiceAutoStartProvider' ServiceAutoStartEnabled = 'True' } ) $MockWebConfiguration = @( @{ SectionPath = 'MockSectionPath' PSPath = 'MockPSPath' Collection = @( [PSCustomObject] @{ Name = 'MockServiceAutoStartProvider'; Type = 'MockApplicationType' } ) } ) $MockAuthenticationInfo = @( New-CimInstance -ClassName MSFT_WebAuthenticationInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Anonymous = 'true' Basic = 'false' Digest = 'false' Windows = 'false' } ` -ClientOnly ) $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' logFormat = $MockParameters.LogFormat period = 'Daily' truncateSize = '1048576' localTimeRollover = 'False' } $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = $MockPreloadAndAutostartProviders LogFile = $MockLogOutput Count = 1 } Mock -CommandName Assert-Module -MockWith {} Context 'Website does not exist' { Mock -CommandName Get-Website $Result = Get-TargetResource -Name $MockWebsite.Name It 'should return Absent' { $Result.Ensure | Should Be 'Absent' } } Context 'There are multiple websites with the same name' { Mock -CommandName Get-Website -MockWith { return @( @{Name = 'MockName'} @{Name = 'MockName'} ) } It 'should throw the correct error' { $ErrorId = 'WebsiteDiscoveryFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteDiscoveryFailure -f 'MockName' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null {Get-TargetResource -Name 'MockName'} | Should Throw $ErrorRecord } } Context 'Single website exists' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfiguration ` -ParameterFilter {$filter -eq '//defaultDocument/files/*'} ` -MockWith { return @{value = 'index.html'} } Mock -CommandName Get-WebConfiguration ` -ParameterFilter {$filter -eq '/system.applicationHost/serviceAutoStartProviders'} ` -MockWith { return $MockWebConfiguration} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockAuthenticationInfo} Mock -CommandName Test-AuthenticationEnabled { return $true } ` -ParameterFilter { ($Type -eq 'Anonymous') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Basic') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Digest') } Mock -CommandName Test-AuthenticationEnabled { return $true } ` -ParameterFilter { ($Type -eq 'Windows') } $Result = Get-TargetResource -Name $MockWebsite.Name It 'should call Get-Website once' { Assert-MockCalled -CommandName Get-Website -Exactly 1 } It 'should call Get-WebConfiguration twice' { Assert-MockCalled -CommandName Get-WebConfiguration -Exactly 2 } It 'should return Ensure' { $Result.Ensure | Should Be 'Present' } It 'should return Name' { $Result.Name | Should Be $MockWebsite.Name } It 'should return PhysicalPath' { $Result.PhysicalPath | Should Be $MockWebsite.PhysicalPath } It 'should return State' { $Result.State | Should Be $MockWebsite.State } It 'should return ApplicationPool' { $Result.ApplicationPool | Should Be $MockWebsite.ApplicationPool } It 'should return BindingInfo' { $Result.BindingInfo.Protocol | Should Be $MockWebBinding.protocol $Result.BindingInfo.BindingInformation | Should Be $MockWebBinding.bindingInformation $Result.BindingInfo.IPAddress | Should Be '*' $Result.BindingInfo.Port | Should Be 443 $Result.BindingInfo.HostName | Should Be 'web01.contoso.com' $Result.BindingInfo.CertificateThumbprint | Should Be $MockWebBinding.certificateHash $Result.BindingInfo.CertificateStoreName | Should Be $MockWebBinding.certificateStoreName $Result.BindingInfo.SslFlags | Should Be $MockWebBinding.sslFlags } It 'should return DefaultPage' { $Result.DefaultPage | Should Be 'index.html' } It 'should return EnabledProtocols' { $Result.EnabledProtocols | Should Be $MockWebsite.EnabledProtocols } It 'should return AuthenticationInfo' { $Result.AuthenticationInfo.CimInstanceProperties['Anonymous'].Value | Should Be 'true' $Result.AuthenticationInfo.CimInstanceProperties['Basic'].Value | Should Be 'false' $Result.AuthenticationInfo.CimInstanceProperties['Digest'].Value | Should Be 'false' $Result.AuthenticationInfo.CimInstanceProperties['Windows'].Value | Should Be 'true' } It 'should return Preload' { $Result.PreloadEnabled | Should Be $MockWebsite.ApplicationDefaults.PreloadEnabled } It 'should return ServiceAutoStartProvider' { $Result.ServiceAutoStartProvider | Should Be $MockWebsite.ApplicationDefaults.ServiceAutoStartProvider } It 'should return ServiceAutoStartEnabled' { $Result.ServiceAutoStartEnabled | Should Be $MockWebsite.ApplicationDefaults.ServiceAutoStartEnabled } It 'should return ApplicationType' { $Result.ApplicationType | Should Be $MockPreloadAndAutostartProvider.ApplicationType } It 'should return correct LogPath' { $Result.LogPath | Should Be $MockWebsite.Logfile.directory } It 'should return LogFlags' { $Result.LogFlags | Should Be $MockWebsite.Logfile.logExtFileFlags } It 'should return LogPeriod' { $Result.LogPeriod | Should Be $MockWebsite.Logfile.period } It 'should return LogTruncateSize' { $Result.LogTruncateSize | Should Be $MockWebsite.Logfile.truncateSize } It 'should return LoglocalTimeRollover' { $Result.LoglocalTimeRollover | Should Be $MockWebsite.Logfile.localTimeRollover } It 'should return LogFormat' { $Result.logFormat | Should Be $MockWebsite.Logfile.logFormat } } } Describe "how $script:DSCResourceName\Test-TargetResource responds to Ensure = 'Present'" { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = 'web01.contoso.com' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'WebHosting' SslFlags = 1 } -ClientOnly ) $MockParameters = @{ Ensure = 'Present' Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' BindingInfo = $MockBindingInfo DefaultPage = @('index.html') EnabledProtocols = 'http' Preload = 'True' ServiceAutoStartProvider = 'MockAutoStartProvider' ServiceAutoStartEnabled = 'True' ApplicationType = 'MockApplicationType' LogPath = 'C:\MockLogLocation' LogFlags = 'Date','Time','ClientIP','UserName','ServerIP' LogPeriod = 'Hourly' LogTruncateSize = '2000000' LoglocalTimeRollover = $True } $MockWebBinding = @( @{ bindingInformation = '*:443:web01.contoso.com' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'WebHosting' sslFlags = '1' } ) $MockPreloadAndAutostartProviders = @( @{ Preload = 'True' ServiceAutoStartProvider = 'MockServiceAutoStartProvider' ServiceAutoStartEnabled = 'True' } ) $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' logFormat = $MockParameters.LogFormat period = 'Daily' truncateSize = '1048576' localTimeRollover = 'False' } $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{ Collection = @($MockWebBinding) } EnabledProtocols = 'http' ApplicationDefaults = @{ Collection = @($MockPreloadAndAutostartProviders) } LogFile = $MockLogOutput Count = 1 } Mock -CommandName Assert-Module -MockWith {} Context 'Website does not exist' { Mock -CommandName Get-Website $Result = Test-TargetResource ` -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath It 'should return False' { $Result | Should Be $false } } Context 'Check PhysicalPath is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath 'C:\Different' ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check State is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -State 'Stopped' ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check ApplicationPool is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Name $MockParameters.Name ` -Ensure $MockParameters.Ensure ` -PhysicalPath $MockParameters.PhysicalPath ` -ApplicationPool 'MockPoolDifferent' ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check BindingInfo is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Test-WebsiteBinding -MockWith {return $false} $Result = Test-TargetResource -Name $MockParameters.Name ` -Ensure $MockParameters.Ensure ` -PhysicalPath $MockParameters.PhysicalPath ` -BindingInfo $MockParameters.BindingInfo ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check DefaultPage is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfiguration -MockWith {return @{value = 'MockDifferent.html'}} $Result = Test-TargetResource -Name $MockParameters.Name ` -Ensure $MockParameters.Ensure ` -PhysicalPath $MockParameters.PhysicalPath ` -DefaultPage $MockParameters.DefaultPage ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check EnabledProtocols is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -EnabledProtocols 'https' ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check AuthenticationInfo is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock Test-AuthenticationEnabled { return $true } ` -ParameterFilter { ($Type -eq 'Anonymous') } Mock Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Basic') } Mock Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Digest') } Mock Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Windows') } $MockAuthenticationInfo = New-CimInstance ` -ClassName MSFT_WebAuthenticationInformation ` -ClientOnly ` -Property @{ Anonymous=$true; Basic=$false; Digest=$false; Windows=$true } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -AuthenticationInfo $MockAuthenticationInfo ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check Preload is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -Preload $False ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check AutoStartEnabled is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -ServiceAutoStartEnabled $False ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check AutoStartProvider is different' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -ServiceAutoStartProvider 'MockAutoStartProviderDifferent' ` -ApplicationType 'MockApplicationTypeDifferent' ` -Verbose:$VerbosePreference It 'should return False' { $Result | Should Be $false } } Context 'Check LogPath is different' { $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = $MockParameters.LogFlags logFormat = $MockParameters.LogFormat period = $MockParameters.LogPeriod truncateSize = $MockParameters.LogTruncateSize localTimeRollover = $MockParameters.LoglocalTimeRollover } Mock -CommandName Test-Path -MockWith {Return $true} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockLogOutput.logExtFileFlags } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -LogPath 'C:\MockLogPath2' ` -Verbose:$VerbosePreference It 'Should return false' { $result | Should be $false } } Context 'Check LogFlags are different' { $MockLogOutput = @{ directory = $MockParameters.LogPath logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' logFormat = $MockParameters.LogFormat period = $MockParameters.LogPeriod truncateSize = $MockParameters.LogTruncateSize localTimeRollover = $MockParameters.LoglocalTimeRollover } Mock -CommandName Test-Path -MockWith {Return $true} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockLogOutput.logExtFileFlags } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -LogFlags 'Date','Time','ClientIP','UserName','ServerIP' ` -Verbose:$VerbosePreference It 'Should return false' { $result | Should be $false } } Context 'Check LogPeriod is different' { $MockLogOutput = @{ directory = $MockParameters.LogPath logExtFileFlags = $MockParameters.LogFlags logFormat = $MockParameters.LogFormat period = 'Daily' truncateSize = $MockParameters.LogTruncateSize localTimeRollover = $MockParameters.LoglocalTimeRollover } Mock -CommandName Test-Path -MockWith {Return $true} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockLogOutput.logExtFileFlags } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -LogPeriod 'Hourly' ` -Verbose:$VerbosePreference It 'Should return false' { $result | Should be $false } } Context 'Check LogTruncateSize is different' { $MockLogOutput = @{ directory = $MockParameters.LogPath logExtFileFlags = $MockParameters.LogFlags logFormat = $MockParameters.LogFormat period = $MockParameters.LogPeriod truncateSize = '1048576' localTimeRollover = $MockParameters.LoglocalTimeRollover } Mock -CommandName Test-Path -MockWith {Return $true} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockLogOutput.logExtFileFlags } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -LogTruncateSize '2000000' ` -Verbose:$VerbosePreference It 'Should return false' { $result | Should be $false } } Context 'Check LoglocalTimeRollover is different' { $MockLogOutput = @{ directory = $MockParameters.LogPath logExtFileFlags = $MockParameters.LogFlags logFormat = $MockParameters.LogFormat period = $MockParameters.LogPeriod truncateSize = $MockParameters.LogTruncateSize localTimeRollover = 'False' } Mock -CommandName Test-Path -MockWith {Return $true} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockLogOutput.logExtFileFlags } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -LoglocalTimeRollover $True ` -Verbose:$VerbosePreference It 'Should return false' { $result | Should be $false } } Context 'Check LogFormat is different' { $MockLogOutput = @{ directory = $MockParameters.LogPath logExtFileFlags = $MockParameters.LogFlags logFormat = 'IIS' period = $MockParameters.LogPeriod truncateSize = $MockParameters.LogTruncateSize localTimeRollover = $MockParameters.LoglocalTimeRollover } $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = $MockPreloadAndAutostartProviders LogFile = $MockLogOutput Count = 1 } Mock -CommandName Test-Path -MockWith {Return $true} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Get-WebConfigurationProperty ` -MockWith {return $MockLogOutput.logExtFileFlags } $Result = Test-TargetResource -Ensure $MockParameters.Ensure ` -Name $MockParameters.Name ` -PhysicalPath $MockParameters.PhysicalPath ` -LogFormat 'W3C' ` -Verbose:$VerbosePreference It 'Should return false' { $result | Should be $false } } } Describe "how $script:DSCResourceName\Set-TargetResource responds to Ensure = 'Present'" { $MockAuthenticationInfo = New-CimInstance ` -ClassName MSFT_WebApplicationAuthenticationInformation ` -ClientOnly ` -Property @{ Anonymous=$true; Basic=$false; Digest=$false; Windows=$true } $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = 'web01.contoso.com' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'WebHosting' SslFlags = 1 } -ClientOnly ) $MockParameters = @{ Ensure = 'Present' Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' BindingInfo = $MockBindingInfo DefaultPage = @('index.html') EnabledProtocols = 'http' Preload = $True ServiceAutoStartProvider = 'MockAutoStartProvider' ServiceAutoStartEnabled = $True ApplicationType = 'MockApplicationType' AuthenticationInfo = $MockAuthenticationInfo LogPath = 'C:\MockLogLocation' LogFlags = 'Date','Time','ClientIP','UserName','ServerIP' LogPeriod = 'Hourly' LogTruncateSize = '2000000' LoglocalTimeRollover = $True LogFormat = 'W3C' } $MockWebBinding = @( @{ bindingInformation = '*:80:' protocol = 'http' certificateHash = '' certificateStoreName = '' sslFlags = '0' } ) $MockPreloadAndAutostartProviders = @( @{ Preload = $True ServiceAutoStartProvider = 'MockServiceAutoStartProvider' ServiceAutoStartEnabled = $True } ) $MockLogOutput = @{ directory = '%SystemDrive%\inetpub\logs\LogFiles' logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' logFormat = 'IIS' period = 'Daily' truncateSize = '1048576' localTimeRollover = 'False' } $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\Different' State = 'Stopped' ApplicationPool = 'MockPoolDifferent' Bindings = @{ Collection = @($MockWebBinding) } EnabledProtocols = 'http' ApplicationDefaults = @{ Collection = @($MockPreloadAndAutostartProviders) } LogFile = $MockLogOutput } Mock -CommandName Assert-Module -MockWith {} Context 'All properties need to be updated and website must be started' { Mock -CommandName Add-WebConfiguration Mock -CommandName Confirm-UniqueBinding -MockWith {return $true} Mock -CommandName Confirm-UniqueServiceAutoStartProviders -MockWith {return $false} Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Test-WebsiteBinding -MockWith {return $false} Mock -CommandName Start-Website Mock -CommandName Set-ItemProperty Mock -CommandName Set-WebConfiguration Mock -CommandName Set-Authentication Mock -CommandName Update-WebsiteBinding Mock -CommandName Update-DefaultPage Mock -CommandName Test-AuthenticationEnabled { return $true } ` -ParameterFilter { ($Type -eq 'Anonymous') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Basic') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Digest') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Windows') } $Result = Set-TargetResource @MockParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Add-WebConfiguration -Exactly 1 Assert-MockCalled -CommandName Confirm-UniqueBinding -Exactly 1 Assert-MockCalled -CommandName Confirm-UniqueServiceAutoStartProviders -Exactly 1 Assert-MockCalled -CommandName Test-AuthenticationEnabled -Exactly 4 Assert-MockCalled -CommandName Test-WebsiteBinding -Exactly 1 Assert-MockCalled -CommandName Update-WebsiteBinding -Exactly 1 Assert-MockCalled -CommandName Update-DefaultPage -Exactly 1 Assert-MockCalled -CommandName Set-Authentication -Exactly 4 Assert-MockCalled -CommandName Set-ItemProperty -Exactly 12 Assert-MockCalled -CommandName Start-Website -Exactly 1 } } Context 'Existing website cannot be started due to a binding conflict' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Set-ItemProperty Mock -CommandName Add-WebConfiguration Mock -CommandName Test-WebsiteBinding -MockWith {return $false} Mock -CommandName Update-WebsiteBinding Mock -CommandName Update-DefaultPage Mock -CommandName Confirm-UniqueBinding -MockWith {return $false} Mock -CommandName Confirm-UniqueServiceAutoStartProviders -MockWith {return $true} Mock -CommandName Start-Website It 'should throw the correct error' { $ErrorId = 'WebsiteBindingConflictOnStart' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteBindingConflictOnStart -f $MockParameters.Name $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null {Set-TargetResource @MockParameters} | Should Throw $ErrorRecord } } Context 'Start-Website throws an error' { Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Set-ItemProperty Mock -CommandName Add-WebConfiguration Mock -CommandName Test-WebsiteBinding -MockWith {return $false} Mock -CommandName Update-WebsiteBinding Mock -CommandName Update-DefaultPage Mock -CommandName Confirm-UniqueBinding -MockWith {return $true} Mock -CommandName Confirm-UniqueServiceAutoStartProviders -MockWith {return $true} Mock -CommandName Start-Website -MockWith {throw} It 'should throw the correct error' { $ErrorId = 'WebsiteStateFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation $ErrorMessage = $LocalizedData.ErrorWebsiteStateFailure -f $MockParameters.Name, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Set-TargetResource @MockParameters } | Should Throw $ErrorRecord } } Context 'All properties need to be updated and website must be stopped' { $MockParameters = $MockParameters.Clone() $MockParameters.State = 'Stopped' $MockWebsite = $MockWebsite.Clone() $MockWebsite.State = 'Started' Mock -CommandName Get-Website -MockWith {return $MockWebsite} Mock -CommandName Set-ItemProperty Mock -CommandName Add-WebConfiguration Mock -CommandName Test-WebsiteBinding -MockWith {return $false} Mock -CommandName Update-WebsiteBinding Mock -CommandName Update-DefaultPage Mock -CommandName Set-Authentication Mock -CommandName Stop-Website Mock -CommandName Test-AuthenticationEnabled { return $true } ` -ParameterFilter { ($Type -eq 'Anonymous') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Basic') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Digest') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Windows') } $Result = Set-TargetResource @MockParameters It 'should call all the mocks' { Assert-MockCalled -CommandName Set-ItemProperty -Exactly 12 Assert-MockCalled -CommandName Add-WebConfiguration -Exactly 1 Assert-MockCalled -CommandName Test-WebsiteBinding -Exactly 1 Assert-MockCalled -CommandName Update-WebsiteBinding -Exactly 1 Assert-MockCalled -CommandName Update-DefaultPage -Exactly 1 Assert-MockCalled -CommandName Set-Authentication -Exactly 4 Assert-MockCalled -CommandName Stop-Website -Exactly 1 } } Context 'Website does not exist' { $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = @{Collection = @($MockPreloadAndAutostartProviders)} LogFile = $MockLogOutput } Mock -CommandName Get-Website Mock -CommandName Get-Command -MockWith { return @{ Parameters = @{ Name = 'MockName' } } } Mock -CommandName New-Website -MockWith { return $MockWebsite } Mock -CommandName Stop-Website Mock -CommandName Test-WebsiteBinding -MockWith { return $false } Mock -CommandName Update-WebsiteBinding Mock -CommandName Set-ItemProperty Mock -CommandName Add-WebConfiguration Mock -CommandName Update-DefaultPage Mock -CommandName Confirm-UniqueBinding -MockWith { return $true } Mock -CommandName Confirm-UniqueServiceAutoStartProviders -MockWith { return $false } Mock -CommandName Set-Authentication Mock -CommandName Start-Website Mock -CommandName Test-AuthenticationEnabled { return $true } ` -ParameterFilter { ($Type -eq 'Anonymous') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Basic') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Digest') } Mock -CommandName Test-AuthenticationEnabled { return $false } ` -ParameterFilter { ($Type -eq 'Windows') } $Result = Set-TargetResource @MockParameters It 'should call all the mocks' { Assert-MockCalled -CommandName New-Website -Exactly 1 Assert-MockCalled -CommandName Stop-Website -Exactly 1 Assert-MockCalled -CommandName Test-WebsiteBinding -Exactly 1 Assert-MockCalled -CommandName Update-WebsiteBinding -Exactly 1 Assert-MockCalled -CommandName Set-ItemProperty -Exactly 10 Assert-MockCalled -CommandName Add-WebConfiguration -Exactly 1 Assert-MockCalled -CommandName Update-DefaultPage -Exactly 1 Assert-MockCalled -CommandName Confirm-UniqueBinding -Exactly 1 Assert-MockCalled -CommandName Confirm-UniqueServiceAutoStartProviders -Exactly 1 Assert-MockCalled -CommandName Set-Authentication -Exactly 4 Assert-MockCalled -CommandName Start-Website -Exactly 1 } } Context 'New website cannot be started due to a binding conflict' { $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' Preload = $True ServiceAutoStartProvider = 'MockAutoStartProvider' ServiceAutoStartEnabled = $True ApplicationType = 'MockApplicationType' } Mock -CommandName Get-Website Mock -CommandName Get-Command -MockWith { return @{ Parameters = @{ Name = 'MockName' } } } Mock -CommandName New-Website -MockWith {return $MockWebsite} Mock -CommandName Stop-Website Mock -CommandName Test-WebsiteBinding -MockWith {return $false} Mock -CommandName Update-WebsiteBinding Mock -CommandName Set-ItemProperty Mock -CommandName Add-WebConfiguration Mock -CommandName Update-DefaultPage Mock -CommandName Confirm-UniqueBinding -MockWith {return $false} Mock -CommandName Confirm-UniqueServiceAutoStartProviders -MockWith {return $true} Mock -CommandName Start-Website It 'should throw the correct error' { $ErrorId = 'WebsiteBindingConflictOnStart' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteBindingConflictOnStart -f $MockParameters.Name $Exception = New-Object -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Set-TargetResource @MockParameters } | Should Throw $ErrorRecord } } Context 'New-Website throws an error' { Mock -CommandName Get-Website Mock -CommandName Get-Command -MockWith { return @{ Parameters = @{ Name = 'MockName' } } } Mock -CommandName New-Website -MockWith {throw} It 'should throw the correct error' { $ErrorId = 'WebsiteCreationFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation $ErrorMessage = $LocalizedData.ErrorWebsiteCreationFailure -f $MockParameters.Name, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Set-TargetResource @MockParameters } | Should Throw $ErrorRecord } } } Describe "how $script:DSCResourceName\Set-TargetResource responds to Ensure = 'Absent'" { $MockParameters = @{ Ensure = 'Absent' Name = 'MockName' PhysicalPath = 'C:\NonExistent' } Mock -CommandName Get-Website -MockWith {return @{Name = $MockParameters.Name}} Mock -CommandName Assert-Module -MockWith {} It 'should call Remove-Website' { Mock -CommandName Remove-Website $Result = Set-TargetResource @MockParameters Assert-MockCalled -CommandName Get-Website -Exactly 1 Assert-MockCalled -CommandName Remove-Website -Exactly 1 } It 'should throw the correct error' { Mock -CommandName Remove-Website -MockWith {throw} $ErrorId = 'WebsiteRemovalFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation $ErrorMessage = $LocalizedData.ErrorWebsiteRemovalFailure -f $MockParameters.Name, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null {Set-TargetResource @MockParameters} | Should Throw $ErrorRecord } } Describe "$script:DSCResourceName\Confirm-UniqueBinding" { Context 'Returns false when LogFlags are incorrect' { $MockLogOutput = @{ logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP','Method','UriStem','UriQuery','HttpStatus','Win32Status','TimeTaken','ServerPort','UserAgent','Referer','HttpSubStatus' } $MockWebsite = @{ Name = 'MockName' LogFile = $MockLogOutput } Mock -CommandName Get-WebSite ` -MockWith { return $MockWebsite } $result = Compare-LogFlags -Name 'MockWebsite' -LogFlags 'Date','Time','ClientIP','UserName','ServerIP' It 'Should return false' { $result | Should be $false } } Context 'Returns true when LogFlags are correct' { $MockLogOutput = @{ logExtFileFlags = 'Date','Time','ClientIP','UserName','ServerIP' } $MockWebsite = @{ Name = 'MockName' LogFile = $MockLogOutput } Mock -CommandName Get-WebSite ` -MockWith { return $MockWebsite } $result = Compare-LogFlags -Name $MockWebsite.Name -LogFlags 'Date','Time','ClientIP','UserName','ServerIP' It 'Should return true' { $result | Should be $true } } } Describe "$script:DSCResourceName\Confirm-UniqueBinding" { $MockParameters = @{ Name = 'MockSite' } Context 'Website does not exist' { Mock -CommandName Get-Website It 'should throw the correct error' { $ErrorId = 'WebsiteNotFound' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteNotFound -f $MockParameters.Name $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Confirm-UniqueBinding -Name $MockParameters.Name } | Should Throw $ErrorRecord } } Context 'Expected behavior' { $GetWebsiteOutput = @( @{ Name = $MockParameters.Name State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } ) } } ) Mock -CommandName Get-Website -MockWith { return $GetWebsiteOutput } It 'should not throw an error' { { Confirm-UniqueBinding -Name $MockParameters.Name } | Should Not Throw } It 'should call Get-Website twice' { Assert-MockCalled -CommandName Get-Website -Exactly 2 } } Context 'Bindings are unique' { $GetWebsiteOutput = @( @{ Name = $MockParameters.Name State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } @{ protocol = 'http'; bindingInformation = '*:8080:' } ) } } @{ Name = 'MockSite2' State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:81:' } ) } } @{ Name = 'MockSite3' State = 'Started' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:8081:' } ) } } ) Mock -CommandName Get-Website -MockWith {return $GetWebsiteOutput} It 'should return True' { Confirm-UniqueBinding -Name $MockParameters.Name | Should Be $true } } Context 'Bindings are not unique' { $GetWebsiteOutput = @( @{ Name = $MockParameters.Name State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } @{ protocol = 'http'; bindingInformation = '*:8080:' } ) } } @{ Name = 'MockSite2' State = 'Started' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } ) } } @{ Name = 'MockSite3' State = 'Started' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:8080:' } ) } } ) Mock -CommandName Get-Website -MockWith {return $GetWebsiteOutput} It 'should return False' { Confirm-UniqueBinding -Name $MockParameters.Name | Should Be $false } } Context 'One of the bindings is assigned to another website that is Stopped' { $GetWebsiteOutput = @( @{ Name = $MockParameters.Name State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } @{ protocol = 'http'; bindingInformation = '*:8080:' } ) } } @{ Name = 'MockSite2' State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } ) } } ) Mock -CommandName Get-Website -MockWith { return $GetWebsiteOutput } It 'should return True if stopped websites are excluded' { Confirm-UniqueBinding -Name $MockParameters.Name -ExcludeStopped | Should Be $true } It 'should return False if stopped websites are not excluded' { Confirm-UniqueBinding -Name $MockParameters.Name | Should Be $false } } Context 'One of the bindings is assigned to another website that is Started' { $GetWebsiteOutput = @( @{ Name = $MockParameters.Name State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } @{ protocol = 'http'; bindingInformation = '*:8080:' } ) } } @{ Name = 'MockSite2' State = 'Stopped' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } ) } } @{ Name = 'MockSite3' State = 'Started' Bindings = @{ Collection = @( @{ protocol = 'http'; bindingInformation = '*:80:' } ) } } ) Mock -CommandName Get-Website -MockWith { return $GetWebsiteOutput } It 'should return False' { Confirm-UniqueBinding -Name $MockParameters.Name -ExcludeStopped | Should Be $false } } } Describe "$script:DSCResourceName\Confirm-UniqueServiceAutoStartProviders" { $MockParameters = @{ Name = 'MockServiceAutoStartProvider' Type = 'MockApplicationType' } Context 'Expected behavior' { $MockWebConfiguration = @( @{ SectionPath = 'MockSectionPath' PSPath = 'MockPSPath' Collection = @( [PSCustomObject] @{ Name = 'MockServiceAutoStartProvider'; Type = 'MockApplicationType' } ) } ) Mock -CommandName Get-WebConfiguration -MockWith {return $MockWebConfiguration} It 'should not throw an error' { { Confirm-UniqueServiceAutoStartProviders ` -ServiceAutoStartProvider $MockParameters.Name ` -ApplicationType $MockParameters.Type } | Should Not Throw } It 'should call Get-WebConfiguration once' { Assert-MockCalled -CommandName Get-WebConfiguration -Exactly 1 } } Context 'Conflicting Global Property' { $MockWebConfiguration = @( @{ SectionPath = 'MockSectionPath' PSPath = 'MockPSPath' Collection = @( [PSCustomObject] @{ Name = 'MockServiceAutoStartProvider'; Type = 'MockApplicationType' } ) } ) Mock -CommandName Get-WebConfiguration -MockWith { return $MockWebConfiguration } It 'should return Throw' { $ErrorId = 'ServiceAutoStartProviderFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation $ErrorMessage = $LocalizedData.ErrorWebsiteTestAutoStartProviderFailure, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Confirm-UniqueServiceAutoStartProviders ` -ServiceAutoStartProvider $MockParameters.Name ` -ApplicationType 'MockApplicationType2'} | Should Throw $ErrorRecord } } Context 'ServiceAutoStartProvider does not exist' { $MockWebConfiguration = @( @{ Name = '' Type = '' } ) Mock -CommandName Get-WebConfiguration -MockWith { return $MockWebConfiguration } It 'should return False' { Confirm-UniqueServiceAutoStartProviders ` -ServiceAutoStartProvider $MockParameters.Name ` -ApplicationType $MockParameters.Type | Should Be $false } } Context 'ServiceAutoStartProvider does exist' { $MockWebConfiguration = @( @{ SectionPath = 'MockSectionPath' PSPath = 'MockPSPath' Collection = @( [PSCustomObject] @{ Name = 'MockServiceAutoStartProvider' ; Type = 'MockApplicationType' } ) } ) Mock -CommandName Get-WebConfiguration -MockWith { return $MockWebConfiguration } It 'should return True' { Confirm-UniqueServiceAutoStartProviders ` -ServiceAutoStartProvider $MockParameters.Name ` -ApplicationType $MockParameters.Type | Should Be $true } } } Describe "$script:DSCResourceName\ConvertTo-CimBinding" { Context 'IPv4 address is passed and the protocol is http' { $MockWebBinding = @{ bindingInformation = '127.0.0.1:80:MockHostName' protocol = 'http' } $Result = ConvertTo-CimBinding -InputObject $MockWebBinding It 'should return the IPv4 Address' { $Result.IPAddress | Should Be '127.0.0.1' } It 'should return the Protocol' { $Result.Protocol | Should Be 'http' } It 'should return the HostName' { $Result.HostName | Should Be 'MockHostName' } It 'should return the Port' { $Result.Port | Should Be '80' } } Context 'IPv6 address is passed and the protocol is http' { $MockWebBinding = @{ bindingInformation = '[0:0:0:0:0:0:0:1]:80:MockHostName' protocol = 'http' } $Result = ConvertTo-CimBinding -InputObject $MockWebBinding It 'should return the IPv6 Address' { $Result.IPAddress | Should Be '0:0:0:0:0:0:0:1' } It 'should return the Protocol' { $Result.Protocol | Should Be 'http' } It 'should return the HostName' { $Result.HostName | Should Be 'MockHostName' } It 'should return the Port' { $Result.Port | Should Be '80' } } Context 'IPv4 address with SSL certificate is passed' { $MockWebBinding = @{ bindingInformation = '127.0.0.1:443:MockHostName' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'MY' sslFlags = '1' } $Result = ConvertTo-CimBinding -InputObject $MockWebBinding It 'should return the IPv4 Address' { $Result.IPAddress | Should Be '127.0.0.1' } It 'should return the Protocol' { $Result.Protocol | Should Be 'https' } It 'should return the HostName' { $Result.HostName | Should Be 'MockHostName' } It 'should return the Port' { $Result.Port | Should Be '443' } It 'should return the CertificateThumbprint' { $Result.CertificateThumbprint | Should Be '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' } It 'should return the CertificateStoreName' { $Result.CertificateStoreName | Should Be 'MY' } It 'should return the SslFlags' { $Result.SslFlags | Should Be '1' } } Context 'IPv6 address with SSL certificate is passed' { $MockWebBinding = @{ bindingInformation = '[0:0:0:0:0:0:0:1]:443:MockHostName' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'MY' sslFlags = '1' } $Result = ConvertTo-CimBinding -InputObject $MockWebBinding It 'should return the IPv6 Address' { $Result.IPAddress | Should Be '0:0:0:0:0:0:0:1' } It 'should return the Protocol' { $Result.Protocol | Should Be 'https' } It 'should return the HostName' { $Result.HostName | Should Be 'MockHostName' } It 'should return the Port' { $Result.Port | Should Be '443' } It 'should return the CertificateThumbprint' { $Result.CertificateThumbprint | Should Be '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' } It 'should return the CertificateStoreName' { $Result.CertificateStoreName | Should Be 'MY' } It 'should return the SslFlags' { $Result.SslFlags | Should Be '1' } } } Describe "$script:DSCResourceName\ConvertTo-WebBinding" { Context 'Expected behaviour' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' BindingInformation = 'NonsenseString' IPAddress = '*' Port = 443 HostName = 'web01.contoso.com' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' CertificateStoreName = 'WebHosting' SslFlags = 1 } -ClientOnly ) $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo It 'should return the correct Protocol value' { $Result.protocol | Should Be 'https' } It 'should return the correct BindingInformation value' { $Result.bindingInformation | Should Be '*:443:web01.contoso.com' } It 'should return the correct CertificateHash value' { $Result.certificateHash | Should Be 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' } It 'should return the correct CertificateStoreName value' { $Result.certificateStoreName | Should Be 'WebHosting' } It 'should return the correct SslFlags value' { $Result.sslFlags | Should Be 1 } } Context 'IP address is invalid' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'http' IPAddress = '127.0.0.256' } -ClientOnly ) It 'should throw the correct error' { $ErrorId = 'WebBindingInvalidIPAddress' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument $ErrorMessage = $LocalizedData.ErrorWebBindingInvalidIPAddress -f $MockBindingInfo.IPAddress, 'Exception calling "Parse" with "1" argument(s): "An invalid IP address was specified."' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { ConvertTo-WebBinding -InputObject $MockBindingInfo } | Should Throw $ErrorRecord } } Context 'Port is not specified' { It 'should set the default HTTP port' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' } ) $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo $Result.bindingInformation | Should Be '*:80:' } It 'should set the default HTTPS port' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' } ) $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo $Result.bindingInformation | Should Be '*:443:' } } Context 'Port is invalid' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'http' Port = 0 } -ClientOnly ) It 'should throw the correct error' { $ErrorId = 'WebBindingInvalidPort' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument $ErrorMessage = $LocalizedData.ErrorWebBindingInvalidPort -f $MockBindingInfo.Port $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null {ConvertTo-WebBinding -InputObject $MockBindingInfo} | Should Throw $ErrorRecord } } Context 'Protocol is HTTPS and CertificateThumbprint contains the Left-to-Right Mark character' { $MockThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' $AsciiEncoding = [System.Text.Encoding]::ASCII $UnicodeEncoding = [System.Text.Encoding]::Unicode $AsciiBytes = $AsciiEncoding.GetBytes($MockThumbprint) $UnicodeBytes = [System.Text.Encoding]::Convert($AsciiEncoding, $UnicodeEncoding, $AsciiBytes) $LrmCharBytes = $UnicodeEncoding.GetBytes([Char]0x200E) # Prepend the Left-to-Right Mark character to CertificateThumbprint $MockThumbprintWithLrmChar = $UnicodeEncoding.GetString(($LrmCharBytes + $UnicodeBytes)) $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' CertificateThumbprint = $MockThumbprintWithLrmChar CertificateStoreName = 'MY' } -ClientOnly ) It 'Input - CertificateThumbprint should contain the Left-to-Right Mark character' { $MockBindingInfo[0].CertificateThumbprint -match '^\u200E' | Should Be $true } It 'Output - certificateHash should not contain the Left-to-Right Mark character' { $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo $Result.certificateHash -match '^\u200E' | Should Be $false } } Context 'Protocol is HTTPS and CertificateThumbprint is not specified' { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' CertificateThumbprint = '' } -ClientOnly ) It 'should throw the correct error' { $ErrorId = 'WebBindingMissingCertificateThumbprint' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument $ErrorMessage = $LocalizedData.ErrorWebBindingMissingCertificateThumbprint -f $MockBindingInfo.Protocol $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { ConvertTo-WebBinding -InputObject $MockBindingInfo } | Should Throw $ErrorRecord } } Context 'Protocol is HTTPS and CertificateStoreName is not specified' { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' CertificateStoreName = '' } -ClientOnly ) It 'should set CertificateStoreName to the default value' { $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo $Result.certificateStoreName | Should Be 'MY' } } Context 'Protocol is HTTPS and HostName is not specified for use with Server Name Indication' { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = '' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' CertificateStoreName = 'WebHosting' SslFlags = 1 } -ClientOnly ) It 'should throw the correct error' { $ErrorId = 'WebBindingMissingSniHostName' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument $ErrorMessage = $LocalizedData.ErrorWebBindingMissingSniHostName $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { ConvertTo-WebBinding -InputObject $MockBindingInfo } | Should Throw $ErrorRecord } } Context 'Protocol is not HTTPS' { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'http' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' CertificateStoreName = 'WebHosting' SslFlags = 1 } -ClientOnly ) It 'should ignore SSL properties' { $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo $Result.certificateHash | Should Be '' $Result.certificateStoreName | Should Be '' $Result.sslFlags | Should Be 0 } } Context 'Protocol is neither HTTP nor HTTPS' { It 'should throw an error if BindingInformation is not specified' { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'net.tcp' BindingInformation = '' } -ClientOnly ) $ErrorId = 'WebBindingMissingBindingInformation' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument $ErrorMessage = $LocalizedData.ErrorWebBindingMissingBindingInformation -f $MockBindingInfo.Protocol $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { ConvertTo-WebBinding -InputObject $MockBindingInfo } | Should Throw $ErrorRecord } It 'should use BindingInformation and ignore IPAddress, Port, and HostName' { $MockBindingInfo = @( New-CimInstance -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -Property @{ Protocol = 'net.tcp' BindingInformation = '808:*' IPAddress = '127.0.0.1' Port = 80 HostName = 'web01.contoso.com' } -ClientOnly ) $Result = ConvertTo-WebBinding -InputObject $MockBindingInfo $Result.BindingInformation | Should Be '808:*' } } } Describe "$script:DSCResourceName\Format-IPAddressString" { Context 'Input value is not valid' { It 'should throw an error' { { Format-IPAddressString -InputString 'Invalid' } | Should Throw } } Context 'Input value is valid' { It 'should return "*" when input value is null' { Format-IPAddressString -InputString $null | Should Be '*' } It 'should return "*" when input value is empty' { Format-IPAddressString -InputString '' | Should Be '*' } It 'should return normalized IPv4 address' { Format-IPAddressString -InputString '192.10' | Should Be '192.0.0.10' } It 'should return normalized IPv6 address enclosed in square brackets' { Format-IPAddressString ` -InputString 'fe80:0000:0000:0000:0202:b3ff:fe1e:8329' | Should Be '[fe80::202:b3ff:fe1e:8329]' } } } Describe "$script:DSCResourceName\Get-AuthenticationInfo" { $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = @{Collection = @($MockPreloadAndAutostartProviders)} Count = 1 } Context 'Expected behavior' { Mock -CommandName Get-WebConfigurationProperty -MockWith { return 'False'} It 'should not throw an error' { { Get-AuthenticationInfo -site $MockWebsite.Name } | Should Not Throw } It 'should call Get-WebConfigurationProperty four times' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 4 } } Context 'AuthenticationInfo is false' { $MockWebConfiguration = @( @{ Value = 'False' } ) Mock -CommandName Get-WebConfigurationProperty -MockWith { $MockWebConfiguration } It 'should all be false' { $result = Get-AuthenticationInfo -site $MockWebsite.Name $result.Anonymous | Should be False $result.Digest | Should be False $result.Basic | Should be False $result.Windows | Should be False } It 'should call Get-WebConfigurationProperty four times' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 4 } } Context 'AuthenticationInfo is true' { $MockWebConfiguration = @( @{ Value = 'True' } ) Mock -CommandName Get-WebConfigurationProperty -MockWith { $MockWebConfiguration } It 'should all be true' { $result = Get-AuthenticationInfo -site $MockWebsite.Name $result.Anonymous | Should be True $result.Digest | Should be True $result.Basic | Should be True $result.Windows | Should be True } It 'should call Get-WebConfigurationProperty four times' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 4 } } } Describe "$script:DSCResourceName\Get-DefaultAuthenticationInfo" { Context 'Expected behavior' { It 'should not throw an error' { { Get-DefaultAuthenticationInfo }| Should Not Throw } } Context 'Get-DefaultAuthenticationInfo should produce a false CimInstance' { It 'should all be false' { $result = Get-DefaultAuthenticationInfo $result.Anonymous | Should be False $result.Digest | Should be False $result.Basic | Should be False $result.Windows | Should be False } } } Describe "$script:DSCResourceName\Set-Authentication" { Context 'Expected behavior' { $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = @{Collection = @($MockPreloadAndAutostartProviders)} Count = 1 } Mock -CommandName Set-WebConfigurationProperty It 'should not throw an error' { { Set-Authentication ` -Site $MockWebsite.Name ` -Type Basic ` -Enabled $true } | Should Not Throw } It 'should call Set-WebConfigurationProperty once' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 1 } } } Describe "$script:DSCResourceName\Set-AuthenticationInfo" { Context 'Expected behavior' { $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = @{Collection = @($MockPreloadAndAutostartProviders)} Count = 1 } Mock -CommandName Set-WebConfigurationProperty $AuthenticationInfo = New-CimInstance ` -ClassName MSFT_WebApplicationAuthenticationInformation ` -ClientOnly ` -Property @{Anonymous='true';Basic='false';Digest='false';Windows='false'} It 'should not throw an error' { { Set-AuthenticationInfo ` -Site $MockWebsite.Name ` -AuthenticationInfo $AuthenticationInfo } | Should Not Throw } It 'should call should call expected mocks' { Assert-MockCalled -CommandName Set-WebConfigurationProperty -Exactly 4 } } } Describe "$script:DSCResourceName\Test-AuthenticationEnabled" { $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = @{Collection = @($MockPreloadAndAutostartProviders)} Count = 1 } Context 'Expected behavior' { $MockWebConfiguration = @( @{ Value = 'False' } ) Mock -CommandName Get-WebConfigurationProperty -MockWith {$MockWebConfiguration} It 'should not throw an error' { { Test-AuthenticationEnabled ` -Site $MockWebsite.Name ` -Type 'Basic'} | Should Not Throw } It 'should call expected mocks' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 1 } } Context 'AuthenticationInfo is false' { $MockWebConfiguration = @( @{ Value = 'False' } ) Mock -CommandName Get-WebConfigurationProperty -MockWith { $MockWebConfiguration } It 'should return false' { Test-AuthenticationEnabled -Site $MockWebsite.Name -Type 'Basic' | Should be False } It 'should call expected mocks' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 1 } } Context 'AuthenticationInfo is true' { $MockWebConfiguration = @( @{ Value = 'True' } ) Mock -CommandName Get-WebConfigurationProperty -MockWith { $MockWebConfiguration} It 'should all be true' { Test-AuthenticationEnabled -Site $MockWebsite.Name -Type 'Basic' | Should be True } It 'should call expected mocks' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 1 } } } Describe "$script:DSCResourceName\Test-AuthenticationInfo" { Mock -CommandName Get-WebConfigurationProperty -MockWith {$MockWebConfiguration} $MockWebsite = @{ Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' Bindings = @{Collection = @($MockWebBinding)} EnabledProtocols = 'http' ApplicationDefaults = @{Collection = @($MockPreloadAndAutostartProviders)} Count = 1 } $MockWebConfiguration = @( @{ Value = 'False' } ) $AuthenticationInfo = New-CimInstance ` -ClassName MSFT_WebApplicationAuthenticationInformation ` -ClientOnly ` -Property @{ Anonymous='false'; Basic='true'; Digest='false'; Windows='false' } Context 'Expected behavior' { It 'should not throw an error' { { Test-AuthenticationInfo ` -Site $MockWebsite.Name ` -AuthenticationInfo $AuthenticationInfo } | Should Not Throw } It 'should call expected mocks' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 2 } } Context 'Return False when AuthenticationInfo is not correct' { Mock -CommandName Get-WebConfigurationProperty -MockWith { $MockWebConfiguration} It 'should return false' { Test-AuthenticationInfo -Site $MockWebsite.Name -AuthenticationInfo $AuthenticationInfo | Should be False } It 'should call expected mocks' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 2 } } Context 'Return True when AuthenticationInfo is correct' { $MockWebConfiguration = @( @{ Value = 'True' } ) $AuthenticationInfo = New-CimInstance ` -ClassName MSFT_WebApplicationAuthenticationInformation ` -ClientOnly ` -Property @{ Anonymous='true'; Basic='true'; Digest='true'; Windows='true' } Mock -CommandName Get-WebConfigurationProperty -MockWith { $MockWebConfiguration} It 'should return true' { Test-AuthenticationInfo ` -Site $MockWebsite.Name ` -AuthenticationInfo $AuthenticationInfo | Should be True } It 'should call expected mocks' { Assert-MockCalled -CommandName Get-WebConfigurationProperty -Exactly 4 } } } Describe "$script:DSCResourceName\Test-BindingInfo" { Context 'BindingInfo is valid' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 80 HostName = '' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = 'web01.contoso.com' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' CertificateStoreName = 'WebHosting' SslFlags = 1 } ) It 'should return True' { Test-BindingInfo -BindingInfo $MockBindingInfo | Should Be $true } } Context 'BindingInfo contains multiple items with the same IPAddress, Port, and HostName combination' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 8080 HostName = 'web01.contoso.com' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 8080 HostName = 'web01.contoso.com' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } ) It 'should return False' { Test-BindingInfo -BindingInfo $MockBindingInfo | Should Be $false } } Context 'BindingInfo contains items that share the same Port but have different Protocols' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '127.0.0.1' Port = 8080 HostName = '' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 8080 HostName = 'web01.contoso.com' CertificateThumbprint = 'C65CE51E20C523DEDCE979B9922A0294602D9D5C' CertificateStoreName = 'WebHosting' SslFlags = 1 } ) It 'should return False' { Test-BindingInfo -BindingInfo $MockBindingInfo | Should Be $false } } Context 'BindingInfo contains multiple items with the same Protocol and BindingInformation combination' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'net.tcp' BindingInformation = '808:*' } New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'net.tcp' BindingInformation = '808:*' } ) It 'should return False' { Test-BindingInfo -BindingInfo $MockBindingInfo | Should Be $false } } } Describe "$script:DSCResourceName\Test-PortNumber" { Context 'Input value is not valid' { It 'should not throw an error' { {Test-PortNumber -InputString 'InvalidString'} | Should Not Throw } It 'should return False' { Test-PortNumber -InputString 'InvalidString' | Should Be $false } It 'should return False when input value is null' { Test-PortNumber -InputString $null | Should Be $false } It 'should return False when input value is empty' { Test-PortNumber -InputString '' | Should Be $false } It 'should return False when input value is not between 1 and 65535' { Test-PortNumber -InputString '100000' | Should Be $false } } Context 'Input value is valid' { It 'should return True' { Test-PortNumber -InputString '443' | Should Be $true } } } Describe "$script:DSCResourceName\Test-WebsiteBinding" { $MockWebBinding = @( @{ bindingInformation = '*:80:' protocol = 'http' certificateHash = '' certificateStoreName = '' sslFlags = '0' } ) $MockWebsite = @{ Name = 'MockName' Bindings = @{Collection = @($MockWebBinding)} } Mock -CommandName Get-WebSite -MockWith {return $MockWebsite} Context 'Test-BindingInfo returns False' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 80 HostName = '' } ) It 'should throw the correct error' { Mock -CommandName Test-BindingInfo -MockWith {return $false} $ErrorId = 'WebsiteBindingInputInvalidation' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteBindingInputInvalidation -f $MockWebsite.Name $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo } | Should Throw $ErrorRecord } } Context 'Bindings comparison throws an error' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 80 HostName = '' } ) $ErrorId = 'WebsiteCompareFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteCompareFailure -f $MockWebsite.Name, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null It 'should not return an error' { { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo} | Should Not Throw $ErrorRecord } } Context 'Port is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 8080 HostName = '' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } ) It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } Context 'Protocol is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 80 HostName = '' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'WebHosting' SslFlags = 0 } ) It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } Context 'IPAddress is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '127.0.0.1' Port = 80 HostName = '' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } ) It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } Context 'HostName is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 80 HostName = 'MockHostName' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } ) It 'should return False' { Test-WebsiteBinding -Name $MockWebsite.Name -BindingInfo $MockBindingInfo | Should Be $false } } Context 'CertificateThumbprint is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = '' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'MY' SslFlags = 0 } ) $MockWebBinding = @( @{ bindingInformation = '*:443:' protocol = 'https' certificateHash = 'B30F3184A831320382C61EFB0551766321FA88A5' certificateStoreName = 'MY' sslFlags = '0' } ) $MockWebsite = @{ Name = 'MockSite' Bindings = @{ Collection = @($MockWebBinding) } } Mock -CommandName Get-WebSite -MockWith {return $MockWebsite} It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } Context 'CertificateStoreName is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = '' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'MY' SslFlags = 0 } ) $MockWebBinding = @{ bindingInformation = '*:443:' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'WebHosting' sslFlags = '0' } $MockWebsite = @{ Name = 'MockSite' Bindings = @{ Collection = @($MockWebBinding) } } Mock -CommandName Get-WebSite -MockWith { return $MockWebsite } It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } Context 'CertificateStoreName is different and no CertificateThumbprint is specified' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = '' CertificateThumbprint = '' CertificateStoreName = 'MY' SslFlags = 0 } ) $MockWebBinding = @{ bindingInformation = '*:443:' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'WebHosting' sslFlags = '0' } $MockWebsite = @{ Name = 'MockSite' Bindings = @{Collection = @($MockWebBinding)} } Mock -CommandName Get-WebSite -MockWith {return $MockWebsite} $ErrorId = 'WebsiteBindingInputInvalidation' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteBindingInputInvalidation -f $MockWebsite.Name $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null It 'should throw the correct error' { { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo} | Should Throw $ErrorRecord } } Context 'SslFlags is different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = 'web01.contoso.com' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'WebHosting' SslFlags = 1 } ) $MockWebBinding = @{ bindingInformation = '*:443:web01.contoso.com' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'WebHosting' sslFlags = '0' } $MockWebsite = @{ Name = 'MockSite' Bindings = @{ Collection = @($MockWebBinding) } } Mock -CommandName Get-WebSite -MockWith {return $MockWebsite} It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } Context 'Bindings are identical' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' Port = 443 IPAddress = '*' HostName = 'web01.contoso.com' CertificateThumbprint = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' CertificateStoreName = 'WebHosting' SslFlags = 1 } New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ IPAddress = '*' Port = 8080 HostName = '' Protocol = 'http' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } ) $MockWebBinding = @( @{ bindingInformation = '*:443:web01.contoso.com' protocol = 'https' certificateHash = '1D3324C6E2F7ABC794C9CB6CA426B8D0F81045CD' certificateStoreName = 'WebHosting' sslFlags = '1' } @{ bindingInformation = '*:8080:' protocol = 'http' certificateHash = '' certificateStoreName = '' sslFlags = '0' } ) $MockWebsite = @{ Name = 'MockSite' Bindings = @{Collection = @($MockWebBinding)} } Mock -CommandName Get-WebSite -MockWith {return $MockWebsite} It 'should return True' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $true } } Context 'Bindings are different' { $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 80 HostName = '' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'http' IPAddress = '*' Port = 8080 HostName = '' CertificateThumbprint = '' CertificateStoreName = '' SslFlags = 0 } ) $MockWebBinding = @( @{ bindingInformation = '*:80:' protocol = 'http' certificateHash = '' certificateStoreName = '' sslFlags = '0' } @{ bindingInformation = '*:8081:' protocol = 'http' certificateHash = '' certificateStoreName = '' sslFlags = '0' } ) $MockWebsite = @{ Name = 'MockSite' Bindings = @{Collection = @($MockWebBinding)} } Mock -CommandName Get-Website -MockWith {return $MockWebsite} It 'should return False' { Test-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo | Should Be $false } } } Describe "$script:DSCResourceName\Update-DefaultPage" { $MockWebsite = @{ Ensure = 'Present' Name = 'MockName' PhysicalPath = 'C:\NonExistent' State = 'Started' ApplicationPool = 'MockPool' DefaultPage = 'index.htm' } Context 'Does not find the default page' { Mock -CommandName Get-WebConfiguration -MockWith { return @{value = 'index2.htm'} } Mock -CommandName Add-WebConfiguration It 'should call Add-WebConfiguration' { $Result = Update-DefaultPage -Name $MockWebsite.Name -DefaultPage $MockWebsite.DefaultPage Assert-MockCalled -CommandName Add-WebConfiguration } } } Describe "$script:DSCResourceName\Update-WebsiteBinding" { $MockWebsite = @{ Name = 'MockSite' ItemXPath = "/system.applicationHost/sites/site[@name='MockSite']" } $MockBindingInfo = @( New-CimInstance ` -ClassName MSFT_WebBindingInformation ` -Namespace root/microsoft/Windows/DesiredStateConfiguration ` -ClientOnly ` -Property @{ Protocol = 'https' IPAddress = '*' Port = 443 HostName = '' CertificateThumbprint = '5846A1B276328B1A32A30150858F6383C1F30E1F' CertificateStoreName = 'MY' SslFlags = 0 } ) Mock -CommandName Get-WebConfiguration -ParameterFilter { $Filter -eq '/system.applicationHost/sites/site' } -MockWith { return $MockWebsite } -Verifiable Mock -CommandName Clear-WebConfiguration -Verifiable Context 'Expected behavior' { Mock -CommandName Add-WebConfiguration Mock -CommandName Set-WebConfigurationProperty Mock -CommandName Get-WebConfiguration -ParameterFilter { $Filter -eq "$($MockWebsite.ItemXPath)/bindings/binding[last()]" } -MockWith { New-Module -AsCustomObject -ScriptBlock { function AddSslCertificate {} } } -Verifiable Update-WebsiteBinding -Name $MockWebsite.Name -BindingInfo $MockBindingInfo It 'should call all the mocks' { Assert-Verifiablemocks Assert-MockCalled -CommandName Add-WebConfiguration -Exactly $MockBindingInfo.Count Assert-MockCalled -CommandName Set-WebConfigurationProperty } } Context 'Website does not exist' { Mock -CommandName Get-WebConfiguration -ParameterFilter { $Filter -eq '/system.applicationHost/sites/site' } -MockWith { return $null } It 'should throw the correct error' { $ErrorId = 'WebsiteNotFound' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteNotFound -f $MockWebsite.Name $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Update-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo} | Should Throw $ErrorRecord } } Context 'Error on adding a new binding' { Mock -CommandName Add-WebConfiguration -ParameterFilter { $Filter -eq "$($MockWebsite.ItemXPath)/bindings" } -MockWith { throw } It 'should throw the correct error' { $ErrorId = 'WebsiteBindingUpdateFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteBindingUpdateFailure -f $MockWebsite.Name, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Update-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo } | Should Throw $ErrorRecord } } Context 'Error on setting sslFlags attribute' { Mock -CommandName Add-WebConfiguration Mock -CommandName Set-WebConfigurationProperty -ParameterFilter { $Filter -eq "$($MockWebsite.ItemXPath)/bindings/binding[last()]" -and $Name -eq 'sslFlags' } ` -MockWith { throw } It 'should throw the correct error' { $ErrorId = 'WebsiteBindingUpdateFailure' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidResult $ErrorMessage = $LocalizedData.ErrorWebsiteBindingUpdateFailure -f $MockWebsite.Name, 'ScriptHalted' $Exception = New-Object ` -TypeName System.InvalidOperationException ` -ArgumentList $ErrorMessage $ErrorRecord = New-Object ` -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Update-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo } | Should Throw $ErrorRecord } } Context 'Error on adding SSL certificate' { Mock -CommandName Add-WebConfiguration Mock -CommandName Set-WebConfigurationProperty Mock -CommandName Get-WebConfiguration -ParameterFilter { $Filter -eq "$($MockWebsite.ItemXPath)/bindings/binding[last()]" } -MockWith { New-Module -AsCustomObject -ScriptBlock { function AddSslCertificate {throw} } } It 'should throw the correct error' { $ErrorId = 'WebBindingCertificate' $ErrorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation $ErrorMessage = $LocalizedData.ErrorWebBindingCertificate -f $MockBindingInfo.CertificateThumbprint, 'Exception calling "AddSslCertificate" with "2" argument(s): "ScriptHalted"' $Exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $ErrorMessage $ErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $Exception, $ErrorId, $ErrorCategory, $null { Update-WebsiteBinding ` -Name $MockWebsite.Name ` -BindingInfo $MockBindingInfo } | Should Throw $ErrorRecord } } } } } #endregion finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Integration/MSFT_SslSettings.config.ps1
MSFT_SslSettings.config.ps1
#requires -Version 4 configuration MSFT_SslSettings_Present { Import-DscResource -ModuleName WebAdministrationDsc Node $AllNodes.NodeName { SslSettings Website { Ensure = 'Present' Name = $Node.Website Bindings = $Node.Bindings } } } configuration MSFT_SslSettings_Absent { Import-DscResource -ModuleName WebAdministrationDsc Node $AllNodes.NodeName { SslSettings Website { Ensure = 'Absent' Name = $Node.Website Bindings = '' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Integration/MSFT_Website.Integration.Tests.ps1
MSFT_Website.Integration.Tests.ps1
$script:DSCModuleName = 'WebAdministrationDsc' $script:DSCResourceName = 'MSFT_Website' #region HEADER $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Integration #endregion [String] $tempName = "$($script:DSCResourceName)_" + (Get-Date).ToString('yyyyMMdd_HHmmss') try { # Now that WebAdministrationDsc should be discoverable, load the configuration data $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $configFile $null = Backup-WebConfiguration -Name $tempName $dscConfig = Import-LocalizedData -BaseDirectory $PSScriptRoot -FileName "$($script:DSCResourceName).config.psd1" # Create a SelfSigned Cert $selfSignedCert = (New-SelfSignedCertificate -DnsName $dscConfig.AllNodes.HTTPSHostname -CertStoreLocation 'cert:\LocalMachine\My') #region HelperFunctions # Function needed to test AuthenticationInfo function Get-AuthenticationInfo { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [String] $Type, [Parameter(Mandatory = $true)] [String] $Website ) (Get-WebConfigurationProperty ` -Filter /system.WebServer/security/authentication/${Type}Authentication ` -Name enabled ` -Location $Website).Value } #endregion Describe "$($script:DSCResourceName)_Present_Started" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Present_Started -ConfigurationData `$dscConfig -OutputPath `$TestEnvironment.WorkingFolder -CertificateThumbprint `$selfSignedCert.Thumbprint" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Should Create a Started Website with correct settings' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Present_Started -ConfigurationData `$DSCConfg -OutputPath `$TestEnvironment.WorkingFolder -CertificateThumbprint `$selfSignedCert.Thumbprint" # Build results to test $result = Get-Website -Name $dscConfig.AllNodes.Website $defaultPages = Get-WebConfiguration ` -Filter '//defaultDocument/files/*' ` -PSPath 'IIS:\Sites\Website' | ForEach-Object -Process {Write-Output -InputObject $_.value} $serviceAutoStartProviders = (Get-WebConfiguration -filter /system.applicationHost/serviceAutoStartProviders).Collection # Test Website basic settings are correct $result.Name | Should Be $dscConfig.AllNodes.Website $result.PhysicalPath | Should Be $dscConfig.AllNodes.PhysicalPath $result.State | Should Be 'Started' $result.ApplicationPool | Should Be $dscConfig.AllNodes.ApplicationPool $result.EnabledProtocols | Should Be $dscConfig.AllNodes.EnabledProtocols # Test Website AuthenticationInfo are correct Get-AuthenticationInfo -Type 'Anonymous' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoAnonymous Get-AuthenticationInfo -Type 'Basic' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoBasic Get-AuthenticationInfo -Type 'Digest' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoDigest Get-AuthenticationInfo -Type 'Windows' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoWindows # Test Website Application settings $result.ApplicationDefaults.PreloadEnabled | Should Be $dscConfig.AllNodes.PreloadEnabled $result.ApplicationDefaults.ServiceAutoStartProvider | Should Be $dscConfig.AllNodes.ServiceAutoStartProvider $result.ApplicationDefaults.ServiceAutoStartEnabled | Should Be $dscConfig.AllNodes.ServiceAutoStartEnabled # Test the serviceAutoStartProviders are present in IIS config $serviceAutoStartProviders.Name | Should Be $dscConfig.AllNodes.ServiceAutoStartProvider $serviceAutoStartProviders.Type | Should Be $dscConfig.AllNodes.ApplicationType # Test bindings are correct $result.bindings.Collection.Protocol | Should Match $dscConfig.AllNodes.HTTPProtocol $result.bindings.Collection.BindingInformation[0] | Should Match $dscConfig.AllNodes.HTTP1Hostname $result.bindings.Collection.BindingInformation[1] | Should Match $dscConfig.AllNodes.HTTP2Hostname $result.bindings.Collection.BindingInformation[2] | Should Match $dscConfig.AllNodes.HTTPSHostname $result.bindings.Collection.BindingInformation[0] | Should Match $dscConfig.AllNodes.HTTPPort $result.bindings.Collection.BindingInformation[1] | Should Match $dscConfig.AllNodes.HTTPPort $result.bindings.Collection.BindingInformation[2] | Should Match $dscConfig.AllNodes.HTTPSPort $result.bindings.Collection.certificateHash[2] | Should Be $selfSignedCert.Thumbprint $result.bindings.Collection.certificateStoreName[2] | Should Be $dscConfig.AllNodes.CertificateStoreName #Test DefaultPage is correct $defaultPages[0] | Should Match $dscConfig.AllNodes.DefaultPage } } Describe "$($script:DSCResourceName)_Present_Stopped" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Present_Stopped -ConfigurationData `$dscConfig -OutputPath `$TestEnvironment.WorkingFolder -CertificateThumbprint `$selfSignedCert.Thumbprint" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Should Create a Stopped Website with correct settings' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Present_Stopped -ConfigurationData `$DSCConfg -OutputPath `$TestEnvironment.WorkingFolder -CertificateThumbprint `$selfSignedCert.Thumbprint" # Build results to test $result = Get-Website -Name $dscConfig.AllNodes.Website $defaultPages = Get-WebConfiguration ` -Filter '//defaultDocument/files/*' ` -PSPath 'IIS:\Sites\Website' | ForEach-Object -Process {Write-Output -InputObject $_.value} $serviceAutoStartProviders = (Get-WebConfiguration -filter /system.applicationHost/serviceAutoStartProviders).Collection # Test Website basic settings are correct $result.Name | Should Be $dscConfig.AllNodes.Website $result.PhysicalPath | Should Be $dscConfig.AllNodes.PhysicalPath $result.State | Should Be 'Stopped' $result.ApplicationPool | Should Be $dscConfig.AllNodes.ApplicationPool $result.EnabledProtocols | Should Be $dscConfig.AllNodes.EnabledProtocols # Test Website AuthenticationInfo are correct Get-AuthenticationInfo -Type 'Anonymous' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoAnonymous Get-AuthenticationInfo -Type 'Basic' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoBasic Get-AuthenticationInfo -Type 'Digest' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoDigest Get-AuthenticationInfo -Type 'Windows' -Website $dscConfig.AllNodes.Website | Should Be $dscConfig.AllNodes.AuthenticationInfoWindows # Test Website Application settings $result.ApplicationDefaults.PreloadEnabled | Should Be $dscConfig.AllNodes.PreloadEnabled $result.ApplicationDefaults.ServiceAutoStartProvider | Should Be $dscConfig.AllNodes.ServiceAutoStartProvider $result.ApplicationDefaults.ServiceAutoStartEnabled | Should Be $dscConfig.AllNodes.ServiceAutoStartEnabled # Test the serviceAutoStartProviders are present in IIS config $serviceAutoStartProviders.Name | Should Be $dscConfig.AllNodes.ServiceAutoStartProvider $serviceAutoStartProviders.Type | Should Be $dscConfig.AllNodes.ApplicationType # Test bindings are correct $result.bindings.Collection.Protocol | Should Match $dscConfig.AllNodes.HTTPProtocol $result.bindings.Collection.BindingInformation[0] | Should Match $dscConfig.AllNodes.HTTP1Hostname $result.bindings.Collection.BindingInformation[1] | Should Match $dscConfig.AllNodes.HTTP2Hostname $result.bindings.Collection.BindingInformation[2] | Should Match $dscConfig.AllNodes.HTTPSHostname $result.bindings.Collection.BindingInformation[0] | Should Match $dscConfig.AllNodes.HTTPPort $result.bindings.Collection.BindingInformation[1] | Should Match $dscConfig.AllNodes.HTTPPort $result.bindings.Collection.BindingInformation[2] | Should Match $dscConfig.AllNodes.HTTPSPort $result.bindings.Collection.certificateHash[2] | Should Be $selfSignedCert.Thumbprint $result.bindings.Collection.certificateStoreName[2] | Should Be $dscConfig.AllNodes.CertificateStoreName #Test DefaultPage is correct $defaultPages[0] | Should Match $dscConfig.AllNodes.DefaultPage } } Describe "$($script:DSCResourceName)_Absent" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Absent -ConfigurationData `$dscConfig -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Should remove the Website' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Absent -ConfigurationData `$DSCConfg -OutputPath `$TestEnvironment.WorkingFolder" # Build results to test $result = Get-Website -Name $dscConfig.AllNodes.Website # Test Website is removed $result | Should BeNullOrEmpty } } Describe 'MSFT_WebBindingInformation' { # Directly interacting with Cim classes is not supported by PowerShell DSC # it is being done here explicitly for the purpose of testing. Please do not # do this in actual resource code $storeNames = (Get-CimClass -Namespace 'root/microsoft/Windows/DesiredStateConfiguration' -ClassName 'MSFT_WebBindingInformation').CimClassProperties['CertificateStoreName'].Qualifiers['Values'].Value foreach ($storeName in $storeNames) { It "Uses valid credential store: $storeName" { (Join-Path -Path Cert:\LocalMachine -ChildPath $storeName) | Should Exist } } } } finally { #region FOOTER Restore-WebConfiguration -Name $tempName Remove-WebConfigurationBackup -Name $tempName Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Integration/MSFT_IisLogging.config.ps1
MSFT_IisLogging.config.ps1
configuration MSFT_IisLogging_Rollover { Import-DscResource -ModuleName @{ModuleName='WebAdministrationDsc'; RequiredVersion='0.1.0.0'} IisLogging Logging { LogPath = 'C:\IISLogFiles' Logflags = @('Date','Time','ClientIP','UserName','ServerIP') LoglocalTimeRollover = $true LogPeriod = 'Hourly' LogFormat = 'W3C' } } configuration MSFT_IisLogging_Truncate { Import-DscResource -ModuleName WebAdministrationDsc IisLogging Logging { LogPath = 'C:\IISLogFiles' Logflags = @('Date','Time','ClientIP','UserName','ServerIP') LoglocalTimeRollover = $true LogTruncateSize = '2097152' LogFormat = 'W3C' } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Integration/MSFT_IisLogging.Integration.Tests.ps1
MSFT_IisLogging.Integration.Tests.ps1
$script:DSCModuleName = 'WebAdministrationDsc' $script:DSCResourceName = 'MSFT_IisLogging' #region HEADER # Integration Test Template Version: 1.1.0 $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Integration #endregion [String]$tempName = "$($script:DSCResourceName)_" + (Get-Date).ToString('yyyyMMdd_HHmmss') try { $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $configFile $null = Backup-WebConfiguration -Name $tempName Describe "$($script:DSCResourceName)_Rollover" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Rollover -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Changing Loggging Rollover Settings ' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Rollover -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force $currentLogSettings = Get-WebConfiguration -filter '/system.applicationHost/sites/siteDefaults/Logfile' $currentLogSettings.directory | Should Be 'C:\IISLogFiles' $currentLogSettings.logExtFileFlags | Should Be 'Date,Time,ClientIP,UserName,ServerIP' $currentLogSettings.logformat | Should Be 'W3C' $currentLogSettings.period | Should Be 'Hourly' $currentLogSettings.localTimeRollover | Should Be 'True' $currentLogSettings.logformat | Should be 'W3C' } } Describe "$($script:DSCResourceName)_Truncate" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Truncate -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Changing Loggging Truncate Settings ' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Truncate -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force $currentLogSettings = Get-WebConfiguration -filter '/system.applicationHost/sites/siteDefaults/Logfile' $currentLogSettings.directory | Should Be 'C:\IISLogFiles' $currentLogSettings.logExtFileFlags | Should Be 'Date,Time,ClientIP,UserName,ServerIP' $currentLogSettings.logformat | Should Be 'W3C' $currentLogSettings.TruncateSize | Should Be '2097152' $currentLogSettings.localTimeRollover | Should Be 'True' $currentLogSettings.logformat | Should be 'W3C' } } } finally { #region FOOTER Restore-WebConfiguration -Name $tempName Remove-WebConfigurationBackup -Name $tempName Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Integration/MSFT_Website.config.ps1
MSFT_Website.config.ps1
#requires -Version 4 configuration MSFT_Website_Present_Started { param( [Parameter(Mandatory = $true)] [String]$CertificateThumbprint ) Import-DscResource -ModuleName WebAdministrationDsc Node $AllNodes.NodeName { Website Website { Name = $Node.Website Ensure = 'Present' ApplicationType = $Node.ApplicationType ApplicationPool = $Node.ApplicationPool AuthenticationInfo = ` MSFT_WebAuthenticationInformation { Anonymous = $Node.AuthenticationInfoAnonymous Basic = $Node.AuthenticationInfoBasic Digest = $Node.AuthenticationInfoDigest Windows = $Node.AuthenticationInfoWindows } BindingInfo = @(MSFT_WebBindingInformation { Protocol = $Node.HTTPProtocol Port = $Node.HTTPPort IPAddress = '*' Hostname = $Node.HTTP1Hostname } MSFT_WebBindingInformation { Protocol = $Node.HTTPProtocol Port = $Node.HTTPPort IPAddress = '*' Hostname = $Node.HTTP2Hostname } MSFT_WebBindingInformation { Protocol = $Node.HTTPSProtocol Port = $Node.HTTPSPort IPAddress = '*' Hostname = $Node.HTTPSHostname CertificateThumbprint = $CertificateThumbprint CertificateStoreName = $Node.CertificateStoreName SslFlags = $Node.SslFlags }) DefaultPage = $Node.DefaultPage EnabledProtocols = $Node.EnabledProtocols PhysicalPath = $Node.PhysicalPath PreloadEnabled = $Node.PreloadEnabled ServiceAutoStartEnabled = $Node.ServiceAutoStartEnabled ServiceAutoStartProvider = $Node.ServiceAutoStartProvider State = 'Started' } } } configuration MSFT_Website_Present_Stopped { param( [Parameter(Mandatory = $true)] [String]$CertificateThumbprint ) Import-DscResource -ModuleName WebAdministrationDsc Node $AllNodes.NodeName { Website Website { Name = $Node.Website Ensure = 'Present' ApplicationType = $Node.ApplicationType ApplicationPool = $Node.ApplicationPool AuthenticationInfo = ` MSFT_WebAuthenticationInformation { Anonymous = $Node.AuthenticationInfoAnonymous Basic = $Node.AuthenticationInfoBasic Digest = $Node.AuthenticationInfoDigest Windows = $Node.AuthenticationInfoWindows } BindingInfo = @( MSFT_WebBindingInformation { Protocol = $Node.HTTPProtocol Port = $Node.HTTPPort IPAddress = '*' Hostname = $Node.HTTP1Hostname } MSFT_WebBindingInformation { Protocol = $Node.HTTPProtocol Port = $Node.HTTPPort IPAddress = '*' Hostname = $Node.HTTP2Hostname } MSFT_WebBindingInformation { Protocol = $Node.HTTPSProtocol Port = $Node.HTTPSPort IPAddress = '*' Hostname = $Node.HTTPSHostname CertificateThumbprint = $CertificateThumbprint CertificateStoreName = $Node.CertificateStoreName SslFlags = $Node.SslFlags }) DefaultPage = $Node.DefaultPage EnabledProtocols = $Node.EnabledProtocols PhysicalPath = $Node.PhysicalPath PreloadEnabled = $Node.PreloadEnabled ServiceAutoStartEnabled = $Node.ServiceAutoStartEnabled ServiceAutoStartProvider = $Node.ServiceAutoStartProvider State = 'Stopped' } } } configuration MSFT_Website_Absent { Import-DscResource -ModuleName WebAdministrationDsc Node $AllNodes.NodeName { Website Website { Name = $Node.Website Ensure = 'Absent' } } }
PowerShellCorpus/PowerShellGallery/WebAdministrationDsc/0.1.0.0/Tests/Integration/MSFT_SslSettings.Integration.Tests.ps1
MSFT_SslSettings.Integration.Tests.ps1
$script:DSCModuleName = 'WebAdministrationDsc' $script:DSCResourceName = 'MSFT_SSLSettings' #region HEADER # Integration Test Template Version: 1.1.0 $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $script:DSCModuleName ` -DSCResourceName $script:DSCResourceName ` -TestType Integration #endregion [String] $tempName = "$($script:DSCResourceName)_" + (Get-Date).ToString('yyyyMMdd_HHmmss') try { $null = Backup-WebConfiguration -Name $tempName # Now that WebAdministrationDsc should be discoverable load the configuration data $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1" . $configFile $DSCConfig = Import-LocalizedData -BaseDirectory $PSScriptRoot -FileName "$($script:DSCResourceName).config.psd1" #region HelperFunctions # Function needed to test SslFlags function Get-SslFlags { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [String] $Website ) Get-WebConfiguration ` -PSPath IIS:\Sites ` -Location "$Website" ` -Filter 'system.webserver/security/access' | ` ForEach-Object { $_.sslFlags } } #endregion # Create a new website for the SSLSettings New-Website -Name $DSCConfig.AllNodes.Website ` -Id 200 ` -PhysicalPath $DSCConfig.AllNodes.PhysicalPath ` -ApplicationPool $DSCConfig.AllNodes.AppPool ` -SslFlags $DSCConfig.AllNodes.SslFlags ` -Port $DSCConfig.AllNodes.HTTPSPort ` -IPAddress '*' ` -HostHeader $DSCConfig.AllNodes.HTTPSHostname ` -Ssl ` -Force ` -ErrorAction Stop Describe "$($script:DSCResourceName)_Present" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Present -ConfigurationData `$DSCConfig -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Should add SSLBindings to a Website' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Present -ConfigurationData `$DSCConfg -OutputPath `$TestEnvironment.WorkingFolder" # Test SslFlags Get-SslFlags -Website $DSCConfig.AllNodes.Website | Should Be $DSCConfig.AllNodes.Bindings } } Describe "$($script:DSCResourceName)_Absent" { #region DEFAULT TESTS It 'Should compile without throwing' { { Invoke-Expression -Command "$($script:DSCResourceName)_Absent -ConfigurationData `$DSCConfig -OutputPath `$TestEnvironment.WorkingFolder" Start-DscConfiguration -Path $TestEnvironment.WorkingFolder -ComputerName localhost -Wait -Verbose -Force } | Should not throw } It 'should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw } #endregion It 'Should remove SSLBindings from a Website' -test { Invoke-Expression -Command "$($script:DSCResourceName)_Absent -ConfigurationData `$DSCConfg -OutputPath `$TestEnvironment.WorkingFolder" # Test SslFlags Get-SslFlags -Website $DSCConfig.AllNodes.Website | Should BeNullOrEmpty } } } finally { #region FOOTER Restore-WebConfiguration -Name $tempName Remove-WebConfigurationBackup -Name $tempName Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/DbWebApi-Client/1.1.1.0/Invoke-DbWebApi.Sample.ps1
Invoke-DbWebApi.Sample.ps1
# Invoke-DbWebApi.Sample.ps1 - DbWebApi Client PowerShell Utility # https://github.com/DataBooster/DbWebApi # Date: 2015-06-09 Import-Module "Microsoft.PowerShell.Utility" -Cmdlet "Invoke-RestMethod" Import-Module "$PSScriptRoot\DbWebApi-Client.psd1" -Force Invoke-DbWebApi @args Exit $error.Count;
PowerShellCorpus/PowerShellGallery/DbWebApi-Client/1.1.1.0/Invoke-DbWebApi.Help.ps1
Invoke-DbWebApi.Help.ps1
# Invoke-DbWebApi.Help.ps1 - DbWebApi Client PowerShell Utility # https://github.com/DataBooster/DbWebApi # Date: 2016-03-03 Import-Module "Microsoft.PowerShell.Utility" -Cmdlet "Invoke-RestMethod" Import-Module "$PSScriptRoot\DbWebApi-Client.psd1" -Force Get-Help Invoke-DbWebApi @args
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Generate Module Manifest.ps1
Generate Module Manifest.ps1
$version = "0.13.0" $manifestPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath "\PoShMon.psd1" Remove-Item -Path $manifestPath -ErrorAction SilentlyContinue $description = "PoShMon is an open source PowerShell-based server and farm monitoring solution. It's an 'agent-less' monitoring tool, which means there's nothing that needs to be installed on any of the environments you want to monitor - you can simply run or schedule the script from a regular workstation and have it monitor a single server or group of servers, using PowerShell remoting. PoShMon is also able to monitor 'farm'-based products like SharePoint, in which multiple servers work together to provide a single platform. Key Features Some of the key features / benefits of PoShMon are: - Agent-less Monitoring - nothing needs to be installed on the remote servers - Core operating system and web-site monitoring - Specialized SharePoint monitoring - Supports frequent/critical as well as comprehensive daily monitoring - Email, Pushbullet (mobile) and Office 365 Teams ('Chat-ops') notifications - Provides a framework for 'self-healing' systems For more information, documentation etc. visit https://github.com/HiltonGiesenow/PoShMon as well as the Samples folder within the module itself." $releaseNotes = " 0.13.0 * Implemented CI server * Created a Merger framework (to merge multiple outputs) * Create a Merger for OS output * Removed ApplicationName from SharePoint Job Health Test * Add 'Last Reboot Time' test 0.12.0 * Added Office Web Apps / Office Online Server monitoring * Added some style to Email output * Changed display to Hard Drive and Memory output * Fixed bug in email footer for skipped tests 0.11.0 * Created 'Self-Healing' Framework into which custom scripts can be injected * Added ability to skip auto-discovered Windows services * Fixed bug where Pushbullet and Office 365 Teams were not showing Environment name * Fixed bug in harddrive space percent test * Fixed bug in cpu test for standalone 'minimal config test 0.10.1 * Added Proxy settings to enable PushBullet and 0365 Teams connectivity * Introduced a 'minimum configuration' for local machine monitoring * Fixed bug in SharePoint UPS Sync monitor * Added Resolver for High CPU usage while SharePoint Search Index is running * Improved Verbose output logging * Added option for harddrive space to track by percent * Add a check for any invalid TestsToSkip * Fixed bug in Update-PoShMon 0.9.2 * Fixed bug in email output * Fixed bug with not terminating Remote sessions correctly 0.9.1 * Fixed a bug crossing hour and day boundaries for Server Time test * Fixed a bug with Services on server testing in non-SharePoint environments 0.9.0 * Added a Server Time test for servers drifting apart * Add an 'update' notification for new versions of PoShMon * Add an 'Update' command to make updating PoShMon easier * Add Try..Catch error handling to each Test method * Switched to dynamically invoking test methods by name * Created a shared 'Core' monitoring function 0.8.3 * Reduced duplication in Test code for Stopwatch * Fixed naming for 'Free Percent' column in Memory Test * For 'Critical' (i.e. NotifyOnFailure) runs, set Email Priority to High if failure occurs * For Exception notifications, set Email Priority to High * Convert all Tests that used a PSSession parameter to using PoShMonConfiguration - improves testability * Added Unit Tests for every main Test-* function 0.8.2 * Added date to UserProfileSync output * Added a function to initialise output for all Test methods * Added PoShMon version to email output * Added Farm Health Test (SharePoint) - not active 0.8.1 * Fixing a bug in the SharePoint UPS sync query for datetime " New-ModuleManifest -Path $manifestPath -ModuleVersion $version -RootModule "PoShMon.psm1" -Guid '6e6cb274-1bed-4540-b288-95bc638bf679' -Author "Hilton Giesenow" -CompanyName "Experts Inside" -FunctionsToExport '*' -Copyright "2016 Hilton Giesenow, All Rights Reserved" -ProjectUri "https://github.com/HiltonGiesenow/PoShMon" -LicenseUri "https://github.com/HiltonGiesenow/PoShMon/blob/master/LICENSE" -Description $description -Tags 'Monitoring','Server','Farm','SharePoint' -ReleaseNotes $releaseNotes -Verbose $t = Test-ModuleManifest -Path $manifestPath $t $t.ExportedCommands.Keys #Remove-Module PoShMon
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Samples/SPMonitoring_Critical.ps1
SPMonitoring_Critical.ps1
Import-Module "C:\Dev\GitHub\PoShMon\src\0.4.0\PoShMon.psd1" -Verbose -Force #This is only necessary if you haven't installed the module into your Modules folder, e.g. via PowerShellGallery / Install-Module #Alternatively, use the lines below #If (!(Get-module PoShMon)) # { Import-Module PoShMon } $VerbosePreference = 'Continue' $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 15 ` -PrimaryServerName 'SPAPPSVR01' ` -ConfigurationName SpFarmPosh ` -TestsToSkip "SPDatabaseHealth","SPUPSSyncHealth" OperatingSystem ` -EventLogCodes 'Critical' WebSite ` -WebsiteDetails @{ "http://intranet" = "Read our terms" "http://extranet.company.com" = "Read our terms" } Notifications -When OnlyOnFailure { Email ` -ToAddress "SharePointTeam@Company.com" ` -FromAddress "Monitoring@company.com" ` -SmtpServer "EXCHANGE.COMPANY.COM" ` } } $monitoringOutput = Invoke-SPMonitoring -PoShMonConfiguration $poShMonConfiguration $poShMonConfiguration.General.PrimaryServerName = '' $poShMonConfiguration.General.ServerNames = 'OWASVR01' $poShMonConfiguration.General.EnvironmentName = 'Office Web Apps' $poShMonConfiguration.General.ConfigurationName = $null $poShMonConfiguration.WebSite = $null $monitoringOutput = Invoke-OSMonitoring -PoShMonConfiguration $poShMonConfiguration #Remove-Module PoShMon
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Samples/SPMonitoring_Daily.ps1
SPMonitoring_Daily.ps1
Import-Module "C:\Dev\GitHub\PoShMon\src\0.4.0\PoShMon.psd1" -Verbose -Force #This is only necessary if you haven't installed the module into your Modules folder, e.g. via PowerShellGallery / Install-Module #Alternatively, use the lines below #If (!(Get-module PoShMon)) # { Import-Module PoShMon } $VerbosePreference = 'Continue' $poShMonConfiguration = New-PoShMonConfiguration { General ` -EnvironmentName 'SharePoint' ` -MinutesToScanHistory 1440 ` -PrimaryServerName 'SPAPPSVR01' ` -ConfigurationName SpFarmPosh ` -TestsToSkip "" OperatingSystem ` -EventLogCodes "Error","Warning" WebSite ` -WebsiteDetails @{ "http://intranet" = "Read our terms" "http://extranet.company.com" = "Read our terms" } Notifications -When OnlyOnFailure { Email ` -ToAddress "SharePointTeam@Company.com" ` -FromAddress "Monitoring@company.com" ` -SmtpServer "EXCHANGE.COMPANY.COM" ` } } $monitoringOutput = Invoke-SPMonitoring -PoShMonConfiguration $poShMonConfiguration $poShMonConfiguration.General.PrimaryServerName = '' $poShMonConfiguration.General.ServerNames = 'OWASVR01' $poShMonConfiguration.General.EnvironmentName = 'Office Web Apps' $poShMonConfiguration.General.ConfigurationName = $null $poShMonConfiguration.WebSite = $null $monitoringOutput = Invoke-OSMonitoring -PoShMonConfiguration $poShMonConfiguration #Remove-Module PoShMon
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/OperatingSystem.ps1
OperatingSystem.ps1
Function OperatingSystem { [CmdletBinding(DefaultParameterSetName="All")] param( [string[]]$EventLogCodes = 'Critical', [hashtable]$EventIDIgnoreList = @{}, [double]$CPULoadThresholdPercent = 90, [double]$FreeMemoryThresholdPercent = 10, [Parameter(ParameterSetName="DriveSpaceFixed")] [double]$DriveSpaceThreshold, #This is GB [Parameter(ParameterSetName="DriveSpacePercent")] [double]$DriveSpaceThresholdPercent, #This is GB [string[]]$WindowsServices = @(), [string[]]$WindowsServicesToSkip = @(), [int]$AllowedMinutesVarianceBetweenServerTimes = 1 ) if ($Script:PoShMon.ConfigurationItems.OperatingSystem -eq $null) { $Script:PoShMon.ConfigurationItems.OperatingSystem = @{} } else { throw "OperatingSystem configuration group already created." } if ($DriveSpaceThresholdPercent -gt 99) { throw "DriveSpaceThresholdPercent too high" } if ($DriveSpaceThresholdPercent -lt 1 -and $DriveSpaceThreshold -lt 0) {throw "DriveSpaceThresholdPercent too low" } if ($DriveSpaceThreshold -lt 0) {throw "DriveSpaceThreshold cannot be below zero" } if ($DriveSpaceThreshold -eq 0 -and $DriveSpaceThresholdPercent -eq 0) { $DriveSpaceThreshold = 10 } #GB return @{ TypeName = "PoShMon.ConfigurationItems.OperatingSystem" EventLogCodes = $EventLogCodes EventIDIgnoreList = $EventIDIgnoreList CPULoadThresholdPercent = $CPULoadThresholdPercent FreeMemoryThresholdPercent = $FreeMemoryThresholdPercent DriveSpaceThreshold = $DriveSpaceThreshold DriveSpaceThresholdPercent = $DriveSpaceThresholdPercent WindowsServices = $WindowsServices WindowsServicesToSkip = $WindowsServicesToSkip AllowedMinutesVarianceBetweenServerTimes = $AllowedMinutesVarianceBetweenServerTimes } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/Email.ps1
Email.ps1
Function Email { [CmdletBinding()] param( [parameter(Mandatory)] [string[]]$ToAddress, [parameter(Mandatory)] [string]$FromAddress, [parameter(Mandatory)] [string]$SmtpServer, [int]$Port = 25, [bool]$UseSSL = $false ) return @{ TypeName = 'PoShMon.ConfigurationItems.Notifications.Email' ToAddress = $ToAddress FromAddress = $FromAddress SmtpServer = $SmtpServer Port = $Port UseSSL = $UseSSL } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/New-PoShMonConfiguration.ps1
New-PoShMonConfiguration.ps1
Function New-PoShMonConfiguration { [CmdletBinding()] param( [parameter(Mandatory, Position = 0)] [scriptblock]$bodyScript ) $Script:PoShMon = @{} $Script:PoShMon.ConfigurationItems = @{} $newConfiguration = @{ TypeName = 'PoShMon.Configuration' General = $null WebSite = $null Notifications = @() } $configurationItems = . $bodyScript foreach ($configurationItem in $configurationItems) { if ($configurationItem.TypeName -eq "PoShMon.ConfigurationItems.General") { $newConfiguration.General = $configurationItem } if ($configurationItem.TypeName -eq "PoShMon.ConfigurationItems.OperatingSystem") { $newConfiguration.OperatingSystem = $configurationItem } if ($configurationItem.TypeName -eq "PoShMon.ConfigurationItems.WebSite") { $newConfiguration.WebSite = $configurationItem } if ($configurationItem.TypeName -eq "PoShMon.ConfigurationItems.SharePoint") { $newConfiguration.SharePoint = $configurationItem } elseif ($configurationItem.TypeName.StartsWith("PoShMon.ConfigurationItems.NotificationCollection")) { $newConfiguration.Notifications += $configurationItem } } if ($newConfiguration.General -eq $null) { $newConfiguration.General = General -ServerNames $Env:COMPUTERNAME } if ($newConfiguration.OperatingSystem -eq $null) { $newConfiguration.OperatingSystem = OperatingSystem } return $newConfiguration }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/SharePoint.ps1
SharePoint.ps1
Function SharePoint { [CmdletBinding()] param( [string]$CentralAdminUrl = '' ) if ($Script:PoShMon.ConfigurationItems.SharePoint -eq $null) { $Script:PoShMon.ConfigurationItems.SharePoint = @{} } else { throw "SharePoint configuration group already created." } if ($CentralAdminUrl -ne '') { if ($CentralAdminUrl.EndsWith("/")) { $CentralAdminUrl = $CentralAdminUrl.Substring(0, $CentralAdminUrl.Length - 1) } elseif ($CentralAdminUrl.ToLower().EndsWith("default.aspx")) { $CentralAdminUrl = $CentralAdminUrl.ToLower().Replace("/default.aspx", "") } } return @{ TypeName = "PoShMon.ConfigurationItems.SharePoint" CentralAdminUrl = $CentralAdminUrl } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/General.ps1
General.ps1
Function General { [CmdletBinding()] param( [string]$EnvironmentName = $env:COMPUTERNAME, [int]$MinutesToScanHistory = 15, [string[]]$TestsToSkip = @(), [parameter(ParameterSetName="PrimaryServer",HelpMessage="For monitoring a 'farm'' product, like SharePoint, specify a server name to run the main monitoring operations.")] [string]$PrimaryServerName = $null, [parameter(ParameterSetName="ServerNames",HelpMessage="For monitoring standalone servers, specify the names of the servers to monitor.")] [string[]]$ServerNames = $null, [parameter(HelpMessage="A ConfiguratioName for PowerShell to create remote sessions using pre-existing configurations")] [string]$ConfigurationName = $null, [switch]$SkipVersionUpdateCheck = $false, [pscredential]$InternetAccessRunAsAccount, [parameter(HelpMessage="Web proxy for internet access (e.g. for notification API calls)")] [string]$ProxyAddress ) if ($Script:PoShMon.ConfigurationItems.General -eq $null) { $Script:PoShMon.ConfigurationItems.General = @{} } else { throw "General configuration group already created." } if ($PrimaryServerName -eq "" -and $ServerNames.Count -eq 0) { $ServerNames += $env:COMPUTERNAME } elseif ($PrimaryServerName -ne "" -and $ServerNames.Count -gt 0) { throw "You cannot specify both PrimaryServerName and ServerNames. If you are monitoring a 'farm' product, like SharePoint, specify PrimaryServerName on which to run the main monitoring operations." ` + "Alternatively, if you are instead wanting to monitor a set of standalone servers, supply ServerNames and do not supply a value for the PrimaryServerName parameter." } $remoteSessionName = "PoShMonSession" return @{ TypeName = "PoShMon.ConfigurationItems.General" EnvironmentName = $EnvironmentName MinutesToScanHistory = $MinutesToScanHistory TestsToSkip = $TestsToSkip PrimaryServerName = $PrimaryServerName ServerNames = $ServerNames ConfigurationName = $ConfigurationName RemoteSessionName = $remoteSessionName SkipVersionUpdateCheck = $SkipVersionUpdateCheck InternetAccessRunAsAccount = $InternetAccessRunAsAccount ProxyAddress = $ProxyAddress } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/Notitications.ps1
Notitications.ps1
Function Notifications { [CmdletBinding()] param( [parameter(Mandatory)] [scriptblock]$bodyScript, [ValidateSet("All", "OnlyOnFailure", "None")] [string]$When = "All" ) if ($Script:PoShMon.ConfigurationItems.Notifications -eq $null) { $Script:PoShMon.ConfigurationItems.Notifications = @{} } if ($Script:PoShMon.ConfigurationItems.Notifications.$When -eq $null) { $Script:PoShMon.ConfigurationItems.Notifications.$When = @{} } else { throw "'$When' Notification group already created" } $sinks = . $bodyScript return @{ TypeName = "PoShMon.ConfigurationItems.NotificationCollection-$When" Sinks = $sinks When = $When } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/WebSite.ps1
WebSite.ps1
Function WebSite { [CmdletBinding()] param( [hashtable]$WebsiteDetails = @{} ) if ($Script:PoShMon.ConfigurationItems.WebSite -eq $null) { $Script:PoShMon.ConfigurationItems.WebSite = @{} } else { throw "WebSite configuration group already created." } return @{ TypeName = "PoShMon.ConfigurationItems.WebSite" WebsiteDetails = $WebsiteDetails } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/O365Teams.ps1
O365Teams.ps1
Function O365Teams { [CmdletBinding()] param( [parameter(Mandatory)] [string]$TeamsWebHookUrl ) return @{ TypeName = 'PoShMon.ConfigurationItems.Notifications.O365Teams' TeamsWebHookUrl = $TeamsWebHookUrl } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Configuration/Pushbullet.ps1
Pushbullet.ps1
Function Pushbullet { [CmdletBinding()] param( [parameter(Mandatory)] [string]$AccessToken, [parameter(Mandatory)] [string]$DeviceId = $null ) return @{ TypeName = 'PoShMon.ConfigurationItems.Notifications.Pushbullet' AccessToken = $AccessToken DeviceId = $DeviceId } }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OfficeOnlineServer/Invoke-OOSMonitoring.ps1
Invoke-OOSMonitoring.ps1
Function Invoke-OOSMonitoring { [CmdletBinding()] Param( [parameter(Mandatory=$true, HelpMessage="A PoShMonConfiguration instance - use New-PoShMonConfiguration to create it")] [hashtable]$PoShMonConfiguration ) $outputValues = Invoke-MonitoringCore ` -PoShMonConfiguration $PoShMonConfiguration ` -TestList (Get-OOSTests) ` -FarmDiscoveryFunctionName 'Get-ServersInOOSFarm' ` -OutputOptimizationList @() #(Get-OOSResolutions) later when these get written one day... return $outputValues }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OfficeOnlineServer/Get-OOSTests.ps1
Get-OOSTests.ps1
Function Get-OOSTests { [CmdletBinding()] Param( ) $tests = [string[]]@( "EventLogs", "CPULoad", "Memory", "DriveSpace", "ComputerTime", "OOSWindowsServiceState" "WebSites" ) return $tests }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OfficeOnlineServer/Get-ServersInOOSFarm.ps1
Get-ServersInOOSFarm.ps1
Function Get-ServersInOOSFarm { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration ) #try #{ $remoteSession = Connect-PrimaryServer -PoShMonConfiguration $PoShMonConfiguration # Auto-Discover Servers $serverNames = Invoke-Command -Session $remoteSession -ScriptBlock { Get-OfficeWebAppsFarm | Select -ExpandProperty Machines | Select -ExpandProperty MachineName } return $serverNames #} catch { # throw $_.Exception #} finally { # if ($remoteSession -ne $null) # { Disconnect-PSSession $remoteSession -ErrorAction SilentlyContinue | Out-Null } #} }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OfficeOnlineServer/Test-OOSWindowsServiceState.ps1
Test-OOSWindowsServiceState.ps1
Function Test-OOSWindowsServiceState { [CmdletBinding()] param ( [hashtable]$PoShMonConfiguration ) $mainOutput = Get-InitialOutputWithTimer -SectionHeader "Windows Service State" -OutputHeaders ([ordered]@{ 'DisplayName' = 'Display Name'; 'Name' = 'Name'; 'Status' = 'Status' }) $serversWithServices = @{} [System.Collections.ArrayList]$defaultServiceList = @('WACSM') if ($PoShMonConfiguration.OperatingSystem.WindowsServices -ne $null -and $PoShMonConfiguration.OperatingSystem.WindowsServices.Count -gt 0) { $defaultServiceList += $PoShMonConfiguration.OperatingSystem.WindowsServices } if ($PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip -ne $null -and $PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip.Count -gt 0) { foreach ($serviceToSkip in $PoShMonConfiguration.OperatingSystem.WindowsServicesToSkip) { $defaultServiceList.Remove($serviceToSkip) } } $serversWithServices = @{} foreach ($ServerName in $PoShMonConfiguration.General.ServerNames) { $serversWithServices.Add($ServerName, $defaultServiceList) } Write-Verbose "`tGetting state of services per server..." foreach ($serverWithServicesKey in $serversWithServices.Keys) { $serverWithServices = $serversWithServices[$serverWithServicesKey] $groupedoutputItem = Test-ServiceStatePartial -ServerName $serverWithServicesKey -Services $serverWithServices $mainOutput.NoIssuesFound = $mainOutput.NoIssuesFound -and $groupedoutputItem.NoIssuesFound $mainOutput.OutputValues += $groupedoutputItem } return (Complete-TimedOutput $mainOutput) }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Monitoring.OfficeOnlineServer/Get-OOSTestNames.ps1
Get-OOSTestNames.ps1
Function Get-OOSTestNames { [CmdletBinding()] Param( ) $tests = Get-OOSTests return "'" + [system.String]::Join("','", $tests) + "'" #formatted easily for use in TestsToSkip }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/New-O365TeamsExceptionSubject.ps1
New-O365TeamsExceptionSubject.ps1
Function New-O365TeamsExceptionSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [ValidateSet("Monitoring", "Repairing")] [string]$Action = "Monitoring" ) return "[PoshMon $($PoShMonConfiguration.General.EnvironmentName) $Action]`r`n" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/New-O365TeamsRepairMessageSubject.ps1
New-O365TeamsRepairMessageSubject.ps1
Function New-O365TeamsRepairMessageSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) return "[PoShMon $($PoShMonConfiguration.General.EnvironmentName) Repair Results]`r`n" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/Send-O365TeamsMessage.ps1
Send-O365TeamsMessage.ps1
Function Send-O365TeamsMessage { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [hashtable]$O365TeamsNotificationSink, [string]$Subject, [string]$Body, [bool]$Critical ) $combinedMessageBody = $subject + $body #$headers = @{"accept"="application/json"; "Content-Type"="application/json"} $finalMessageBody = "{""text"": ""$combinedMessageBody""}" $params = @{ Uri = $O365TeamsNotificationSink.TeamsWebHookUrl Headers = @{"accept"="application/json"; "Content-Type"="application/json"} Method = "Post" Body = $finalMessageBody ErrorAction = "SilentlyContinue" } if ($PoShMonConfiguration.General.InternetAccessRunAsAccount -ne $null) { $params.Add("Credential", $PoShMonConfiguration.General.InternetAccessRunAsAccount) } if ($PoShMonConfiguration.General.ProxyAddress -ne $null) { $params.Add("Proxy", $PoShMonConfiguration.General.ProxyAddress) } #$response = Invoke-WebRequest -Uri $O365TeamsNotificationSink.TeamsWebHookUrl -Headers $headers -Body $finalMessageBody -Method Post $response = Invoke-WebRequest @params }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/New-O365TeamsExceptionBody.ps1
New-O365TeamsExceptionBody.ps1
Function New-O365TeamsExceptionBody { [CmdletBinding()] Param( [System.Exception]$Exception, [string]$Action = "monitor" ) $messageBody += "An exception occurred while trying to $Action the environment.`r`n" $messageBody += "Details: $($Exception.ToString())" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/New-O365TeamsRepairMessageBody.ps1
New-O365TeamsRepairMessageBody.ps1
Function New-O365TeamsRepairMessageBody { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) $messageBody = '' foreach ($repairOutputValue in $RepairOutputValues) { $messageBody += "$($repairOutputValue.SectionHeader) : " if ($repairOutputValue.ContainsKey("Exception")) { $messageBody += "(Exception occurred)`r`n" } else { $messageBody += "Repair performed`r`n" } } return $messageBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/New-O365TeamsMessageBody.ps1
New-O365TeamsMessageBody.ps1
Function New-O365TeamsMessageBody { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [ValidateSet("All","OnlyOnFailure","None")][string]$SendNotificationsWhen, [System.Collections.ArrayList]$TestOutputValues, [TimeSpan]$TotalElapsedTime ) $messageBody = '' foreach ($testOutputValue in $testOutputValues) { if ($testOutputValue.NoIssuesFound) { $foundValue = "No" } else { $foundValue = "Yes" } if ($testOutputValue.ContainsKey("Exception")) { $foundValue += " (Exception occurred)" } $messageBody += "$($testOutputValue.SectionHeader) : issue(s) found - $foundValue `r`n" } return $messageBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.O365Teams/New-O365TeamsMessageSubject.ps1
New-O365TeamsMessageSubject.ps1
Function New-O365TeamsMessageSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues ) return "[$($PoShMonConfiguration.General.EnvironmentName) Monitoring Report]`r`n" }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/New-PushbulletMessageSubject.ps1
New-PushbulletMessageSubject.ps1
Function New-PushbulletMessageSubject { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [System.Collections.ArrayList]$TestOutputValues ) $issueCount = 0 foreach ($outputValue in $TestOutputValues) { if (($outputValue.NoIssuesFound -eq $false)) { $issueCount++ } } $subject = "[PoshMon $($PoShMonConfiguration.General.EnvironmentName) Monitoring Results ($issueCount Issue(s) Found)]" return $subject }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/New-PushbulletExceptionBody.ps1
New-PushbulletExceptionBody.ps1
Function New-PushbulletExceptionBody { [CmdletBinding()] Param( [System.Exception]$Exception, [string]$Action = "monitor" ) $messageBody = '' $messageBody += "An exception occurred while trying to $Action the environment.`r`n" $messageBody += "Details: $($Exception.ToString())" return $messageBody }
PowerShellCorpus/PowerShellGallery/PoShMon/0.13.0/Functions/PoShMon.Notifications.Pushbullet/New-PushbulletRepairMessageBody.ps1
New-PushbulletRepairMessageBody.ps1
Function New-PushbulletRepairMessageBody { [CmdletBinding()] Param( [hashtable]$PoShMonConfiguration, [object[]]$RepairOutputValues ) $messageBody = '' foreach ($repairOutputValue in $RepairOutputValues) { $messageBody += "$($repairOutputValue.SectionHeader) : " if ($repairOutputValue.ContainsKey("Exception")) { $messageBody += "(Exception occurred)`r`n" } else { $messageBody += "Repair performed`r`n" } } return $messageBody }