full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Functions/PSUri/Test_Uri.ps1
Test_Uri.ps1
function Test_Uri { [CmdletBinding()] param( [string]$Uri, [bool]$DisableSSLValidation=$false, [string]$AllowedStatusCodeRegexp, [Int32]$TimeOutSeconds, [hashtable]$ReplaceRules ) $result = New-Object PsObject -Property @{ ComputerName = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName TestType='UriTest' Test=$Uri Passed = $false Result = $null Status = $null Uri=$Uri ReplaceRules = $ReplaceRules AllowedStatusRegexp = $AllowedStatusCodeRegexp DisableSSLValidation = $DisableSSLValidation TimeOutSeconds = $TimeOutSeconds } if ($DisableSSLValidation) { Write-Verbose "Disabling SSL Validation for Invoke-WebRequest" try { Add-Type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy } catch { Write-Error "Disabling SSL Validation failed." Write-Error $_ } } try { # Transform Uris if ($ReplaceRules) { $ReplaceRules.GetEnumerator() | ForEach-Object { $result.Uri = $result.Uri -replace $_.Key,$_.Value } } $result.Result = Invoke-WebRequest -UseBasicParsing -uri $result.Uri -TimeoutSec $result.TimeOutSeconds -ErrorAction Stop # Evaluate Response if ($result.Result) { $result.Status = $result.Result.StatusCode $result.Passed = ($result.Result.StatusCode -match $AllowedStatusCodeRegexp) } } catch { $result.Passed = $false $result.Status = $_ $result.Result = $_ Write-Error $_ } $result }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/Import-LocalModule.ps1
Import-LocalModule.ps1
# Load module from the local filesystem, instead from the ModulePath Remove-Module PSWebConfig -Force -ErrorAction SilentlyContinue Import-Module (Split-Path $PSScriptRoot -Parent) $script:FunctionPath = Resolve-Path (Join-Path $PSScriptRoot '../Functions') $script:FixturePath = Resolve-Path (Join-Path $PSScriptRoot 'Fixtures')
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/Module/ScriptAnalyzer.tests.ps1
ScriptAnalyzer.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $scriptSources = Get-ChildItem -Path $script:FunctionPath -Filter '*.ps1' -Recurse $scriptAnalyzer = Get-Module PSScriptAnalyzer -ListAvailable if (-Not $scriptAnalyzer) { Write-Verbose "PSScriptAnalyzer module is not available." return } Describe "Script Source analysis" { Import-Module PSScriptAnalyzer $scriptSources | ForEach-Object { Context "Source $($_.Name)" { $results = Invoke-ScriptAnalyzer -Path $_.FullName -ErrorVariable $errors it "should have no errors" { $errors | Should BeNullOrEmpty } it "should not have warnings" { $results | Where-Object Severity -eq "Warning" | Should BeNullOrEmpty } } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/Module/Module.tests.ps1
Module.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $moduleName = 'PSWebConfig' $exportedCommands = (Get-Command -Module $moduleName) $expectedCommands = @( 'Get-PSWebConfig' 'Get-PSAppConfig' 'Decrypt-PSWebConfig' 'Unprotect-PSWebConfig' 'Test-PSWebConfig' 'Test-WebConfigFile' 'Test-PSAppConfig' 'Get-PSAppSetting' 'Get-PSConnectionString' 'Test-PSConnectionString' 'Get-PSEndpoint' 'Get-PSUri' 'Test-PSUri' ) Describe "$moduleName Module" { It "Should be loaded" { Get-Module $moduleName | Should Not BeNullOrEmpty } } Describe 'Exported commands' { # Test if the exported command is expected Foreach ($command in $exportedCommands) { Context $command { It 'Should be an expected command' { $expectedCommands -contains $command.Name | Should Be $true } It 'Should have proper help' { $help = Get-Help $command.Name $help.description | Should Not BeNullOrEmpty $help.Synopsis | Should Not BeNullOrEmpty $help.examples | Should Not BeNullOrEmpty } } } } Describe 'Expected commands' { # Test if the expected command is exported Foreach ($command in $expectedCommands) { Context $command { It 'Should be an exported command' { $exportedCommands.Name -contains $command | Should Be $true } } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSWebConfig/Get-WebConfig.tests.ps1
Get-WebConfig.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') $webConfigFile = Join-Path $script:FixturePath 'web.config' $webConfigSections = @( "appSettings" "connectionStrings" ) $testInput = New-Object -TypeName PsObject -Property @{ physicalPath = $webConfigFile } Describe "Web.config file test" { It "Test-file Should exists" { $webConfigFile | Should Exist } $xml = [xml](Get-Content $webConfigFile) It "Should be a valid XMLDocument" { $xml.GetType().Name | Should Be "XmlDocument" } foreach($section in $webConfigSections) { It "Should have '$section' configuration section" { $xml.configuration.$section | Should Not BeNullOrEmpty } } } Describe "Get-PSWebConfig" { Context "Parameters input" { It "should accept -Path" { Get-PSWebConfig -Path $webConfigFile -AsXml -Verbose:$isVerbose | Select-Object -ExpandProperty File | Should Be $webConfigFile } It "should accept Path at 0 position" { Get-PSWebConfig $webConfigFile -AsXml -Verbose:$isVerbose | Select-Object -ExpandProperty File | Should Be $webConfigFile } It "should accept -InputObject" { Get-PSWebConfig -InputObject $testInput -AsXml -Verbose:$isVerbose | Select-Object -ExpandProperty File | Should Be $testInput.physicalPath } } Context "Pipeline input" { It "should accept testInputObject" { $testInput | Get-PSWebConfig -AsXml -Verbose:$isVerbose | Select-Object -ExpandProperty File | Should Be $testInput.physicalPath } It "should accept FileInfo" { Get-Item $webConfigFile | Get-PSWebConfig -AsXml -Verbose:$isVerbose | Select-Object -ExpandProperty File | Should Be $testInput.physicalPath } } } Describe "Get-PSWebConfig" { Context "Invalid Paths" { It "Should not return anything" { Get-PSWebConfig -Path 'clearly:\invalid\path\to_fail' -Verbose:$isVerbose | Should BeNullOrEmpty } } Context "Default XML output" { It "should return the XML object by default" { $defaultConfig = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose $defaultConfig | Should Not BeNullOrEmpty $defaultConfig.GetType().Name | Should Be 'XmlDocument' #$defaultConfig.OuterXml | Set-Content ./default.txt -Enc UTF8 $xmlConfig = Get-PSWebConfig -Path $webConfigFile -AsXml -Verbose:$isVerbose $xmlConfig | Should Not BeNullOrEmpty $xmlConfig.GetType().Name | Should Be 'XmlDocument' #$xmlConfig.OuterXml | Set-Content ./xml.txt -Enc UTF8 $defaultConfig.OuterXml | Should Be $xmlConfig.OuterXml } It "should have PSWebConfig.WebConfig additional type" { $config = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose $config | Should Not BeNullOrEmpty $config.psobject.TypeNames -contains 'PsWebConfig.WebConfig' | Should Be $true } It "Should be a valid XML Configuration" { $config = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose $config.GetType().Name | Should Be 'XmlDocument' $config.configuration | Should Not BeNullOrEmpty $config.configuration.GetType().Name | Should Be 'XmlElement' } } Context "AsFileInfo output" { It "should match the source File" { $config = Get-PSWebConfig -Path $webConfigFile -AsFileInfo -Verbose:$isVerbose $config | Should Not BeNullOrEmpty $config | Should Be $webConfigFile $config.GetType().Name | Should Be 'FileInfo' } It "should find web.config in folders" { $config = Get-PSWebConfig -Path $script:FixturePath -AsFileInfo -Verbose:$isVerbose $config | Should Not BeNullOrEmpty $config.FullName | Should Be $webConfigFile } } Context "Unencrypted text output" { It "should be the same XML string as the source file" { $config = Get-PSWebConfig -Path $webConfigFile -AsText -Verbose:$isVerbose $config | Should Not BeNullOrEmpty $config.GetType().Name | Should Be 'String' $rawConfig = Get-Content -Path $webConfigFile #Convert both String to XML to strip unnessary whitespaces ([xml]$config).OuterXml | Should Be ([xml]$rawConfig).OuterXml } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSWebConfig/Get_ConfigFile.tests.ps1
Get_ConfigFile.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') Describe "Get_ConfigFile helper" { # Function to test . (Join-Path $script:FunctionPath 'PSWebConfig/Get_ConfigFile.ps1') $webConfigFile = Join-Path $script:FixturePath 'web.config' It "Should be able to find web.config files recursively" { $files = Get_ConfigFile -Path $script:FixturePath -AsFileInfo:$true -Recurse:$true -Verbose:$isVerbose $files | Should Not BeNullOrEmpty $files.GetType().Name | Should Be 'FileInfo' } It "Should be able to return XML content" { $xml = Get_ConfigFile -Path $webConfigFile -Verbose:$isVerbose $xml | Should Not BeNullOrEmpty $xml.configuration.GetType().Name | Should Be 'XmlElement' $xml.File | Should Be $webConfigFile $xml.ComputerName | Should Be ([System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName) } It "Should be able to read the file content" { $content = Get_ConfigFile -Path $webConfigFile -AsText:$true -Verbose:$isVerbose $content | Should Not BeNullOrEmpty $content.GetType().Name | Should Be 'String' } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSAppSetting/Get-PSAppSetting.tests.ps1
Get-PSAppSetting.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') $webConfigFile = Join-Path $script:FixturePath 'web.config' Describe 'Get-PSAppSetting' { Context 'Local web.config' { $config = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose $appSettings = $config | Get-PSAppSetting -Verbose:$isVerbose It 'should return all AppSettings' { $appSettings | Should Not BeNullOrEmpty $appSettings.Count | Should Be 5 $appSettings | Foreach-Object { $_.psobject.TypeNames -contains 'PSWebConfig.AppSetting' | Should Be $true $_.SectionPath | Should Be 'appSettings' $_.key | Should Not BeNullOrEmpty $_.value | Should Not BeNullOrEmpty } } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSConnectionString/Test_ConnectionString.tests.ps1
Test_ConnectionString.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') Describe "Test_ConnectionString helper function" { # Function to test . (Join-Path $script:FunctionPath 'PSConnectionString/Test_ConnectionString.ps1') @{ Invalid='IvServer=localhost;IvDatabase=##DB##;Connection Timeout=1' NonExisting="Server=localhost;Database=##DB##ThatShouldNotExist;User Id=uname;Password=4bCd;Connection Timeout=1;" NonExistingWithPasswordEnd="Server=localhost;Database=##DB##ThatShouldNotExist;User Id=uname;Connection Timeout=1;Password=4bCd" }.GetEnumerator() | ForEach-Object { context "$($_.Key) SqlConnectionString" { $failingConnectionString=$_.Value It "Should have failed test result properties" { $result = Test_ConnectionString -ConnectionString $failingConnectionString -Verbose:$isVerbose -ShowPassword $true -EA 0 $result | Should Not BeNullOrEmpty $result.ComputerName | Should Be ([System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName) $result.TestType | Should Be 'SqlTest' $result.Test | Should Be $failingConnectionString $result.ConnectionString | Should Be $failingConnectionString $result.Passed | Should Be $false $result.Result | Should Not BeNullOrEmpty $result.Status | Should Match 'Failed' } It "Should replace ConnectionString with ReplaceRules" { $replacedFailingConnectionString=$failingConnectionString -replace '##DB##','DB_SUBST' $replaceRule = @{'##DB##'='DB_SUBST'} $result = Test_ConnectionString -ConnectionString $failingConnectionString -ReplaceRules $replaceRule -Verbose:$isVerbose -ShowPassword $true -EA 0 $result.Test | Should Be $failingConnectionString $result.ConnectionString | Should Be $replacedFailingConnectionString } if ($failingConnectionString -imatch "Password=") { It "Should replace replace Password= field to ***" { $result = Test_ConnectionString -ConnectionString $failingConnectionString -Verbose:$isVerbose -EA 0 $result.Test | Should Match 'Password=\*\*\*' $result.ConnectionString | Should Match 'Password=\*\*\*' } } } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSConnectionString/Get-PSConnectionString.tests.ps1
Get-PSConnectionString.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') $webConfigFile = Join-Path $script:FixturePath 'web.config' Describe "Get-PSConnectionString" { Context "Local web.config connectionStrings section" { $config = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose It "should return only connectionStrings by default" { $connStrs = $config | Get-PSConnectionString -Verbose:$isVerbose $connStrs | Should Not BeNullOrEmpty $connStrs.GetType().Name | Should Be "XmlElement" $connStrs.psobject.TypeNames -contains 'PSWebConfig.ConnectionString' | Should Be $true $connStrs.name | Should Be 'login' $connStrs.SectionPath | Should Be 'connectionStrings' $connStrs.connectionstring | Should Not BeNullOrEmpty } It "should return connectionStrings with -IncludeAppSettings" { $connStrs = $config | Get-PSConnectionString -IncludeAppSettings -Verbose:$isVerbose $connStrs | Should Not BeNullOrEmpty $connStrs.Count | Should Be 2 $connStrs | Foreach-Object { $_.psobject.TypeNames -contains 'PSWebConfig.ConnectionString' | Should Be $true @('login','AppConfigSqlConnectionString') -contains $_.name | Should Be $true @('connectionStrings','appSettings') -contains $_.SectionPath | Should Be $true $_.connectionstring | Should Not BeNullOrEmpty } } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSUri/Get-PSUri.tests.ps1
Get-PSUri.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') $webConfigFile = Join-Path $script:FixturePath 'web.config' Describe 'Get-PSUri' { Context 'Local web.config' { $config = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose $addresses = $config | Get-PSUri -Verbose:$isVerbose -IncludeAppsettings $endpoints = (Get-PSEndpoint -ConfigXml $config -Verbose:$isVerbose) It 'should return all addresses with -IncludeAppsettings' { $addresses | Should Not BeNullOrEmpty $addresses.Count | Should Be (2+2) # appSetting + endpoints $addresses | Foreach-Object { $_.psobject.TypeNames -contains 'PSWebConfig.Uri' | Should Be $true $_.SectionPath | Should Match '^system.serviceModel/client/endpoint$|^appSettings$' $_.name | Should Not BeNullOrEmpty $_.address | Should Not BeNullOrEmpty $_.Uri | Should Match '^http[s]*:' } } It 'should contain all service endpoints' { $addresses | Should Not BeNullOrEmpty foreach ($e in $endpoints) { $addresses -contains $e | Should Be $true } } It 'should be the same as Get-PSEndpoint without -IncludeAppsettings' { $addressesWithouAppSettings = $config | Get-PSUri -Verbose:$isVerbose $addressesWithouAppSettings | Should Not BeNullOrEmpty $addressesWithouAppSettings | Should Be $endpoints } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSUri/Test_Uri.tests.ps1
Test_Uri.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') Describe "Test_Uri helper function" { # Function to test . (Join-Path $script:FunctionPath 'PSUri/Test_Uri.ps1') Context "Testing multiple URIs and StatusCodes" { $uriTests = Import-Csv -LiteralPath (Join-Path $script:FixturePath 'webrequests.csv') -Delimiter ',' foreach ($uriTest in $uriTests) { $verb = 'fail' if ($uriTest.shouldpass -eq 1) { $verb = 'pass'} It "'$($uriTest.uri)' should $verb if statuscode matches '$($uriTest.statuscodes)'" { $result = $null if ($uriTest.statuscodes) { $result = Test_Uri -Uri $uriTest.uri -AllowedStatusCodeRegexp $uriTest.statuscodes -ErrorAction SilentlyContinue -Verbose:$isVerbose } else { $result = Test_Uri -Uri $uriTest.uri -ErrorAction SilentlyContinue -Verbose:$isVerbose } $result | Should Not BeNullOrEmpty $result.ComputerName | Should Be ([System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName) $result.TestType | Should Be 'UriTest' $result.Test | Should Be $UriTest.uri $result.Uri | Should Be $UriTest.uri $result.Passed | Should Be ($uriTest.shouldpass -eq 1) $result.Result | Should Not BeNullOrEmpty $result.Status | Should Not BeNullOrEmpty } } } }
PowerShellCorpus/PowerShellGallery/PSWebConfig/1.7.0.0/Tests/PSUri/Get-PSEndpoint.tests.ps1
Get-PSEndpoint.tests.ps1
. (Join-Path $PSScriptRoot '../Import-LocalModule.ps1') $isVerbose=($VerbosePreference -eq 'Continue') $webConfigFile = Join-Path $script:FixturePath 'web.config' Describe "Get-PSEndpoint" { Context "Local web.config" { $config = Get-PSWebConfig -Path $webConfigFile -Verbose:$isVerbose $endpoints = $config | Get-PSEndpoint -Verbose:$isVerbose It "should return all client endpoints as an address" { $endpoints | Should Not BeNullOrEmpty $endpoints.Count | Should Be 2 $endpoints | Foreach-Object { $_.psobject.TypeNames -contains 'PSWebConfig.Uri' | Should Be $true $_.SectionPath | Should Be 'system.serviceModel/client/endpoint' $_.name | Should Not BeNullOrEmpty $_.address | Should Not BeNullOrEmpty $_.Uri | Should Not BeNullOrEmpty } } } }
PowerShellCorpus/PowerShellGallery/DSCHelperFunctions/1.1.0/Examples/CertificateUpdate.ps1
CertificateUpdate.ps1
Configuration Meta { Node $AllNodes.NodeName { LocalConfigurationManager { CertificateId = $Node.Thumbprint RebootNodeIfNeeded = $true AllowModuleOverwrite = $true RefreshMode = "Pull" RefreshFrequencyMins = 15 ConfigurationModeFrequencyMins = 30 ConfigurationMode = "ApplyAndAutoCorrect" DownloadManagerCustomData = @{ServerURL = 'https://dsc.contoso.com:8080/PSDSCPullServer.svc'} } } } $Nodes = @{ AllNodes = @( @{ NodeName = "Server01" } ); } #Build Configuration $Nodes = Update-ConfigurationDataCertificates -ConfigurationData $Nodes Meta -ConfigurationData $Nodes #By adding the extra "Update-ConfigurationDataCertificates" function, thumbprint and certificatefile info is added to the data so that passwords can be encrypted in the mof.
PowerShellCorpus/PowerShellGallery/DSCHelperFunctions/1.1.0/Examples/Update-ConfigData.ps1
Update-ConfigData.ps1
#This parameter hastable contains common locations for "stuff". Most of these variables are "defaulted" in the functions. $Parameters = @{ PullServerConfiguration = "$env:PROGRAMFILES\WindowsPowershell\DscService\Configuration" CertStore = "$env:PROGRAMFILES\WindowsPowershell\DscService\NodeCertificates" PasswordData = "$env:PROGRAMFILES\WindowsPowershell\DscService\passwords.xml" GUIDData = "$env:PROGRAMFILES\WindowsPowershell\DscService\DSCNodes.csv" } #Sample Configuration data for consumption $ConfigurationData = @{ AllNodes = @( @{ NodeName = '*' DomainName = "lab.contoso.com" }, @{ NodeName = "dc-01" Service = 'ActiveDirectory' Role = 'PDC' DNSServerAddresses = "192.168.1.102","127.0.0.1" }, @{ NodeName = "dc-02" Service = 'ActiveDirectory' Role = 'RODC' DNSServerAddresses = "192.168.1.100","127.0.0.1" } ); } #Each function in action, updating info with certificate, passwords and GUID information $ConfigurationData = Update-ConfigurationDataCertificates -ConfigurationData $ConfigurationData -CertStore $Parameters.CertStore $ConfigurationData = Update-ConfigurationDataPasswords -ConfigurationData $ConfigurationData -PasswordData $Parameters.PasswordData $ConfigurationData = Update-ConfigurationDataNames -ConfigurationData $ConfigurationData -GUIDData $Parameters.GUIDData #3 functions are seperate as different companies will have different needs. WMF5 ConfigurationName users, for example, will never convert nodenames to GUID.
PowerShellCorpus/PowerShellGallery/DSCHelperFunctions/1.1.0/Examples/new-samplefiles.ps1
new-samplefiles.ps1
#Use this command to create "sample" files for password, node/guid, and certificate share. Install-DSCHelperStores
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Import-GraphOauthAccessToken.ps1
Import-GraphOauthAccessToken.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/9/2017 6:55 AM Edited on: 3/30/2017 Created by: Mark Kraus Organization: Mitel Filename: Import-GraphOauthAccessToken.ps1 =========================================================================== .DESCRIPTION Import-GraphOauthAccessToken function #> <# .SYNOPSIS Imports an exported Graph OAuth Access Token Object .DESCRIPTION Imports an exported Graph OAuth Access Token Object and retruns a Graph OAuth Access Token Object. .PARAMETER Path Specifies the XML files where the Graph Application Object was exported. .PARAMETER LiteralPath Specifies the XML files where the Graph Application Object was exported. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. .EXAMPLE PS C:\> $GraphAccessToken = Import-GraphOAuthAccessToken -Path 'c:\GraphAccessToken.xml' .NOTES See Export-GraphOauthAccessToken for exporting Graph AcessToken Objects See Get-GraphOauthAccessToken for obtaining a Graph Access Token from the API .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .OUTPUTS MSGraphAPI.Oauth.AccessToken #> function Import-GraphOauthAccessToken { [CmdletBinding(DefaultParameterSetName = 'Path', ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphOAuthAccessToken', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.Oauth.AccessToken')] param ( [Parameter(ParameterSetName = 'Path', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string[]]$Path, [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$LiteralPath ) Process { Switch ($PsCmdlet.ParameterSetName) { 'Path' { $ImportFiles = $Path } 'LiteralPath' { $ImportFiles = $LiteralPath } } foreach ($ImportFile in $ImportFiles) { if ($pscmdlet.ShouldProcess($ImportFile)) { Write-Verbose "Processing $($ImportFile)." $Params = @{ "$($PsCmdlet.ParameterSetName)" = $ImportFile ErrorAction = 'Stop' } try { $InObject = Import-Clixml @Params } Catch { $ErrorMessage = "Unable to import from '{0}': {1}" -f @( $ImportFile $_.Exception.Message ) Write-Error $ErrorMessage } Write-Verbose "Reconstituting Application object" $Application = $InObject.Application | New-GraphApplication Write-Verbose 'Reconstituting Session object' $Session = [Microsoft.PowerShell.Commands.WebRequestSession]::new() $Session.Certificates = $InObject.Session.Certificates $Session.Credentials = $InObject.Session.Credentials try { $InObject.Session.Headers.GetEnumerator() | ForEach-Object { $Session.Headers[$_.key] = $_.value } } catch { Write-Warning "Session headers could not be imported." } $Session.MaximumRedirection = $InObject.Session.MaximumRedirection $Session.Proxy = $InObject.Session.Proxy $Session.UseDefaultCredentials = $InObject.Session.UseDefaultCredentials $Session.UserAgent = $Application.UserAgent Write-Verbose 'Create Graph Token Object' $Params = @{ Application = $Application AccessTokenCredential = $InObject.AccessTokenCredential RefreshTokenCredential = $InObject.RefreshTokenCredential RequestedDate = $InObject.RequestedDate Response = $InObject.Response ResponseHeaders = $InObject.ResponseHeaders LastRequestDate = $InObject.LastRequestDate Session = $Session GUID = $InObject.GUID } New-GraphOauthAccessToken @Params } #End Should Process } #End Foreach } #End Process } #End Function
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Update-GraphOauthAccessToken.ps1
Update-GraphOauthAccessToken.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/9/2017 7:43 AM Created by: Mark Kraus Organization: Mitel Filename: Update-GraphOauthAccessToken.ps1 =========================================================================== .DESCRIPTION Update-GraphOauthAccessToken Function #> <# .SYNOPSIS Refreshes a Graph Oauth Access Token .DESCRIPTION Requests a refresh of the Graph OAuth Access Token from Graph. .PARAMETER AccessToken Graph OAUth Access Token Object created by Get-GraphOAuthAccessToken. .PARAMETER BaseUrl Base Url for the OAuth Submission end point. This is not required. Defaults to https://login.microsoftonline.com/common/oauth2/token .PARAMETER Force By default, a Token will not be renewed if it is not expired. Using force will attempt a token refresh the token even if it is not expired. .PARAMETER PassThru Indicates that the cmdlet sends items from the interactive window down the pipeline as input to other commands. By default, this cmdlet does not generate any output. .PARAMETER RenewalPeriod The renewal period in seconds. The default is 300 (5 minutes). This is the number of seconds before the expiration date that a token will be refreshed. This will prevent the access_token from being expired should the time between the token provider and the local system be offset. If the token is already expired, this will be ignored. .EXAMPLE PS C:\> $GraphToken = $GraphToken | Update-GraphOAuthAccessToken .OUTPUTS MSGraphAPI.Oauth.AccessToken .NOTES Ses Get-GraphOauthAccessToken for retrieving an OAuth Access Token from Graph .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Update-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphOauthAccessToken #> function Update-GraphOauthAccessToken { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Justification = "Converts plaintext returned from API to secure string.")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Impliments Force param. Updates in memory object only.")] [CmdletBinding(ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Update-GraphOauthAccessToken')] [OutputType('MSGraphAPI.Oauth.AccessToken')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [pstypename('MSGraphAPI.Oauth.AccessToken')] [Alias('Token')] [System.Management.Automation.PSObject[]]$AccessToken, [Parameter(Mandatory = $false)] [ValidateScript({ [system.uri]::IsWellFormedUriString( $_, [System.UriKind]::Absolute ) })] [string]$BaseUrl = 'https://login.microsoftonline.com/common/oauth2/token', [int]$RenewalPeriod = 300, [switch]$Force, [switch]$PassThru ) process { Foreach ($RefreshToken in $AccessToken) { Write-Verbose "Processing token '$($RefreshToken.GUID.ToString())'" If (!$AccessToken.isExpired -and !$Force -and (get-date) -lt $AccessToken.Expires.addseconds(-$RenewalPeriod)) { Write-Verbose "Token is not expired. Skipping" Continue } $Body = @( 'grant_type=refresh_token' '&redirect_uri={0}' -f [System.Web.HttpUtility]::UrlEncode($RefreshToken.Application.RedirectUri) '&client_id={0}' -f [System.Web.HttpUtility]::UrlEncode($RefreshToken.Application.ClientID) '&client_secret={0}' -f [System.Web.HttpUtility]::UrlEncode($RefreshToken.Application.GetClientSecret()) '&refresh_token={0}' -f [System.Web.HttpUtility]::UrlEncode($RefreshToken.GetRefreshToken()) '&resource={0}' -f [System.Web.HttpUtility]::UrlEncode($RefreshToken.Resource) ) -join '' $Params = @{ Uri = $BaseUrl WebSession = $RefreshToken.Session Method = 'POST' Body = $Body } $RequestTime = Get-Date try { $WebRequest = Invoke-WebRequest @Params } catch { $ErrorMessage = $_.Exception.Message Write-Error "Failed to refresh token: $ErrorMessage" continue } try { $Content = $WebRequest.Content | ConvertFrom-Json -ErrorAction Stop } Catch { $ErrorMessage = $_.Exception.Message $Message = "Failed to convert response from JSON: {0}" -f $ErrorMessage Write-Error $Message Write-Error $WebRequest.Content return } $RefreshToken.AccessTokenCredential = [pscredential]::new('access_token', $($Content.access_token | ConvertTo-SecureString -AsPlainText -Force)) $RefreshToken.Response = $Content | Select-Object -property * -ExcludeProperty access_token, refresh_token $RefreshToken.RequestedDate = $RequestTime if ($PassThru) { Write-Verbose "Sending Token to the Pipeline" $RefreshToken } } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADGroupById.ps1
Get-AADGroupById.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/14/2017 6:08 AM Edited On: 2/23/2017 Created by: Mark Kraus Organization: Filename: Get-AADGroupById.ps1 =========================================================================== .DESCRIPTION Get-AADGroupById Function #> <# .SYNOPSIS Retrieves an Azure AD Group by hte provided Object ID .DESCRIPTION Searches Azure Active Directory Graph API for a Group by the provided Object ID. The provided Object ID must be a full case-insensitive match. Partial matches and wildcards are not supported. The Object ID is the Azure AD Object ID and not the ObjectGUID synced from an On-prem AD. A MSGraphAPI.DirectoryObject.Group object will be returned for the matching group. Get-AADGroupById requires a MSGraphAPI.Oauth.AccessToken issued for the https://graph.windows.net resource. See the Get-GraphOauthAccessToken help for more information. Get-Help -Name Get-GraphOauthAccessToken -Parameter Resource .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. Access Token must be issued for the https://graph.windows.net resource. .PARAMETER ObjectId The group's Azure AD ObjectID e.g d377e755-9365-400f-ab42-c0bf278c386e This is not the ObjectGUID synced from an On-prem AD .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion Version of the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADGroup = Get-AADGroupByID -AccessToken $GraphAccessToken -ObjectID d377e755-9365-400f-ab42-c0bf278c386e .OUTPUTS MSGraphAPI.DirectoryObject.Group .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByID .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupMember .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByDisplayName .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .LINK https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations .LINK https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options#filter #> function Get-AADGroupByID { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByID')] [OutputType('MSGraphAPI.DirectoryObject.Group')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')] $AccessToken, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$ObjectId, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$APIversion = '1.6' ) process { foreach ($GroupId in $ObjectId) { if (-not $pscmdlet.ShouldProcess($GroupId)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}/{3}?api-version={4}' -f @( $BaseUrl $Tenant 'groups' $GroupId $APIversion ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query Group '{0}': {1}" -f $GroupId, $_.Exception.Message Write-Error -Message $ErrorMessage -Exception $_.Exception return } $OutputObject = $Result.ContentObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.Group') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADServicePrinicpalbyDisplayName.ps1
Get-AADServicePrinicpalbyDisplayName.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 12:20 PM Last Edited: 2/14/2017 Created by: Mark Kraus Organization: Mitel Filename: Get-AADServicePrinicpalbyDisplayName.ps1 =========================================================================== .DESCRIPTION Get-AADServicePrinicpalbyDisplayName Function #> <# .SYNOPSIS Retrieves an Azure AD ServicePrincipal by the Display name .DESCRIPTION Retrieves an Azure AD ServicePrincipal by the Display Name .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. .PARAMETER DisplayName The ServicePrincipal's Display Name. This must be an exact match and does not support wildcards .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADServicePrincipal = Get-AADServicePrincipalByDisplayName -AccessToken $GraphAccessToken -DisplayName 'Contoso Web App' .OUTPUTS MSGraphAPI.DirectoryObject.ServicePrincipal .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrinicpalbyDisplayName #> function Get-AADServicePrinicpalbyDisplayName { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrinicpalbyDisplayName')] [OutputType('MSGraphAPI.DirectoryObject.ServicePrincipal')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')] $AccessToken, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$DisplayName, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$APIversion = '1.6' ) process { foreach ($ServiceName in $DisplayName) { if (-not $pscmdlet.ShouldProcess($ServiceId)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}?api-version={3}&$filter=displayName+eq+%27{4}%27' -f @( $BaseUrl $Tenant 'servicePrincipals' $APIversion [System.Web.HttpUtility]::UrlEncode($ServiceName) ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query User '{0}': {1}" -f $UserId, $_.Exception.Message Write-Error $ErrorMessage return } foreach ($ServiceObject in $Result.ContentObject.value) { $OutputObject = $ServiceObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.ServicePrincipal') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADUserByID.ps1
Get-AADUserByID.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 10:38 AM Created by: Mark Kraus Organization: Mitel Filename: Get-AADUserByID.ps1 =========================================================================== .DESCRIPTION Get-AADUserByID function #> <# .SYNOPSIS Retrieves an Azure AD User by their Object ID .DESCRIPTION Retrieves an Azure AD User by their Object ID .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. .PARAMETER ObjectId The user's ObjectID e.g d377e755-9365-400f-ab42-c0bf278c386e .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADUser = Get-AADUserByID -AccessToken $GraphAccessToken -ObjectID d377e755-9365-400f-ab42-c0bf278c386e .OUTPUTS MSGraphAPI.DirectoryObject.User .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserByID #> function Get-AADUserByID { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserByID')] [OutputType('MSGraphAPI.DirectoryObject.User')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')]$AccessToken, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$ObjectId, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$APIversion = '1.6' ) process { foreach ($UserId in $ObjectId) { if (-not $pscmdlet.ShouldProcess($UserId)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}/{3}?api-version={4}' -f @( $BaseUrl $Tenant 'users' $UserId $APIversion ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query User '{0}': {1}" -f $UserId, $_.Exception.Message Write-Error $ErrorMessage return } $OutputObject = $Result.ContentObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.User') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADGroupMember.ps1
Get-AADGroupMember.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/14/2017 6:02 AM Edited on: 3/30/2017 Created by: Mark Kraus Organization: Mitel Filename: Get-AADGroupMember.ps1 =========================================================================== .DESCRIPTION Get-AADGroupMember Function #> <# .SYNOPSIS Returns the members for the given Group .DESCRIPTION Returns the members for the given Group .PARAMETER Group A MSGraphAPI.DirectoryObject.Group object retruned by Get-AADGroup* cmdlets .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version of the API to use. Default is 1.6 .PARAMETER ResultsPerPage The number of results to request from the API per call. This is the '$top' API query filter. Default is 100. Valid Range is 1-999. This will not limit the number of resutls retruned by the command. .OUTPUTS MSGraphAPI.DirectoryObject.User .INPUTS MSGraphAPI.DirectoryObject.Group .EXAMPLE PS C:\> $AADGroupMembers = $AADGroup | Get-AADGroupMembers .NOTES Additional information about the function. .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupMember .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByID .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByDisplayName #> function Get-AADGroupMember { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupMember')] [OutputType('MSGraphAPI.DirectoryObject.User')] [Alias('Get-AADGroupMembers')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.DirectoryObject.Group')] [object[]]$Group, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$APIVersion = '1.6', [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateRange(1,999)] [int]$ResultsPerPage = 100 ) process { Foreach ($GroupObject in $Group) { if (-not $pscmdlet.ShouldProcess($GroupObject.objectId)) { return } $AccessToken = $GroupObject._AccessToken $Application = $AccessToken.Application $Tenant = $Application.Tenant $SkipToken = $null do { $Url = '{0}/{1}/{2}/{3}/{4}?api-version={5}{6}{7}' -f @( $BaseUrl $Tenant 'groups' $GroupObject.objectId 'members' $APIversion '&$top={0}' -f $ResultsPerPage $SkipToken ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Results = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query members for group '{0}': {1}" -f $GroupObject.objectId, $_.Exception.Message Write-Error $ErrorMessage break } foreach ($Result in $Results.ContentObject.value) { $OutputObject = $Result.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.User') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } $SkipToken = $Results.ContentObject.'odata.nextLink' -replace '^.*skiptoken', '&$skiptoken' } while ($SkipToken) } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADUserByUserPrincipalName.ps1
Get-AADUserByUserPrincipalName.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 2:53 PM Edited on: 2/16/2017 Created by: Mark Kraus Organization: Mitel Filename: Get-AADUserByUserPrincipalName.ps1 =========================================================================== .DESCRIPTION A description of the file. #> <# .SYNOPSIS Retrieves an Azure AD User by their UserPrincipalName .DESCRIPTION Retrieves an Azure AD User by their UserPrincipalName .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. .PARAMETER UserPrincipalName The user's UserPrincipalName e.g bob.testerton@adatum.com .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADUser = Get-AADUserByID -AccessToken $GraphAccessToken -UserPrincipalName bob.testerton@adatum.com .OUTPUTS MSGraphAPI.DirectoryObject.User .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserByUserPrincipalName #> function Get-AADUserByUserPrincipalName { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserByUserPrincipalName')] [OutputType('MSGraphAPI.DirectoryObject.User')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')] $AccessToken, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$UserPrincipalName, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$APIversion = '1.6' ) process { foreach ($UPN in $UserPrincipalName) { if (-not $pscmdlet.ShouldProcess($UserId)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}/{3}?api-version={4}' -f @( $BaseUrl $Tenant 'users' $UPN $APIversion ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query User '{0}': {1}" -f $UPN, $_.Exception.Message Write-Error $ErrorMessage return } $OutputObject = $Result.ContentObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.User') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Import-GraphApplication.ps1
Import-GraphApplication.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 8:32 AM Edited on: 3/30/2017 Created by: Mark Kraus Organization: Mitel Filename: Import-GraphApplication.ps1 =========================================================================== .DESCRIPTION Import-GraphApplication Function #> <# .SYNOPSIS Imports an exported Graph Application Object .DESCRIPTION Imports an exported Graph Application Object and retruns a Graph Application Object. .PARAMETER Path Specifies the XML files where the Graph Application Object was exported. .PARAMETER LiteralPath Specifies the XML files where the Graph Application Object was exported. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. .EXAMPLE PS C:\> $GraphApp = Import-GraphApplication -Path 'c:\GraphApp.xml' .NOTES See Export-GraphApplication for exporting Graph Application Objects See New-GraphApplication for creating new Graph Application Objects .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphApplication .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphApplication .LINK http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphApplication .OUTPUTS MSGraphAPI.Application #> function Import-GraphApplication { [CmdletBinding(DefaultParameterSetName = 'Path', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphApplication', ConfirmImpact = 'Low', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.Application')] param ( [Parameter(ParameterSetName = 'Path', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string[]]$Path, [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$LiteralPath ) Process { Switch ($PsCmdlet.ParameterSetName) { 'Path' { $ImportFiles = $Path $ImportParam = 'Path' } 'LiteralPath' { $ImportFiles = $LiteralPath $ImportParam = 'LiteralPath' } } foreach ($ImportFile in $ImportFiles) { if ($pscmdlet.ShouldProcess($ImportFile)) { $Params = @{ "$ImportParam" = $ImportFile ErrorAction = 'Stop' } try { $InObject = Import-Clixml @Params } catch { $ErrorMessage = "Unable to import from '{0}': {1}" -f @( $ImportFile $_.Exception.Message ) Write-Error $ErrorMessage } $InObject | New-GraphApplication } #End Should Process } #End Foreach } #End Process } #End Function
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADServicePrincipalAppRoleAssignedTo.ps1
Get-AADServicePrincipalAppRoleAssignedTo.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 12:49 PM Last Modified: 2/14/2017 Created by: Mark Kraus Organization: Mitel Filename: Get-AADServicePrincipalAppRoleAssignedTo.ps1 =========================================================================== .DESCRIPTION Get-AADServicePrincipalAppRoleAssignedTo Function #> <# .SYNOPSIS Returns the App Role Assigmnets for the given Service Principal .DESCRIPTION Returns the App Role Assigmnets for the given Service Principal. this can be used to see what users have been assigned access to an Azure AD SaaS Application (Service Principal) .PARAMETER ServicePrincipal A MSGraphAPI.DirectoryObject.ServicePrincipal object retruned by Get-AADServicePrinicpalbyDisplayName or Get-AADServicePrinicpalbyId .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADAppAssignments = $AADServicePrincipal | Get-AADServicePrincipalAppRoleAssignedTo .NOTES Additional information about the function. .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrincipalAppRoleAssignedTo #> function Get-AADServicePrincipalAppRoleAssignedTo { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrincipalAppRoleAssignedTo')] [OutputType('MSGraphAPI.DirectoryObject.AppRoleAssignment')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.DirectoryObject.ServicePrincipal')][object[]]$ServicePrincipal, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$APIVersion = '1.6' ) process { Foreach ($ServiceObject in $ServicePrincipal) { if (-not $pscmdlet.ShouldProcess($ServiceObject.objectId)) { return } $AccessToken = $ServiceObject._AccessToken $Application = $AccessToken.Application $Tenant = $Application.Tenant $SkipToken = $null do { $Url = '{0}/{1}/{2}/{3}/{4}?api-version={5}{6}' -f @( $BaseUrl $Tenant 'servicePrincipals' $ServiceObject.objectId 'appRoleAssignedTo' $APIversion $SkipToken ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Results = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query App Assignments for service principal '{0}': {1}" -f $ServiceObject.objectId, $_.Exception.Message Write-Error $ErrorMessage break } foreach ($Result in $Results.ContentObject.value) { $OutputObject = $Result.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.AppRoleAssignment') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } $SkipToken = $Results.ContentObject.'odata.nextLink' -replace '^.*skiptoken', '&$skiptoken' } while ($SkipToken) } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADServicePrinicpalbyId.ps1
Get-AADServicePrinicpalbyId.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 12:15 PM Created by: Mark Kraus Organization: Mitel Filename: Get-AADServicePrinicpalbyId.ps1 =========================================================================== .DESCRIPTION Get-AADServicePrinicpalbyId Function #> <# .SYNOPSIS Retrieves an Azure AD ServicePrincipal by the Object ID .DESCRIPTION Retrieves an Azure AD ServicePrincipal by the Object ID .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. .PARAMETER ObjectId The ServicePrincipal's ObjectID e.g d377e755-9365-400f-ab42-c0bf278c386e .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADUser = Get-AADServicePrincipalByID -AccessToken $GraphAccessToken -ObjectID d377e755-9365-400f-ab42-c0bf278c386e .OUTPUTS MSGraphAPI.DirectoryObject.ServicePrincipal .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrinicpalbyId #> function Get-AADServicePrinicpalbyId { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrinicpalbyId')] [OutputType('MSGraphAPI.DirectoryObject.ServicePrincipal')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')] $AccessToken, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$ObjectId, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$APIversion = '1.6' ) process { foreach ($ServiceId in $ObjectId) { if (-not $pscmdlet.ShouldProcess($ServiceId)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}/{3}?api-version={4}' -f @( $BaseUrl $Tenant 'servicePrincipals' $ServiceId $APIversion ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query User '{0}': {1}" -f $UserId, $_.Exception.Message Write-Error $ErrorMessage return } $OutputObject = $Result.ContentObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.ServicePrincipal') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Remove-AADAppRoleAssignment.ps1
Remove-AADAppRoleAssignment.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 1:26 PM Created by: Mark Kraus Organization: Mitel Filename: Remove-AADAppRoleAssignment.ps1 =========================================================================== .DESCRIPTION Remove-AADAppRoleAssignment Function #> <# .SYNOPSIS Removes an App Role Assignment .DESCRIPTION Removes an App Role Assignment. This can be used to remove a users access to an Azure AD SaaS Application (Service Principal) .PARAMETER AppRoleAssignment MSGraphAPI.DirectoryObject.AppRoleAssignment object .PARAMETER BaseUrl The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $Results = $AADAppAssignments | Remove-AADAppRoleAssignment .OUTPUTS MSGraphAPI.RequestResult .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Remove-AADAppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Add-AADAppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserAppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrincipalAppRoleAssignedTo #> function Remove-AADAppRoleAssignment { [CmdletBinding(ConfirmImpact = 'High', SupportsPaging = $false, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Remove-AADAppRoleAssignment', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.RequestResult')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.DirectoryObject.AppRoleAssignment')][object[]]$AppRoleAssignment, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$APIVersion = '1.6' ) Process { foreach ($AppRole in $AppRoleAssignment) { if (-not $pscmdlet.ShouldProcess($AppRole.ObjectId)) { return } $AccessToken = $AppRole._AccessToken $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}/{3}/{4}/{5}?api-version={6}' -f @( $BaseUrl $Tenant 'users' $AppRole.principalId 'appRoleAssignments' [System.Web.HttpUtility]::UrlEncode($AppRole.ObjectId) $APIversion ) $Params = @{ Uri = $Url Method = 'DELETE' AccessToken = $AccessToken ErrorAction = 'Stop' } try { Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to remove App Assignments for App Role Assignment '{0}': {1}" -f $AppRole.ObjectId, $_.Exception.Message Write-Error $ErrorMessage return } } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADGroupByDisplayName.ps1
Get-AADGroupByDisplayName.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/14/2017 5:53 AM Edited on: 4/22/2017 Created by: Mark Kraus Organization: Filename: Get-AADGroupByDisplayName.ps1 =========================================================================== .DESCRIPTION Get-AADGroupByDisplayName Function #> <# .SYNOPSIS Retrieves an Azure AD Group by the provided Display name .DESCRIPTION Searches Azure Active Directory Graph API for a Group by the provided display name. The provided displayname must be a full case-insensitive match. Partial matches and wildcards are not supported. A MSGraphAPI.DirectoryObject.Group object will be returned for the matching group. Get-AADGroupByDisplayName requires a MSGraphAPI.Oauth.AccessToken issued for the https://graph.windows.net resource. See the Get-GraphOauthAccessToken help for more information. Get-Help -Name Get-GraphOauthAccessToken -Parameter Resource .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. Access Token must be issued for the https://graph.windows.net resource. .PARAMETER DisplayName The Group's Display Name. This must be an exact case-insensitive match and does not support wildcards or partial matches. .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion Version of the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADGroup = Get-AADGroupByDisplayName -AccessToken $GraphAccessToken -DisplayName 'Adataum Finance' .OUTPUTS MSGraphAPI.DirectoryObject.Group .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByDisplayName .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupMember .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByID .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .LINK https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations .LINK https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options#filter #> function Get-AADGroupByDisplayName { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADGroupByDisplayName')] [OutputType('MSGraphAPI.DirectoryObject.Group')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')] $AccessToken, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string[]]$DisplayName, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$APIversion = '1.6' ) process { foreach ($GroupName in $DisplayName) { if (-not $pscmdlet.ShouldProcess($ServiceId)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $Url = '{0}/{1}/{2}?api-version={3}&$filter=displayName+eq+%27{4}%27' -f @( $BaseUrl $Tenant 'groups' $APIversion [System.Web.HttpUtility]::UrlEncode($GroupName) ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query Group '{0}': {1}" -f $GroupName, $_.Exception.Message Write-Error -Message $ErrorMessage -Exception $_.Exception return } foreach ($ServiceObject in $Result.ContentObject.value) { $OutputObject = $ServiceObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.Group') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Invoke-GraphRequest.ps1
Invoke-GraphRequest.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 6:14 AM Edited on: 2/16/2017 Created by: Mark Kraus Organization: Mitel Filename: Invoke-GraphRequest.ps1 =========================================================================== .DESCRIPTION Invoke-GraphRequest Function #> <# .SYNOPSIS Submits an access reqest to the Graph API .DESCRIPTION This is esentially an Invoke-ebRequest wrapper that handles the Access Token lifecycle and Authorization header. This requires a valid Access Token in the form of a MSGraphAPI.Oauth.AccessToken and returns a MSGraphAPI.RequestResult Object .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. .PARAMETER Uri Specifies the Uniform Resource Identifier (URI) of the Internet resource to which the web request is sent. Enter a URI. This parameter supports HTTP, HTTPS, FTP, and FILE values. .PARAMETER Method Specifies the method used for the web request. The acceptable values for this parameter are: - Default - Delete - Get - Head - Merge - Options - Patch - Post - Put - Trace .PARAMETER Body Specifies the body of the request. The body is the content of the request that follows the headers. The Body parameter can be used to specify a list of query parameters or specify the content of the response. When the input is a GET request and the body is an IDictionary (typically, a hash table), the body is added to the URI as query parameters. For other GET requests, the body is set as the value of the request body in the standard name=value format. When the body is a form, or it is the output of an Invoke-GraphRequest call, Windows PowerShell sets the request content to the form fields. .PARAMETER Headers Specifies the headers of the web request. Enter a hash table or dictionary. Any Authirzation header supplied here will be overwritten by what is provided in the Access Token. To set UserAgent headers, use the UserAgent parameter. You cannot use this parameter to specify UserAgent or cookie headers. .PARAMETER TimeoutSec Specifies how long the request can be pending before it times out. Enter a value in seconds. The default value, 0, specifies an indefinite time-out. A Domain Name System (DNS) query can take up to 15 seconds to return or time out. If your request contains a host name that requires resolution, and you set TimeoutSec to a value greater than zero, but less than 15 seconds, it can take 15 seconds or more before a WebException is thrown, and your request times out. .PARAMETER ContentType Specifies the content type of the web request. The default value is 'application/json' .EXAMPLE PS C:\> Invoke-GraphRequest -AccessToken $value1 -Uri 'Value2' -Method $value3 .OUTPUTS MSGraphAPI.RequestResult .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Invoke-GraphRequest .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .LINK https://graph.microsoft.io/en-us/docs .LINK https://msdn.microsoft.com/en-us/library/azure/hh974476.aspx #> function Invoke-GraphRequest { [CmdletBinding(ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Invoke-GraphRequest', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.RequestResult')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')]$AccessToken, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.Uri]$Uri, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = 'Default', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Object]$Body, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [System.Collections.IDictionary]$Headers, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateRange(0,2147483647)] [System.Int32]$TimeoutSec, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [System.String]$ContentType = 'application/json' ) Process { Try { Write-Verbose "Performing token refresh" $AccessToken | Update-GraphOauthAccessToken -ErrorAction Stop } Catch { $ErrorMessage = "Unable to refresh Access Token '{0}': {1}" -f $AccessToken.GUID, $_.Exception.Message Write-Error $ErrorMessage return } if (-not $pscmdlet.ShouldProcess("$Uri")) { Return } Write-Verbose "Set base parameters" $Params = @{ ContentType = $ContentType Uri = $Uri WebSession = $AccessToken.Session Method = $Method ErrorAction = 'Stop' } if ($Body) { Write-Verbose "Setting Body Parameter" $Params['Body'] = $Body } if ($TimeoutSec) { Write-Verbose "Setting TimeoutSec Parameter" $Params['TimeoutSec'] = $TimeoutSec } Write-Verbose "Setting Headers Parameter" $Params['Headers'] = @{ } if ($Headers) { Write-Verbose "Setting user supplied headers" $Params['Headers'] = $Headers } Write-Verbose "Setting Authorization header" $Params['Headers']['Authorization'] = 'Bearer {0}' -f $AccessToken.GetAccessToken() $RequestedDate = Get-Date try { $Result = Invoke-WebRequest @Params $ReceivedDate = Get-Date } catch { $response = $_.Exception.Response $Stream = $response.GetResponseStream() $Stream.Position = 0 $StreamReader = New-Object System.IO.StreamReader $Stream $ResponseBody = $StreamReader.ReadToEnd() $ErrorMessage = "Unable to query Uri '{0}': {1}: {2}" -f $Uri, $_.Exception.Message, $ResponseBody Set-Variable -Scope global -Name _invokeGraphRequestException -Value $_ Write-Error -message $ErrorMessage -Exception $_.Exception return } Write-Verbose "Truncating Authorization header" try { $Params['Headers']['Authorization'] = '{0}...{1}<truncated>' -f $Params.Headers.Authorization.Substring(0, 25), $Params.Headers.Authorization.Substring(($Params.Headers.Authorization.Length - 11), 10) } catch { Write-Verbose "No Authorization header to truncate" } switch ($Result.Headers.'Content-Type') { { $_ -match 'application/json' } { Write-Verbose "Converting result from JSON to PSObject" $ConentObject = $Result.Content | ConvertFrom-Json -ErrorAction SilentlyContinue break } { $_ -match 'application/xml' } { Write-Verbose "Converting result from XML to PSObject" [xml]$ConentObject = $Result.Content break } default { Write-Verbose "Unhandled Content-Type. ContentObject will be raw." $ConentObject = $Result.Content } } Write-Verbose "Setting LastRequestDate on Access Token" $AccessToken.LastRequestDate = $RequestedDate [pscustomobject]@{ PSTypeName = 'MSGraphAPI.RequestResult' Result = $Result Uri = $Uri Headers = $Params.Headers InvokeWebRequestParameters = $Params ContentType = $ContentType TimeoutSec = $TimeoutSec Body = $Body RequestedDate = $RequestedDate RecievedDate = $ReceivedDate AccessToken = $AccessToken ContentObject = $ConentObject } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/New-GraphOauthAccessToken.ps1
New-GraphOauthAccessToken.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/9/2017 5:46 AM Created by: Mark Kraus Organization: Mitel Filename: New-GraphOauthAccessToken.ps1 =========================================================================== .DESCRIPTION New-GraphOauthAccessToken Function #> <# .SYNOPSIS Creates an MSGraphAPI.Oauth.AccessToken Object .DESCRIPTION This creates a MSGraphAPI.Oauth.AccessToken object. This only creates the objects used in this module. It does not make any API calls. To retrieve an OAuth Access Token, use Get-GraphOauthAccessToken .PARAMETER Application A MSGraphAPI.Application object. See New-GraphApplication .PARAMETER AccessTokenCredential A PSCredential Object containing the access_token as a password. Username is ignored. .PARAMETER RefreshTokenCredential A PSCredential Object containing the refresh_token as a password. Username is ignored. .PARAMETER RequestedDate The date and time the current access_token was requested .PARAMETER Response A PSObject containing the last response from the API converted from JSON and striped of the access_token and refresh_token .PARAMETER ResponseHeaders A headers dictionary retruned from the API. .PARAMETER LastRequestDate A datetime of the last API call made using thie token. .PARAMETER Session The Session object used to access the API. This creates a consistent experience accross API cals by mimicing a browser session. .PARAMETER GUID A GUID to identify the Graph OAuth Token Object. If one is not provided, a new GUID will be generated. This is used for internal reference only and is not consumed by the Graph API. .EXAMPLE PS C:\> New-GraphOauthAccessToken -Application $GraphApp -AccessTokenCredential $AccessTokenCredential -RefreshTokenCredential $RefreshTokenCredential -RequestedDate (get-date) -Response $Response -ResponseHeaders $Result.Headers -LastRequestDate (get-date) .NOTES See Get-GraphOauthAccessToken .OUTPUTS MSGraphAPI.Oauth.AccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Update-GraphOauthAccessToken #> function New-GraphOauthAccessToken { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Creates in memory object only.")] [CmdletBinding(ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphOauthAccessToken')] [OutputType('MSGraphAPI.Oauth.AccessToken')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Application')]$Application, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential]$AccessTokenCredential, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential]$RefreshTokenCredential, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [datetime]$RequestedDate, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [System.Management.Automation.PSObject]$Response, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [System.Management.Automation.PSObject]$ResponseHeaders, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [datetime]$LastRequestDate, [Parameter(Mandatory = $false, ValueFromPipeline = $false)] [Microsoft.PowerShell.Commands.WebRequestSession]$Session, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [guid]$GUID = [Guid]::NewGuid() ) Process { [pscustomobject]@{ PSTypeName = 'MSGraphAPI.Oauth.AccessToken' Application = $Application AccessTokenCredential = $AccessTokenCredential RefreshTokenCredential = $RefreshTokenCredential RequestedDate = $RequestedDate Response = $Response | Select-Object -property * -ExcludeProperty access_token, refresh_token ResponseHeaders = $ResponseHeaders LastRequestDate = $LastRequestDate Session = $Session GUID = $GUID } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Export-GraphOauthAccessToken.ps1
Export-GraphOauthAccessToken.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/9/2017 5:25 AM Edited on: 2/16/2017 Created by: Mark Kraus Organization: Mitel Filename: Export-GraphOauthAccessToken.ps1 =========================================================================== .DESCRIPTION Export-GraphOauthAccessTokenFunction #> <# .SYNOPSIS Exports a Graph OAuth Access Token object to a file. .DESCRIPTION Used to Export a Graph OAuth Access Token object to a file so it can later be imported. .PARAMETER Path Specifies the path to the file where the XML representation of the Graph AccessToken object will be stored .PARAMETER LiterlPath Specifies the path to the file where the XML representation of the Graph AccessToken object will be stored. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. .PARAMETER Encoding Specifies the type of encoding for the target file. The acceptable values for this parameter are: -- ASCII -- UTF8 -- UTF7 -- UTF32 -- Unicode -- BigEndianUnicode -- Default -- OEM The default value is Unicode. .PARAMETER AccessToken Graph OAuth Acess Token Object to be exported. .EXAMPLE PS C:\> $GraphAccessToken | Export-GraphOAuthAccessToken -Path 'c:\GraphAccessToken.xml' .OUTPUTS System.IO.FileInfo, System.IO.FileInfo .NOTES This is an Export-Clixml wrapper. See Import-GraphOauthAccessToken for importing exported Graph AccessToken Objects See Get-GraphOauthAccessToken for obtaining a Graph AccessToken Objects .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken #> function Export-GraphOauthAccessToken { [CmdletBinding(DefaultParameterSetName = 'Path', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOAuthAccessToken', ConfirmImpact = 'Low', SupportsShouldProcess = $true)] [OutputType([System.IO.FileInfo])] param ( [Parameter(ParameterSetName = 'Path', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$Path, [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string]$LiterlPath, [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Parameter(ParameterSetName = 'Path', Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateSet('ASCII', 'UTF8', 'UTF7', 'UTF32', 'Unicode', 'BigEndianUnicode', 'Default', 'OEM')] [string]$Encoding = 'Unicode', [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Parameter(ParameterSetName = 'Path', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [pstypename('MSGraphAPI.OAuth.AccessToken')] [Alias('Token')] [System.Management.Automation.PSObject]$AccessToken ) Process { # Strip the ScriptProperty properties to prevent cleartext secrets in the export # These will be reconstituted when imported $ExportProperties = $AccessToken.psobject.Properties.where({ $_.MemberType -ne 'ScriptProperty' }).Name Write-Verbose "Propertes: $($ExportProperties -join ' ')" $ExportToken = $AccessToken | Select-Object -Property $ExportProperties switch ($PsCmdlet.ParameterSetName) { 'Path' { $Params = @{ Encoding = $Encoding Path = $Path InputObject = $ExportToken } $Target = $Path } 'LiteralPath' { $Params = @{ Encoding = $Encoding LiteralPath = $LiterlPath InputObject = $ExportToken } $Target = $LiteralPath } } if ($pscmdlet.ShouldProcess($Target)) { Export-Clixml @Params } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/New-GraphApplication.ps1
New-GraphApplication.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 7:34 AM Created by: Mark Kraus Organization: Mitel Filename: New-GraphApplication.ps1 =========================================================================== .DESCRIPTION New-GraphApplication Function #> <# .SYNOPSIS Creates a Graph Application object .DESCRIPTION Creates a Graph Application object containing data used by various cmdltes to define the parameters of the App registered on Azure AD. This does not make any calls to Azure or the Gtaph API. The Application will be inbeded in the Graph OAuthToken objects. The MSGraphAPI.Application object contains the following properties: Name Name of the Application Description Description of the Application UserAgent The User-Agent header the Application will use to access the Graph API ClientID The Client ID of the Registered Azure App RedirectUri The Redirect URI of the Registered Azure App ClientCredential A PS Crednetial containing the Client ID as the username and the Client Secret as the password UserCredential The Reddit Username and password of the developer account used for a Script application GUID A GUID to identitfy the application wihin this module (not consumed or used by Azure or Graph) .PARAMETER Name Name of the Graph App. This does not need to match the name registered on Azure. It is used for convenient identification and ducomentation purposes only. .PARAMETER ClientCredential A PScredential object containging the Client ID as the Username and the Client Secret as the password. .PARAMETER RedirectUri Redirect URI as registered on Azure for the App. This must match exactly as entered in the App definition or authentication will fail. .PARAMETER Tenant The Azure/Office365 Tenant ID. e.g. adadtum.onmicrosft.com .PARAMETER Description Description of the Graph App. This is not required or used for anything. It is provided for convenient identification and documentation purposes only. .PARAMETER GUID A GUID to identify the application. If one is not perovided, a new GUID will be generated. .EXAMPLE PS C:\> $ClientCredential = Get-Credential PS C:\> $Params = @{ Name = 'MyGraphApp' Description = 'My Graph Application!' ClientCredential = $ClientCredential RedirectUri = 'https://adataum/ouath?' UserAgent = 'Windows:PowerShell:GraphApplication' } PS C:\> $GraphApp = New-GraphApplication @Params .OUTPUTS MSGraphAPI.Application .LINK http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphApplication .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphApplication .Link http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphApplication #> function New-GraphApplication { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "", Justification = "Creates in memory object only.")] [CmdletBinding(ConfirmImpact = 'None', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphApplication')] [OutputType('MSGraphAPI.Application')] param ( [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Alias('AppName')] [string]$Name, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Alias('ClientInfo')] [System.Management.Automation.PSCredential]$ClientCredential, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [ValidateScript({ [system.uri]::IsWellFormedUriString( $_, [System.UriKind]::Absolute ) })] [string]$RedirectUri, [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $true)] [string]$Tenant, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$Description, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [System.Guid]$GUID = [system.guid]::NewGuid() ) Process { [pscustomobject]@{ PSTypeName = 'MSGraphAPI.Application' Name = $Name Description = $Description ClientCredential = $ClientCredential RedirectUri = $RedirectUri Tenant = $Tenant GUID = $GUID } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Add-AADAppRoleAssignment.ps1
Add-AADAppRoleAssignment.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/13/2017 1:59 PM Created by: Mark Kraus Organization: Mitel Filename: Add-AADAppRoleAssignment.ps1 =========================================================================== .DESCRIPTION Add-AADAppRoleAssignment Function #> <# .SYNOPSIS Adds an Azure AD App Role Assignment for the given user to the given servcie principal .DESCRIPTION Adds an Azure AD App Role Assignment for the given user to the given servcie principal .PARAMETER ServicePrincipal MSGraphAPI.DirectoryObject.ServicePrincipal retruned by the Get-AADServicePrincipal* cmdlets .PARAMETER User MSGraphAPI.DirectoryObject.User object returnedfrom the Get-AADUser* cmdltes .PARAMETER BaseUrl The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .PARAMETER RoleID This is the Role ID that will be added for the user. The dafault is 00000000-0000-0000-0000-000000000000 .EXAMPLE PS C:\> Add-AADAppRoleAssignment -ServicePrincipal $AADServicePrincipal -User $AADUser .OUTPUTS MSGraphAPI.DirectoryObject.AppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Add-AADAppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Remove-AADAppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserAppRoleAssignment .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADServicePrincipalAppRoleAssignedTo #> function Add-AADAppRoleAssignment { [CmdletBinding(ConfirmImpact = 'Medium', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Add-AADAppRoleAssignment', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.DirectoryObject.AppRoleAssignment')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [object[]]$ServicePrincipal, [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [object[]]$User, [string]$BaseURL = 'https://graph.windows.net', [string]$APIVersion = '1.6', [string]$RoleID = '00000000-0000-0000-0000-000000000000' ) Process { foreach ($ServiceObject in $ServicePrincipal) { foreach ($UserObject in $User) { $ProcessText = "User: '{0}' ServicePrincipal: '{1}' RoleID: '{2}'" -f $UserObject.ObjectId, $ServiceObject.ObjectId, $RoleID if (-not $pscmdlet.ShouldProcess($ProcessText)) { continue } $AccessToken = $ServiceObject._AccessToken $Application = $AccessToken.Application $Tenant = $Application.Tenant $Body = @{ id = $RoleID resourceId = $ServiceObject.ObjectId principalId = $UserObject.ObjectId } | ConvertTo-Json $Url = '{0}/{1}/{2}/{3}/{4}?api-version={5}' -f @( $BaseUrl $Tenant 'users' $UserObject.ObjectId 'appRoleAssignments' $APIversion ) $Params = @{ Uri = $Url Body = $Body Method = 'POST' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Result = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to add App Assignments for User '{0}' to ServicePrincipal '{1}': {2}" -f $UserObject.ObjectId, $ServiceObject.ObjectId, $_.Exception.Message Write-Error $ErrorMessage return } $OutputObject = $Result.ContentObject.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.AppRoleAssignment') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Export-GraphApplication.ps1
Export-GraphApplication.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 8:26 AM Edited on: 2/14/2017 Created by: Mark Kraus Organization: Mitel Filename: Export-GraphApplication.ps1 =========================================================================== .DESCRIPTION Export-GraphApplication Function #> <# .SYNOPSIS Exports a Graph Application object to a file. .DESCRIPTION Used to Export a Graph Application object to a file so it can later be imported. .PARAMETER Path Specifies the path to the file where the XML representation of the Graph Application object will be stored .PARAMETER LiterlPath Specifies the path to the file where the XML representation of the Graph Application object will be stored. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. .PARAMETER Encoding Specifies the type of encoding for the target file. The acceptable values for this parameter are: -- ASCII -- UTF8 -- UTF7 -- UTF32 -- Unicode -- BigEndianUnicode -- Default -- OEM The default value is Unicode. .PARAMETER Application Graph Application Object to be exported. .EXAMPLE PS C:\> $GraphApp | Export-RedditApplication -Path 'c:\GraphApp.xml' .OUTPUTS System.IO.FileInfo, System.IO.FileInfo .NOTES This is an Export-Clixml wrapper. See Import-GraphApplication for importing exported Graph Application Objects See New-GraphApplication for creating new Graph Application objects .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphApplication .Link http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphApplication .Link http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphApplication #> function Export-GraphApplication { [CmdletBinding(DefaultParameterSetName = 'Path', ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphApplication', SupportsShouldProcess = $true)] [OutputType([System.IO.FileInfo])] param ( [Parameter(ParameterSetName = 'Path', Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$Path, [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromRemainingArguments = $true)] [ValidateNotNullOrEmpty()] [string]$LiterlPath, [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Parameter(ParameterSetName = 'Path', Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [ValidateSet('ASCII', 'UTF8', 'UTF7', 'UTF32', 'Unicode', 'BigEndianUnicode', 'Default', 'OEM')] [string]$Encoding = 'Unicode', [Parameter(ParameterSetName = 'LiteralPath', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [Parameter(ParameterSetName = 'Path', Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [pstypename('MSGraphAPI.Application')] [Alias('App', 'GraphApplication')] [System.Management.Automation.PSObject]$Application ) Process { $ExportProperties = $Application.psobject.Properties.where({ $_.MemberType -ne 'ScriptProperty' }).Name Write-Verbose "Propertes: $($ExportProperties -join ' ')" $ExportApplication = $Application | Select-Object -Property $ExportProperties switch ($PsCmdlet.ParameterSetName) { 'Path' { $Params = @{ Encoding = $Encoding Path = $Path InputObject = $ExportApplication } $Target = $Path } 'LiteralPath' { $Params = @{ Encoding = $Encoding LiteralPath = $LiterlPath InputObject = $ExportApplication } $Target = $LiteralPath } } if ($pscmdlet.ShouldProcess("Target")) { Export-Clixml @Params } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADUserAppRoleAssignment.ps1
Get-AADUserAppRoleAssignment.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/14/2017 5:17 AM Created by: Mark Kraus Organization: Mitel Filename: Get-AADUserAppRoleAssignment.ps1 =========================================================================== .DESCRIPTION Get-AADUserAppRoleAssignment Function #> <# .SYNOPSIS Returns the App Role Assigmnets for the given user .DESCRIPTION Returns the App Role Assigmnets for the given user. This can be used to see what applications to which Azure AD SaaS Applications (Service Principals) the user has been assigned access. .PARAMETER User A MSGraphAPI.DirectoryObject.User object retruned by Get-AADUser* cmdlets .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER APIVersion version og the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADAppAssignments = $AADUser | Get-AADUserAppRoleAssignment .NOTES Additional information about the function. .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserAppRoleAssignment #> function Get-AADUserAppRoleAssignment { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserAppRoleAssignment')] [OutputType('MSGraphAPI.DirectoryObject.AppRoleAssignment')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.DirectoryObject.User')] [object[]]$User, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$APIVersion = '1.6' ) process { Foreach ($UserObject in $User) { if (-not $pscmdlet.ShouldProcess($UserObject.objectId)) { return } $AccessToken = $UserObject._AccessToken $Application = $AccessToken.Application $Tenant = $Application.Tenant $SkipToken = $null do { $Url = '{0}/{1}/{2}/{3}/{4}?api-version={5}{6}' -f @( $BaseUrl $Tenant 'users' $UserObject.objectId 'appRoleAssignments' $APIversion $SkipToken ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Results = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query App Assignments for service principal '{0}': {1}" -f $UserObject.objectId, $_.Exception.Message Write-Error $ErrorMessage break } foreach ($Result in $Results.ContentObject.value) { $OutputObject = $Result.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.AppRoleAssignment') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } $SkipToken = $Results.ContentObject.'odata.nextLink' -replace '^.*skiptoken', '&$skiptoken' } while ($SkipToken) } } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-AADUserAll.ps1
Get-AADUserAll.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/14/2017 6:38 AM Created by: Mark Kraus Organization: Mitel Filename: Get-AADUserAll.ps1 =========================================================================== .DESCRIPTION Get-AADUserAll Function #> <# .SYNOPSIS Returns All Azure AD Users .DESCRIPTION Returns All Azure AD Users .PARAMETER AccessToken MSGraphAPI.Oauth.AccessToken object obtained from Get-GraphOauthAccessToken. .PARAMETER BaseURL The Azure AD Graph Base URL. This is not required. Deafult https://graph.windows.net .PARAMETER Filter The Azure AD Graph API $filter to be applied. The string will be url encoded. .PARAMETER APIVersion version of the API to use. Default is 1.6 .EXAMPLE PS C:\> $AADUsers = Get-AADUserAll -AccesToken $GraphAccessToken .OUTPUTS MSGraphAPI.DirectoryObject.User .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserAll #> function Get-AADUserAll { [CmdletBinding(SupportsShouldProcess = $true, HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-AADUserAll')] [OutputType('MSGraphAPI.DirectoryObject.User')] param ( [Parameter(Mandatory = $true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [PSTypeName('MSGraphAPI.Oauth.AccessToken')] $AccessToken, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$filter, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$BaseUrl = 'https://graph.windows.net', [Parameter(ValueFromPipelineByPropertyName = $true)] [string]$APIVersion = '1.6' ) process { if (-not $pscmdlet.ShouldProcess($AccessToken.GUID)) { return } $Application = $AccessToken.Application $Tenant = $Application.Tenant $SkipToken = $null do { $Url = '{0}/{1}/{2}?api-version={3}{4}{5}' -f @( $BaseUrl $Tenant 'users' $APIversion '&$filter={0}' -f [System.Web.HttpUtility]::UrlEncode($Filter) $SkipToken ) $Params = @{ Uri = $Url Method = 'GET' AccessToken = $AccessToken ErrorAction = 'Stop' } try { $Results = Invoke-GraphRequest @Params } catch { $ErrorMessage = "Unable to query members for user: {0}" -f $_.Exception.Message Write-Error $ErrorMessage break } foreach ($Result in $Results.ContentObject.value) { $OutputObject = $Result.psobject.copy() $OutputObject.psobject.TypeNames.Insert(0, 'MSGraphAPI.DirectoryObject.User') $OutputObject | Add-Member -MemberType NoteProperty -Name _AccessToken -Value $AccessToken $OutputObject } $SkipToken = $Results.ContentObject.'odata.nextLink' -replace '^.*skiptoken', '&$skiptoken' } while ($SkipToken) } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-GraphOauthAccessToken.ps1
Get-GraphOauthAccessToken.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 10:26 AM Edited on:: 4/22/2017 Created by: Mark Kraus Organization: Filename: Get-GraphOauthAccessToken.ps1 =========================================================================== .DESCRIPTION Get-GraphOauthAccessToken Function #> <# .SYNOPSIS Retieves an OAuth Access Token from Microsoft .DESCRIPTION Takes an OAuth Acces Authorization code returned from Get-GraphOauthAuthorizationCode and requests an OAuth Access Token for the provided resource from Microsoft. A MSGraphAPI.Oauth.AccessToken object is returned. This object is required for making calls to Invoke-GraphRequest and many other functions provided by this module. .PARAMETER AuthenticationCode The Authentication Code returned from Get-GraphOauthAuthorizationCode .PARAMETER BaseURL The Base URL used for retrieving OAuth Acces Tokens. This is not required. the default is https://login.microsoftonline.com/common/oauth2/token .PARAMETER Resource The resource for which the OAuth Access token will be requested. The default is https://graph.microsoft.com You must set the resource to match the endpoints your token will be valid for. Microsft Graph: https://graph.microsoft.com Azure AD Graph API: https://graph.windows.net Office 365 Unified Mail API: https://outlook.office.com If you need to access more than one resrouce, you will need to request multiple OAuth Access Tokens and use the correct tokens for the correct endpoints. .EXAMPLE PS C:\> $ClientCredential = Get-Credential PS C:\> $Params = @{ Name = 'MyGraphApp' Description = 'My Graph Application!' ClientCredential = $ClientCredential RedirectUri = 'https://adataum/ouath?' UserAgent = 'Windows:PowerShell:GraphApplication' } PS C:\> $GraphApp = New-GraphApplication @Params PS C:\> $GraphAuthCode = Get-GraphOauthAuthorizationCode -Application $GraphApp PS C:\> $GraphAccessToken = Get-GraphOauthAccessToken -AuthenticationCode $GraphAuthCode .OUTPUTS MSGraphAPI.Oauth.AccessToken .NOTES See Get-GraphOauthAuthorizationCode for obtaining a OAuth Authorization code. See Export-GraphOauthAccessToken for exporting Graph Acess Token Objects See Import-GraphOauthAccessToken for importing exported Graph AcessToken Objects See Update-GraphOauthAccessToken for refreshing the Graph Access Token .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAuthorizationCode .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Export-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Import-GraphOauthAccessToken .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Update-GraphOauthAccessToken .LINK https://graph.microsoft.io/en-us/docs/authorization/auth_overview #> function Get-GraphOauthAccessToken { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText","")] [CmdletBinding(ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAccessToken', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.Oauth.AccessToken')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [pstypename('MSGraphAPI.Oauth.AuthorizationCode')] [ValidateNotNullOrEmpty()] [Alias('AuthCode')] $AuthenticationCode, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Alias('URL')] [string]$BaseURL = 'https://login.microsoftonline.com/common/oauth2/token', [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$Resource = 'https://graph.microsoft.com' ) Process { $Application = $AuthenticationCode.Application if (-not $pscmdlet.ShouldProcess($Application.ClientID)) { return } $Client_Id = [System.Web.HttpUtility]::UrlEncode($Application.ClientID) $Redirect_uri = [System.Web.HttpUtility]::UrlEncode($Application.RedirectUri) $Resource_encoded = [System.Web.HttpUtility]::UrlEncode($Resource) $AuthCode = [System.Web.HttpUtility]::UrlEncode($AuthenticationCode.GetAuthCode()) $Body = @( 'grant_type=authorization_code' '&redirect_uri={0}' -f $Redirect_uri '&client_id={0}' -f $Client_Id '&code={0}' -f $AuthCode '&resource={0}' -f $Resource_encoded '&client_secret={0}' -f [System.Web.HttpUtility]::UrlEncode( $Application.GetClientSecret()) ) -join '' Write-Verbose "Body: $Body" $RequestedDate = Get-Date $Params = @{ Uri = $BaseURL Method = 'POST' ContentType = "application/x-www-form-urlencoded" Body = $Body ErrorAction = 'Stop' SessionVariable = 'Session' } try { Write-Verbose "Retrieving OAuth Access Token from $BaseURL..." $Result = Invoke-WebRequest @Params } catch { $_.Exception. psobject. TypeNames. Insert(0,'MSGraphAPI.Oauth.Exception') Write-Error -Exception $_.Exception return } try { $Content = $Result.Content | ConvertFrom-Json -ErrorAction Stop } Catch { $Params = @{ MemberType = 'NoteProperty' Name = 'Respone' Value = $Result } $_.Exception | Add-Member @Params Write-Error -Exception $_.Exception return } $SecureAccessToken = $Content.access_token | ConvertTo-SecureString -AsPlainText -Force $SecureRefreshToken = $Content.refresh_token | ConvertTo-SecureString -AsPlainText -Force $AccessTokenCredential = [pscredential]::new('access_token', $SecureAccessToken ) $RefreshTokenCredential = [pscredential]::new('refresh_token', $SecureRefreshToken) $Params = @{ Application = $Application AccessTokenCredential = $AccessTokenCredential RefreshTokenCredential = $RefreshTokenCredential RequestedDate = $RequestedDate Response = $Content | Select-Object -property * -ExcludeProperty access_token, refresh_token ResponseHeaders = $Result.Headers LastRequestDate = $RequestedDate Session = $Session GUID = [guid]::NewGuid() } New-GraphOauthAccessToken @Params } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Public/Get-GraphOauthAuthorizationCode.ps1
Get-GraphOauthAuthorizationCode.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 8:48 AM Edited on: 2/27/2017 Created by: Mark Kraus Organization: Mitel Filename: Get-GraphOauthAuthorizationCode.ps1 =========================================================================== .DESCRIPTION Get-GraphOauthAuthorizationCode Function #> <# .SYNOPSIS Retrieves an OAuth Authorization code form Microsoft .DESCRIPTION Retrieves an OAuth Authorization code form Microsoft for a given Graph Application. This commandlet requires an interactive session as you will need to provide your credentials and authorize the Graph Application. The OAuth Authorization code will be used to obtain an OAuth Access Token. .PARAMETER Application MSGraphAPI.Application object (See New-GraphApplication) .PARAMETER BaseURL The base URL for obtaining an OAuth Authorization Code form Microsoft. This is provided in the event that a different URL is required. The default is https://login.microsoftonline.com/common/oauth2/authorize .EXAMPLE PS C:\> $GraphAuthCode = Get-GraphOauthAuthorizationCode -Application $GraphApp .OUTPUTS MSGraphAPI.Oauth.AuthorizationCode .LINK http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAuthorizationCode .LINK https://graph.microsoft.io/en-us/docs/authorization/auth_overview .LINK http://psmsgraph.readthedocs.io/en/latest/functions/New-GraphApplication #> function Get-GraphOauthAuthorizationCode { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [CmdletBinding(ConfirmImpact = 'Low', HelpUri = 'http://psmsgraph.readthedocs.io/en/latest/functions/Get-GraphOauthAuthorizationCode', SupportsShouldProcess = $true)] [OutputType('MSGraphAPI.Oauth.AuthorizationCode')] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Alias('App')] [PSTypeName('MSGraphAPI.Application')]$Application, [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [Alias('URL')] [string]$BaseURL = 'https://login.microsoftonline.com/common/oauth2/authorize' ) Process { if (-not $pscmdlet.ShouldProcess($Application.ClientID)) { return } $Client_Id = [System.Web.HttpUtility]::UrlEncode($Application.ClientId) $Redirect_Uri = [System.Web.HttpUtility]::UrlEncode($Application.RedirectUri) $Url = "{0}?response_type=code&redirect_uri={1}&client_id={2}" -f @( $BaseURL $Redirect_Uri $Client_Id ) Write-Verbose "URL: '$URL'" $Params = @{ TypeName = 'System.Windows.Forms.Form' Property = @{ Width = 440 Height = 640 } } $Form = New-Object @Params $Params = @{ TypeName = 'System.Windows.Forms.WebBrowser' Property = @{ Width = 420 Height = 600 Url = $Url } } $Web = New-Object @Params $DocumentCompleted_Script = { if ($web.Url.AbsoluteUri -match "error=[^&]*|code=[^&]*") { $form.Close() } } # ScriptErrorsSuppressed must be $false or AD FS tenants will fail on Windows Integrated Authentication pages $web.ScriptErrorsSuppressed = $false $web.Add_DocumentCompleted($DocumentCompleted_Script) $form.Controls.Add($web) $form.Add_Shown({ $form.Activate() }) [void]$form.ShowDialog() $QueryOutput = [System.Web.HttpUtility]::ParseQueryString($web.Url.Query) $Response = @{ } foreach ($key in $queryOutput.Keys) { $Response["$key"] = $QueryOutput[$key] } $SecAuthCode = 'NOAUTHCODE' | ConvertTo-SecureString -AsPlainText -Force $AuthCodeCredential = [pscredential]::new('NOAUTHCODE', $SecAuthCode) if ($Response.Code) { $SecAuthCode = $Response.Code | ConvertTo-SecureString -AsPlainText -Force $AuthCodeCredential = [pscredential]::new('AuthCode', $SecAuthCode) $Response.Remove('Code') } [pscustomobject]@{ PSTypeName = 'MSGraphAPI.Oauth.AuthorizationCode' AuthCodeCredential = $AuthCodeCredential ResultURL = $web.Url.psobject.copy() Application = $Application AuthCodeBaseURL = $BaseURL Response = $Response Issued = Get-date } [void]$form.Close() [void]$Web.Dispose() [void]$Form.Dispose() } }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Types/MSGraphAPI.Oauth.Exception.ps1
MSGraphAPI.Oauth.Exception.ps1
<# .NOTES =========================================================================== Created with: VSCode Created on: 4/21/2017 6:51 PM Edited on: 4/21/2017 Created by: Mark Kraus Organization: Filename: MSGraphAPI.Oauth.Exception.ps1 =========================================================================== .DESCRIPTION MSGraphAPI.Oauth.Exception Type Definition #> @{ Name = 'MSGraphAPI.Oauth.Exception' Properties = @( @{ MemberType = 'ScriptProperty' MemberName = 'JSONResonse' Value = { if($this.Response.ContentType -match 'application/json' ){ $Stream= $This.Response.GetResponseStream() $StreamReader = New-Object System.IO.StreamReader $Stream $Stream.Position = 0 $StreamReader.ReadToEnd() -replace '\\r\\n',"`r`n" | ConvertFrom-Json } } } ) }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Types/MSGraphAPI.Application.ps1
MSGraphAPI.Application.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 8:24 AM Edited on: 2/16/2017 Created by: Mark Kraus Organization: Mitel Filename: MSGraphAPI.Application.ps1 =========================================================================== .DESCRIPTION Contains type definition for MSGraphAPI.Application #> @{ Name = 'MSGraphAPI.Application' DefaultDisplayPropertySet = @( 'GUID' 'Name' 'Description' 'RedirectUri' 'ClientID' ) Properties = @( @{ MemberType = 'ScriptMethod' MemberName = 'ToString' Value = { 'Guid: {0} Name: {1}' -f $This.GUID, $This.Name } } @{ MemberType = 'ScriptProperty' MemberName = 'ClientID' Value = { $This.ClientCredential.UserName } } @{ MemberType = 'ScriptMethod' MemberName = 'GetClientSecret' Value = { try { $This.ClientCredential.GetNetworkCredential().Password } catch { $null } } } ) }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Types/MSGraphAPI.Oauth.AuthorizationCode.ps1
MSGraphAPI.Oauth.AuthorizationCode.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 10:19 AM Eedited on: 2/16/2017 Created by: Mark Kraus Organization: Mitel Filename: MSGraphAPI.Oauth.AuthorizationCode.ps1 =========================================================================== .DESCRIPTION MSGraphAPI.Oauth.AuthorizationCode Type definition #> @{ Name = 'MSGraphAPI.Oauth.AuthorizationCode' DefaultDisplayPropertySet = @( 'AuthCodeBaseURL' 'Success' 'Issued' 'IsExpired' 'Expires' 'NotBefore' 'Application' ) Properties = @( @{ MemberType = 'ScriptProperty' MemberName = 'Success' Value = { if ($This.AuthCodeCredential.UserName -eq 'NOAUTHCODE') { return $false } return $True } } @{ MemberType = 'ScriptProperty' MemberName = 'Expires' Value = { $This.Issued.AddMinutes(10) } } @{ MemberType = 'ScriptProperty' MemberName = 'IsExpired' Value = { $now = Get-date if ($now -gt $this.Expires) { return $true } return $false } } @{ MemberType = 'ScriptMethod' MemberName = 'GetAuthCode' Value = { try { $This.AuthCodeCredential.GetNetworkCredential().password } catch { $null } } } ) }
PowerShellCorpus/PowerShellGallery/psmsgraph/1.0.26.43/Types/MSGraphAPI.Oauth.AccessToken.ps1
MSGraphAPI.Oauth.AccessToken.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2017 v5.4.135 Created on: 2/8/2017 2:05 PM Edited on: 2/16/2017 Created by: Mark Kraus Organization: Mitel Filename: MSGraphAPI.Oauth.AccessToken.ps1 =========================================================================== .DESCRIPTION MSGraphAPI.Oauth.AccessToken Type Definition #> @{ Name = 'MSGraphAPI.Oauth.AccessToken' DefaultDisplayPropertySet = @( 'GUID' 'RequestedDate' 'LastRequestDate' 'IsExpired' 'Expires' 'NotBefore' 'Scope' 'Resource' 'IsRefreshable' 'Application' ) Properties = @( @{ MemberType = 'ScriptMethod' MemberName = 'ToString' Value = { "Guid: {0} IsExpired '{1}'" -f $This.GUID, $This.IsExpired } } @{ MemberType = 'ScriptMethod' MemberName = 'GetAccessToken' Value = { try { $This.AccessTokenCredential.GetNetworkCredential().password } catch { $null } } } @{ MemberType = 'ScriptMethod' MemberName = 'GetRefreshToken' Value = { try { $This.RefreshTokenCredential.GetNetworkCredential().password } catch { $null } } } @{ MemberType = 'ScriptProperty' MemberName = 'TokenType' Value = { $this.Response.token_type } } @{ MemberType = 'ScriptProperty' MemberName = 'Expires' Value = { if ($This.Response.expires_on) { (get-date '1970/01/01 -0').AddSeconds($This.Response.expires_on) } else { [DateTime]::MinValue } } } @{ MemberType = 'ScriptProperty' MemberName = 'NotBefore' Value = { if ($This.Response.not_before) { (get-date '1970/01/01 -0').AddSeconds($This.Response.not_before) } else { [DateTime]::MaxValue } } } @{ MemberType = 'ScriptProperty' MemberName = 'IsExpired' Value = { $(get-date) -ge $this.Expires } } @{ MemberType = 'ScriptProperty' MemberName = 'Scope' Value = { $This.Response.Scope -split ' ' } } @{ MemberType = 'ScriptProperty' MemberName = 'Resource' Value = { $This.Response.Resource } } @{ MemberType = 'ScriptMethod' MemberName = 'InvokeTokenRefresh' Value = { $This | Update-GraphOauthAccessToken } } @{ MemberType = 'ScriptProperty' MemberName = 'IsRefreshable' Value = { if ($This.GetRefreshToken() -eq 'NOREFRESH') { Return $False } Return $True } } ) }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Invoke-PublishToGallery.ps1
Invoke-PublishToGallery.ps1
#Invoke-Pester Publish-Module -Name New-OutputObject -NuGetApiKey de08953c-ed96-4633-a039-bac9385e88c7 -Verbose
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Private/Test-CharsInPath.ps1
Test-CharsInPath.ps1
Function Test-CharsInPath { <# .SYNOPSIS PowerShell function intended to verify if in the string what is the path to file or folder are incorrect chars. .DESCRIPTION PowerShell function intended to verify if in the string what is the path to file or folder are incorrect chars. Exit codes - 0 - everything OK - 1 - nothing to check - 2 - an incorrect char found in the path part - 3 - an incorrect char found in the file name part - 4 - incorrect chars found in the path part and in the file name part .PARAMETER Path Specifies the path to an item for what path (location on the disk) need to be checked. The Path can be an existing file or a folder on a disk provided as a PowerShell object or a string e.g. prepared to be used in file/folder creation. .PARAMETER SkipCheckCharsInFolderPart Skip checking in the folder part of path. .PARAMETER SkipCheckCharsInFileNamePart Skip checking in the file name part of path. .EXAMPLE [PS] > Test-CharsInPath -Path $(Get-Item C:\Windows\Temp\new.csv') -Verbose VERBOSE: The path provided as a string was devided to, directory part: C:\Windows\Temp ; file name part: new.csv 0 Testing existing file. Returned code means that all chars are acceptable in the name of folder and file. .EXAMPLE [PS] > Test-CharsInPath -Path "C:\newfolder:2\nowy|.csv" -Verbose VERBOSE: The path provided as a string was devided to, directory part: C:\newfolder:2\ ; file name part: nowy|.csv VERBOSE: The incorrect char | with the UTF code [124] found in FileName part 3 Testing the string if can be used as a file name. The returned value means that can't do to an unsupported char in the file name. .OUTPUTS Exit code as an integer number. See description section to find the exit codes descriptions. .LINK https://github.com/it-praktyk/New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, FileSystem REMARKS: # Based on the Power Tips # Finding Invalid File and Path Characters # http://powershell.com/cs/blogs/tips/archive/2016/04/20/finding-invalid-file-and-path-characters.aspx CURRENT VERSION - 0.5.4 - 2016-11-07 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md #> [cmdletbinding()] [OutputType([System.Int32])] param ( [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] $Path, [parameter(Mandatory = $false)] [switch]$SkipCheckCharsInFolderPart, [parameter(Mandatory = $false)] [switch]$SkipCheckCharsInFileNamePart ) BEGIN { $PathInvalidChars = [System.IO.Path]::GetInvalidPathChars() #36 chars $FileNameInvalidChars = [System.IO.Path]::GetInvalidFileNameChars() #41 chars #$FileOnlyInvalidChars = @(':', '*', '?', '\', '/') #5 chars - as a difference $IncorectCharFundInPath = $false $IncorectCharFundInFileName = $false $NothingToCheck = $true } PROCESS { $PathType = ($Path.GetType()).Name If (@('DirectoryInfo', 'FileInfo') -contains $PathType) { If (($SkipCheckCharsInFolderPart.IsPresent -and $PathType -eq 'DirectoryInfo') -or ($SkipCheckCharsInFileNamePart.IsPresent -and $PathType -eq 'FileInfo')) { Return 1 } ElseIf ($PathType -eq 'DirectoryInfo') { [String]$DirectoryPath = $Path.FullName } elseif ($PathType -eq 'FileInfo') { [String]$DirectoryPath = $Path.DirectoryName [String]$FileName = $Path.Name } } ElseIf ($PathType -eq 'String') { [String]$DirectoryPath = "" #Convert String to Array of chars $PathArray = $Path.ToCharArray() $PathLength = $PathArray.Length #It should be removed in a future and for loop changed to $i-- #Reverse PathArray to speedup of finding the folder indicator chars '\' or '/' [array]::Reverse($PathArray) For ($i = 0; $i -lt $PathLength; $i++) { If (@('\', '/') -contains $PathArray[$i]) { [String]$DirectoryPath = [String]$Path.Substring(0, $($PathArray.Length - $i)) break } } If ([String]::IsNullOrEmpty($DirectoryPath)) { [String]$FileName = [String]$Path } Else { [String]$FileName = $Path.Replace($DirectoryPath, "") } } Else { [String]$MessageText = "Input object {0} can't be tested" -f ($Path.GetType()).Name Throw $MessageText } [String]$MessageText = "The path provided as a string was divided to: directory part: {0} ; file name part: {1} ." -f $DirectoryPath, $FileName Write-Verbose -Message $MessageText If ($SkipCheckCharsInFolderPart.IsPresent -and $SkipCheckCharsInFileNamePart.IsPresent) { Return 1 } If (-not ($SkipCheckCharsInFolderPart.IsPresent) -and -not [String]::IsNullOrEmpty($DirectoryPath)) { $NothingToCheck = $false foreach ($Char in $PathInvalidChars) { If ($DirectoryPath.ToCharArray() -contains $Char) { $IncorectCharFundInPath = $true [String]$MessageText = "The incorrect char {0} with the UTF code [{1}] found in the Path part." -f $Char, $([int][char]$Char) Write-Verbose -Message $MessageText } } } If (-not ($SkipCheckCharsInFileNamePart.IsPresent) -and -not [String]::IsNullOrEmpty($FileName)) { $NothingToCheck = $false foreach ($Char in $FileNameInvalidChars) { If ($FileName.ToCharArray() -contains $Char) { $IncorectCharFundInFileName = $true [String]$MessageText = "The incorrect char {0} with the UTF code [{1}] found in FileName part." -f $Char, $([int][char]$Char) Write-Verbose -Message $MessageText } } } } END { If ($IncorectCharFundInPath -and $IncorectCharFundInFileName) { Return 4 } elseif ($NothingToCheck) { Return 1 } elseif ($IncorectCharFundInPath) { Return 2 } elseif ($IncorectCharFundInFileName) { Return 3 } Else { Return 0 } } }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Private/Get-OverwriteDecision.ps1
Get-OverwriteDecision.ps1
function Get-OverwriteDecision { <# .SYNOPSIS Display dialog to user with question about overwrite file/folder. .DESCRIPTION PowerShell function intended to display dialog to user with a question about overwrite existing file/folder. Result/decission is returned as an exit code. Exit codes - 0 - keep existing - 1 - overwrite - 2 - cancel was selected The function doesn't test if the object .PARAMETER Path A path - as a string - to an item for what path decision need to be taken. .PARAMETER ItemType Type of object to overwrite. Used only to display. .EXAMPLE PS :\> Get-OverwriteDecision -Path C:\Windows\Temp\test.txt -ItemType file Overwrite file The file C:\Windows\Temp\test.txt already exist [Y] Yes [N] No [C] Cancel [?] Help (default is "Y"): y 0 Taking decission from user about overwrite file. Returned code means that user took decision to overwrite file. .OUTPUTS Exit code as an integer number. See description section to find the exit codes descriptions. .LINK https://github.com/it-praktyk/New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, Dialog CURRENT VERSION - 0.1.1 - 2017-05-02 - Initial version HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md #> param ( [Parameter(Mandatory = $true)] [String]$Path, [Parameter(Mandatory = $false)] [ValidateSet('File', 'Folder')] [String]$ItemType = 'File' ) #Dialog for decision to overwrite [String]$Title = "Overwrite {0}" -f $ItemType.ToLower() [String]$MessageText = "The {0} {1} already exist" -f $ItemType.ToLower(), $Path $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", ` "The folder already exists. Overwrite the existing folder." $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", ` "Retain the existing folder." $cancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel", ` "Cancel." $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no, $cancel) $Answer = $host.ui.PromptForChoice($Title, $MessageText, $Options, 0) Return $Answer }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Public/New-OutputFile.ps1
New-OutputFile.ps1
Function New-OutputFile { <# .SYNOPSIS Function intended for preparing a PowerShell object for output files like reports or logs. .DESCRIPTION Function intended for preparing a PowerShell custom object what contains e.g. file name for output/create files like reports or log. The name is prepared based on prefix, middle name part, suffix, date, etc. with verification if provided path exist and is it writable. Returned object contains properties - OutputFilePath - to use it please check examples - as a [System.IO.FileInfo] - ExitCode - ExitCodeDescription Exit codes and descriptions - 0 = "Everything is fine :-)" - 1 = "Provided parent path <PATH> doesn't exist" - 2 = "The result name contains unacceptable chars" - 3 = "Provided patch <PATH> is not writable" - 4 = "The file <PATH>\\<FILE_NAME> already exist - can be overwritten" - 5 = "The file <PATH>\\<FILE_NAME> already exist - can't be overwritten" .PARAMETER ParentPath The folder path what will be used as the parent path for the new created object. When non existing path will be provided the error code will be returned. By default output files are stored in the current path. .PARAMETER OutputFileNamePrefix Prefix used for creating output files name .PARAMETER OutputFileNameMidPart Part of the name which will be used in midle of output file name .PARAMETER OutputFileNameSuffix Part of the name which will be used at the end of output file name .PARAMETER IncludeDateTimePartInOutputFileName Set to TRUE if report file name should contains part based on date and time - format yyyyMMdd-HHmm is used .PARAMETER DateTimePartInOutputFileName Set to date and time which should be used in output file name, by default current date and time is used .PARAMETER DateTimePartFormat Format string used to format date and time in output file name. .PARAMETER OutputFileNameExtension Set to extension which need to be used for output file, by default ".txt" is used .PARAMETER NamePartsSeparator A char used to separate parts in the name, by default "-" is used .PARAMETER BreakIfError Break function execution if parameters provided for output file creation are not correct or destination file path is not writables .EXAMPLE PS \> (Get-Item env:COMPUTERNAME).Value WXDX75 PS \> $FileNeeded = @{ ParentPath = 'C:\USERS\UserName\'; OutputFileNamePrefix = 'Messages'; OutputFileNameMidPart = (Get-Item env:COMPUTERNAME).Value; IncludeDateTimePartInOutputFileName = $true; BreakIfError = $true } PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded PS \> $PerServerReportFileMessages | Format-List OutputFilePath : C:\users\UserName\Messages-WXDX75-20151021-001205.txt ExitCode : 0 ExitCodeDescription : Everything is fine :-) PS \> New-Item -Path $PerServerReportFileMessages.OutputFilePath -ItemType file Directory: C:\USERS\UserName Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 21/10/2015 00:12 0 Messages-WXDX75-20151021-001205.txt The file created on provided parameters. Under preparation the file name is created, provided part of names are used, and availability of name (if the file exist now) is checked. .EXAMPLE $FileNeeded = @{ ParentPath = 'C:\USERS\UserName\'; OutputFileNamePrefix = 'Messages'; OutputFileNameMidPart = 'COMPUTERNAME'; IncludeDateTimePartInOutputFileName = $false; OutputFileNameExtension = "csv"; OutputFileNameSuffix = "failed" } PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded PS \> $PerServerReportFileMessages.OutputFilePath | Select-Object -Property Name,Extension,Directory | Format-List Name : Messages-COMPUTERNAME-failed.csv Extension : .csv Directory : C:\USERS\UserName PS \> ($PerServerReportFileMessages.OutputFilePath).gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True FileInfo System.IO.FileSystemInfo PS \> Test-Path ($PerServerReportFileMessages.OutputFilePath) False The funciton return object what contain the property named OutputFilePath what is the object of type System.IO.FileSystemInfo. File is not created. Only the object in the memory is prepared. .OUTPUTS System.Object[] .LINK https://github.com/it-praktyk/New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, File, FileSystem CURRENT VERSION - 0.9.9 - 2017-05-16 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md LICENSE Copyright (c) 2016 Wojciech Sciesinski This function is licensed under The MIT License (MIT) Full license text: https://opensource.org/licenses/MIT #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','')] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $false)] [String]$ParentPath = ".", [parameter(Mandatory = $false)] [String]$OutputFileNamePrefix = "Output", [parameter(Mandatory = $false)] [String]$OutputFileNameMidPart = $null, [parameter(Mandatory = $false)] [String]$OutputFileNameSuffix = $null, [parameter(Mandatory = $false)] [Bool]$IncludeDateTimePartInOutputFileName = $true, [parameter(Mandatory = $false)] [Nullable[DateTime]]$DateTimePartInOutputFileName = $null, [Parameter(Mandatory = $false)] [String]$DateTimePartFormat = "yyyyMMdd-HHmmss", [parameter(Mandatory = $false)] [String]$OutputFileNameExtension = ".txt", [parameter(Mandatory = $false)] [alias("Separator")] [String]$NamePartsSeparator = "-", [parameter(Mandatory = $false)] [Switch]$BreakIfError ) $params = @{ ObjectType = 'File' ParentPath = $ParentPath OutputObjectNamePrefix = $OutputFileNamePrefix OutputObjectNameMidPart = $OutputFileNameMidPart OutputObjectNameSuffix = $OutputFileNameSuffix IncludeDateTimePartInOutputObjectName = $IncludeDateTimePartInOutputFileName DateTimePartInOutputObjectName = $DateTimePartInOutputFileName DateTimePartFormat = $DateTimePartFormat OutputFileNameExtension = $OutputFileNameExtension NamePartsSeparator = $NamePartsSeparator BreakIfError = $BreakIfError } $Result = New-OutputObject @params Return $Result }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Public/New-OutputFolder.ps1
New-OutputFolder.ps1
Function New-OutputFolder { <# .SYNOPSIS Function intended for preparing a PowerShell object for output/create folders for e.g. reports or logs. .DESCRIPTION Function intended for preparing a PowerShell custom object what contains e.g. folder name for output/create folders. The name is prepared based on prefix, middle name part, suffix, date, etc. with verification if provided path exist and is it writable. Returned object contains properties - ParentPath - to use it please check an examples - as a [System.IO.DirectoyInfo] - ExitCode - ExitCodeDescription Exit codes and descriptions - 0 = "Everything is fine :-)" - 1 = "Provided parent path <PATH> doesn't exist" - 2 = "The result name contains unacceptable chars" - 3 = "Provided patch <PATH> is not writable" - 4 = "The folder <PATH>\\<FOLDER_NAME> already exist - can be overwritten" - 5 = "The folder <PATH>\\<FOLDER_NAME> already exist - can't be overwritten" .PARAMETER ParentPath The folder path what will be used as the parent path for the new created object. When non existing path will be provided the error code will be returned. By default output files are stored in the current path. .PARAMETER OutputFolderNamePrefix Prefix used for creating output folders name .PARAMETER OutputFolderNameMidPart Part of the name which will be used in midle of output folder name .PARAMETER OutputFolderNameSuffix Part of the name which will be used at the end of output folder name .PARAMETER IncludeDateTimePartInOutputFolderName Set to TRUE if report folder name should contains part based on date and time - format yyyyMMdd is used .PARAMETER DateTimePartInOutputFolderName Set to date and time which should be used in output folder name, by default current date and time is used .PARAMETER DateTimePartFormat Format string used to format date and time in output folder name. .PARAMETER NamePartsSeparator A char used to separate parts in the name, by default "-" is used .PARAMETER BreakIfError Break function execution if parameters provided for output folder creation are not correct or destination folder path is not writables .EXAMPLE PS \> (Get-Item env:COMPUTERNAME).Value WXDX75 PS \> $FolderNeeded= @{ ParentPath = 'C:\USERS\UserName\'; OutputFolderNamePrefix = 'Messages'; OutputFolderNameMidPart = (Get-Item env:COMPUTERNAME).Value IncludeDateTimePartInOutputFolderName = $false; BreakIfError = $true } PS \> $PerServerReportFolderMessages = New-OutputFolder @FolderNeeded PS \> $PerServerReportFolderMessages | Format-List OutputFilePath : C:\users\UserName\Messages-WXDX75 ExitCode : 0 ExitCodeDescription : Everything is fine :-) PS \> New-Item -Path $PerServerReportFolderMessages.OutputFolderPath -ItemType Directory Directory: C:\USERS\UserName Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 21/10/2015 00:12 0 Messages-WXDX75 The file created on provided parameters. Under preparation the file name is created, provided part of names are used, and availability of name (if the file exist now) is checked. .EXAMPLE $FolderNeeded= @{ ParentPath = 'C:\USERS\UserName\'; OutputFolderNamePrefix = 'Messages'; OutputFolderNameMidPart = 'COMPUTERNAME'; OutputFolderNameSuffix = "failed" } PS \> $PerServerReportFolderMessages = New-OutputFolder @FolderNeeded PS \> $PerServerReportFolderMessages.OutputFolderPath | Select-Object -Property Name,Parent,exists | Format-List Name : Messages-COMPUTERNAME-20161112-failed Parent : UserName Exists : False PS \> ($PerServerReportFolderMessages.OutputFolderPath).gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True DirectoryInfo System.IO.FileSystemInfo PS \> Test-Path ($PerServerReportFolderMessages.OutputFilePath) False The function return object what contain the property named OutputFilePath what is the object of type System.IO.DirectoryInfo. Folder is not created. Only the object in the memory is prepared. .OUTPUTS System.Object[] .LINK https://github.com/it-praktyk/New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, Folder, FileSystem CURRENT VERSION - 0.9.9 - 2017-05-16 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md LICENSE Copyright (c) 2016 Wojciech Sciesinski This function is licensed under The MIT License (MIT) Full license text: https://opensource.org/licenses/MIT #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','')] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $false)] [String]$ParentPath = ".", [parameter(Mandatory = $false)] [String]$OutputFolderNamePrefix = "Output", [parameter(Mandatory = $false)] [String]$OutputFolderNameMidPart = $null, [parameter(Mandatory = $false)] [String]$OutputFolderNameSuffix = $null, [parameter(Mandatory = $false)] [Bool]$IncludeDateTimePartInOutputFolderName = $true, [parameter(Mandatory = $false)] [Nullable[DateTime]]$DateTimePartInOutputFolderName = $null, [Parameter(Mandatory = $false)] [String]$DateTimePartFormat="yyyyMMdd", [parameter(Mandatory = $false)] [alias("Separator")] [String]$NamePartsSeparator="-", [parameter(Mandatory = $false)] [Switch]$BreakIfError ) $params = @{ ObjectType = 'Folder' ParentPath = $ParentPath OutputObjectNamePrefix = $OutputFolderNamePrefix OutputObjectNameMidPart = $OutputFolderNameMidPart OutputObjectNameSuffix = $OutputFolderNameSuffix IncludeDateTimePartInOutputObjectName = $IncludeDateTimePartInOutputFolderName DateTimePartInOutputObjectName = $DateTimePartInOutputFolderName DateTimePartFormat = $DateTimePartFormat NamePartsSeparator = $NamePartsSeparator BreakIfError = $BreakIfError } $Result = New-OutputObject @params Return $Result }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Public/New-OutputObject.ps1
New-OutputObject.ps1
Function New-OutputObject { <# .SYNOPSIS Function intended for preparing a PowerShell object for output files like reports or logs. .DESCRIPTION Function intended for preparing a PowerShell custom object what contains e.g. file name for output/create files like reports or log. The name is prepared based on prefix, middle name part, suffix, date, etc. with verification if provided path exist and is it writable. Returned object contains properties - OutputObjectPath - to use it please check examples - as a [System.IO.FileInfo] - ExitCode - ExitCodeDescription Exit codes and descriptions - 0 = "Everything is fine :-)" - 1 = "Provided parent path <PATH> doesn't exist" - 2 = "The name not created due to unaccepatable chars" - 3 = "Provided patch <PATH> is not writable" - 4 = "The file\folder <PATH>\\<FILE_OR_FOLDER_NAME> already exist - can be overwritten" - 5 = "The file\folder <PATH>\\<FILE_OR_FOLDER_NAME> already exist - can't be overwritten" .PARAMETER ObjectType Type of object to prepare - file or folder .PARAMETER ParentPath The folder path what will be used as the parent path for the new created object. When non existing path will be provided the error code will be returned. By default output files are stored in the current path. .PARAMETER OutputObjectNamePrefix Prefix used for creating output files name .PARAMETER OutputObjectNameMidPart Part of the name which will be used in midle of output file name .PARAMETER OutputObjectNameSuffix Part of the name which will be used at the end of output file name .PARAMETER IncludeDateTimePartInOutputObjectName Set to TRUE if report file name should contains part based on date and time - format yyyyMMdd-HHmm is used .PARAMETER DateTimePartInOutputObjectName Set to date and time which should be used in output file name, by default current date and time is used .PARAMETER DateTimePartFormat Format string used to format date and time in output object name. .PARAMETER OutputFileNameExtension Set to extension which need to be used for output file, by default ".txt" is used .PARAMETER NamePartsSeparator A char used to separate parts in the name, by default "-" is used .PARAMETER BreakIfError Break function execution if parameters provided for output file creation are not correct or destination file path is not writables .EXAMPLE PS \> (Get-Item env:COMPUTERNAME).Value WXDX75 PS \> $FileNeeded = @{ ParentPath = 'C:\USERS\UserName\'; OutputObjectNamePrefix = 'Messages'; OutputObjectNameMidPart = (Get-Item env:COMPUTERNAME).Value; IncludeDateTimePartInOutputObjectName = $true; IncludeDateTimePartInOutputObjectName = $true; BreakIfError = $true } PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded PS \> $PerServerReportFileMessages | Format-List OutputObjectPath : C:\users\UserName\Messages-WXDX75-20151021-001205.txt ExitCode : 0 ExitCodeDescription : Everything is fine :-) PS \> New-Item -Path $PerServerReportFileMessages.OutputObjectPath -ItemType file Directory: C:\USERS\UserName Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 21/10/2015 00:12 0 Messages-WXDX75-20151021-001205.txt The file created on provided parameters. Under preparation the file name is created, provided part of names are used, and availability of name (if the file exist now) is checked. .EXAMPLE $FileNeeded = @{ ParentPath = 'C:\USERS\UserName\'; OutputObjectNamePrefix = 'Messages'; OutputObjectNameMidPart = 'COMPUTERNAME'; IncludeDateTimePartInOutputObjectName = $false; OutputFileNameExtension = "csv"; OutputObjectNameSuffix = "failed" } PS \> $PerServerReportFileMessages = New-OutputFile @FileNeeded PS \> $PerServerReportFileMessages.OutputObjectPath | Select-Object -Property Name,Extension,Directory | Format-List Name : Messages-COMPUTERNAME-failed.csv Extension : .csv Directory : C:\USERS\UserName PS \> ($PerServerReportFileMessages.OutputObjectPath).gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True FileInfo System.IO.FileSystemInfo PS \> Test-Path ($PerServerReportFileMessages.OutputObjectPath) False The funciton return object what contain the property named OutputObjectPath what is the object of type System.IO.FileSystemInfo. File is not created. Only the object in the memory is prepared. .OUTPUTS System.Object[] .LINK https://github.com/it-praktyk/New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, File, Folder, FileSystem CURRENT VERSION - 0.9.9 - 2017-05-16 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md LICENSE Copyright (c) 2016 Wojciech Sciesinski This function is licensed under The MIT License (MIT) Full license text: https://opensource.org/licenses/MIT #> [cmdletbinding()] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions','')] [OutputType([System.Object[]])] param ( [parameter(Mandatory = $true)] [ValidateSet('File', 'Folder')] [Alias('ItemType')] [String]$ObjectType, [parameter(Mandatory = $false)] [String]$ParentPath = ".", [parameter(Mandatory = $false)] [String]$OutputObjectNamePrefix = "Output", [parameter(Mandatory = $false)] [String]$OutputObjectNameMidPart = $null, [parameter(Mandatory = $false)] [String]$OutputObjectNameSuffix = $null, [parameter(Mandatory = $false)] [Bool]$IncludeDateTimePartInOutputObjectName = $true, [parameter(Mandatory = $false)] [Nullable[DateTime]]$DateTimePartInOutputObjectName = $null, [parameter(Mandatory = $false)] [String]$DateTimePartFormat, [parameter(Mandatory = $false)] [String]$OutputFileNameExtension, [parameter(Mandatory = $false)] [alias("Separator")] [String]$NamePartsSeparator = "-", [parameter(Mandatory = $false)] [Switch]$BreakIfError ) #Declare variable [Int]$ExitCode = 0 [String]$ExitCodeDescription = 'Everything is fine :-)' $Result = New-Object -TypeName PSObject If ($ObjectType -eq 'File') { $PathType = 'Leaf' $ItemTypeLower = 'file' $ItemTypeCapitalized = 'File' If ([String]::IsNullOrEmpty($DateTimePartFormat)) { $DateTimePartFormat = 'yyyyMMdd-HHmmss' } Else { $TestCharsResult = Test-CharsInPath -Path $DateTimePartFormat -SkipCheckCharsInFolderPart If ( $BreakIfError.IsPresent -and $TestCharsResult -eq 3 ) { $FileNameInvalidChars = [System.IO.Path]::GetInvalidFileNameChars() #41 chars $MessageText = "Provided {0} value for DateTimePartFormat contains char what is not allowed in a file name. Unallowed chars are: {0}" -f $FileNameInvalidChars Throw $MessageText } Elseif ( $TestCharsResult -eq 3) { [Int]$ExitCode = 2 [String]$ExitCodeDescription = "The name not created due to unaccepatable chars" } } if ( [String]::IsNullOrEmpty($OutputFileNameExtension)) { $OutputFileNameExtension = '.txt' } } Else { $PathType = 'Container' $ItemTypeLower = 'folder' $ItemTypeCapitalized = 'Folder' If ([String]::IsNullOrEmpty($DateTimePartFormat)) { $DateTimePartFormat = 'yyyyMMdd' } Else { $TestCharsResult = Test-CharsInPath -Path $DateTimePartFormat -SkipCheckCharsInFileNamePart If ( $BreakIfError.IsPresent -and $TestCharsResult -eq 2 ) { $PathInvalidChars = [System.IO.Path]::GetInvalidPathChars() #36 chars $MessageText = "Provided value for DateTimePartFormat contains char what is not allowed in a folder name. Unallowed chars are: {0}" -f $PathInvalidChars Throw $MessageText } Elseif ( $TestCharsResult -eq 2) { [Int]$ExitCode = 2 [String]$ExitCodeDescription = "The name not created due to unaccepatable chars" } } if (-not [String]::IsNullOrEmpty($OutputFileNameExtension)) { [String]$MessageText = 'The value assigned to the parameter OutputFileNameExtension for a folder OutputType is ignored.' Write-Warning -Message $MessageText } } #Convert relative path to absolute path [String]$ParentPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ParentPath) #Assign value to the variable $IncludeDateTimePartInOutputObjectName if is not initialized If ($IncludeDateTimePartInOutputObjectName -and ($null -eq $DateTimePartInOutputObjectName)) { [String]$DateTimePartInObjectNameString = $(Get-Date -format $DateTimePartFormat) } elseif ($IncludeDateTimePartInOutputObjectName) { [String]$DateTimePartInObjectNameString = $(Get-Date -Date $DateTimePartInOutputObjectName -format $DateTimePartFormat) } #Check if Output directory exist If (-not (Test-Path -Path $ParentPath -PathType Container)) { [Int]$ExitCode = 1 [String]$MessageText = "Provided parent path {0} doesn't exist" -f $ParentPath [String]$ExitCodeDescription = $MessageText } #Try if Output directory is writable - a temporary object is created for that Else { #Try if Output directory is writable - a temporary file is created for that Try { [String]$TempObjectName = [System.IO.Path]::GetTempFileName() -replace '.*\\', '' [String]$TempObjectPath = "{0}{1}" -f $ParentPath, $TempObjectName New-Item -Path $TempObjectPath -type File -ErrorAction Stop | Out-Null } Catch { [String]$MessageText = "Provided path {0} is not writable" -f $ParentPath If ($BreakIfError.IsPresent) { Throw $MessageText } Else { [Int]$ExitCode = 3 [String]$ExitCodeDescription = $MessageText } } Remove-Item -Path $TempObjectPath -ErrorAction SilentlyContinue | Out-Null } #Constructing the object name If (!($IncludeDateTimePartInOutputObjectName) -and !([String]::IsNullOrEmpty($OutputObjectNameMidPart))) { [String]$OutputObjectPathTemp1 = "{0}\{1}{3}{2}" -f $ParentPath, $OutputObjectNamePrefix, $OutputObjectNameMidPart, $NamePartsSeparator } Elseif (!($IncludeDateTimePartInOutputObjectName) -and [String]::IsNullOrEmpty($OutputObjectNameMidPart)) { [String]$OutputObjectPathTemp1 = "{0}\{1}" -f $ParentPath, $OutputObjectNamePrefix } ElseIf ($IncludeDateTimePartInOutputObjectName -and !([String]::IsNullOrEmpty($OutputObjectNameMidPart))) { [String]$OutputObjectPathTemp1 = "{0}\{1}{4}{2}{4}{3}" -f $ParentPath, $OutputObjectNamePrefix, $OutputObjectNameMidPart, $DateTimePartInObjectNameString, $NamePartsSeparator } Else { [String]$OutputObjectPathTemp1 = "{0}\{1}{3}{2}" -f $ParentPath, $OutputObjectNamePrefix, $DateTimePartInObjectNameString, $NamePartsSeparator } If ($ObjectType -eq 'File' -and (-not [String]::IsNullOrEmpty($OutputFileNameExtension))) { If ([String]::IsNullOrEmpty($OutputObjectNameSuffix)) { [String]$OutputObjectPathTemp = "{0}.{1}" -f $OutputObjectPathTemp1, $OutputFileNameExtension } Else { [String]$OutputObjectPathTemp = "{0}{3}{1}.{2}" -f $OutputObjectPathTemp1, $OutputObjectNameSuffix, $OutputFileNameExtension, $NamePartsSeparator } } Else { If ([String]::IsNullOrEmpty($OutputObjectNameSuffix)) { [String]$OutputObjectPathTemp = "{0}" -f $OutputObjectPathTemp1 } Else { [String]$OutputObjectPathTemp = "{0}{2}{1}" -f $OutputObjectPathTemp1, $OutputObjectNameSuffix, $NamePartsSeparator } } If ( $ExitCode -eq 2 ) { If ($ObjectType -eq 'File') { [System.IO.FileInfo]$OutputObjectPath = $null } Else { [System.IO.DirectoryInfo]$OutputObjectPath = $null } } Else { If ($ObjectType -eq 'File') { #Replacing doubled chars \\ , -- , .. - except if \\ is on begining - means that path is UNC share [System.IO.FileInfo]$OutputObjectPath = "{0}{1}" -f $OutputObjectPathTemp.substring(0, 2), (($OutputObjectPathTemp.substring(2, $OutputObjectPathTemp.length - 2).replace("\\", '\')).replace("--", "-")).replace("..", ".") } Else { #Replacing doubled chars \\ , -- , .. - except if \\ is on begining - means that path is UNC share [System.IO.DirectoryInfo]$OutputObjectPath = "{0}{1}" -f $OutputObjectPathTemp.substring(0, 2), (($OutputObjectPathTemp.substring(2, $OutputObjectPathTemp.length - 2).replace("\\", '\')).replace("--", "-")).replace("..", ".") } If (Test-Path -Path $OutputObjectPath -PathType $PathType) { $Answer = Get-OverwriteDecision -Path $OutputObjectPath -ItemType $ObjectType switch ($Answer) { 0 { [Int]$ExitCode = 4 [String]$MessageText = "The {0} {1} already exist - can be overwritten" -f $ItemTypeLower, $OutputObjectPath.FullName [String]$ExitCodeDescription = $MessageText } 1 { [Int]$ExitCode = 5 [String]$MessageText = "The {0} {1} already exist - can't be overwritten" -f $ItemTypeLower, $OutputObjectPath [String]$ExitCodeDescription = $MessageText } 2 { Throw $MessageText } } } } $Result | Add-Member -MemberType NoteProperty -Name OutputObjectPath -Value $OutputObjectPath #$Result | Add-Member -MemberType AliasProperty -Name Path -Value OutputObjectPath If ($ObjectType -eq 'File') { $Result | Add-Member -MemberType AliasProperty -Name OutputFilePath -Value OutputObjectPath } Else { $Result | Add-Member -MemberType AliasProperty -Name OutputFolderPath -Value OutputObjectPath } $Result | Add-Member -MemberType NoteProperty -Name ExitCode -Value $ExitCode $Result | Add-Member -MemberType NoteProperty -Name ExitCodeDescription -Value $ExitCodeDescription Return $Result }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Tests/New-OutputObject-Module-Specific.Tests.ps1
New-OutputObject-Module-Specific.Tests.ps1
<# .SYNOPSIS Pester tests to general validation of the New-OutputObject module - e.g. help, PSScriptAnalyzer results, style rules .LINK https://github.com/it-praktyk/New-OutputObject .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, Pester, psd1, New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech CURRENT VERSION - 0.9.8 - 2017.05.02 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md #> $ModuleName = "New-OutputObject" $RelativePathToModuleRoot = "{0}\.." -f $PSScriptRoot $RelativePathToModuleManifest = "{0}\{1}.psd1" -f $RelativePathToModuleRoot, $ModuleName Describe "General tests for the $ModuleName module" { BeforeAll { # If BeforeAll fails, Skip everything $Global:PSDefaultParameterValues["It:Skip"]=$true #Remove module if it's currently loaded Get-Module -Name $ModuleName -ErrorAction SilentlyContinue | Remove-Module -Force it 'Format-Pester should load without error' -Skip:$false { {Import-Module -FullyQualifiedName $RelativePathToModuleManifest -Force -Scope Global } | should not throw Get-Module -Name $ModuleName | should not be null # Since BeforeAll has passed, set skip to false $Global:PSDefaultParameterValues["It:Skip"]=$false } } } #Section mostly based on the blog post http://www.lazywinadmin.com/2016/05/using-pester-to-test-your-comment-based.html #Author: Fran"ois-Xavier Cat fxcat[at]lazywinadmin[dot]com #Corrected by Wojciech Sciesinski wojciech[at]sciesinski[dot]net Describe "Module $ModuleName functions help" -Tags "Help" { $FunctionsList = (get-command -Module $ModuleName | Where-Object -FilterScript { $_.CommandType -eq 'Function'} ).Name ForEach ($Function in $FunctionsList) { # Retrieve the Help of the function $Help = Get-Help -Name $Function -Full #Parsing Notes can be added also #$Notes = ($Help.alertSet.alert.text -split '\n') $Links = ($Help.relatedlinks.navigationlink.uri -split '\n') # Parse the function using AST $AST = [System.Management.Automation.Language.Parser]::ParseInput((Get-Content function:$Function), [ref]$null, [ref]$null) Context "$Function - Help"{ It "Synopsis"{ $help.Synopsis | Should not BeNullOrEmpty } It "Description"{ $help.Description | Should not BeNullOrEmpty } # Get the parameters declared in the Comment Based Help $RiskMitigationParameters = 'Whatif', 'Confirm' [String[]]$HelpParameters = $help.parameters.parameter | Where-Object name -NotIn $RiskMitigationParameters # Get the parameters declared in the AST PARAM() Block [String[]]$ASTParameters = $AST.ParamBlock.Parameters.Name.variablepath.userpath It "Parameter - Compare amount of parameters Help vs AST" { $HelpParameters.count -eq $ASTParameters.count | Should Be $true } # Parameter Description $help.parameters.parameter | ForEach-Object { It "Parameter $($_.Name) - Should contains description"{ $_.description | Should not BeNullOrEmpty } } # Examples it "Example - Count should be greater than 0"{ $Help.examples.example.code.count | Should BeGreaterthan 0 } # Examples - Remarks (small description that comes with the example) foreach ($Example in $Help.examples.example) { it "Example - Remarks on $($Example.Title)"{ $Example.remarks | Should not BeNullOrEmpty } } } } } #Section mostly based on the blog post https://blog.kilasuit.org/2016/03/29/invoking-psscriptanalyzer-in-pester-tests-for-each-rule/ #Author: Ryan Yates ryan[dot]yates[at]kilasuit[dot]org #Corrected by Wojciech Sciesinski wojciech[at]sciesinski[dot]net $Here = Split-Path -Parent $MyInvocation.MyCommand.Path $Scripts = Get-ChildItem "$here\..\" -Filter "*.ps1" -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $Modules = Get-ChildItem "$here\..\" -Filter "*.psm1" -Recurse $Excluderules = @() $Rules = Get-ScriptAnalyzerRule | Where-Object -FilterScript { $_.RuleName -notin $Excluderules } if ($Modules.count -gt 0) { Describe "Testing all Modules in this Repo to be be correctly formatted" -Tag "PSScriptAnalyzer" { foreach ($module in $modules) { Context "Testing Module $($module.BaseName) for Standard Processing" { foreach ($rule in $rules) { It "passes the PSScriptAnalyzer Rule $rule" { (Invoke-ScriptAnalyzer -Path $module.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0 } } } } } } if ($Scripts.count -gt 0) { Describe 'Testing all Scripts in this Repo to be be correctly formatted' -Tag "PSScriptAnalyzer" { foreach ($Script in $scripts) { Context "Testing Script $($script.BaseName) for Standard Processing" { foreach ($rule in $rules) { It "passes the PSScriptAnalyzer Rule $rule" { (Invoke-ScriptAnalyzer -Path $script.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0 } } } } } } #Style rules based on Pester v. 4.0.2-rc2 Describe 'Style rules' -Tags "Style"{ $files = @( Get-ChildItem $RelativePathToModuleRoot\* -Include *.ps1, *.psm1 Get-ChildItem (Join-Path $RelativePathToModuleRoot 'Public') -Include *.ps1, *.psm1 -Recurse Get-ChildItem (Join-Path $RelativePathToModuleRoot 'Private') -Include *.ps1, *.psm1 -Recurse Get-ChildItem (Join-Path $RelativePathToModuleRoot 'Tests') -Include *.ps1, *.psm1 -Recurse ) It "$ModuleName source files contain no trailing whitespace" { $badLines = @( foreach ($file in $files) { $lines = [System.IO.File]::ReadAllLines($file.FullName) $lineCount = $lines.Count for ($i = 0; $i -lt $lineCount; $i++) { if ($lines[$i] -match '\s+$') { 'File: {0}, Line: {1}' -f $file.FullName, ($i + 1) } } } ) if ($badLines.Count -gt 0) { throw "The following $($badLines.Count) lines contain trailing whitespace: `r`n`r`n$($badLines -join "`r`n")" } } It "$ModuleName source files lines start with a tab character" { $badLines = @( foreach ($file in $files) { $lines = [System.IO.File]::ReadAllLines($file.FullName) $lineCount = $lines.Count for ($i = 0; $i -lt $lineCount; $i++) { if ($lines[$i] -match '^[ ]*\t|^\t|^\t[ ]*') { 'File: {0}, Line: {1}' -f $file.FullName, ($i + 1) } } } ) if ($badLines.Count -gt 0) { throw "The following $($badLines.Count) lines start with a tab character: `r`n`r`n$($badLines -join "`r`n")" } } It "$ModuleName source files all end with a newline" { $badFiles = @( foreach ($file in $files) { $string = [System.IO.File]::ReadAllText($file.FullName) if ($string.Length -gt 0 -and $string[-1] -ne "`n") { $file.FullName } } ) if ($badFiles.Count -gt 0) { throw "The following files do not end with a newline: `r`n`r`n$($badFiles -join "`r`n")" } } } #Describe Verify versions { #}
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Tests/Test-CharsInPath.Tests.ps1
Test-CharsInPath.Tests.ps1
<# .SYNOPSIS Pester tests for function Test-CharsInPath .LINK https://github.com/it-praktyk/New-OutputObject .LINK https://www.linkedin.com/in/sciesinskiwojciech .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, FileSystem, Pester CURRENT VERSION - 0.5.0 - 2016-11-11 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md #> $here = Split-Path -Parent $MyInvocation.MyCommand.Path $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.' . "$here\..\Private\$sut" [Bool]$VerboseFunctionOutput = $false Describe "Test-CharsInPath" { Context "Input is a file or a directory PSObject" { $TestFile = New-Item -Path "TestDrive:" -Name "TestFile1.txt" -ItemType File $TestDir = New-Item -Path "TestDrive:" -Name "TestDir1" -ItemType Container It "Input is a di rectory, SkipCheckCharsInFolderPart" { Test-CharsInPath -path $TestDir -SkipCheckCharsInFolderPart | Should Be 1 } It "Input is a file, SkipCheckCharsInFileNamePart" { Test-CharsInPath -path $TestFile -SkipCheckCharsInFileNamePart | Should Be 1 } } Context "Input is a string" { [String]$CorrectPathString = 'C:\Windows\Temp\Add-GroupsMember.ps1' [String]$InCorrectPathString = 'C:\Win>dows\Te%mp\Add-ADGroupMember.ps1' [String]$InCorrectFileNameString = 'C:\Windows\Temp\Ard-ADGrou|p<Member.ps1' [String]$IncorrectFullPathString = 'C:\Win>dows\Temp\Ard-ADGrou|p<Member.ps1' [String]$IncorrectDirectoryOnly = 'C:\AppData\Loc>al\' [String]$CorrectDirectoryOnly = 'C:\AppData\Local\' [String]$IncorrectFileNameOnly = 'Test-File-201606*08-1315.txt' [String]$CorrectFileNameOnly = 'Test-File-20160608-1315.txt' It "Input is string, CorrectPathString" { Test-CharsInPath -Path $CorrectPathString -verbose:$VerboseFunctionOutput | should be 0 } It "Input is string, SkipCheckCharsInFolderPart, CorrectPathString" { Test-CharsInPath -Path $CorrectPathString -SkipCheckCharsInFolderPart -verbose:$VerboseFunctionOutput | should be 0 } It "Input is string, SkipCheckCharsInFileNamePart, CorrectPathString" { Test-CharsInPath -Path $CorrectPathString -SkipCheckCharsInFileNamePart -verbose:$VerboseFunctionOutput | should be 0 } It "Input is string, SkipCheckCharsInFolderPart, IncorrectDirectoryOnly" { Test-CharsInPath -Path $IncorrectDirectoryOnly -SkipCheckCharsInFolderPart -verbose:$VerboseFunctionOutput | should be 1 } It "Input is string, IncorrectDirectoryOnly" { Test-CharsInPath -Path $IncorrectDirectoryOnly -verbose:$VerboseFunctionOutput | should be 2 } It "Input is string, CorrectDirectoryOnly only" { Test-CharsInPath -Path $CorrectDirectoryOnly -verbose:$VerboseFunctionOutput | should be 0 } It "Input is string, SkipCheckCharsInFileNamePart, InCorrectFileNameString" { Test-CharsInPath -Path $InCorrectFileNameString -SkipCheckCharsInFileNamePart -verbose:$VerboseFunctionOutput | should be 0 } It "Input is string, InCorrectFileNameString" { Test-CharsInPath -Path $InCorrectFileNameString -verbose:$VerboseFunctionOutput | should be 3 } It "Input is string, SkipCheckCharsInFileNamePart, IncorrectFileNameOnly" { Test-CharsInPath -Path $IncorrectFileNameOnly -SkipCheckCharsInFileNamePart -verbose:$VerboseFunctionOutput | should be 1 } It "Input is string, IncorrectFileNameOnly only" { Test-CharsInPath -Path $IncorrectFileNameOnly -verbose:$VerboseFunctionOutput | should be 3 } It "Input is string, SkipCheckCharsInFileNamePart, CorrectFileNameOnly" { Test-CharsInPath -Path $CorrectFileNameOnly -SkipCheckCharsInFileNamePart -verbose:$VerboseFunctionOutput | should be 1 } It "Input is string, CorrectFileNameOnly only" { Test-CharsInPath -Path $CorrectFileNameOnly -verbose:$VerboseFunctionOutput | should be 0 } It "Input is string, SkipCheckCharsInFolderPart and SkipCheckCharsInFileNamePart, InCorrectPathString" { Test-CharsInPath -Path $CorrectPathString -SkipCheckCharsInFileNamePart -SkipCheckCharsInFolderPart -verbose:$VerboseFunctionOutput | should be 1 } } Context "Input is other than string or System.IO.X" { It "Input is Int32" { [Int]$PathToTest = 23 { Test-CharsInPath -Path $PathToTest -verbose:$VerboseFunctionOutput } | should Throw } } }
PowerShellCorpus/PowerShellGallery/New-OutputObject/0.9.9/Tests/New-OutputObject.Tests.ps1
New-OutputObject.Tests.ps1
<# .SYNOPSIS Pester tests to validate the New-OutputObject.ps1 function .LINK https://github.com/it-praktyk/New-OutputObject .NOTES AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net KEYWORDS: PowerShell, Pester, psd1, New-OutputObject, New-OutputObject CURRENT VERSION - 0.9.8 - 2017-05-06 HISTORY OF VERSIONS https://github.com/it-praktyk/New-OutputObject/VERSIONS.md #> $ModuleName = "New-OutputObject" #Provided path asume that your module manifest (a file with the psd1 extension) exists in the parent directory for directory where the current test script is stored $RelativePathToModuleManifest = "{0}\..\{1}.psd1" -f $PSScriptRoot, $ModuleName #Remove module if it's currently loaded Get-Module -Name $ModuleName -ErrorAction SilentlyContinue | Remove-Module Import-Module -FullyQualifiedName $RelativePathToModuleManifest -Force -Scope Global $FunctionName = "New-OutputObject" $ObjectTypes = @('File', 'Folder') foreach ($ObjectType in $ObjectTypes) { If ($ObjectType -eq 'File') { $ItemTypeLower = 'file' $ExpectedObjectType = 'System.Io.FileInfo' [System.String]$DateTimeFormatToMock = 'yyyyMMdd-HHmmss' [String]$IncorrectFileNameOnly = 'Test-File-201606*08-1315.txt' } Else { $ItemTypeLower = 'folder' $ExpectedObjectType = 'System.Io.DirectoryInfo' [System.String]$DateTimeObjectToMock = 'yyyyMMdd' [String]$IncorrectDirectoryOnly = 'C:\AppData\Loc>al\' } Describe "Tests for $FunctionName and the ObjectType [$ObjectType]" { $LocationAtBegin = Get-Location Set-Location TestDrive: $ContextName = "run without parameters" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" $ResultProxyFunction = New-OutputFile } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" $ResultProxyFunction = New-OutputFolder } $Result = New-OutputObject -ObjectType $ObjectType It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with OutputObjectNamePrefix" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "AAA-20161108-000002.txt" $ResultProxyFunction = New-OutputFile -OutputFileNamePrefix "AAA" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "AAA-20161108" $ResultProxyFunction = New-OutputFolder -OutputFolderNamePrefix "AAA" } $Result = New-OutputObject -ObjectType $ObjectType -OutputObjectNamePrefix "AAA" It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with OutputObjectNameMidPart" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-BBB-20161108-000002.txt" $ResultProxyFunction = New-OutputFile -OutputFileNameMidPart "BBB" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-BBB-20161108" $ResultProxyFunction = New-OutputFolder -OutputFolderNameMidPart "BBB" } $Result = New-OutputObject -ObjectType $ObjectType -OutputObjectNameMidPart "BBB" It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with OutputObjectNameSuffix" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002-CCC.txt" $ResultProxyFunction = New-OutputFile -OutputFileNameSuffix "CCC" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-CCC" $ResultProxyFunction = New-OutputFolder -OutputFolderNameSuffix "CCC" } $Result = New-OutputObject -ObjectType $ObjectType -OutputObjectNameSuffix "CCC" It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with DateTimePartInOutputFileName" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161101-120001' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161101-120001.txt" $ResultProxyFunction = New-OutputFile -DateTimePartInOutputFileName (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161101' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161101" $ResultProxyFunction = New-OutputFolder -DateTimePartInOutputFolderName (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") } $Result = New-OutputObject -ObjectType $ObjectType -DateTimePartInOutputObjectName (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with DateTimePartInOutputObjectName, without DateTimePart" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { $ExpectedOutputObjectName = "Output.txt" $params = @{ DateTimePartInOutputFileName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") IncludeDateTimePartInOutputFileName = $false } $ResultProxyFunction = New-OutputFile @params } Else { $ExpectedOutputObjectName = "Output" $params = @{ DateTimePartInOutputFolderName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") IncludeDateTimePartInOutputFolderName = $false } $ResultProxyFunction = New-OutputFolder @params } $params = @{ ObjectType = $ObjectType DateTimePartInOutputObjectName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") IncludeDateTimePartInOutputObjectName = $false } $Result = New-OutputObject @params It "Function $FunctionName - $ContextName - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with OutputFileNameExtension" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.csv" $ResultProxyFunction = New-OutputFile -OutputFileNameExtension ".csv" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" $ResultProxyFunction = New-OutputFolder } $Result = New-OutputObject -ObjectType $ObjectType -OutputFileNameExtension "csv" It "Function $FunctionName - $ContextName - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with NamePartsSeparator" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output_20161108-000002.txt" $ResultProxyFunction = New-OutputFile -NamePartsSeparator "_" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output_20161108" $ResultProxyFunction = New-OutputFolder -NamePartsSeparator "_" } $Result = New-OutputObject -ObjectType $ObjectType -NamePartsSeparator "_" It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with all name parts, with DateTimePartInOutputObjectName" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161101-120001' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "AAA-BBB-20161101-120001-CCC.txt" $params = @{ OutputFileNamePrefix = "AAA" OutputFileNameMidPart = "BBB" OutputFileNameSuffix = "CCC" DateTimePartInOutputFileName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") } $ResultProxyFunction = New-OutputFile @params } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161101' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "AAA-BBB-20161101-CCC" $params = @{ OutputFolderNamePrefix = "AAA" OutputFolderNameMidPart = "BBB" OutputFolderNameSuffix = "CCC" DateTimePartInOutputFolderName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") } $ResultProxyFunction = New-OutputFolder @params } $params = @{ ObjectType = $ObjectType OutputObjectNamePrefix = "AAA" OutputObjectNameMidPart = "BBB" OutputObjectNameSuffix = "CCC" DateTimePartInOutputObjectName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") } $Result = New-OutputObject @params It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run with all name parts, without DateTimePart" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { $ExpectedOutputObjectName = "AAA-BBB-CCC.txt" $params = @{ OutputFileNamePrefix = "AAA" OutputFileNameMidPart = "BBB" OutputFileNameSuffix = "CCC" DateTimePartInOutputFileName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") IncludeDateTimePartInOutputFileName = $false } $ResultProxyFunction = New-OutputFile @params } Else { $ExpectedOutputObjectName = "AAA-BBB-CCC" $params = @{ OutputFolderNamePrefix = "AAA" OutputFolderNameMidPart = "BBB" OutputFolderNameSuffix = "CCC" DateTimePartInOutputFolderName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") IncludeDateTimePartInOutputFolderName = $false } $ResultProxyFunction = New-OutputFolder @params } $params = @{ ObjectType = $ObjectType OutputObjectNamePrefix = "AAA" OutputObjectNameMidPart = "BBB" OutputObjectNameSuffix = "CCC" DateTimePartInOutputObjectName = (Get-Date -Date "2016-11-01 12:00:01" -Format "yyyy-MM-dd hh:mm:ss") IncludeDateTimePartInOutputObjectName = $false } $Result = New-OutputObject @params It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 0 $ResultProxyFunction.ExitCode | Should Be 0 } It "Function $FunctionName - $ContextName - exit code description" { $Result.ExitCodeDescription | Should Be "Everything is fine :-)" $ResultProxyFunction.ExitCodeDescription | Should Be "Everything is fine :-)" } } $ContextName = "run without parameters, non existing destination directory." Context "Function $FunctionName - $ContextName" { $ParentPath = "TestDrive:\TestFolder" If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" $ResultProxyFunction = New-OutputFile -ParentPath $ParentPath } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" $ResultProxyFunction = New-OutputFolder -ParentPath $ParentPath } $Result = New-OutputObject -ObjectType $ObjectType -ParentPath $ParentPath It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 1 $ResultProxyFunction.ExitCode | Should Be 1 } It "Function $FunctionName - $ContextName - exit code description" { [System.String]$RequiredMessage = "Provided parent path {0} doesn't exist" -f $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$ParentPath") $Result.ExitCodeDescription | Should Be $RequiredMessage } } $ContextName = "run with existing, non writable destination folder." Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" } $TestDestinationFolder = "TestDrive:\ExistingNotWritable\" New-Item -Path $TestDestinationFolder -ItemType Directory | Out-Null $ChangedACL = $OriginalAcl = Get-Acl -Path $TestDestinationFolder $colRights = [System.Security.AccessControl.FileSystemRights]"AppendData,WriteData" $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::InheritOnly $objType = [System.Security.AccessControl.AccessControlType]::Deny $objUser = New-Object System.Security.Principal.NTAccount($(whoami)) $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule ($objUser, $colRights, $InheritanceFlag, $PropagationFlag, $objType) $ChangedACL.AddAccessRule($objACE) Set-ACL -Path $TestDestinationFolder $ChangedACL If ($ObjectType -eq 'File') { $ResultProxyFunction = New-OutputFile -ParentPath $TestDestinationFolder } Else { $ResultProxyFunction = New-OutputFolder -ParentPath $TestDestinationFolder } $Result = New-OutputObject -ObjectType $ObjectType -ParentPath $TestDestinationFolder It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 3 $ResultProxyFunction.ExitCode | Should Be 3 } It "Function $FunctionName - $ContextName - exit code description" { [System.String]$RequiredMessage = "Provided path {0} is not writable" -f $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$TestDestinationFolder") $Result.ExitCodeDescription | Should Be $RequiredMessage $ResultProxyFunction.ExitCodeDescription | Should Be $RequiredMessage } } $ContextName = "run with existing, non writable destination folder, break on error" Context "Function $FunctionName - $ContextName" { $TestDestinationFolder = "TestDrive:\ExistingNotWritable\" New-Item -Path $TestDestinationFolder -ItemType Container | Out-Null $ChangedACL = $OriginalAcl = Get-Acl -Path $TestDestinationFolder $colRights = [System.Security.AccessControl.FileSystemRights]"AppendData,WriteData" $InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None $PropagationFlag = [System.Security.AccessControl.PropagationFlags]::InheritOnly $objType = [System.Security.AccessControl.AccessControlType]::Deny $objUser = New-Object System.Security.Principal.NTAccount($(whoami)) $objACE = New-Object System.Security.AccessControl.FileSystemAccessRule ($objUser, $colRights, $InheritanceFlag, $PropagationFlag, $objType) $ChangedACL.AddAccessRule($objACE) Set-ACL -Path $TestDestinationFolder $ChangedACL If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { { $Result = New-OutputObject -ObjectType $ObjectType -ParentPath $TestDestinationFolder -BreakIfError } | Should Throw { $ResultProxyFunction = New-OutputFile -ParentPath $TestDestinationFolder -BreakIfError } | Should Throw } } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { { $Result = New-OutputObject -ObjectType $ObjectType -ParentPath $TestDestinationFolder -BreakIfError } | Should Throw { $ResultProxyFunction = New-OutputFolder -ParentPath $TestDestinationFolder -BreakIfError } | Should Throw } } } [System.String]$ContextName = "run without parameters, destination {0} exists, decision overwrite" -f $ObjectType Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" $OutputTypeToCreate = 'file' [System.String]$TestExistingObject = "TestDrive:\Output-20161108-000002.txt" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" $OutputTypeToCreate = 'directory' [System.String]$TestExistingObject = "TestDrive:\Output-20161108" } New-Item -Path $TestExistingObject -ItemType $OutputTypeToCreate Mock -ModuleName New-OutputObject -CommandName Get-OverwriteDecision -MockWith { Return [int]0 } If ($ObjectType -eq 'File') { $ResultProxyFunction = New-OutputFile } Else { $ResultProxyFunction = New-OutputFolder } $Result = New-OutputObject -ObjectType $ObjectType It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 4 $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code description" { [System.String]$RequiredMessage = "The {0} {1} already exist - can be overwritten" -f $ObjectType, $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$TestExistingObject") $Result.ExitCodeDescription | Should Be $RequiredMessage $ResultProxyFunction.ExitCodeDescription | Should Be $RequiredMessage } } [System.String]$ContextName = "run without parameters, destination {0} exists, decision leave" -f $ObjectType Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" $OutputTypeToCreate = 'file' [System.String]$TestExistingObject = "TestDrive:\Output-20161108-000002.txt" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" $OutputTypeToCreate = 'directory' [System.String]$TestExistingObject = "TestDrive:\Output-20161108" } New-Item -Path $TestExistingObject -ItemType $OutputTypeToCreate Mock -ModuleName New-OutputObject -CommandName Get-OverwriteDecision -MockWith { Return [int]1 } If ($ObjectType -eq 'File') { $ResultProxyFunction = New-OutputFile } Else { $ResultProxyFunction = New-OutputFolder } $Result = New-OutputObject -ObjectType $ObjectType It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { $Result.OutputObjectPath | Should BeOfType $ExpectedObjectType $ResultProxyFunction.OutputObjectPath | Should BeOfType $ExpectedObjectType } It "Function $FunctionName - $ContextName - OutputObjectPath - Name " { $Result.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName $ResultProxyFunction.OutputObjectPath.Name | Should Be $ExpectedOutputObjectName } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 5 $ResultProxyFunction.ExitCode | Should Be 5 } It "Function $FunctionName - $ContextName - exit code description" { [System.String]$RequiredMessage = "The {0} {1} already exist - can't be overwritten" -f $ItemTypeLower, $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$TestExistingObject") $Result.ExitCodeDescription | Should Be $RequiredMessage $ResultProxyFunction.ExitCodeDescription | Should Be $RequiredMessage } } $ContextName = "run without parameters, destination file exists, decision cancel" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" $OutputTypeToCreate = 'file' [System.String]$TestExistingObject = "TestDrive:\Output-20161108-000002.txt" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" $OutputTypeToCreate = 'directory' [System.String]$TestExistingObject = "TestDrive:\Output-20161108" } New-Item -Path $TestExistingObject -ItemType $OutputTypeToCreate Mock -ModuleName New-OutputObject -CommandName Get-OverwriteDecision -MockWith { Return [int]2 } If ($ObjectType -eq 'File') { It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { { $Result = New-OutputObject -ObjectType $ObjectType } | Should Throw { $ResultProxyFunction = New-OutputFile } | Should Throw } } Else { It "Function $FunctionName - $ContextName - OutputObjectPath - an object type" { { $Result = New-OutputObject -ObjectType $ObjectType } | Should Throw { $ResultProxyFunction = New-OutputFolder } | Should Throw } } } $ContextName = "run without parameters, incorrect chars in DateTimePartFormat, BreakIfError" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108-000002' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108-000002.txt" } Else { Mock -ModuleName New-OutputObject -CommandName Get-Date -MockWith { Return [System.String]'20161108' } -ParameterFilter { $Format } $ExpectedOutputObjectName = "Output-20161108" } If ($ObjectType -eq 'File') { It "Function $FunctionName - $ContextName" { { $Result = New-OutputObject -ObjectType $ObjectType -DateTimePartFormat "yyyyMMdd-HH:mm:ss" -BreakIfError } | Should Throw { $ResultProxyFunction = New-OutputFile -DateTimePartFormat "yyyyMMdd-HH:mm:ss" -BreakIfError } | Should Throw } } Else { It "Function $FunctionName - $ContextName" { { $Result = New-OutputObject -ObjectType $ObjectType -DateTimePartFormat "yyyyMMdd-HH>mm/ss" -BreakIfError } | Should Throw { $ResultProxyFunction = New-OutputFolder -DateTimePartFormat "yyyyMMdd-HH>mm/ss" -BreakIfError } | Should Throw } } } $ContextName = "run without parameters, incorrect chars in DateTimePartFormat, not BreakIfError" Context "Function $FunctionName - $ContextName" { If ($ObjectType -eq 'File') { $Result = New-OutputObject -ObjectType $ObjectType -DateTimePartFormat "yyyyMMdd-HH:mm:ss" $ResultProxyFunction = New-OutputFile -DateTimePartFormat "yyyyMMdd-HH:mm:ss" } Else { $Result = New-OutputObject -ObjectType $ObjectType -DateTimePartFormat "yyyyMMdd-HH>mm/ss" $ResultProxyFunction = New-OutputFolder -DateTimePartFormat "yyyyMMdd-HH>mm/ss" } It "Function $FunctionName - $ContextName - exit code" { $Result.ExitCode | Should Be 2 $ResultProxyFunction.ExitCode | Should Be 2 } It "Function $FunctionName - $ContextName - exit code description" { [System.String]$RequiredMessage = "The name not created due to unaccepatable chars" $Result.ExitCodeDescription | Should Be $RequiredMessage $ResultProxyFunction.ExitCodeDescription | Should Be $RequiredMessage } } Set-Location -Path $LocationAtBegin } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/psake.ps1
psake.ps1
# PSake makes variables declared here available in other scriptblocks # Init some things Properties { # Find the build folder based on build system $ProjectRoot = $ENV:BHProjectPath if(-not $ProjectRoot) { $ProjectRoot = $PSScriptRoot } $Timestamp = Get-date -uformat "%Y%m%d-%H%M%S" $PSVersion = $PSVersionTable.PSVersion.Major $TestFile = "TestResults_PS$PSVersion`_$TimeStamp.xml" $lines = '----------------------------------------------------------------------' $Verbose = @{} if($ENV:BHCommitMessage -match "!verbose") { $Verbose = @{Verbose = $True} } } Task Default -Depends Deploy Task Init { $lines Set-Location $ProjectRoot "Build System Details:" Get-Item ENV:BH* "`n" } Task Test -Depends Init { $lines Write-Host "Hahaha, tests" } Task Build -Depends Test { $lines # Bump the module version $Version = Get-NextPSGalleryVersion -Name $env:BHProjectName Update-Metadata -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -Value $Version } Task Deploy -Depends Build { $lines # Gate deployment if( $ENV:BHBuildSystem -ne 'Unknown' -and $ENV:BHBranchName -eq "master" -and $ENV:BHCommitMessage -match '!deploy' ) { $Params = @{ Path = $ProjectRoot Force = $true } Invoke-PSDeploy @Verbose @Params } else { "Skipping deployment: To deploy, ensure that...`n" + "`t* You are in a known build system (Current: $ENV:BHBuildSystem)`n" + "`t* You are committing to the master branch (Current: $ENV:BHBranchName) `n" + "`t* Your commit message includes !deploy (Current: $ENV:BHCommitMessage)" } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/deploy.psdeploy.ps1
deploy.psdeploy.ps1
# Generic module deployment. # This stuff should be moved to psake for a cleaner deployment view # ASSUMPTIONS: # folder structure of: # - RepoFolder # - This PSDeploy file # - ModuleName # - ModuleName.psd1 # Nuget key in $ENV:NugetApiKey # Set-BuildEnvironment from BuildHelpers module has populated ENV:BHProjectName # find a folder that has psd1 of same name... if($ENV:BHProjectName -and $ENV:BHProjectName.Count -eq 1) { Deploy Module { By PSGalleryModule { FromSource $ENV:BHPSModulePath To PSGallery WithOptions @{ ApiKey = $ENV:NugetApiKey } } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/build.ps1
build.ps1
# Grab nuget bits, install modules, set build variables, start build. Get-PackageProvider -Name NuGet -ForceBootstrap | Out-Null Install-Module Psake, PSDeploy, Pester, BuildHelpers -force Import-Module Psake, BuildHelpers Set-BuildEnvironment Invoke-psake .\psake.ps1 exit ( [int]( -not $psake.build_success ) )
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/SendItemsToOutput.ps1
SendItemsToOutput.ps1
function SendItemsToOutput { Param ( [parameter()] [PSObject[]]$items, [parameter(Mandatory=$true)] [string[]]$typeName ) foreach ($i in $items) { $i.PSObject.TypeNames.Insert(0, $typeName) Write-Output $i } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/Join-Parts.ps1
Join-Parts.ps1
#Function used to join URL. #Credit to http://stackoverflow.com/questions/9593535/best-way-to-join-parts-with-a-separator-in-powershell function Join-Parts { param ( [parameter(ValueFromRemainingArguments=$true)] [string[]]$Parts = $null ) $Separator = "/" ($Parts | Where { $_ } | Foreach { ([string]$_).trim($Separator) } | ? { $_ } ) -join $Separator }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/GetItemsFromRabbitMQApi.ps1
GetItemsFromRabbitMQApi.ps1
function GetItemsFromRabbitMQApi { [CmdletBinding()] Param ( [parameter(Mandatory=$true, Position = 0)] [alias("HostName", "cn")] [string]$BaseUri = $defaultComputerName, [parameter(Mandatory=$true, Position = 1)] [PSCredential]$cred = $defaultCredentials, [parameter(Mandatory=$true, Position = 2)] [string]$function, [int]$Port = 15672 ) Add-Type -AssemblyName System.Web #Add-Type -AssemblyName System.Net $url = Join-Parts $BaseUri "/api/$function" Write-Verbose "Invoking REST API: $url" return Invoke-RestMethod $url -Credential $cred -DisableKeepAlive -AllowEscapedDotsAndSlashes }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/ApplyFilter.ps1
ApplyFilter.ps1
function ApplyFilter { Param ( [parameter()] [PSObject[]]$items, [parameter(Mandatory=$true)] [string]$prop, [string[]]$name ) if (-not $name) { return $items } # apply property filter $filter = @() foreach($n in $name) { $filter += '$_.' + $prop + '-like "' + $n + '"' } $sb = [scriptblock]::create($filter -join ' -or ') return $items | ? $sb }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/NamesToString.ps1
NamesToString.ps1
function NamesToString { Param ( [string[]]$name, [string]$altText = "" ) if (-not $name) { return $altText } return $name -join ';' }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/Invoke-RestMethod.ps1
Invoke-RestMethod.ps1
function Invoke-RestMethod { [CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=217034')] param( [Microsoft.PowerShell.Commands.WebRequestMethod] ${Method}, [Parameter(Mandatory=$true, Position=0)] [ValidateNotNullOrEmpty()] [uri] ${Uri}, [Microsoft.PowerShell.Commands.WebRequestSession] ${WebSession}, [Alias('SV')] [string] ${SessionVariable}, [pscredential] ${Credential}, [switch] ${UseDefaultCredentials}, [ValidateNotNullOrEmpty()] [string] ${CertificateThumbprint}, [ValidateNotNull()] [System.Security.Cryptography.X509Certificates.X509Certificate] ${Certificate}, [string] ${UserAgent}, [switch] ${DisableKeepAlive}, [int] ${TimeoutSec}, [System.Collections.IDictionary] ${Headers}, [ValidateRange(0, 2147483647)] [int] ${MaximumRedirection}, [uri] ${Proxy}, [pscredential] ${ProxyCredential}, [switch] ${ProxyUseDefaultCredentials}, [Parameter(ValueFromPipeline=$true)] [System.Object] ${Body}, [string] ${ContentType}, [ValidateSet('chunked','compress','deflate','gzip','identity')] [string] ${TransferEncoding}, [string] ${InFile}, [string] ${OutFile}, [switch] ${PassThru}, [switch] ${AllowEscapedDotsAndSlashes}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\Invoke-RestMethod', [System.Management.Automation.CommandTypes]::Cmdlet) # check whether need to disable UnEscapingDotsAndSlases on UriParser $requiresDisableUnEscapingDotsAndSlashes = ($AllowEscapedDotsAndSlashes -and $Uri.OriginalString -match '%2f') # remove additional proxy parameter to prevent original function from failing if($PSBoundParameters['AllowEscapedDotsAndSlashes']) { $null = $PSBoundParameters.Remove('AllowEscapedDotsAndSlashes') } #By default the content-length is -1, which prevents ['Body'] from setting the content length. if($PSBoundParameters['Body']) { if ($PSBoundParameters['Headers']) { $PSBoundParameters['Headers']['content-length'] = 0 } else { $PSBoundParameters['Headers'] = @{ 'content-length' = 0 } } } #It seems that sometimes errors occur if you don't yield a short time. Start-Sleep -Milliseconds 100 $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { # Disable UnEscapingDotsAndSlashes on UriParser when necessary if ($requiresDisableUnEscapingDotsAndSlashes) { PreventUnEscapeDotsAndSlashesOnUri } $steppablePipeline.Process($_) } finally { # Restore UnEscapingDotsAndSlashes on UriParser when necessary if ($requiresDisableUnEscapingDotsAndSlashes) { RestoreUriParserFlags } } } end { try { $steppablePipeline.End() } catch { throw } } } <# .ForwardHelpTargetName Invoke-RestMethod .ForwardHelpCategory Cmdlet #>
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/Constants.ps1
Constants.ps1
$defaultComputerName = "http://localhost:15672" $defaultVirtualhost = "/" $defaultUserName = "guest" $defaultPassword = "guest" $defaultCredentials = New-Object System.Management.Automation.PSCredential ($defaultUserName, $(ConvertTo-SecureString $defaultPassword -AsPlainText -Force))
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Private/PreventUnEscapeDotsAndSlashesOnUri.ps1
PreventUnEscapeDotsAndSlashesOnUri.ps1
if (-not $UnEscapeDotsAndSlashes) { Set-Variable -Scope Script -name UnEscapeDotsAndSlashes -value 0x2000000 } function GetUriParserFlags { $getSyntax = [System.UriParser].GetMethod("GetSyntax", 40) $flags = [System.UriParser].GetField("m_Flags", 36) $parser = $getSyntax.Invoke($null, "http") return $flags.GetValue($parser) } function SetUriParserFlags([int]$newValue) { $getSyntax = [System.UriParser].GetMethod("GetSyntax", 40) $flags = [System.UriParser].GetField("m_Flags", 36) $parser = $getSyntax.Invoke($null, "http") $flags.SetValue($parser, $newValue) } function PreventUnEscapeDotsAndSlashesOnUri { if (-not $uriUnEscapesDotsAndSlashes) { return } Write-Verbose "Switching off UnEscapesDotsAndSlashes flag on UriParser." $newValue = $defaultUriParserFlagsValue -bxor $UnEscapeDotsAndSlashes SetUriParserFlags $newValue } function RestoreUriParserFlags { if (-not $uriUnEscapesDotsAndSlashes) { return } Write-Verbose "Restoring UriParser flags - switching on UnEscapesDotsAndSlashes flag." try { SetUriParserFlags $defaultUriParserFlagsValue } catch [System.Exception] { Write-Error "Failed to restore UriParser flags. This may cause your scripts to behave unexpectedly. You can find more at get-help about_UnEsapingDotsAndSlashes." throw } } if (-not $defaultUriParserFlagsValue) { Set-Variable -Scope Script -name defaultUriParserFlagsValue -value (GetUriParserFlags) } if (-not $uriUnEscapesDotsAndSlashes) { Set-Variable -Scope Script -name uriUnEscapesDotsAndSlashes -value (($defaultUriParserFlagsValue -band $UnEscapeDotsAndSlashes) -eq $UnEscapeDotsAndSlashes) }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQUser.ps1
Add-RabbitMQUser.ps1
<# .Synopsis Adds user to RabbitMQ server. .DESCRIPTION The Add-RabbitMQUser cmdlet allows to create new users in RabbitMQ server. To add a user to remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Add-RabbitMQUser -Name Admin -NewPassword p4ssw0rd -Tag administrator Create new user with name Admin having administrator tags set. User is added to local RabbitMQ server. .EXAMPLE Add-RabbitMQUser -HostName rabbitmq.server.com Admin p4ssw0rd administrator Create new user with name "Admin", password "p4ssw0rd" having "administrator" tags set. User is added to rabbitmq.server.com server. This command uses positional parameters. Note that password for new user is specified as -NewPassword parameter and not -Password parameter, which is used for authorisation to the server. .INPUTS You can pipe Name, NewPassword, Tags and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQUser { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")] Param ( # Name of user to create. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string]$Name, # Password for new user. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [string]$NewPassword, # Comma-separated list of user tags. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [ValidateSet("administrator", "monitoring", "policymaker", "management")] [string[]]$Tag, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri", "Add user $Name with tag: $Tag")) { $url = Join-Parts $BaseUri "/api/users/$([System.Web.HttpUtility]::UrlEncode($Name))" $body = @{ 'password' = $NewPassword 'tags' = $Tag -join ',' } | ConvertTo-Json $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" -Body $body Write-Verbose "Created user $User with tags $Tag" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Created $cnt new users." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQConnection.ps1
Remove-RabbitMQConnection.ps1
<# .Synopsis Closes connection to RabbitMQ server. .DESCRIPTION The Remove-RabbitMQConnection allows for closing connection to the RabbitMQ server. This cmdlet is marked with High impact. To close connections to the remote server you need to provide -HostName parameter. You may pipe an object with names and, optionally, with computer names to close multiple connection. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Remove-RabbitMQConnection conn1 This command closes connection to local RabbitMQ server named "conn1". .EXAMPLE Remove-RabbitMQConnection c1, c1 This command closes connections to local RabbitMQ server named "c1" and "c2". .EXAMPLE Remove-RabbitMQConnection c1 -HostName myrabbitmq.servers.com This command closes connection c1 to myrabbitmq.servers.com server. .EXAMPLE @("c1", "c2") | Remove-RabbitMQConnection This command pipes list of connection to be closed. In the above example two connections named "c1" and "c2" will be closed. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "c1"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "c2"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "c3"} ) $a | Remove-RabbitMQConnection Above example shows how to pipe both connection name and Computer Name to specify server. The above example will close two connection named "c1" and "c2" to local server, and one connection named "c3" to the server 127.0.0.1. .INPUTS You can pipe connection names and optionally HostNames to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQConnection { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of RabbitMQ connection. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("ConnectionName")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if (-not $pscmdlet.ShouldProcess("server: $BaseUri", "Close connection(s): $(NamesToString $Name '(all)')")) { foreach ($qn in $Name) { Write "Closing connection $qn to server=$BaseUri" $cnt++ } return } foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/connections/$([System.Web.HttpUtility]::UrlEncode($n))" $result = Invoke-RestMethod $url -Credential $Credentials -DisableKeepAlive -ErrorAction Continue -Method Delete Write-Verbose "Closed connection $n to server $BaseUri" $cnt++ } } End { if ($cnt > 1) { Write-Verbose "Closed $cnt connection(s)." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQVirtualHost.ps1
Remove-RabbitMQVirtualHost.ps1
<# .Synopsis Removes Virtual Hosts from RabbitMQ server. .DESCRIPTION The Remove-RabbitMQVirtualHost allows for removing Virtual Hosts in given RabbitMQ server. This cmdlet is marked with High impact. To remove Virtual Hosts from remote server you need to provide -HostName. You may pipe an object with names and, optionally, with computer names to remove multiple VirtualHosts. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Remove-RabbitMQVirtualHost testHost This command removes Virtual Host named "testHost" from local RabbitMQ server. .EXAMPLE Remove-RabbitMQVirtualHost VHost1, VHost2 This command removes Virtual Hosts named "VHost1" and "VHost2" from local RabbitMQ server. .EXAMPLE Remove-RabbitMQVirtualHost testHost -HostName myrabbitmq.servers.com This command removes Virtual Host named "testHost" from myrabbitmq.servers.com server. .EXAMPLE @("VHost1", "VHost2") | Remove-RabbitMQVirtualHost This command pipes list of Virtual Hosts to be removed from the RabbitMQ server. In the above example two Virtual Hosts named "VHost1" and "VHost2" will be removed from local RabbitMQ server. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "vh1"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "vh2"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "vh3"} ) $a | Remove-RabbitMQVirtualHost Above example shows how to pipe both Virtual Host name and Computer Name to specify server from which the Virtual Host should be removed. In the above example two Virtual Hosts named "vh1" and "vh2" will be removed from RabbitMQ local server, and one Virtual Host named "vh3" will be removed from the server 127.0.0.1. .INPUTS You can pipe VirtualHost names and optionally HostNames to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQVirtualHost { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of RabbitMQ Virtual Host. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "VirtualHost")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if (-not $pscmdlet.ShouldProcess("server: $BaseUri", "Remove vhost(s): $(NamesToString $Name '(all)')")) { foreach ($qn in $Name) { Write "Deleting Virtual Host(s) $qn (server=$BaseUri)" $cnt++ } return } foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/vhosts/$([System.Web.HttpUtility]::UrlEncode($n))" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete -ContentType "application/json" Write-Verbose "Removed Virtual Host $n on server $BaseUri" $cnt++ } } End { Write-Verbose "Removed $cnt Virtual Host(s)." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQUser.ps1
Remove-RabbitMQUser.ps1
<# .Synopsis Removes user from RabbitMQ server. .DESCRIPTION The Remove-RabbitMQUser cmdlet allows to delete users from RabbitMQ server. To remove a user from remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Remove-RabbitMQUser -Name Admin Deletes user "Admin"from local RabbitMQ server. .EXAMPLE Remove-RabbitMQUser -HostName rabbitmq.server.com Admin Deletes user "Admin" from rabbitmq.server.com server. This command uses positional parameters. .INPUTS You can pipe Name and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQUser { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of user to delete. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string]$Name, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri", "Delete user $Name")) { $url = Join-Parts $BaseUri "/api/users/$([System.Web.HttpUtility]::UrlEncode($Name))" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete -ContentType "application/json" Write-Verbose "Deleted user $User" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Deleted $cnt users." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQQueue.ps1
Remove-RabbitMQQueue.ps1
<# .Synopsis Removes Queue from RabbitMQ server. .DESCRIPTION The Remove-RabbitMQQueue allows for removing queues in given RabbitMQ server. This cmdlet is marked with High impact. To remove Queue from remote server you need to provide -HostName. You may pipe an object with names and, optionally, with computer names to remove multiple Queues. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Remove-RabbitMQQueue q1 -VirtualHost vh1 This command removes Queue named "q1" from virtual host vh1 located in local RabbitMQ server. .EXAMPLE Remove-RabbitMQQueue q1, q2 -VirtualHost vh1 This command removes Queues named "q1" and "q2" from local RabbitMQ server. .EXAMPLE Remove-RabbitMQQueue test -VirtualHost vh1 -HostName myrabbitmq.servers.com This command removes Queue named "test" from myrabbitmq.servers.com server. .EXAMPLE @("q1", "q2") | Remove-RabbitMQQueue -VirtualHost vh1 This command pipes list of Queues to be removed from the RabbitMQ server. In the above example two Queues named "q1" and "q2" will be removed from local RabbitMQ server. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "e1"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "e2"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "e3"} ) $a | Remove-RabbitMQQueue Above example shows how to pipe both Exchange name and Computer Name to specify server from which the Exchange should be removed. In the above example two Exchanges named "e1" and "e2" will be removed from RabbitMQ local server, and one Exchange named "e3" will be removed from the server 127.0.0.1. .INPUTS You can pipe Exchange names and optionally HostNames to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQQueue { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of RabbitMQ Queue. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("queue", "QueueName")] [string[]]$Name, # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri, vhost: $VirtualHost", "Remove queue(s): $(NamesToString $Name '(all)')")) { foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/queues/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($n))" Write-Verbose "Invoking REST API: $url" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete Write-Verbose "Deleted Queue $n on server $BaseUri, Virtual Host $VirtualHost" $cnt++ } } } End { if ($cnt -gt 1) { Write-Verbose "Deleted $cnt Queue(s)." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQChannel.ps1
Get-RabbitMQChannel.ps1
<# .Synopsis Gets open RabbitMQ Channels. .DESCRIPTION The Get-RabbitMQChannel cmdlet gets list of opened channels. The cmdlet allows you to show list of opened channels or filter them by name using wildcards. The result may be zero, one or many RabbitMQ.Channel objects. To get Nodes from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQChannel This command gets a list of opened channels. .EXAMPLE Get-RabbitMQChannel -HostName myrabbitmq.servers.com This command gets a list of opened channels to myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQChannel *53232* This command gets a list of all opened channels which name has "53232" number in it. .EXAMPLE Get-RabbitMQChannel -VirtualHost vhost1 This command gets all opened channels which are using Virtual Host named "vhost1". .EXAMPLE @("*53232*", "*53234*") | Get-RabbitMQChannel This command pipes channel name filters to Get-RabbitMQChannel cmdlet. .INPUTS You can pipe channel Name to filter the results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.Channel objects which describe cluster nodes. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQChannel { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Node. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Channel", "ChannelName")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseURI = $defaultComputerName, # Name of the virtual host to filter channels by. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseURI", "Get node(s): $(NamesToString $Name '(all)')")) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseURI $Credentials "channels" $result = ApplyFilter $result 'name' $Name if ($VirtualHost) { $result = ApplyFilter $result 'vhost' $VirtualHost } $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseURI SendItemsToOutput $result "RabbitMQ.Channel" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQVirtualHost.ps1
Add-RabbitMQVirtualHost.ps1
<# .Synopsis Adds Virtual Hosts to RabbitMQ server. .DESCRIPTION The Add-RabbitMQVirtualHost allows for creating new Virtual Hosts in given RabbitMQ server. To add Virtual Hosts to remote server you need to provide -HostName. You may pipe an object with names and, optionally, with computer names to create multiple VirtualHosts. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Add-RabbitMQVirtualHost testHost This command adds new Virtual Host named "testHost" to local RabbitMQ server. .EXAMPLE Add-RabbitMQVirtualHost VHost1, VHost2 This command adds two new Virtual Hosts named "VHost1" and "VHost2" to local RabbitMQ server. .EXAMPLE Add-RabbitMQVirtualHost testHost -HostName myrabbitmq.servers.com This command adds new Virtual Host named "testHost" to myrabbitmq.servers.com server. .EXAMPLE @("VHost1", "VHost2") | Add-RabbitMQVirtualHost This command pipes list of Virtual Hosts to add to the RabbitMQ server. In the above example two new Virtual Hosts named "VHost1" and "VHost2" will be created in local RabbitMQ server. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "vh1"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "vh2"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "vh3"} ) $a | Add-RabbitMQVirtualHost Above example shows how to pipe both Virtual Host name and Computer Name to specify server on which the Virtual Host should be created. In the above example two new Virtual Hosts named "vh1" and "vh1" will be created in RabbitMQ local server, and one Virtual Host named "vh3" will be created on the server 127.0.0.1. .INPUTS You can pipe VirtualHost names and optionally HostNames to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQVirtualHost { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")] Param ( # Name of RabbitMQ Virtual Host. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "VirtualHost")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials ) Begin { $cnt = 0 } Process { if (-not $pscmdlet.ShouldProcess("server: $BaseUri", "Add vhost(s): $(NamesToString $Name '(all)')")) { foreach ($qn in $Name) { Write "Creating new Virtual Host $qn on server $BaseUri" $cnt++ } return } foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/vhosts/$([System.Web.HttpUtility]::UrlEncode($n))" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" Write-Verbose "Created Virtual Host $n on server $BaseUri" $cnt++ } } End { Write-Verbose "Created $cnt Virtual Host(s)." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQConnection.ps1
Get-RabbitMQConnection.ps1
<# .Synopsis Gets Connections to the server. .DESCRIPTION The Get-RabbitMQConnection cmdlet gets connections to the RabbitMQ server. The cmdlet allows you to show all Connections or filter them by name using wildcards. The result may be zero, one or many RabbitMQ.Connection objects. To get Connections from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQConnection This command gets a list of all connections to local RabbitMQ server. .EXAMPLE Get-RabbitMQConnection -HostName myrabbitmq.servers.com This command gets a list of all connections myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQConnection con1* This command gets a list of all Connections with name starting with "con1". .EXAMPLE Get-RabbitMQConnection private*, public* This command gets a list of all Connections with name starting with either "private" or "public". .EXAMPLE @("private*", "*public") | Get-RabbitMQConnection This command pipes name filters to Get-RabbitMQConnection cmdlet. .INPUTS You can pipe Name to filter the results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.Connection objects which describe connections. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQConnection { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Connection. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Connection", "ConnectionName")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get connection(s): $(NamesToString $Name '(all)')")) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "connections" $result = ApplyFilter $result 'name' $Name $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri SendItemsToOutput $result "RabbitMQ.Connection" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQQueueBinding.ps1
Remove-RabbitMQQueueBinding.ps1
<# .Synopsis Removes binding between RabbitMQ Queue and Exchange. .DESCRIPTION The Remove-RabbitMQQueueBinding allows for removing bindings between RabbitMQ queues and exchanges. This cmdlet is marked with High impact. To remove Queue binding from remote server you need to provide -HostName. You may pipe an object with names and, optionally, with computer names to remove multiple Queues. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Remove-RabbitMQQueueBinding vh1 e1 q1 'e1-q1' This command removes binding "e1-q1" between exchange named "e1" and queue named "q1". The operation is performed on local server in virtual host vh1. .EXAMPLE Remove-RabbitMQQueueBinding vh1 e1 q1 'e1-q1' 127.0.0.1 This command removes binding "e1-q1" between exchange named "e1" and queue named "q1". The operation is performed on server 127.0.0.1 in default virtual host (/). .EXAMPLE Remove-RabbitMQQueueBinding -HostName 127.0.0.0 -VirtualHost vh1 -ExchangeName e1 -QueueName q1 -RoutingKey 'e1-q1' This command removes binding "e1-q1" between exchange named "e1" and queue named "q1". The operation is performed on server 127.0.0.1 in default virtual host (/). .EXAMPLE .INPUTS .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQQueueBinding { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of RabbitMQ Virtual Host. [parameter(Mandatory = $false, ValueFromPipelineByPropertyName=$true, Position = 0)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of RabbitMQ Exchange. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("exchange")] [string]$ExchangeName, # Name of RabbitMQ Queue. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("queue", "QueueName")] [string]$Name, # Routing key. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=3)] [Alias("rk")] [string]$RoutingKey, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=4)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("$BaseUri/$VirtualHost", "Remove binding between exchange $ExchangeName and queue $Name")) { $url = Join-Parts $BaseUri "/api/bindings/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/e/$([System.Web.HttpUtility]::UrlEncode($ExchangeName))/q/$([System.Web.HttpUtility]::UrlEncode($Name))/$([System.Web.HttpUtility]::UrlEncode($RoutingKey))" Write-Verbose "Invoking REST API: $url" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete Write-Verbose "Removed binding between exchange $ExchangeName and queue $Name $n on $BaseUri/$VirtualHost" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Unbound $cnt Queues." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Set-RabbitMQUser.ps1
Set-RabbitMQUser.ps1
<# .Synopsis Adds user to RabbitMQ server. .DESCRIPTION The Set-RabbitMQUser cmdlet allows to create new users in RabbitMQ server. To add a user to remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Set-RabbitMQUser -Name Admin -NewPassword p4ssw0rd -Tag administrator Create new user with name Admin having administrator tags set. User is added to local RabbitMQ server. .EXAMPLE Set-RabbitMQUser -HostName rabbitmq.server.com Admin p4ssw0rd administrator Create new user with name "Admin", password "p4ssw0rd" having "administrator" tags set. User is added to rabbitmq.server.com server. This command uses positional parameters. Note that password for new user is specified as -NewPassword parameter and not -Password parameter, which is used for authorisation to the server. .INPUTS You can pipe Name, NewPassword, Tags and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Set-RabbitMQUser { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] Param ( # Name of user to update. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string]$Name, # New password for user. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [string]$NewPassword, # Comma-separated list of user tags. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [ValidateSet("administrator", "monitoring", "policymaker", "management")] [string[]]$Tag, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $user = Get-RabbitMQUser -Credentials $Credentials -BaseUri $BaseUri -Name $Name if (-not $user) { throw "User $Name doesn't exist in server $BaseUri" } $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri", $(GetShouldProcessText))) { $url = Join-Parts $BaseUri "/api/users/$([System.Web.HttpUtility]::UrlEncode($Name))" $body = @{} if ($NewPassword) { $body.Add("password", $NewPassword) } if ($Tag) { $body.Add("tags", $Tag -join ',') } else { $body.Add("tags", $user.tags) } $bodyJson = $body | ConvertTo-Json $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" -Body $bodyJson Write-Verbose "Update user $User" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Updated $cnt new users." } } } function GetShouldProcessText { $str = "Update " if ($NewPassword -and $Tags) { $str += "password and tags" } if ($NewPassword) { $str += "password " } if ($Tag) { $str += "tags" } $str += " for user $user." if ($Tag) { $str += "New tags: $Tag" } return $str }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Move-RabbitMQMessage.ps1
Move-RabbitMQMessage.ps1
<# .Synopsis Moves messages from one RabbitMQ Queue to another. .DESCRIPTION The Move-RabbitMQMessage cmdlet allows to move messages from one RabbitMQ queue to another. Both source and destination queues must be in the same Virtual Host. The "exchange" and "routing_key" properties on moved messages will ba changed. Moving messages is done by publishing source message on the destination queue and removing it from source queue. The cmdlet is not designed to be used on sensitive data. WARNING This operation is not transactional and may result in not all messages being moved or some messages being duplicated. Also, if there are new messages published to the source queue or messages are consumed, then the operation may fail with unexpected result. Because of the nature of moving messages, this operation may change order of messages in the destination queue. To move messages on remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Move-RabbitMQMessage vh1 q1 q2 Moves all messages from q1 to q2 on Virtual Host vh1. .EXAMPLE Move-RabbitMQMessage vh1 q1 q2 5 Moves first 5 messages from q1 to q2 on Virtual Host vh1. .EXAMPLE Move-RabbitMQMessage -VirtualHost vh1 -$SourceQueueName q1 -$DestinationQueueName q2 -Count 5 Moves first 5 messages from q1 to q2 on Virtual Host vh1. .INPUTS .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Move-RabbitMQMessage { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] Param ( # Name of the virtual host to filter channels by. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of RabbitMQ Queue from which messages should be copied. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("from", "fromQueue")] [string]$SourceQueueName, # Name of RabbitMQ Queue to which messages should be copied. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("to", "toQueue")] [string]$DestinationQueueName, # If specified, gives the number of messages to copy. [parameter(ValueFromPipelineByPropertyName=$true, Position=3)] [int]$Count, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=4)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 $exchange = Get-RabbitMQQueueBinding -VirtualHost $VirtualHost -Name $DestinationQueueName -Credentials $Credentials | ? source -ne "" | select -First 1 } Process { $s = @{$true=$Count;$false='all'}[$Count -gt 0] if ($pscmdlet.ShouldProcess("server: $BaseUri/$VirtualHost", "Move $s messages from queue $SourceQueueName to queue $DestinationQueueName.")) { $m = Get-RabbitMQMessage -Credentials $Credentials -VirtualHost $VirtualHost -Name $SourceQueueName $c = $m.message_count + 1 if ($Count -eq 0 -or $Count -gt $c ) { $Count = $c } Write-Verbose "There are $Count messages to be copied." for ($i = 1; $i -le $Count; $i++) { # get message to be copies, but do not remove it from the server yet. $m = Get-RabbitMQMessage -Credentials $Credentials -VirtualHost $VirtualHost -Name $SourceQueueName # publish message to copying exchange, this will publish it onto dest queue as well as src queue. Add-RabbitMQMessage -Credentials $Credentials -VirtualHost $VirtualHost -ExchangeName $exchange.source -RoutingKey $exchange.routing_key -Payload $m.payload -Properties $m.properties # remove message from src queue. It has been published step earlier. $m = Get-RabbitMQMessage -Credentials $Credentials -VirtualHost $VirtualHost -Name $SourceQueueName -Remove Write-Verbose "published message $i out of $Count" $cnt++ } } } End { Write-Verbose "`r`nMoved $cnt messages from queue $SourceQueueName to queue $DestinationQueueName." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQVirtualHost.ps1
Get-RabbitMQVirtualHost.ps1
<# .Synopsis Gets Virtual Hosts registered with the server. .DESCRIPTION The Get-RabbitMQVirtualHost gets Virtual Hosts registered with RabbitMQ server. The cmdlet allows you to show all Virtual Hosts or filter them by name using wildcards. The result may be zero, one or many RabbitMQ.VirtualHost objects. To get Virtual Hosts from remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQVirtualHost This command gets a list of all Virtual Hosts registered with RabbitMQ on local server. .EXAMPLE Get-RabbitMQVirtualHost -HostName myrabbitmq.servers.com This command gets a list of all Virtual Hosts registered with RabbitMQ on myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQVirtualHost private* This command gets a list of all Virtual Hosts which name starts with "private". .EXAMPLE Get-RabbitMQVirtualHost private*, public* This command gets a list of all Virtual Hosts which name starts with "private" or "public". .EXAMPLE Get-RabbitMQVirtualHost private*, public* This command gets a list of all Virtual Hosts which name starts with "private" or "public". .EXAMPLE Get-RabbitMQVirtualHost marketing_private | select * This command selects all properties for given Virtual Host. .EXAMPLE @("private*", "*public") | Get-RabbitMQVirtualHost This command pipes name filters to Get-RabbitMQVirtualHost cmdlet. .INPUTS You can pipe Virtual Host names to filter results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.VirtualHost objects which describe Virtual Hosts. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQVirtualHost { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position = 0)] [Alias("vh", "VirtualHost")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get vhost(s): $(NamesToString $Name '(all)')")) { $vhosts = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "vhosts" $result = ApplyFilter $vhosts "name" $Name foreach($i in $result) { $i | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri } SendItemsToOutput $result "RabbitMQ.VirtualHost" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQQueueBinding.ps1
Add-RabbitMQQueueBinding.ps1
<# .Synopsis Adds binding between RabbitMQ exchange and queue. .DESCRIPTION The Add-RabbitMQQueueBinding binds RabbitMQ exchange with queue using RoutingKey To add QueueBinding to remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Add-RabbitMQQueueBinding -VirtualHost vh1 -ExchangeName e1 -Name q1 -RoutingKey 'e1-q1' This command binds exchange "e1" with queue "q1" using routing key "e1-q1". The operation is performed on local server in virtual host vh1. .EXAMPLE Add-RabbitMQQueueBinding -VirtualHost '/' -ExchangeName e1 -Name q1 -RoutingKey 'e1-q1' -BaseUri 127.0.0.1 This command binds exchange "e1" with queue "q1" using routing key "e1-q1". The operation is performed on server 127.0.0.1 in default virtual host (/). .EXAMPLE Add-RabbitMQQueueBinding -VirtualHost '/' -ExchangeName e1 -Name q1 -Headers @{FirstHeaderKey='FirstHeaderValue'; SecondHeaderKey='SecondHeaderValue'} -BaseUri 127.0.0.1 This command binds exchange "e1" with queue "q1" using the headers argument @{FirstHeaderKey='FirstHeaderValue'; SecondHeaderKey='SecondHeaderValue'}. The operation is performed on server 127.0.0.1 in default virtual host (/). .INPUTS .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQQueueBinding { [CmdletBinding(DefaultParameterSetName='RoutingKey', SupportsShouldProcess=$true, ConfirmImpact="Low")] Param ( # Name of the virtual host. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of RabbitMQ Exchange. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("exchange", "source")] [string]$ExchangeName, # Name of RabbitMQ Queue. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("queue", "QueueName", "destination")] [string]$Name, # Routing key. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=3, ParameterSetName='RoutingKey')] [Alias("rk", "routing_key")] [string]$RoutingKey, # Headers hashtable [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=3, ParameterSetName='Headers')] [Hashtable]$Headers = @{}, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=4)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("$BaseUri/$VirtualHost", "Add queue binding from exchange $ExchangeName to queue $Name with $($PSCmdlet.ParameterSetName)")) { foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/bindings/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/e/$([System.Web.HttpUtility]::UrlEncode($ExchangeName))/q/$([System.Web.HttpUtility]::UrlEncode($Name))" Write-Verbose "Invoking REST API: $url" $body = @{ "routing_key" = $RoutingKey "arguments" = $headers } $bodyJson = $body | ConvertTo-Json -Depth 3 -Compress $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Post -ContentType "application/json" -Body $bodyJson Write-Verbose "Bound exchange $ExchangeName to queue $Name $n on $BaseUri/$VirtualHost" $cnt++ } } } End { Write-Verbose "Created $cnt Binding(s)." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQExchange.ps1
Remove-RabbitMQExchange.ps1
<# .Synopsis Removes Exchange from RabbitMQ server. .DESCRIPTION The Remove-RabbitMQExchange allows for removing exchanges in given RabbitMQ server. This cmdlet is marked with High impact. To remove Exchange from remote server you need to provide -HostName. You may pipe an object with names and, optionally, with computer names to remove multiple Exchanges. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Remove-RabbitMQExchange test This command removes Exchange named "test" from local RabbitMQ server. .EXAMPLE Remove-RabbitMQExchange e1, e2 This command removes Exchanges named "e1" and "e2" from local RabbitMQ server. .EXAMPLE Remove-RabbitMQExchange test -HostName myrabbitmq.servers.com This command removes Exchange named "test" from myrabbitmq.servers.com server. .EXAMPLE @("e1", "e2") | Remove-RabbitMQExchange This command pipes list of Exchanges to be removed from the RabbitMQ server. In the above example two Exchanges named "e1" and "e2" will be removed from local RabbitMQ server. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "e1"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "e2"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "e3"} ) $a | Remove-RabbitMQExchange Above example shows how to pipe both Exchange name and Computer Name to specify server from which the Exchange should be removed. In the above example two Exchanges named "e1" and "e2" will be removed from RabbitMQ local server, and one Exchange named "e3" will be removed from the server 127.0.0.1. .INPUTS You can pipe Exchange names and optionally HostNames to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQExchange { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of RabbitMQ Exchange. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("Exchange", "ExchangeName")] [string[]]$Name, # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri, vhost: $VirtualHost", "Remove exchange(s): $(NamesToString $Name '(all)')")) { foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/exchanges/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($n))" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete Write-Verbose "Deleted Exchange $n on server $BaseUri, Virtual Host $VirtualHost" $cnt++ } } } End { if ($cnt -gt 1) { Write-Verbose "Deleted $cnt Exchange(s)." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQExchange.ps1
Add-RabbitMQExchange.ps1
<# .Synopsis Adds Exchange to RabbitMQ server. .DESCRIPTION The Add-RabbitMQExchange allows for creating new Exchanges in given RabbitMQ server. To add Exchange to remote server you need to provide -HostName You may pipe an object with names and parameters, including HostName, to create multiple Exchanges. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Add-RabbitMQExchange -Type direct TestExchange Creates direct exchange named TestExchange in the local RabbitMQ server. .EXAMPLE Add-RabbitMQExchange -Type direct TestExchange -Durable -AutoDelete -Internal -AlternateExchange e2 Creates direct exchange named TestExchange in the local RabbitMQ server and sets its properties to be Durable, AutoDelete, Internal and to use alternate exchange called e2. .EXAMPLE Add-RabbitMQExchange -Type fanout TestExchange, ProdExchange Creates in the local RabbitMQ server two fanout exchanges named TestExchange and ProdExchange. .EXAMPLE Add-RabbitMQExchange -Type direct TestExchange -HostName myrabbitmq.servers.com Creates direct exchange named TestExchange in the myrabbitmq.servers.com server. .EXAMPLE @("e1", "e2") | Add-RabbitMQExchange -Type direct This command pipes list of exchanges to add to the RabbitMQ server. In the above example two new Exchanges named "e1" and "e2" will be created in local RabbitMQ server. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "e1", "Type"="direct"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "e2", "Type"="fanout"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "e3", "Type"="topic", Durable=$true, $Internal=$true} ) $a | Add-RabbitMQExchange Above example shows how to pipe parameters for creating new exchanges. In the above example three new exchanges will be created with different parameters. .INPUTS You can pipe Name, Type, Durable, AutoDelete, Internal, AlternateExchange, VirtualHost and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQExchange { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] Param ( # Name of RabbitMQ Exchange. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("Exchange", "ExchangeName")] [string[]]$Name, # Type of the Exchange to create. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [ValidateSet("topic", "fanout", "direct", "headers")] [string]$Type, # Determines whether the exchange should be Durable. [parameter(ValueFromPipelineByPropertyName=$true)] [switch]$Durable, # Determines whether the exchange will be deleted once all queues have finished using it. [parameter(ValueFromPipelineByPropertyName=$true)] [switch]$AutoDelete, # Determines whether the exchange should be Internal. [parameter(ValueFromPipelineByPropertyName=$true)] [switch]$Internal, # Allows to set alternate exchange to which all messages which cannot be routed will be send. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("alt")] [string]$AlternateExchange, # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri, vhost: $VirtualHost", "Add exchange(s): $(NamesToString $Name '(all)')")) { $body = @{ type = "$Type" } if ($Durable) { $body.Add("durable", $true) } if ($AutoDelete) { $body.Add("auto_delete", $true) } if ($Internal) { $body.Add("internal", $true) } if ($AlternateExchange) { $body.Add("arguments", @{ "alternate-exchange"=$AlternateExchange }) } $bodyJson = $body | ConvertTo-Json foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/exchanges/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($n))" Write-Verbose "Invoking REST API: $url" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" -Body $bodyJson Write-Verbose "Created Exchange $n on server $BaseUri, Virtual Host $VirtualHost" $cnt++ } } } End { if ($cnt -gt 1) { Write-Verbose "Created $cnt Exchange(s)." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Remove-RabbitMQPermission.ps1
Remove-RabbitMQPermission.ps1
<# .Synopsis Removes permissions to virtual host for a user. .DESCRIPTION The Remove-RabbitMQPermission cmdlet allows to remove user permissions to virtual host. To remove permissions to remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Remove-RabbitMQPermission -VirtualHost '/' -User Admin Removes permissions for user Admin to default virtual host (/) on local RabbitMQ server. .EXAMPLE Remove-RabbitMQPermission -HostName rabbitmq.server.com '/' Admin Removes permissions for user Admin to default virtual host (/) on remote RabbitMQ rabbitmq.server.com. .INPUTS You can pipe VirtualHost, User and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Remove-RabbitMQPermission { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] Param ( # Virtual host to set permission for. [parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vhost", "vh")] [string]$VirtualHost = $defaultVirtualhost, # Name of user to set permission for. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [string]$User, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $p = Get-RabbitMQPermission -BaseUri $BaseUri -Credentials $Credentials -VirtualHost $VirtualHost -User $User if (-not $p) { throw "Permissions to virtual host $VirtualHost for user $User do not exist. To create permissions use Add-RabbitMQPermission cmdlet." } $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri", "Remove permissions to virtual host $VirtualHost for user $User : $Configure, $Read $Write")) { $url = Join-Parts $BaseUri "/api/permissions/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($User))" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete Write-Verbose "Removed permissions to $VirtualHost for $User : $Configure, $Read, $Write" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Removed $cnt permissions." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQMessage.ps1
Add-RabbitMQMessage.ps1
<# .Synopsis Gets messages from RabbitMQ Queue. .DESCRIPTION The Add-RabbitMQMessage cmdlet gets messages from RabbitMQ queue. The result may be zero, one or many RabbitMQ.Message objects. To get Connections from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Add-RabbitMQMessage vh1 q1 This command gets first message from queue "q1" on virtual host "vh1". .EXAMPLE Add-RabbitMQMessage test q1 -Count 10 This command gets first 10 messages from queue "q1" on virtual host "vh1". .EXAMPLE Add-RabbitMQMessage test q1 127.0.0.1 This command gets first message from queue "q1" on virtual host "vh1", server 127.0.0.1. .INPUTS .OUTPUTS By default, the cmdlet returns list of RabbitMQ.QueueMessage objects which describe connections. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQMessage { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of the virtual host to filter channels by. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of RabbitMQ Exchange. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("exchange")] [string]$ExchangeName, # Routing key to be used when publishing message. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("rk")] [string]$RoutingKey, # Massage's payload [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=3)] [string]$Payload, # Array with message properties. [parameter(ValueFromPipelineByPropertyName=$true, Position=4)] $Properties, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { if ($Properties -eq $null) { $Properties = @{} } } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri/$VirtualHost", "Publish message to exchange $ExchangeName with routing key $RoutingKey")) { $url = Join-Parts $BaseUri "/api/exchanges/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($ExchangeName))/publish" Write-Verbose "Invoking REST API: $url" $body = @{ routing_key = $RoutingKey payload_encoding = "string" payload = $Payload properties = $Properties } $bodyJson = $body | ConvertTo-Json $retryCounter = 0 while ($retryCounter -lt 3) { $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Post -ContentType "application/json" -Body $bodyJson if ($result.routed -ne $true) { Write-Warning "Message was no routed. Operation will be retried. URI: $url" $retryCounter++ } else { break } } } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQUser.ps1
Get-RabbitMQUser.ps1
<# .Synopsis Gets list of users. .DESCRIPTION The Get-RabbitMQUser gets list of users registered in RabbitMQ server. The result may be zero, one or many RabbitMQ.User objects. To get users from remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQUser Gets list of all users in local RabbitMQ server. .EXAMPLE Get-RabbitMQUser -HostName myrabbitmq.servers.com Gets list of all users in myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQUser gu* Gets list of all users whose name starts with "gu". .EXAMPLE Get-RabbitMQUser guest, admin Gets data for users guest and admin. .EXAMPLE Get-RabbitMQUser -View Flat Gets flat list of all users. This view doesn't group users by HostName as the default view do. .INPUTS You can pipe Names and HostNames to filter results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.User objects which describe user. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQUser { [CmdletBinding(SupportsShouldProcess=$true, PositionalBinding=$false)] Param ( # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [string[]]$Name, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("cn", "HostName")] [string]$BaseUri = $defaultComputerName, [ValidateSet("Default", "Flat")] [string]$View, [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get user(s)")) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "users" $result = ApplyFilter $result 'name' $Name $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri if (-not $View) { SendItemsToOutput $result "RabbitMQ.User" } else { SendItemsToOutput $result "RabbitMQ.User" | ft -View $View } } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Clear-RabbitMQQueue.ps1
Clear-RabbitMQQueue.ps1
<# .Synopsis Purges all messages from RabbitMQ Queue. .DESCRIPTION The Clear-RabbitMQQueue removes all messages from given RabbitMQ queue. To remove message from Queue on remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Clear-RabbitMQQueue vh1 q1 Removes all messages from queue "q1" in Virtual Host "vh1" on local computer. .EXAMPLE Clear-RabbitMQQueue -VirtualHost vh1 -Name q1 Removes all messages from queue "q1" in Virtual Host "vh1" on local computer. .EXAMPLE Clear-RabbitMQQueue -VirtualHost vh1 -Name q1 -HostName rabbitmq.server.com Removes all messages from queue "q1" in Virtual Host "vh1" on "rabbitmq.server.com" server. #> function Clear-RabbitMQQueue { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")] Param ( # Name of RabbitMQ Virtual Host. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualHost, # The name of the queue from which to receive messages [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("qn", "QueueName")] [string]$Name, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("cn", "HostName")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri/$VirtualHost", "purge queue $Name")) { $url = Join-Parts $BaseUri "/api/queues/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($Name))/contents" Write-Verbose "Invoking REST API: $url" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Delete } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQNode.ps1
Get-RabbitMQNode.ps1
<# .Synopsis Gets RabbitMQ Nodes. .DESCRIPTION The Get-RabbitMQNode cmdlet gets nodes in RabbitMQ cluster. The cmdlet allows you to show list of cluster nodes or filter them by name using wildcards. The result may be zero, one or many RabbitMQ.Node objects. To get Nodes from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQNode This command gets a list of nodes in RabbitMQ cluster. .EXAMPLE Get-RabbitMQNode -HostName myrabbitmq.servers.com This command gets a list of nodes in the cluster on myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQNode second* This command gets a list of nodes in a cluster which name starts with "second". .EXAMPLE Get-RabbitMQNode secondary*, primary This command gets cluster nodes which name is either "primary" or starts with "secondary". .EXAMPLE @("primary", "secondary") | Get-RabbitMQNode This command pipes node name filters to Get-RabbitMQNode cmdlet. .INPUTS You can pipe Name to filter the results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.Node objects which describe cluster nodes. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQNode { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Node. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Node", "NodeName")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get node(s): $(NamesToString $Name '(all)')")) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "nodes" $result = ApplyFilter $result 'name' $Name $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri SendItemsToOutput $result "RabbitMQ.Node" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQQueue.ps1
Get-RabbitMQQueue.ps1
<# .Synopsis Gets open RabbitMQ Channels. .DESCRIPTION The Get-RabbitMQQueue cmdlet gets queues registered with RabbitMQ server. The cmdlet allows you to show list of all queues or filter them by name using wildcards. The result may be zero, one or many RabbitMQ.Queue objects. To get Queues from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQQueue This command gets a list of all queues reigsters with local RabbitMQ server. .EXAMPLE Get-RabbitMQQueue -HostName myrabbitmq.servers.com This command gets a list of all queues registerd with myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQQueue services* This command gets a list of all queues which name starts with "services". .EXAMPLE Get-RabbitMQQueue -VirtualHost vhost1 This command gets a list of all queues in Virtual Host "vhost1". .EXAMPLE Get-RabbitMQQueue -NotEmpty This command gets a list of all queues having messages. .EXAMPLE Get-RabbitMQQueue -ShowStats This command shows queue statistics. It is equivalent to running Get-RabbitMQQueue | Format-Table -View Stats .EXAMPLE @("services*", "posion*") | Get-RabbitMQQueue This command pipes queue name filters to Get-RabbitMQQueue cmdlet. .INPUTS You can pipe queue Name, VirtualHost and HostName to filter the results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.Queue objects which describe RabbitMQ queue. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQQueue { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ queue. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("queue", "QueueName")] [string[]]$Name = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Name of the virtual host to filter channels by. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost, # When set then returns only queues which have messages. [switch]$NotEmpty, # When set then displays queue statistics. [switch]$ShowStats, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get queues(s): $(NamesToString $Name '(all)')")) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "queues" $result = ApplyFilter $result 'name' $Name if ($VirtualHost) { $result = ApplyFilter $result 'vhost' $VirtualHost } foreach ($item in $result) { if ($item.messages -eq $null) { $item | Add-Member -MemberType NoteProperty -Name messages -Value 0 } if ($item.messages_ready -eq $null) { $item | Add-Member -MemberType NoteProperty -Name messages_ready -Value 0 } if ($item.messages_unacknowledged -eq $null) { $item | Add-Member -MemberType NoteProperty -Name messages_unacknowledged -Value 0 } } if ($NotEmpty) { $result = $result | ? messages -ne 0 } $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri if ($ShowStats) { SendItemsToOutput $result "RabbitMQ.Queue" | ft -View Stats } else { SendItemsToOutput $result "RabbitMQ.Queue" } } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Copy-RabbitMQMessage.ps1
Copy-RabbitMQMessage.ps1
<# .Synopsis Copies messages from one RabbitMQ Queue to another. .DESCRIPTION The Copy-RabbitMQMessage cmdlet allows to copy messages from one RabbitMQ queue to another. Both source and destination queues must be in the same Virtual Host. The "exchange" and "routing_key" properties on copied messages will ba changed. Copying messages is done by creating new exchange, binding both from and to queues to it and republishing messages from source queue. The cmdlet is not designed to be used on sensitive data. WARNING This operation is not transactional and may result in not all messages being copied or some messages being duplicated. Also, if there are new messages published to the source queue or messages are consumed, then the operation may fail with unexpected result. Because of the nature of copying messages, this operation may change order of messages in the source queue. To copy messages on remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Copy-RabbitMQMessage vh1 q1 q2 Copy all messages from q1 to q2 on Virtual Host vh1. .EXAMPLE Copy-RabbitMQMessage vh1 q1 q2 5 Copy first 5 messages from q1 to q2 on Virtual Host vh1. .EXAMPLE Copy-RabbitMQMessage -VirtualHost vh1 -$SourceQueueName q1 -$DestinationQueueName q2 -Count 5 Copy first 5 messages from q1 to q2 on Virtual Host vh1. .INPUTS .OUTPUTS By default, the cmdlet returns list of RabbitMQ.QueueMessage objects which describe connections. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Copy-RabbitMQMessage { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] Param ( # Name of the virtual host to filter channels by. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Name of RabbitMQ Queue from which messages should be copied. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Alias("from", "fromQueue")] [string]$SourceQueueName, # Name of RabbitMQ Queue to which messages should be copied. [parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("to", "toQueue")] [string]$DestinationQueueName, # If specified, gives the number of messages to copy. [parameter(ValueFromPipelineByPropertyName=$true, Position=3)] [int]$Count, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=4)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 $requiresMessageRemoval = $SourceQueueName -ne $DestinationQueueName } Process { $s = @{$true=$Count;$false='all'}[$Count -gt 0] if ($pscmdlet.ShouldProcess("server: $BaseUri/$VirtualHost", "Copy $s messages from queue $SourceQueueName to queue $DestinationQueueName.")) { $ename = "RabbitMQTools_copy" $routingKey = "RabbitMQTools_copy" Add-RabbitMQExchange -BaseUri $BaseUri -VirtualHost $VirtualHost -Type fanout -AutoDelete -Name $ename -Credentials $Credentials Add-RabbitMQQueueBinding -BaseUri $BaseUri -VirtualHost $VirtualHost -ExchangeName $ename -Name $SourceQueueName -RoutingKey $routingKey -Credentials $Credentials Add-RabbitMQQueueBinding -BaseUri $BaseUri -VirtualHost $VirtualHost -ExchangeName $ename -Name $DestinationQueueName -RoutingKey $routingKey -Credentials $Credentials try { $m = Get-RabbitMQMessage -Credentials $Credentials -BaseUri $BaseUri -VirtualHost $VirtualHost -Name $SourceQueueName $c = $m.message_count + 1 if ($Count -eq 0 -or $Count -gt $c ) { $Count = $c } Write-Verbose "There are $Count messages to be copied." for ($i = 1; $i -le $Count; $i++) { # get message to be copies, but do not remove it from the server yet. $m = Get-RabbitMQMessage -Credentials $Credentials -BaseUri $BaseUri -VirtualHost $VirtualHost -Name $SourceQueueName # publish message to copying exchange, this will publish it onto dest queue as well as src queue. Add-RabbitMQMessage -Credentials $Credentials -BaseUri $BaseUri -VirtualHost $VirtualHost -ExchangeName $ename -RoutingKey $routingKey -Payload $m.payload -Properties $m.properties # remove message from src queue. It has been published step earlier. if ($requiresMessageRemoval) { $m = Get-RabbitMQMessage -Credentials $Credentials -BaseUri $BaseUri -VirtualHost $VirtualHost -Name $SourceQueueName -Remove } [int]$p = ($i * 100) / $Count if ($p -gt 100) { $p = 100 } Write-Progress -Activity "Copying messages from $SourceQueueName to $DestinationQueueName" -Status "Copying message $i out of $Count" -PercentComplete $p Write-Verbose "published message $i out of $Count" $cnt++ } } finally { Remove-RabbitMQExchange -Credentials $Credentials -BaseUri $BaseUri -VirtualHost $VirtualHost -Name $ename -Confirm:$false } } } End { Write-Verbose "`r`nCopied $cnt messages from queue $SourceQueueName to queue $DestinationQueueName." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQQueueBinding.ps1
Get-RabbitMQQueueBinding.ps1
<# .Synopsis Gets bindings for given RabbitMQ Queue. .DESCRIPTION The Get-RabbitMQQueueBinding cmdlet gets bindings for given RabbitMQ Queue. The cmdlet allows you to show all Bindings for given RabbitMQ Queue. The result may be zero, one or many RabbitMQ.Connection objects. To get Connections from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQQueueBinding vh1 q1 This command gets a list of bindings for queue named "q1" on virtual host "vh1". .EXAMPLE Get-RabbitMQQueueBinding -VirtualHost vh1 -Name q1 -HostName myrabbitmq.servers.com This command gets a list of bindings for queue named "q1" on virtual host "vh1" and server myrabbitmq.servers.com. .EXAMPLE Get-RabbitMQQueueBinding vh1 q1,q2,q3 This command gets a list of bindings for queues named "q1", "q2" and "q3" on virtual host "vh1". .INPUTS You can pipe Name, VirtualHost and HostName to this cmdlet. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.QueueBinding objects which describe connections. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQQueueBinding { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Queue. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("queue", "QueueName")] [string[]]$Name = "", # Name of the virtual host to filter channels by. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true, Position=2)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if (-not $VirtualHost) { # figure out the Virtual Host value $p = @{} $p.Add("Credentials", $Credentials) if ($BaseUri) { $p.Add("BaseUri", $BaseUri) } $queues = Get-RabbitMQQueue @p | ? Name -eq $Name if (-not $queues) { return; } if (-not $queues.GetType().IsArray) { $VirtualHost = $queues.vhost } else { $vhosts = $queues | select vhost $s = $vhosts -join ',' Write-Error "Queue $Name exists in multiple Virtual Hosts: $($queues.vhost -join ', '). Please specify Virtual Host to use." } } if ($pscmdlet.ShouldProcess("server $BaseUri", "Get bindings for queue(s): $(NamesToString $Name '(all)')")) { foreach ($n in $Name) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "queues/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($n))/bindings" $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri SendItemsToOutput $result "RabbitMQ.QueueBinding" } } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Register-RabbitMQServer.ps1
Register-RabbitMQServer.ps1
<# .Synopsis Registers RabbitMQ server. .DESCRIPTION Register-RabbitMQ server cmdlet allows to add RabbitMQ server to the tab completition list for HostName. .EXAMPLE Register-RabbitMQServer '127.0.0.1' Adds server 127.0.0.1 to auto completition list for HostName parameter. .EXAMPLE Register-RabbitMQServer '127.0.0.1' 'My local PC' Adds server 127.0.0.1 to auto completition list for HostName parameter. The text 'My local PC' will be used as a tooltip. #> function Register-RabbitMQServer { [CmdletBinding()] Param ( # Name of the RabbitMQ server to be registered. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] $BaseUri, # Description to be used in tooltip. If not provided then computer name will be used. [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)] $Description ) Begin { if (-not $global:RabbitMQServers) { $global:RabbitMQServers = @() } } Process { $obj += $global:RabbitMQServers | ? ListItemText -eq $BaseUri if (-not $obj) { if (-not $Description) { $Description = $BaseUri } $escapedHostName = $BaseUri -replace '\[', '``[' -replace '\]', '``]' $global:RabbitMQServers += New-Object System.Management.Automation.CompletionResult $escapedHostName, $BaseUri, 'ParameterValue', $Description } else { Write-Warning "Server $BaseUri is already registered. If you want to update the entry you need to unregister the server and register it again" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Set-RabbitMQPermission.ps1
Set-RabbitMQPermission.ps1
<# .Synopsis Updates permissions to virtual host for a user. .DESCRIPTION The Set-RabbitMQPermission cmdlet allows to update user permissions to virtual host. To update permissions to remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Set-RabbitMQPermission -VirtualHost '/' -User Admin -Configure .* -Read .* -Write .* Update configure, read and write permissions for user Admin to default virtual host (/). .EXAMPLE Set-RabbitMQPermission -HostName rabbitmq.server.com '/' Admin .* .* .* Update configure, read and write permissions for user Admin to default virtual host (/) on server rabbitmq.server.com. This command uses positional parameters. .INPUTS You can pipe VirtualHost, User, Configure, Read, Write and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Set-RabbitMQPermission { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] Param ( # Virtual host to set permission for. [parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vhost", "vh")] [string]$VirtualHost = $defaultVirtualhost, # Name of user to set permission for. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [string]$User, # Configure permission regexp. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [string]$Configure, # Read permission regexp. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=3)] [string]$Read, # Write permission regexp. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=4)] [string]$Write, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $p = Get-RabbitMQPermission -BaseUri $BaseUri -Credentials $Credentials -VirtualHost $VirtualHost -User $User if (-not $p) { throw "Permissions to virtual host $VirtualHost for user $User do not exist. To create permissions use Add-RabbitMQPermission cmdlet." } $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri", "Changes permission to virtual host $VirtualHost for user $User : $Configure, $Read $Write")) { $url = Join-Parts $BaseUri "/api/permissions/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($User))" $body = @{ 'configure' = $Configure 'read' = $Read 'write' = $Write } | ConvertTo-Json $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" -Body $body Write-Verbose "Changed permission to $VirtualHost for $User : $Configure, $Read, $Write" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Changed $cnt permissions." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Unregister-RabbitMQServer.ps1
Unregister-RabbitMQServer.ps1
<# .Synopsis Unregisters RabbitMQ server. .DESCRIPTION Unregister-RabbitMQ server cmdlet allows to remove RabbitMQ server from tab completition list for HostName. .EXAMPLE Unregister-RabbitMQServer '127.0.0.1' Removes server 127.0.0.1 from auto completition list for HostName parameter. #> function Unregister-RabbitMQServer { [CmdletBinding()] Param ( # Name of the RabbitMQ server to be unregistered. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] $BaseUri ) Begin { if (-not $global:RabbitMQServers) { $global:RabbitMQServers = @() } } Process { $obj += $global:RabbitMQServers | ? ListItemText -eq $BaseUri if ($obj) { $global:RabbitMQServers = $global:RabbitMQServers | ? ListItemText -ne $BaseUri } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQExchange.ps1
Get-RabbitMQExchange.ps1
<# .Synopsis Gets Virtual Hosts registered with the server. .DESCRIPTION The Get-RabbitMQVirtualHost gets Virtual Hosts registered with RabbitMQ server. The cmdlet allows you to show all Virtual Hosts or filter them by name using wildcards. The result may be zero, one or many RabbitMQ.VirtualHost objects. To get Virtual Hosts from remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQVirtualHost This command gets a list of all Virtual Hosts registered with RabbitMQ on local server. .EXAMPLE Get-RabbitMQVirtualHost -HostName myrabbitmq.servers.com This command gets a list of all Virtual Hosts registered with RabbitMQ on myrabbitmq.servers.com server. .EXAMPLE Get-RabbitMQVirtualHost private* This command gets a list of all Virtual Hosts which name starts with "private". .EXAMPLE Get-RabbitMQVirtualHost private*, public* This command gets a list of all Virtual Hosts which name starts with "private" or "public". .EXAMPLE Get-RabbitMQVirtualHost private*, public* This command gets a list of all Virtual Hosts which name starts with "private" or "public". .EXAMPLE Get-RabbitMQVirtualHost marketing_private | select * This command selects all properties for given Virtual Host. .EXAMPLE @("private*", "*public") | Get-RabbitMQVirtualHost This command pipes name filters to Get-RabbitMQVirtualHost cmdlet. .INPUTS You can pipe Virtual Host names to filter results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.VirtualHost objects which describe Virtual Hosts. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQExchange { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Exchange. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("ex", "Exchange", "ExchangeName")] [string[]]$Name = "", # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh")] [string]$VirtualHost = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get exchange(s): $(NamesToString $Name '(all)')")) { $exchanges = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "exchanges" $result = ApplyFilter $exchanges 'vhost' $VirtualHost $result = ApplyFilter $result 'name' $Name $result | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri SendItemsToOutput $result "RabbitMQ.Exchange" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQMessage.ps1
Get-RabbitMQMessage.ps1
<# .Synopsis Gets messages from RabbitMQ Queue. .DESCRIPTION The Get-RabbitMQMessage cmdlet gets messages from RabbitMQ queue. The result may be zero, one or many RabbitMQ.Message objects. To get Connections from remote server you need to provide -HostName parameter. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQMessage vh1 q1 This command gets first message from queue "q1" on virtual host "vh1". .EXAMPLE Get-RabbitMQMessage test q1 -Count 10 This command gets first 10 messages from queue "q1" on virtual host "vh1". .EXAMPLE Get-RabbitMQMessage test q1 127.0.0.1 This command gets first message from queue "q1" on virtual host "vh1", server 127.0.0.1. .INPUTS .OUTPUTS By default, the cmdlet returns list of RabbitMQ.QueueMessage objects which describe connections. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQMessage { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Queue. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("queue", "QueueName")] [string]$Name = "", # Name of the virtual host to filter channels by. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Number of messages to get. Default value is 1. [parameter(ValueFromPipelineByPropertyName=$true)] [int]$Count = 1, # Indicates whether messages should be removed from the queue. Default setting is to not remove messages. [parameter(ValueFromPipelineByPropertyName=$true)] [switch]$Remove, # Determines message body encoding. [parameter(ValueFromPipelineByPropertyName=$true)] [ValidateSet("auto", "base64")] [string]$Encoding = "auto", # Indicates whether messages body should be truncated to given size (in bytes). [parameter(ValueFromPipelineByPropertyName=$true)] [int]$Truncate, # Indicates what view should be used to present the data. [ValidateSet("Default", "Payload", "Details")] [string]$View = "Default", # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $cnt = 0 } Process { if (-not $VirtualHost) { # figure out the Virtual Host value $p = @{} $p.Add("Credentials", $Credentials) if ($BaseUri) { $p.Add("BaseUri", $BaseUri) } $queues = Get-RabbitMQQueue @p | ? Name -eq $Name if (-not $queues) { return; } if (-not $queues.GetType().IsArray) { $VirtualHost = $queues.vhost } else { $vhosts = $queues | select vhost $s = $vhosts -join ',' Write-Error "Queue $Name exists in multiple Virtual Hosts: $($queues.vhost -join ', '). Please specify Virtual Host to use." } } [string]$s = "" if ([bool]$Remove) { $s = "Messages will be removed from the queue." } else {$s = "Messages will be requeued."} if ($pscmdlet.ShouldProcess("server: $BaseUri/$VirtualHost", "Get $Count message(s) from queue $Name. $s")) { $url = Join-Parts $BaseUri "/api/queues/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($Name))/get" Write-Verbose "Invoking REST API: $url" $body = @{ "count" = $Count "requeue" = -not [bool]$Remove "encoding" = $Encoding } if ($Truncate) { $body.Add("truncate", $Truncate) } $bodyJson = $body | ConvertTo-Json Write-Debug "body: $bodyJson" $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Post -ContentType "application/json" -Body $bodyJson $result | Add-Member -NotePropertyName "QueueName" -NotePropertyValue $Name foreach ($item in $result) { $cnt++ $item | Add-Member -NotePropertyName "no" -NotePropertyValue $cnt $item | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri $item | Add-Member -NotePropertyName "VirtualHost" -NotePropertyValue $VirtualHost } if ($View) { switch ($View.ToLower()) { 'payload' { SendItemsToOutput $result "RabbitMQ.QueueMessage" | fc } 'details' { SendItemsToOutput $result "RabbitMQ.QueueMessage" | ft -View Details } Default { SendItemsToOutput $result "RabbitMQ.QueueMessage" } } } } } End { Write-Verbose "`r`nGot $cnt messages from queue $Name, vhost $VirtualHost, server: $BaseUri." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQPermission.ps1
Add-RabbitMQPermission.ps1
<# .Synopsis Adds permissions to virtual host for a user. .DESCRIPTION The Add-RabbitMQPermission cmdlet allows to add user permissions to virtual host. To add permissions to remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Add-RabbitMQPermission -VirtualHost '/' -User Admin -Configure .* -Read .* -Write .* Add configure, read and write permissions for user Admin to default virtual host (/). .EXAMPLE Add-RabbitMQPermission -HostName rabbitmq.server.com '/' Admin .* .* .* Add configure, read and write permissions for user Admin to default virtual host (/) on server rabbitmq.server.com. This command uses positional parameters. .INPUTS You can pipe VirtualHost, User, Configure, Read, Write and HostName to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQPermission { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] Param ( # Virtual host to set permission for. [parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("vhost", "vh")] [string]$VirtualHost = $defaultVirtualhost, # Name of user to set permission for. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [string]$User, # Configure permission regexp. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [string]$Configure, # Read permission regexp. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=3)] [string]$Read, # Write permission regexp. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=4)] [string]$Write, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { $p = Get-RabbitMQPermission -BaseUri $BaseUri -Credentials $Credentials -VirtualHost $VirtualHost -User $User if ($p) { throw "Permissions to virtual host $VirtualHost for user $User already exist. To change permissions use Set-RabbitMQPermission cmdlet." } $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri", "Create permission to virtual host $VirtualHost for user $User : $Configure, $Read $Write")) { $url = Join-Parts $BaseUri "/api/permissions/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($User))" $body = @{ 'configure' = $Configure 'read' = $Read 'write' = $Write } | ConvertTo-Json $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" -Body $body Write-Verbose "Created permission to $VirtualHost for $User : $Configure, $Read, $Write" $cnt++ } } End { if ($cnt -gt 1) { Write-Verbose "Created $cnt permissions." } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQOverview.ps1
Get-RabbitMQOverview.ps1
<# .Synopsis Get overview information about RabbitMQ server. .DESCRIPTION The Get-RabbitMQOverview gets overview information about one or more RabbitMQ servers. Returned object contains information about RabbitMQ server such as its version, Erlang version, node name, number of exchanges, queues, messages, consumers, connection and channels. It also contains object with server statistics. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .INPUTS You can pipe HostName to the cmdlet. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.ServerOverview objects which describe RabbitMQ server. .EXAMPLE Get-RabbitMQOverview Gets overview information about local RabbitMQ server. .EXAMPLE Get-RabbitMQOverview localhost, 127.0.0.1 Gets overview information about following servers: localhost and 127.0.0.1. This command can be used to compare different instances. .EXAMPLE @('localhost', '127.0.0.1') | Get-RabbitMQOverview This example shows how to pipe list of servers for which to get overview information. In the above example the cmdlet will show information about following servers: localhost and 127.0.0.1. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQOverview { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("cn", "HostName", "ComputerName")] [string[]]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if (-not $pscmdlet.ShouldProcess("server $BaseUri", "Get overview: $(NamesToString $Name '(all)')")) { foreach ($cn in $BaseUri) { Write-Host "Getting overview for server: $cn" } return; } foreach ($cn in $BaseUri) { $overview = GetItemsFromRabbitMQApi -BaseUri $cn $Credentials "overview" $overview | Add-Member -NotePropertyName "HostName" -NotePropertyValue $cn $overview.PSObject.TypeNames.Insert(0, "RabbitMQ.ServerOverview") Write-Output $overview } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Add-RabbitMQQueue.ps1
Add-RabbitMQQueue.ps1
<# .Synopsis Adds Queue to RabbitMQ server. .DESCRIPTION The Add-RabbitMQQueue allows for creating new queues in RabbitMQ server. To add Queue to remote server you need to provide -HostName. You may pipe an object with Name, Queue parameters, VirtualHost and HostName to create multiple queues. For more information how to do that see Examples. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html To support requests using default virtual host (/), the cmdlet will temporarily disable UnEscapeDotsAndSlashes flag on UriParser. For more information check get-help about_UnEsapingDotsAndSlashes. .EXAMPLE Add-RabbitMQQueue queue1 This command adds new Queue named "queue1" to local RabbitMQ server. .EXAMPLE Add-RabbitMQQueue queue1, queue2 This command adds two new queues named "queue1" and "queue2" to local RabbitMQ server. .EXAMPLE Add-RabbitMQQueue queue1 -HostName myrabbitmq.servers.com This command adds new queue named "queue1" to myrabbitmq.servers.com server. .EXAMPLE @("queue1", "queue2") | Add-RabbitMQQueue This command pipes list of Queues to add to the RabbitMQ server. In the above example two new queues named "queue1" and "queue2" will be created in local RabbitMQ server. .EXAMPLE $a = $( New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "vh1"} New-Object -TypeName psobject -Prop @{"HostName" = "localhost"; "Name" = "vh2"} New-Object -TypeName psobject -Prop @{"HostName" = "127.0.0.1"; "Name" = "vh3"} ) $a | Add-RabbitMQQueue Above example shows how to pipe queue definitions to Add-RabbitMQQueue cmdlet. .EXAMPLE Add-RabbitMQQueue -Name 'queue-with-ttl' -Arguments @{'x-message-ttl' = 60000} This command will create a new queue and set message TTL to 60 seconds. .INPUTS You can pipe VirtualHost names and optionally HostNames to this cmdlet. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Add-RabbitMQQueue { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")] Param ( # Name of RabbitMQ Queue. [parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("queue", "QueueName")] [string[]]$Name, # Name of the virtual host to filter channels by. [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("vh", "vhost")] [string]$VirtualHost = $defaultVirtualhost, # Determines whether the queue should be durable. [parameter(ValueFromPipelineByPropertyName=$true)] [switch]$Durable = $false, # Determines whether the queue should be deleted automatically after all consumers have finished using it. [parameter(ValueFromPipelineByPropertyName=$true)] [switch]$AutoDelete = $false, # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials, # Optional arguments [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [hashtable]$Arguments ) Begin { $cnt = 0 } Process { if ($pscmdlet.ShouldProcess("server: $BaseUri/$VirtualHost", "Add queue(s): $(NamesToString $Name '(all)'); Durable=$Durable, AutoDelete=$AutoDelete")) { foreach($n in $Name) { $url = Join-Parts $BaseUri "/api/queues/$([System.Web.HttpUtility]::UrlEncode($VirtualHost))/$([System.Web.HttpUtility]::UrlEncode($n))" Write-Verbose "Invoking REST API: $url" $body = @{} if ($Durable) { $body.Add("durable", $true) } if ($AutoDelete) { $body.Add("auto_delete", $true) } if ($Arguments -ne $null -and $Arguments.Count -gt 0) { $body.Add("arguments", $Arguments) } $bodyJson = $body | ConvertTo-Json $result = Invoke-RestMethod $url -Credential $Credentials -AllowEscapedDotsAndSlashes -DisableKeepAlive -ErrorAction Continue -Method Put -ContentType "application/json" -Body $bodyJson Write-Verbose "Created Queue $n on $BaseUri/$VirtualHost" $cnt++ } } } End { Write-Verbose "Created $cnt Queue(s)." } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Public/Get-RabbitMQPermission.ps1
Get-RabbitMQPermission.ps1
<# .Synopsis Gets Permissions for VirtualHost and/or user. .DESCRIPTION The Get-RabbitMQPermission cmdlet shows permissions users have to work with virtual hosts. The cmdlet allows you to show all permissions or filter them by VirtualHost and/or User using wildcards. The result may be zero, one or many RabbitMQ.Permission objects. To get permissions from remote server you need to provide -HostName. The cmdlet is using REST Api provided by RabbitMQ Management Plugin. For more information go to: https://www.rabbitmq.com/management.html .EXAMPLE Get-RabbitMQPermission Show permissions of all users and all virtual hosts from the local RabbitMQ server. .EXAMPLE Get-RabbitMQPermission -HostName myrabbitmq.servers.com Show permissions of all users and all virtual hosts from the myrabbitmq.servers.com server RabbitMQ server. .EXAMPLE Get-RabbitMQPermission -VirtualHost / -User guest List user guest permissions to virtual host /. .EXAMPLE Get-RabbitMQPermission private* Show permissions of all users in virtual hosts which name starts with "private". .EXAMPLE Get-RabbitMQPermission private*, public* This command gets a list of all Virtual Hosts which name starts with "private" or "public". .INPUTS You can pipe Virtual Host and User names to filter results. .OUTPUTS By default, the cmdlet returns list of RabbitMQ.Permission objects. .LINK https://www.rabbitmq.com/management.html - information about RabbitMQ management plugin. #> function Get-RabbitMQPermission { [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='None')] Param ( # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position = 0)] [Alias("vh")] [string[]]$VirtualHost = "", # Name of RabbitMQ Virtual Host. [parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position = 1)] [string[]]$User = "", # Name of the computer hosting RabbitMQ server. Defalut value is localhost. [parameter(ValueFromPipelineByPropertyName=$true)] [Alias("HostName", "hn", "cn")] [string]$BaseUri = $defaultComputerName, # Credentials to use when logging to RabbitMQ server. [Parameter(Mandatory=$false)] [PSCredential]$Credentials = $defaultCredentials ) Begin { } Process { if ($pscmdlet.ShouldProcess("server $BaseUri", "Get permission(s) for VirtualHost = $(NamesToString $VirtualHost '(all)') and User = $(NamesToString $User '(all)')")) { $result = GetItemsFromRabbitMQApi -BaseUri $BaseUri $Credentials "permissions" $result = ApplyFilter $result "vhost" $VirtualHost $result = ApplyFilter $result "user" $User foreach($i in $result) { $i | Add-Member -NotePropertyName "HostName" -NotePropertyValue $BaseUri } SendItemsToOutput $result "RabbitMQ.Permission" } } End { } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/ScriptsToProcess/TabExpansions.ps1
TabExpansions.ps1
$BaseUriCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $global:RabbitMQServers } $virtualHostCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQVirtualHost @parms | where name -like "$wordToComplete*" | select name | ForEach-Object { $vhname = @{$true="Default"; $false= $_.name}[$_.name -eq "/"] $cname = @{$true="localhost"; $false = $fakeBoundParameter.BaseUri}[$fakeBoundParameter.BaseUri -eq $null] $tooltip = "$vhname on $cname." createCompletionResult $_.name $_.name $tooltip } } $exchangeCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.VirtualHost) { $parms.Add("VirtualHost", $fakeBoundParameter.VirtualHost) } if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQExchange @parms | where name -like "$wordToComplete*" | select name | ForEach-Object { $ename = @{$true="(AMQP default)"; $false=$_.name}[$_.name -eq ""] $vhname = @{$true="[default]"; $false= $fakeBoundParameter.VirtualHost}[$fakeBoundParameter.VirtualHost -eq "/"] $cname = @{$true="localhost"; $false = $fakeBoundParameter.BaseUri}[$fakeBoundParameter.BaseUri -eq $null] $tooltip = "$ename on $cname/$vhname." createCompletionResult $ename $ename $tooltip } } $connectionCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQConnection @parms | where name -like "$wordToComplete*" | select name | ForEach-Object { $cname = @{$true="localhost"; $false = $fakeBoundParameter.BaseUri}[$fakeBoundParameter.BaseUri -eq $null] $tooltip = "$_.name on $cname." createCompletionResult $_.name $_.name $tooltip } } $nodeCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQNode @parms | where name -like "$wordToComplete*" | select name | ForEach-Object { $cname = @{$true="localhost"; $false = $fakeBoundParameter.BaseUri}[$fakeBoundParameter.BaseUri -eq $null] $tooltip = $_.name + " on " + $cname + "." createCompletionResult $_.name $_.name $tooltip } } $channelCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.VirtualHost) { $parms.Add("VirtualHost", $fakeBoundParameter.VirtualHost) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQChannel @parms | where name -like "$wordToComplete*" | select name | ForEach-Object { $cname = @{$true="localhost"; $false = $fakeBoundParameter.BaseUri}[$fakeBoundParameter.BaseUri -eq $null] $tooltip = $_.name + " on " + $cname + "." createCompletionResult $_.name $_.name $tooltip } } $queueCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.VirtualHost) { $parms.Add("VirtualHost", $fakeBoundParameter.VirtualHost) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQQueue @parms | where name -like "$wordToComplete*" | ForEach-Object { $cname = @{$true="localhost"; $false = $fakeBoundParameter.BaseUri}[$fakeBoundParameter.BaseUri -eq $null] $n = "$($_.name) ($($_.messages))" $tooltip = "$($_.name) on $cname/$($_.vhost) ($($_.messages) messages)." createCompletionResult $n $_.name $tooltip } } $routingKeyGeneration_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.VirtualHost) { $parms.Add("VirtualHost", $fakeBoundParameter.VirtualHost) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } $tooltip = "Bind exchange " + $fakeBoundParameter.ExchangeName + " to queue " + $fakeBoundParameter.Name + "." createCompletionResult $fakeBoundParameter.Name $tooltip createCompletionResult $($fakeBoundParameter.ExchangeName + "-" + $fakeBoundParameter.Name) $tooltip createCompletionResult $($fakeBoundParameter.ExchangeName + "->" + $fakeBoundParameter.Name) $tooltip createCompletionResult $($fakeBoundParameter.ExchangeName + ".." + $fakeBoundParameter.Name) $tooltip } $routingKeyCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.VirtualHost) { $parms.Add("VirtualHost", $fakeBoundParameter.VirtualHost) } #if ($fakeBoundParameter.ExchangeName) { $parms.Add("ExchangeName", $fakeBoundParameter.ExchangeName) } if ($fakeBoundParameter.Name) { $parms.Add("Name", $fakeBoundParameter.Name) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } #Get-RabbitMQQueueBinding @parms | where name -like "$wordToComplete*" | select routing_key | ForEach-Object { $a = Get-RabbitMQQueueBinding @parms $b = $a | where source -eq $fakeBoundParameter.ExchangeName | select routing_key $b | ForEach-Object { createCompletionResult $_.routing_key $_.routing_key $_.routing_key } } $userCompletion_Process = { param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $parms = @{} if ($fakeBoundParameter.BaseUri) { $parms.Add("BaseUri", $fakeBoundParameter.BaseUri) } if ($fakeBoundParameter.Credentials) { $parms.Add("Credentials", $fakeBoundParameter.Credentials) } if ($fakeBoundParameter.UserName) { $parms.Add("UserName", $fakeBoundParameter.UserName) } if ($fakeBoundParameter.Password) { $parms.Add("Password", $fakeBoundParameter.Password) } Get-RabbitMQUser @parms | where name -like "$wordToComplete*" | ForEach-Object { $tooltip = "$($_.name) [$($_.tags)]" createCompletionResult $_.name $_.name $tooltip } } function createCompletionResult([string]$text, [string]$value, [string]$tooltip) { if ([string]::IsNullOrEmpty($value)) { return } if ([string]::IsNullOrEmpty($text)) { $text = $value } if ([string]::IsNullOrEmpty($tooltip)) { $tooltip = $value } $completionText = @{$true="'$value'"; $false=$value }[$value -match "\W"] $completionText = $completionText -replace '\[', '``[' -replace '\]', '``]' return New-Object System.Management.Automation.CompletionResult $completionText, $text, 'ParameterValue', $tooltip } if (-not $global:options) { $global:options = @{CustomArgumentCompleters = @{};NativeArgumentCompleters = @{}}} $global:options['CustomArgumentCompleters']['Test1:Name'] = $testCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQOverview:Name'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQVirtualHost:Name'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQVirtualHost:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQVirtualHost:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQVirtualHost:Name'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQVirtualHost:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQExchange:Name'] = $exchangeCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQExchange:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQExchange:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQExchange:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQExchange:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQExchange:Name'] = $exchangeCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQExchange:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQExchange:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQConnection:Name'] = $connectionCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQConnection:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQConnection:Name'] = $connectionCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQConnection:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQNode:Name'] = $nodeCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQNode:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQChannel:Name'] = $channelCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQChannel:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQChannel:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQQueue:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQQueue:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQQueue:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueue:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueue:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueue:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueue:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueue:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQQueueBinding:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQQueueBinding:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQQueueBinding:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueueBinding:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueueBinding:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueueBinding:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueueBinding:ExchangeName'] = $exchangeCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQQueueBinding:RoutingKey'] = $routingKeyGeneration_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueueBinding:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueueBinding:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueueBinding:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueueBinding:ExchangeName'] = $exchangeCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQQueueBinding:RoutingKey'] = $routingKeyCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQMessage:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQMessage:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQMessage:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Clear-RabbitMQQueue:Name'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Clear-RabbitMQQueue:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Clear-RabbitMQQueue:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Copy-RabbitMQMessage:SourceQueueName'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Copy-RabbitMQMessage:DestinationQueueName'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Copy-RabbitMQMessage:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Copy-RabbitMQMessage:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Move-RabbitMQMessage:SourceQueueName'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Move-RabbitMQMessage:DestinationQueueName'] = $queueCompletion_Process $global:options['CustomArgumentCompleters']['Move-RabbitMQMessage:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Move-RabbitMQMessage:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQUser:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQUser:Name'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQUser:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQUser:Name'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Set-RabbitMQUser:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Set-RabbitMQUser:Name'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQUser:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQUser:Name'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQPermission:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQPermission:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Get-RabbitMQPermission:User'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQPermission:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQPermission:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Add-RabbitMQPermission:User'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Set-RabbitMQPermission:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Set-RabbitMQPermission:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Set-RabbitMQPermission:User'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQPermission:BaseUri'] = $BaseUriCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQPermission:VirtualHost'] = $virtualHostCompletion_Process $global:options['CustomArgumentCompleters']['Remove-RabbitMQPermission:User'] = $userCompletion_Process $global:options['CustomArgumentCompleters']['Unregister-RabbitMQServer:BaseUri'] = $BaseUriCompletion_Process $function:tabexpansion2 = $function:tabexpansion2 -replace 'End\r\n{','End { if ($null -ne $options) { $options += $global:options} else {$options = $global:options}'
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/GetOverview.Tests.ps1
GetOverview.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path . "$here\TestSetup.ps1" . "$here\..\Public\Get-RabbitMQOverview.ps1" Describe -Tags "Example" "Get-RabbitMQOverview" { It "should get server overview" { $actual = Get-RabbitMQOverview -BaseUri $server | select -ExpandProperty HostName $actual | Should Be $server } It "should get overview for several servers" { $actual = Get-RabbitMQOverview -BaseUri $server, $server | select -ExpandProperty HostName $actual | Should Be $server } It "should get server names from pipe" { $actual = $($($server) | Get-RabbitMQOverview) | select -ExpandProperty HostName $actual | Should Be $server } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/GetVirtualHost.Tests.ps1
GetVirtualHost.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path . "$here\TestSetup.ps1" . "$here\..\Public\Get-RabbitMQVirtualHost.ps1" function SetUpTest($vhosts = ("vh1","vh2")) { Add-RabbitMQVirtualHost -BaseUri $server -Name $vhosts } function TearDownTest($vhosts = ("vh1","vh2")) { foreach($vhost in $vhosts){ Remove-RabbitMQVirtualHost -BaseUri $server -Name $vhost -ErrorAction Continue -Confirm:$false } } Describe -Tags "Example" "Get-RabbitMQVirtualHost" { It "should get Virtual Hosts registered with the server" { SetUpTest $actual = Get-RabbitMQVirtualHost -BaseUri $server | select -ExpandProperty name $expected = $("/", "vh1", "vh2") AssertAreEqual $actual $expected TearDownTest } It "should get Virtual Hosts filtered by name" { SetUpTest $actual = Get-RabbitMQVirtualHost -BaseUri $server vh* | select -ExpandProperty name $expected = $("vh1", "vh2") AssertAreEqual $actual $expected TearDownTest } It "should get VirtualHost names to filter by from the pipe" { SetUpTest $actual = $('vh1', 'vh2') | Get-RabbitMQVirtualHost -BaseUri $server | select -ExpandProperty name $expected = $("vh1", "vh2") AssertAreEqual $actual $expected TearDownTest } It "should get VirtualHost and BaseUri from the pipe" { SetUpTest $pipe = $( New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "Name" = "vh1" } New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "Name" = "vh2" } ) $actual = $pipe | Get-RabbitMQVirtualHost | select -ExpandProperty name $expected = $("vh1", "vh2") AssertAreEqual $actual $expected TearDownTest } It "should pipe result from itself" { SetUpTest $actual = Get-RabbitMQVirtualHost -BaseUri $server | Get-RabbitMQVirtualHost | select -ExpandProperty name $expected = Get-RabbitMQVirtualHost -BaseUri $server | select -ExpandProperty name AssertAreEqual $actual $expected TearDownTest } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/TestSetup.ps1
TestSetup.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path #$server = "192.168.232.129" $server = "http://localhost:15672" . "$here\..\Private\Constants.ps1" . "$here\..\Private\Invoke-RestMethod.ps1" . "$here\..\Private\NamesToString.ps1" . "$here\..\Private\PreventUnEscapeDotsAndSlashesOnUri.ps1" . "$here\..\Private\SendItemsToOutput.ps1" . "$here\..\Private\Join-Parts.ps1" . "$here\..\Private\GetItemsFromRabbitMQApi.ps1" . "$here\..\Private\ApplyFilter.ps1" function AssertAreEqual($actual, $expected) { if ($actual -is [System.Array]) { if ($expected -isnot [System.Array]) { throw "Expected {$expected} to be an array, but it is not." } if ($actual.Length -ne $expected.Length) { $al = $actual.Length $el = $expected.Length throw "Expected $el elements but were $al" } for ($i = 0; $i -lt $actual.Length; $i++) { $a = $actual[$i] $e = $expected[$i] if ($a -ne $e) { throw "Expected element at position $i to be {$e} but was {$a}" } } } else { if($actual -ne $expected) { throw "Expected $actual to be $expected" } } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/GetExchange.Tests.ps1
GetExchange.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path . "$here\TestSetup.ps1" . "$here\..\Public\Get-RabbitMQExchange.ps1" Describe -Tags "Example" "Get-RabbitMQExchange" { It "should get Exchanges registered with the server" { $actual = Get-RabbitMQExchange -BaseUri $server | select -ExpandProperty name $actual.length | Should Not Be 0 } It "should get Exchanges filtered by name" { $actual = Get-RabbitMQExchange -BaseUri $server -Name "amq.*" | select -ExpandProperty name | Sort-Object | Get-Unique $expected = $( "amq.direct", "amq.fanout", "amq.headers", "amq.match", "amq.rabbitmq.log", "amq.rabbitmq.trace", "amq.topic" ) AssertAreEqual $actual $expected } It "should get Exchanges filtered by VirtualHost" { $actual = Get-RabbitMQExchange -BaseUri $server -VirtualHost / $actual.length | Should Not Be 0 } It "should get Exchange names to filter by from the pipe" { $actual = $('amq.direct', 'amq.fanout') | Get-RabbitMQExchange -BaseUri $server | select -ExpandProperty name | Sort-Object | Get-Unique $expected = $('amq.direct', 'amq.fanout') AssertAreEqual $actual $expected } It "should get VirtualHost and BaseUri from the pipe" { $pipe = $( New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "VirtualHost" = "/"; "Name"="amq.direct" } New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "VirtualHost" = "/"; "Name"="amq.fanout" } ) $actual = $pipe | Get-RabbitMQExchange | select -ExpandProperty name $expected = $('amq.direct', 'amq.fanout') AssertAreEqual $actual $expected } #It "should pipe result from itself" { # # $actual = Get-RabbitMQExchange -BaseUri $server | Get-RabbitMQExchange | select -ExpandProperty name # # $expected = Get-RabbitMQExchange -BaseUri $server | select -ExpandProperty name # # AssertAreEqual $actual $expected #} }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/RemoveExchange.Tests.ps1
RemoveExchange.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path . "$here\TestSetup.ps1" . "$here\..\Public\Remove-RabbitMQExchange.ps1" Describe -Tags "Example" "Remove-RabbitMQExchange" { It "should remove existing Exchange" { Add-RabbitMQExchange -BaseUri $server -Name "e1" -Type direct Remove-RabbitMQExchange -BaseUri $server -Name "e1" -Confirm:$false $actual = Get-RabbitMQExchange -BaseUri $server -Name e1 | select -ExpandProperty name $actual | Should Be $() } }
PowerShellCorpus/PowerShellGallery/RabbitMQTools/1.1/Tests/AddExchange.Tests.ps1
AddExchange.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path . "$here\TestSetup.ps1" . "$here\..\Public\Add-RabbitMQExchange.ps1" function TearDownTest() { $exchanges = Get-RabbitMQExchange -BaseUri $server -Name e1, e2 ($exchanges) | Remove-RabbitMQExchange -BaseUri $server -ErrorAction Continue -Confirm:$false } Describe -Tags "Example" "Add-RabbitMQExchange" { It "should create new Exchange" { Add-RabbitMQExchange -BaseUri $server -Type direct e1 $actual = Get-RabbitMQExchange -BaseUri $server -Name e1 | select -ExpandProperty name $actual | Should Be "e1" TearDownTest } It "should do nothing when Exchange already exists" { Add-RabbitMQExchange -BaseUri $server -Type direct -Name "e1" Add-RabbitMQExchange -BaseUri $server -Type direct -Name "e1" $actual = Get-RabbitMQExchange -BaseUri $server -Name "e1" | select -ExpandProperty name $actual | Should Be "e1" TearDownTest } It "should create many Exchanges" { Add-RabbitMQExchange -BaseUri $server -Type direct -Name e1,e2 $actual = Get-RabbitMQExchange -BaseUri $server -Name e1,e2 | select -ExpandProperty name $expected = $("e1", "e2") AssertAreEqual $actual $expected TearDownTest } It "should get Exchange to be created from the pipe" { $("e1", "e2") | Add-RabbitMQExchange -BaseUri $server -Type direct $actual = $($("e1", "e2") | Get-RabbitMQExchange -BaseUri $server) | select -ExpandProperty name $expected = $("e1", "e2") AssertAreEqual $actual $expected TearDownTest } It "should get Exchange with properties to be created from the pipe" { $pipe = $( New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "Name" = "e1"; "Type" = "direct" } New-Object -TypeName psobject -Prop @{"BaseUri" = $server; "Name" = "e2"; "Type" = "fanout" } ) $pipe | Add-RabbitMQExchange $actual = $($pipe | Get-RabbitMQExchange -BaseUri $server) | select -ExpandProperty name $expected = $("e1", "e2") AssertAreEqual $actual $expected TearDownTest } }