full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/xXMLConfigFile/2.0.0.0/Examples/AddRemovModifyeSingleAttributeValue/AddRemovModifyeSingleAttributeValue.ps1
AddRemovModifyeSingleAttributeValue.ps1
configuration AddRemoveModifySingleAttributeValue { param ( [string[]]$NodeName = 'localhost' ) Import-DscResource -Module xXMLConfigFile Node $NodeName { #ensure attribute exists and has specified value XMLConfigFile MaxRetries { ConfigPath = "C:\Temp\Test.config" XPath = '//MRSConfiguration' Name = 'MaxRetries' Value = '40' isAttribute= $true Ensure = 'Present' } #ensure attribute exists and has specified value XMLConfigFile MaxPerSourceDB { ConfigPath = "C:\Temp\Test.config" XPath = '//MRSConfiguration' Name = 'MaxActiveMovesPerSourceMDB' Value = '20' isAttribute= $true Ensure = 'Present' } #make sure attribute FoolMe doesn't exists XMLConfigFile FoolMe { ConfigPath = "C:\Temp\Test.config" XPath = '//MRSConfiguration' Name = 'FoolMe' isAttribute= $true Ensure = 'Absent' } } } AddRemoveModifySingleAttributeValue -Verbose Start-DscConfiguration -Path .\AddRemoveModifySingleAttributeValue -Verbose -Wait -Force
PowerShellCorpus/PowerShellGallery/xXMLConfigFile/2.0.0.0/Examples/AddRemoveModifyElement/AddRemoveModifyElement.ps1
AddRemoveModifyElement.ps1
configuration AddElement { param ( [string[]]$NodeName = 'localhost' ) Import-DscResource -Name xXMLConfigFile Node $NodeName { XMLConfigFile Element { ConfigPath = 'C:\temp\Test.config' XPath = '/*' Name = 'ElementA' Value = 'Root' isElementTextValue = $true Ensure = 'present' } XMLConfigFile ChildElement { ConfigPath = 'C:\temp\Test.config' XPath = '//appSettings' Name = 'ElementB' Value = 'ChildElement' isElementTextValue = $true Ensure = 'present' } } } AddElement -Verbose Start-DscConfiguration -Path .\AddElement -Verbose -Wait -Force configuration RemoveElement { param ( [string[]]$NodeName = 'localhost' ) Import-DscResource -Name xXMLConfigFile Node $NodeName { XMLConfigFile Element { ConfigPath = 'C:\temp\Test.config' XPath = '/*' Name = 'ElementA' isElementTextValue = $true Ensure = 'absent' } XMLConfigFile ChildElement { ConfigPath = 'C:\temp\Test.config' XPath = '//appSettings' Name = 'ElementB' isElementTextValue = $true Ensure = 'absent' } } } RemoveElement -Verbose Start-DscConfiguration -Path .\RemoveElement -Verbose -Wait -Force
PowerShellCorpus/PowerShellGallery/PowerPlan/2.0.0.0/Examples/PowerPlan.ps1
PowerPlan.ps1
Configuration PowerSettings { Import-DscResource -ModuleName PowerPlan PowerPlan HighPerformance { Name = 'High performance' } } PowerSettings -outputpath C:\DSC\PowerPlan
PowerShellCorpus/PowerShellGallery/PowerPlan/2.0.0.0/Tests/PowerPlan.Tests.ps1
PowerPlan.Tests.ps1
#Requires -modules PowerPlan -RunAsAdministrator Describe 'Discovers and and sets power plan' { $plans = Get-Powerplan Context 'List power plans' { ForEach ($plan in $plans) { $plan = $plan.ElementName It "the returned list includes the $plan plan" { $plans.ElementName -contains $plan | Should Be True } It "can specifically get the $plan plan" { (Get-Powerplan -PlanName $plan).ElementName | Should Be $plan } } It 'uses the -ComputerName parameter correctly against localhost' { $ComputerName = 'localhost' $results = Get-Powerplan -ComputerName $ComputerName | ForEach-Object ElementName $results.count -gt 0 | Should Be True } It 'returns the expected properties of a plan' { $properties = Get-Powerplan | Get-Member -MemberType Property $properties.Name | Should Be @('Caption', 'Description', 'ElementName', 'InstanceID', 'IsActive', 'PSComputerName') } It 'returns the expected plan using the -Active parameter' { $active = Get-CimInstance -Namespace 'root\cimv2\power' -ClassName 'Win32_PowerPlan' -Filter 'IsActive=True' (Get-Powerplan -Active).InstanceID | Should Be $active.InstanceID } } Context 'Set a Powerplan active' { Mock -ModuleName PowerPlan -CommandName Invoke-CimMethod -MockWith {} ForEach ($plan in $plans) { $plan = $plan.ElementName It "handles the plan $plan without error" { {Set-PowerPlan $plan} | Should Not Throw } It "calls the correct mocks" { Assert-MockCalled -ModuleName PowerPlan -CommandName Invoke-CimMethod -Times 1 } } It 'uses the -ComputerName parameter correctly against localhost' { $ComputerName = 'localhost' {Set-Powerplan -ComputerName $ComputerName -PlanName 'Balanced'} | Should Not Throw } It "calls the correct mocks" { Assert-MockCalled -ModuleName PowerPlan -CommandName Invoke-CimMethod -Times 1 } } Context 'Set-PowerPlan implements -WhatIf' { Mock -ModuleName PowerPlan -CommandName Invoke-CimMethod -MockWith {} It "handles -whatif without error" { {Set-PowerPlan 'Balanced' -whatif} | Should Not Throw } It "does not call the mock" { Assert-MockCalled -ModuleName PowerPlan -CommandName Invoke-CimMethod -Times 0 } } }
PowerShellCorpus/PowerShellGallery/PowerPlan/2.0.0.0/Tests/Syntax.Tests.ps1
Syntax.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path | Split-Path -Parent function Measure-String { [cmdletbinding()] Param( [Parameter(ValueFromPipeline)] [string[]]$InputObject , [string]$SearchString , [switch]$SkipComments ) Begin { $count = 0 $inCommentSection = $false $PreviousStr = "" } Process { if ($SearchString.Length -gt 1) { foreach ($str in $InputObject) { if($SkipComments.IsPresent) { if ($Str.Contains("<#")) { $inCommentSection = $true Write-Verbose "in commentssection" } $trimmed = $str.TrimStart() if ($PreviousStr.Contains("#>")) { Write-Verbose "end of commentssection" $inCommentSection = $false } $PreviousStr = $str if ($trimmed.StartsWith("#") -or $inCommentSection -eq $true) { continue } } Write-Verbose "Searching [$str] for [$SearchString]" $stringlength = $str.length $searchTextLength = $SearchString.Length $replaced = $str.ToLower().Replace($SearchString.ToLower(),"") $foundCount = ($stringlength - $replaced.length) / $searchTextLength $count += $foundCount } } else { foreach ($str in $InputObject) { if($SkipComments.IsPresent) { if ($Str.Contains("<#")) { $inCommentSection = $true Write-Verbose "Start of comment ssection" } $trimmed = $str.TrimStart() if ($PreviousStr.Contains("#>")) { Write-Verbose "End of comment ssection" $inCommentSection = $false } $PreviousStr = $str if ($trimmed.StartsWith("#") -or $inCommentSection -eq $true) { Write-Verbose "Skipping searching [$str] for [$SearchString]" continue } } Write-Verbose "Searching [$str] for [$SearchString]" foreach ($char in $str.ToCharArray()) { if ($char -eq $SearchString) { $count++ } } } } } END { [Pscustomobject]@{ SearchString = $SearchString Count = $count } } } Describe "Powershell Syntax Tests" { $files = Get-ChildItem -Path $here -File | Where-Object Name -like *.psm1 foreach ($file in $files) { $content = Get-Content -Path $file.fullname -Encoding UTF8 -ReadCount 0 -Raw $fileName = $file.FileName $name = $file.BaseName $functionNameCount = Measure-String -InputObject $content -SearchString $name | Select-Object -ExpandProperty Count $quotes = Measure-String -InputObject $content -SearchString "'" -SkipComments | Select-Object -ExpandProperty Count $doubleQuotes = Measure-String -InputObject $content -SearchString '"' | Select-Object -ExpandProperty Count $doubleDollar = Measure-String -InputObject $content -SearchString '$$' | Select-Object -ExpandProperty Count $ifFormatting = Measure-String -InputObject $content -SearchString "if(" | Select-Object -ExpandProperty Count $foreachFormatting = Measure-String -InputObject $content -SearchString "foreach(" | Select-Object -ExpandProperty Count $cmdletbindingCount = Measure-String -InputObject $content -SearchString "cmdletbinding(" | Select-Object -ExpandProperty Count $aliasExceptions = @("foreach","h","r","type") $aliases = Get-Alias | Where Name -notin $aliasExceptions | Select-Object -ExpandProperty Name foreach ($alias in $aliases) { $aliasCount = (Measure-String -InputObject $content -SearchString " $alias " -SkipComments).Count if ($aliasCount -ne 0) { It "[$name] should not use Alias [$alias]" { $aliasCount | Should Be 0 } } } It "[$name] should not be null" { $content | Should Not Be $null } It "[$name] should match function Name" { $functionNameCount | Should Not Be 0 } It "[$name] Quotes count should be even" { $quotes % 2 | Should Be 0 } It "[$name] doubleQuotes count should be even" { $doubleQuotes % 2 | Should Be 0 } It "[$name] double dollar count should be 0" { $doubleDollar | Should Be 0 } It "[$name] should not have if() formatting" { $ifFormatting | Should Be 0 } It "[$name] should not have foreach() formatting" { $foreachFormatting | Should Be 0 } It "[$name] should have cmdletbinding specified" { $cmdletbindingCount | should BeGreaterThan 0 } $aliasCount = 0 } }
PowerShellCorpus/PowerShellGallery/VMware.VimAutomation.Srm/6.5.1.5374694/VMware.VimAutomation.Srm.ps1
VMware.VimAutomation.Srm.ps1
[VMware.VimAutomation.Sdk.Interop.V1.CoreServiceFactory]::CoreService.OnImportModule( "VMware.VimAutomation.Srm.Commands", (Split-Path $script:MyInvocation.MyCommand.Path)); # SIG # Begin signature block # MIIdVgYJKoZIhvcNAQcCoIIdRzCCHUMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUFgd135mkZk0UwFWagUI/oNk/ # OzCgghhpMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV # UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu # dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q # WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC # i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhFpS+JzueZ5/6M4lc/PcaS3Er4 # ezPkeQr78HWIQZz/xQNRmarXbJ+TaYdlKYOFwmAUxMjJOxTawIHwHw103pI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zh1ASybzaZ4p9ljM8sT7li9zdKL+wBrucY6I8eicB2MHbBfYU16GGQG # jlQsQjvoO71tqEgW3nZQP44d61qlE5EoLRYJoYICCzCCAgcGCSqGSIb3DQEJBjGC # AfgwggH0AgEBMHIwXjELMAkGA1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENv # cnBvcmF0aW9uMTAwLgYDVQQDEydTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZp # Y2VzIENBIC0gRzICEA7P9DjI/r81bgTYapgbGlAwCQYFKw4DAhoFAKBdMBgGCSqG # SIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDQxODE5MDUy # NlowIwYJKoZIhvcNAQkEMRYEFIMtX3rbIHMY72buXFDg3qAIWuj8MA0GCSqGSIb3 # DQEBAQUABIIBADSgTdr6eX95JZ8tO9byNVh9tjsgiLGn9svhnhbpv/YN7IX6TAzK # TKU7lQQWLImmiPdLG7MIIa1Ye1VzCSBj+1KzpqPuylnNETKHWorVy2BBXSkUMfhM # jKNuo4EMryIMXOQSloOEtp9foSI70aHz7XfyOfaEYPbfLL3GA0v/AjigTVRhG+mm # qbGHRXWxO79/EMtCMVHTiUAnlVEZ2NiJC3CEQp25bjc51m+TFA8JqBAel29pIaUP # 7sIr/nKtqDIyu0vzc3UmLPSAW2nkutzW69db7NdpDuUC8rKJd8XajgjeIf5WsbZX # 6xG06NPJnS//qV9/Fb6W/EjRmgXuPm/Xtos= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Get-SqlMessage.ps1
Get-SqlMessage.ps1
<# .Synopsis Returns any available informational messages. .Description Get-SqlMessage returns any informational messages generated by Invoke-SqlScalar, Invoke-SqlQuery, or Invoke-SqlUpdate. Not all providers support informational messages. If you use Print or Raiserror without the "NoWait", then messages will be batched to 8kb and then sent. To get messages immediately sent, your query needs to use RAISERROR('your message', 10,1) WITH NOWAIT .Parameter ConnectionName User defined name for connection. #> Function Get-SqlMessage { [cmdletBinding()] Param([string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { Try { While ($Script:Connections.$ConnectionName.HasMessages()) { Write-Output $Script:Connections.$ConnectionName.GetMessage() } } Catch [System.NotSupportedException] { Write-Warning ("[{0}] {1}" -f $Script:Connections.$ConnectionName.ProviderType(), $_.exception.message) } } } Export-ModuleMember -Function Get-SqlMessage
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Complete-SqlTransaction.ps1
Complete-SqlTransaction.ps1
<# .Synopsis Complete a sql transaction. .Description Complete (COMMIT) a sql transaction. .Parameter ConnectionName User defined name for connection. #> Function Complete-SqlTransaction { [cmdletBinding()] Param([string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { $Script:Connections.$ConnectionName.CommitTransaction() } } Export-ModuleMember -Function Complete-SqlTransaction
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Invoke-SqlUpdate.ps1
Invoke-SqlUpdate.ps1
<# .Synopsis Executes a query and returns number of record affected. .Description Executes a query against the targeted connection and returns the the number of records affected. .Parameter Query SQL statement to run. .Parameter Parameters Parameters required by the query. Key matches the parameter name, Value is the value of the parameter. .Parameter CommandTimeout The timeout, in seconds, for this SQL statement, defaults to the command timeout for the SqlConnection. .Parameter ConnectionName User defined name for connection. #> Function Invoke-SqlUpdate { [CmdletBinding(DefaultParameterSetName="default")] Param([Parameter(Mandatory, ParameterSetName="default", Position=0)][string[]]$Query , [Parameter(ParameterSetName="default")][hashtable]$Parameters = @{} , [Parameter(ParameterSetName="default")][int]$CommandTimeout = -1 , [Parameter(Mandatory,ParameterSetName="cmd")][System.Data.IDbCommand]$Command , [string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { If($PSCmdlet.ParameterSetName -eq "default") { [string]$Query = $Query -join [System.Environment]::NewLine $cmd = $Script:Connections.$ConnectionName.GetCommand($Query, $CommandTimeout, $Parameters) Try { Write-Output $cmd.ExecuteNonQuery() } Finally { $cmd.Dispose() } } Else { $Script:Connections.$ConnectionName.AttachTransaction($Command) Write-Output $Command.ExecuteNonQuery() } } } Set-Alias -Name isu -Value Invoke-SqlUpdate Export-ModuleMember -Function Invoke-SqlUpdate -Alias isu
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Invoke-SqlQuery.ps1
Invoke-SqlQuery.ps1
<# .Synopsis Executes a query and returns data. .Description Executes a query against the targeted connection and returns the data. This can handle multiple result sets (if underlying provider supports it). If there are multiple result sets, the output is datatables, otherwise datarows. If the ‘Stream’ switch is used, only the first result set is returned and the output is a PSObject for each row in the result set. .Parameter Query SQL statement to run. .Parameter Parameters Parameters required by the query. Key matches the parameter name, Value is the value of the parameter. .Parameter CommandTimeout The timeout, in seconds, for this SQL statement, defaults to the command timeout for the SqlConnection. .Parameter ConnectionName User defined name for connection. .Parameter Stream Uses a datareader to stream PSObject representing the results of the query to the pipeline, results will appear as soon as the connection begins returning data. #> Function Invoke-SqlQuery { [CmdletBinding()] Param([Parameter(Mandatory)][string[]]$Query , [hashtable]$Parameters = @{} , [int]$CommandTimeout = -1 , [string]$ConnectionName = "default" , [switch]$Stream) If(TestConnectionName -ConnectionName $ConnectionName) { [string]$Query = $Query -join [System.Environment]::NewLine $cmd = $Script:Connections.$ConnectionName.GetCommand($Query, $CommandTimeout, $Parameters) Try { If($stream.IsPresent) { $dr = $cmd.ExecuteReader() Try { [DataReaderToPSObject]::Translate($dr) } Finally { $dr.Dispose() } } Else { Try { $ds = $Script:Connections.$ConnectionName.GetDataSet($cmd) If($ds.Tables.Count -gt 1) { Write-Output $ds.Tables } Else { Write-Output $ds.Tables[0].Rows } } Finally { If($ds) { $ds.Dispose() } } } } Finally { $cmd.Dispose() } } } Set-Alias -Name isq -Value Invoke-SqlQuery Export-ModuleMember -Function Invoke-SqlQuery -Alias isq
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Clear-SqlMessage.ps1
Clear-SqlMessage.ps1
<# .Synopsis Clears all available informational messages. .Description Clear-SqlMessage removes all informational messages generated by Invoke-SqlScalar, Invoke-SqlQuery, or Invoke-SqlUpdate. Not all providers support informational messages. .Parameter ConnectionName User defined name for connection. #> Function Clear-SqlMessage { [cmdletBinding()] Param([string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { Try { $Script:Connections.$ConnectionName.ClearMessages() } Catch [System.NotSupportedException] { Write-Warning ("[{0}] {1}" -f $Script:Connections.$ConnectionName.ProviderType(), $_.exception.message) } } } Export-ModuleMember -Function Clear-SqlMessage
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Open-SqlConnection.ps1
Open-SqlConnection.ps1
$val = @' <# .Synopsis Open a connection to a database server. .Description Open a connection to a database server. Supports: <<<DESCRIPTION>>> .Parameter ConnectionName The name to associate with the newly created connection. This connection will be used with other cmdlets when specifying -ConnectionName <name>. If you don't specify one, it will be set to the default. .Parameter Provider Specifies which provider is being used for this connection. Acceptable provider names are: <<<LIST>>> The command Get-SqlProviderHelp provides information on the additional parameters available to be used. .Parameter ConnectionString Specifies a provider specific connectionstring to be used. #> Function Open-SqlConnection { [CmdletBinding(DefaultParameterSetName="default")] Param([Alias("cn")][string]$ConnectionName = "default" , [int]$CommandTimeout = 30 , [ValidateSet(<<<LIST>>>)][string]$Provider , [Parameter(Mandatory, ParameterSetName="Conn")][string]$ConnectionString) DynamicParam { If(-not $PSBoundParameters.ContainsKey("Provider") -and $Script:Providers.ContainsKey("SQL")) { $PSBoundParameters["Provider"] = "SQL" } $pName = $PSBoundParameters["Provider"] If($Script:Providers.$pName.GenerateParameters().Count -gt 0) { Return $Script:Providers.$pName.GenerateParameters() } } End { If($Script:Connections.ContainsKey($ConnectionName)) { Close-SqlConnection $ConnectionName } $PSBoundParameters.ParameterSetName = $PSCmdlet.ParameterSetName $PSBoundParameters.ConnectionName = $ConnectionName $PSBoundParameters.CommandTimeout = $CommandTimeout $PSBoundParameters = $PSBoundParameters | AddDynamicParameterDefaults #Select First Object, otherwise you get a collection $Script:Connections.$ConnectionName = $Script:Providers.$pName.CreateProvider.Invoke($PSBoundParameters) | Select-Object -First 1 } } '@ $desc = @() $list = '"{0}"' -f ($Script:Providers.Keys -Join '","') $Script:Providers.Keys | ForEach-Object { If([string]::IsNullOrWhiteSpace($Script:Providers.$_.ShortDescription)) { $desc += $_ } Else { $desc += $Script:Providers.$_.ShortDescription } } $desc = $desc -join "`n " $val = $val.Replace("<<<DESCRIPTION>>>", $desc).Replace("<<<LIST>>>", $list) Invoke-Expression $val Set-Alias -Name osc -Value Open-SqlConnection Export-ModuleMember -Function Open-SqlConnection -Alias osc Remove-Variable list, val, desc
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Close-SqlConnection.ps1
Close-SqlConnection.ps1
<# .Synopsis Closes an existing connection. .Description Closes the connection and disposes of the underlying object. This will also rollback the current transaction if there is one. .Parameter ConnectionName User Defined name for the SqlConnection. #> Filter Close-SqlConnection { [CmdletBinding()] Param([parameter(ValueFromPipeline, Position=0)]$ConnectionName = "default") If(-not (TestConnectionName $ConnectionName)) { return } Else { If($Script:Connections.$ConnectionName.HasTransaction()) { $Script:Connections.$ConnectionName.RollbackTransaction() } Try { $Script:Connections.$ConnectionName.Connection.Close() } Finally { $Script:Connections.$ConnectionName.Connection.Dispose() $Script:Connections.Remove($ConnectionName) } } } Set-Alias -Name csc -Value Close-SqlConnection Export-ModuleMember -Function Close-SqlConnection -Alias csc
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Undo-SqlTransaction.ps1
Undo-SqlTransaction.ps1
<# .Synopsis Undo a sql transaction. .Description Undo (ROLLBACK) a sql transaction. .Parameter ConnectionName User defined name for connection. #> Function Undo-SqlTransaction { [cmdletBinding()] Param([string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { $Script:Connections.$ConnectionName.RollbackTransaction() } } Export-ModuleMember -Function Undo-SqlTransaction
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Get-SqlProviderHelp.ps1
Get-SqlProviderHelp.ps1
$val = @' <# .Synopsis Provides Help for SimplySql providers. .Description Provides Help information for the Providers in the SimplySql module. .Parameter Provider Specifies which provider to provide help for. Acceptable provider names are: <<<LIST>>> #> Function Get-SqlProviderHelp { [CmdletBinding()] Param([Parameter(Mandatory,Position=1)][ValidateSet(<<<LIST>>>)][string]$Provider) Write-Output "" Write-Output ("PROVIDER NAME: {0}" -f ($Script:Providers.Keys | Where-Object {$_ -eq $Provider})) Write-Output "" Write-Output "SYNOPSIS" Write-Output (" {0}" -f $Script:Providers.$Provider.ShortDescription) Write-Output "" Write-Output "DESCRIPTION" Write-Output ("{0}" -f $Script:Providers.$Provider.HelpText) Write-Output "" Write-Output "PARAMETERS" ForEach($kvp in $Script:Providers.$Provider.GenerateParameters().GetEnumerator()) { If($kvp.Value.IsSet) { $value = " = {0}" -f $kvp.Value.Value.ToString() } Else { $value = "" } Write-Output (" -{0} <{1}>{2}" -f $kvp.Key, $kvp.Value.ParameterType.Name, $value) $msg = $kvp.Value.Attributes | Where-Object { $_ -Is [System.Management.Automation.ParameterAttribute] -and $_.HelpMessage } | Select-Object -First 1 -ExpandProperty HelpMessage If($msg) { Write-Output (" {0}" -f $msg) } Write-Output "" } } '@ $list = '"{0}"' -f ($Script:Providers.Keys -Join '","') Invoke-Expression $val.Replace("<<<LIST>>>", $list) Export-ModuleMember -Function Get-SqlProviderHelp Remove-Variable list, val
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Set-SqlConnection.ps1
Set-SqlConnection.ps1
<# .Synopsis Set options on the SqlConnection. .Description Set Database and/or Command Timeout for the SqlConnection. Changing the database may not be valid for all providers. .Parameter ConnectionName User defined name for connection. .Parameter Database Name of the database to connect to. .Parameter CommandTimeout Command timeout in seconds. #> Function Set-SqlConnection { [cmdletBinding()] Param([string]$Database , [int]$CommandTimeout = -1 , [string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { If($CommandTimeout -ge 0) { $Script:Connections.$ConnectionName.CommandTimeout = $CommandTimeout } If($Database) { Try { $Script:Connections.$ConnectionName.ChangeDatabase($Database) } Catch [System.NotImplementedException], [System.NotSupportedException] { Write-Warning ("Changing the databse is not available for this provider: {0}" -f $Script:Connections[$ConnectionName].ProviderType()) } } } } Export-ModuleMember -Function Set-SqlConnection
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Test-SqlConnection.ps1
Test-SqlConnection.ps1
<# .Synopsis Tests to see if there is a connection. .Description Tests to see if there is a connection, use the -All switch to determine if there are any connections. .Parameter ConnectionName User defined name for the connection to test for. .Parameter All Returns true if there are any connections, otherwise false. #> Function Test-SqlConnection { [cmdletBinding(DefaultParameterSetName="single")] Param([Parameter(ParameterSetName="single")][string]$ConnectionName = "default" , [Parameter(Mandatory, ParameterSetName="all")][switch]$All) If($all.IsPresent -and $Script:Connections.Count -gt 0) { return $true } ElseIf($Script:Connections.ContainsKey($ConnectionName)) { return $true } Else { return $false } } Set-Alias -Name tsc -Value Test-SqlConnection Export-ModuleMember -Function Test-SqlConnection -Alias tsc
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Invoke-SqlScalar.ps1
Invoke-SqlScalar.ps1
<# .Synopsis Executes a Scalar query. .Description Executes a Scalar query against the targeted connection. If the sql statement generates multiple rows and/or columns, only the first column of the first row is returned. .Parameter Query SQL statement to run. .Parameter Parameters Parameters required by the query. Key matches the parameter name, Value is the value of the parameter. .Parameter CommandTimeout The timeout, in seconds, for this SQL statement, defaults to the command timeout for the SqlConnection. .Parameter ConnectionName User defined name for connection. #> Function Invoke-SqlScalar { [CmdletBinding()] Param([Parameter(Mandatory)][string[]]$Query , [hashtable]$Parameters = @{} , [int]$CommandTimeout = -1 , [string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { [string]$Query = $Query -join [System.Environment]::NewLine Write-Output $Script:Connections.$ConnectionName.GetScalar($Query, $CommandTimeout, $Parameters) } } Set-Alias -Name iss -Value Invoke-SqlScalar Export-ModuleMember -Function Invoke-SqlScalar -Alias iss
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Show-SqlConnection.ps1
Show-SqlConnection.ps1
<# .Synopsis Lists the current or all SqlConnections. .Description Lists the current SqlConnection information or outputs a list of all SqlConnections currently active. .Parameter ConnectionName User Defined name for the SqlConnection. .Parameter All Returns a list of names for all active SqlConnections. #> Filter Show-SqlConnection { [CmdletBinding()] Param([parameter(ParameterSetName="single", ValueFromPipeline, Position=0)]$ConnectionName = "default" , [parameter(ParameterSetName="all", Mandatory)][switch]$All) If($All.IsPresent) { [string[]]$keys = $Script:Connections.Keys | ForEach-Object { $_ } $keys | Write-Output } Else { If(-not (TestConnectionName $ConnectionName)) { return } Else { $Script:Connections.$ConnectionName.ConnectionInfo() | Write-Output } } } Set-Alias -Name ssc -Value Show-SqlConnection Export-ModuleMember -Function Show-SqlConnection -Alias ssc
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Start-SqlTransaction.ps1
Start-SqlTransaction.ps1
<# .Synopsis Start a sql transaction. .Description Start (BEGIN) a sql transaction. .Parameter ConnectionName User defined name for connection. #> Function Start-SqlTransaction { [cmdletBinding()] Param([string]$ConnectionName = "default") If(TestConnectionName -ConnectionName $ConnectionName) { $Script:Connections.$ConnectionName.BeginTransaction() } } Export-ModuleMember -Function Start-SqlTransaction
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Cmdlets/Invoke-SqlBulkCopy.ps1
Invoke-SqlBulkCopy.ps1
<# .Synopsis Executes a bulk copy between two connections. .Description Executes a bulk copy operation between two connections. This is highly optimized if the destination has a managed bulkcopy implemenation, otherwise it is only generally optimized. For example, SQL Server has a bulk copy class (SqlBulkCopy) that is easily implemented and provides an efficient means of inserting data into SQL Server. The default implemenation, if the provider does not provider a managed bulk copy mechanism is to prepare the sql insert, and wrap multiple inserts into a single transaction (batching). This provides a significant performance improvement over looping with Invoke-SqlUpdate. CONSIDERATIONS * You must specify either a SourceConnectionName or DestinationConnectionName, whichever one is not specified will use 'default', not specifying either will cause an error. * If you don’t specify DestinationTable, it will use SourceTable; however DestinationTable is required if you use SourceQuery. * If you specify ColumnMap and Source Table, then the select against the SourceConnection will be limited to the columns you specified in ColumnMap. Returns number of rows copied. .Parameter SourceConnectionName User defined name for connection where data will be queried from. .Parameter DestinationConnectionName User defined name for connection where data will be inserted to. .Parameter SourceTable The name of the table in the source connection. .Parameter DestinationTable The name of the table to write to in the destination connection. If not specified, will be taken from SourceTable parameter. .Parameter ColumnMap Key is the column name in the source connection, Value is the column name in the destination connection. .Parameter BatchSize How many inserts are batched together at one time. .Parameter BatchTimeout How long, in seconds, that each batch can take. Defaults to the command timeout for the destination connection. .Parameter Notify If present, as each batch completes a progress notification will be generated with the total number of rows inserted so far. .Parameter SourceQuery The query to determine the source data, instead of specifying a table. .Parameter SourceParameters Parameters needed for the source query. #> Function Invoke-SqlBulkCopy { [CmdletBinding()] Param( [string]$SourceConnectionName = "default" , [string]$DestinationConnectionName = "default" , [Parameter(Mandatory, ParameterSetName="table")][string]$SourceTable , [Parameter(Mandatory, ParameterSetName="query")][string]$SourceQuery , [Parameter(ParameterSetName="query")][hashtable]$SourceParameters = @{} , [Parameter(ParameterSetName="table")] [Parameter(Mandatory, ParameterSetName="query")] [string]$DestinationTable , [hashtable]$ColumnMap = @{} , [ValidateRange(1,5000)][int]$BatchSize = 500 , [int]$BatchTimeout = -1 , [switch]$Notify ) If($SourceConnectionName -eq $DestinationConnectionName) { $PSCmdlet.ThrowTerminatingError( [System.Management.Automation.ErrorRecord]::new( [System.Management.Automation.PSArgumentException]::new( "You cannot use the same connection for both the source and destination!", "SourceConnectionName, DestinationConnectionName" ), $null, [System.Management.Automation.ErrorCategory]::InvalidArgument, $null ) ) } If((TestConnectionName -ConnectionName $SourceConnectionName) -and (TestConnectionName -ConnectionName $DestinationConnectionName)) { If($BatchTimeout -lt 0) { $BatchTimeout = $script:Connections.$DestinationConnectionName.CommandTimeout } Try { If($PSCmdlet.ParameterSetName -eq "table") { If([string]::IsNullOrWhiteSpace($DestinationTable)) { $DestinationTable -eq $SourceTable } If($ColumnMap -and $ColumnMap.Count -gt 0) { $SourceQuery = "SELECT {0} FROM $SourceTable" -f $ColumnMap.Keys -join ", " } Else { $SourceQuery = "SELECT * FROM $SourceTable" } } $srcReader = $script:Connections.$SourceConnectionName.GetReader($SourceQuery, $BatchTimeout, $SourceParameters) If($Notify.IsPresent) { $script:Connections.$DestinationConnectionName.BulkLoad($srcReader, $DestinationTable, $ColumnMap, $BatchSize, $BatchTimeout, { Param([int]$insertCount) Write-Progress -Activity "SimplySql BulkCopy" -Status $DestinationTable -CurrentOperation "Inserted $insertCount rows." }.GetNewClosure()) Write-Progress -Activity "SimplySql BulkCopy" -Status "Finished" -Completed } Else { $script:Connections.$DestinationConnectionName.BulkLoad($srcReader, $DestinationTable, $ColumnMap, $BatchSize, $BatchTimeout, $null) } } Finally { If(Test-Path variable:srcReader) { $srcReader.Dispose() } } } Else { Throw [System.Management.Automation.PSArgumentException]::new("Invalid Connection Name(s).", "SourceConnectionName, DestinationConnectionName") } } Export-ModuleMember -Function Invoke-SqlBulkCopy
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Providers/SQLite/init.ps1
init.ps1
#Load Up SQLite libraries Add-Type -Path "$PSScriptRoot\System.Data.SQLite.dll"
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Providers/SQLite/sqlite.ps1
sqlite.ps1
Write-Output ([ProviderConfig]::new( "SQLite (System.Data.SQLite)", @" SQLite (System.Data.SQLite) SQLite Development Team @ https://sqlite.org/ .NET Provider @ http://system.data.sqlite.org/ "@, @( @{Name = "DataSource" Type = [string] ParameterHashes = @( @{ ValueFromPipelineByPropertyName = $true HelpMessage = "The datasource for the connection." } ) Alias = "FilePath" DefaultValue = ":memory:" }, @{Name = "Password" Type = [string] ParameterHashes = @( @{ ValueFromPipelineByPropertyName = $true HelpMessage = "Password for the database file." } ) } ), { Param([hashtable]$ht) return [SQLiteProvider]::New($ht.ConnectionName, $ht.CommandTimeout, [SQLiteProvider]::CreateConnection($ht)) } ))
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Providers/SQLite/SQLiteProvider.ps1
SQLiteProvider.ps1
Class SQLiteProvider : ProviderBase { SQLiteProvider([string]$ConnectionName , [int]$CommandTimeout , [System.Data.SQLite.SQLiteConnection]$Connection) { $this.ConnectionName = $ConnectionName $this.CommandTimeout = $CommandTimeout $this.Connection = $Connection } [string] ProviderType() { return "SQLite" } [PSCustomObject] ConnectionInfo() { return [PSCustomObject]@{ ConnectionName = $this.ConnectionName ProviderType = $this.ProviderType() ConnectionState = $this.Connection.State ConnectionString = $this.Connection.ConnectionString ServerVersion = $this.Connection.ServerVersion DataSource = $this.Connection.DataSource CommandTimeout = $this.CommandTimeout HasTransaction = $this.HasTransaction() } } [System.Data.DataSet] GetDataSet([System.Data.IDbCommand]$cmd) { $ds = [System.Data.DataSet]::new() $da = [System.Data.SQLite.SQLiteDataAdapter]::new($cmd) Try { $da.Fill($ds) return $ds } Catch { Throw $_ } Finally { $da.dispose() } } [Void] GetMessage() { Write-Warning "SQLiteProvider does not support SqlMessages." } [Void] ClearMessages() { Write-Warning "SQLiteProvider does not support SqlMessages." } static [System.Data.IDbConnection] CreateConnection([hashtable]$ht) { If($ht.ParameterSetName -ne "Default") { Throw [System.InvalidOperationException]::new("Invalid ParameterSet passed to CreateConnection") } $sb = [System.Data.SQLite.SQLiteConnectionStringBuilder]::new() If($ht.ContainsKey("ConnectionString")) { $sb["Connection String"] = $ht.ConnectionString } Else { If($ht.ContainsKey("DataSource")) { $sb["Data Source"] = $ht.DataSource } If($ht.ContainsKey("Password")) { $sb.Password = $ht.Password } } $conn = [System.Data.SQLite.SQLiteConnection]::new($sb.ConnectionString) Try { $conn.Open() } Catch { $conn.Dispose() Throw $_ } return $conn } }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Providers/SQL/sql.ps1
sql.ps1
Write-Output ([ProviderConfig]::new( "Microsoft SQL Server (System.Data.SqlClient)", @" Microsoft SQL Server (System.Data.SqlClient) MSDN Library @ https://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx "@, @( @{Name = "DataSource" Type = [string] ParameterHashes = @( @{ ValueFromPipelineByPropertyName = $true HelpMessage = "The datasource for the connection." }, @{ ParameterSetName = "user" ValueFromPipelineByPropertyName = $true HelpMessage = "The datasource for the connection." }, @{ ParameterSetName = "cred" ValueFromPipelineByPropertyName = $true HelpMessage = "The datasource for the connection." } ) Alias = "SqlInstance" DefaultValue = "localhost" }, @{Name = "InitialCatalog" Type = [string] ParameterHashes = @( @{ ValueFromPipelineByPropertyName = $true HelpMessage = "Database catalog to connect to." }, @{ ParameterSetName = "user" ValueFromPipelineByPropertyName = $true HelpMessage = "Database catalog to connect to." }, @{ ParameterSetName = "cred" ValueFromPipelineByPropertyName = $true HelpMessage = "Database catalog to connect to." } ) Alias = "SqlDatabase" DefaultValue = "master" }, @{Name = "User" Type = [string] ParameterHashes = @( @{ ParameterSetName = "user" Mandatory = $true ValueFromPipelineByPropertyName = $true HelpMessage = "Username to connect as." } ) }, @{Name = "Password" Type = [string] ParameterHashes = @( @{ ParameterSetName = "user" Mandatory = $true ValueFromPipelineByPropertyName = $true HelpMessage = "Password for the user connecting as." } ) }, @{Name = "Credential" Type = [pscredential] ParameterHashes = @( @{ ParameterSetName = "cred" Mandatory = $true ValueFromPipelineByPropertyName = $true HelpMessage = "Credential object containing the SQL user/pass." }, @{ ParameterSetName = "Conn" ValueFromPipelineByPropertyName = $true HelpMessage = "Credential object containing the SQL user/pass." } ) } ), { Param([hashtable]$ht) return [SQLProvider]::New($ht.ConnectionName, $ht.CommandTimeout, [SQLProvider]::CreateConnection($ht)) } ))
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Providers/SQL/SqlProvider.ps1
SqlProvider.ps1
Class SQLProvider : ProviderBase { SQLProvider([string]$ConnectionName , [int]$CommandTimeout , [System.Data.SqlClient.SqlConnection]$Connection) { $this.ConnectionName = $ConnectionName $this.CommandTimeout = $CommandTimeout $this.Connection = $Connection $messages = $this.Messages $handler = {Param($sender, [System.Data.SqlClient.SqlInfoMessageEventArgs]$e) $messages.Enqueue(([SqlMessage]@{Received=(Get-Date); Message=$e.Message})) }.GetNewClosure() $this.Connection.add_InfoMessage([System.Data.SqlClient.SqlInfoMessageEventHandler]$handler) } [string] ProviderType() { return "SQL" } [PSCustomObject] ConnectionInfo() { return [PSCustomObject]@{ ConnectionName = $this.ConnectionName ProviderType = $this.ProviderType() ConnectionState = $this.Connection.State ConnectionString = $this.Connection.ConnectionString ServerVersion = $this.Connection.ServerVersion DataSource = $this.Connection.DataSource Database = $this.Connection.Database CommandTimeout = $this.CommandTimeout HasTransaction = $this.HasTransaction() } } [void] ChangeDatabase([string]$DatabaseName) { $this.Connection.ChangeDatabase($DatabaseName) } [System.Data.DataSet] GetDataSet([System.Data.IDbCommand]$cmd) { $ds = [System.Data.DataSet]::new() $da = [System.Data.SqlClient.SqlDataAdapter]::new($cmd) Try { $da.Fill($ds) return $ds } Catch { Throw $_ } Finally { $da.dispose() } } [long] BulkLoad([System.Data.IDataReader]$DataReader , [string]$DestinationTable , [hashtable]$ColumnMap = @{} , [int]$BatchSize , [int]$BatchTimeout , [ScriptBlock]$Notify) { [long]$RowCount = 0 $bcp = [System.Data.SqlClient.SqlBulkCopy]::new($this.Connection, [System.Data.SqlClient.SqlBulkCopyOptions]::KeepIdentity, $null) Try { $bcp.DestinationTableName = $DestinationTable $bcp.BatchSize = $BatchSize $bcp.BulkCopyTimeout = $BatchTimeout $bcp.EnableStreaming = $true If($ColumnMap -and $ColumnMap.Count -gt 0) { ForEach ($de in $ColumnMap.GetEnumerator()) { $bcp.ColumnMappings.Add($de.Key, $de.Value) } } If ($Notify) { $bcp.NotifyAfter = $BatchSize $bcp.add_SqlRowsCopied({ Param($sender, [System.Data.SqlClient.SqlRowsCopiedEventArgs]$e) $Notify.Invoke($e.RowsCopied) }) } Else { $bcp.NotifyAfter = $BatchSize $bcp.add_SqlRowsCopied() } $RowCount -= $this.GetScalar("SELECT COUNT(1) FROM [$DestinationTable]", 30, @{}) $bcp.WriteToServer($DataReader) $RowCount += $this.GetScalar("SELECT COUNT(1) FROM [$DestinationTable]", 30, @{}) } Finally { $bcp.Close() $bcp.Dispose() $DataReader.Close() $DataReader.Dispose() } return $RowCount } static [System.Data.IDbConnection] CreateConnection([hashtable]$ht) { If($ht.ParameterSetName -notin @("Default", "Conn", "user", "cred")) { Throw [System.InvalidOperationException]::new("Invalid ParameterSet passed to CreateConnection") } $sb = [System.Data.SqlClient.SqlConnectionStringBuilder]::new() If($ht.ContainsKey("ConnectionString")) { $sb["Connection String"] = $ht.ConnectionString } Else { If($ht.ContainsKey("DataSource")) { $sb.Server = $ht.DataSource } If($ht.ContainsKey("InitialCatalog")) { $sb.Database = $ht.InitialCatalog } If($ht.ContainsKey("User")) { $sb["User Id"] = $ht.User } Else { $sb["Integrated Security"] = $true } If($ht.ContainsKey("Password")) { $sb.Password = $ht.Password } } $sb["Application Name"] = "PowerShell ({0})" -f $ht.ConnectionName If($ht.ContainsKey("Credential")) { [securestring]$sqlCred = $ht.Credential.Password.Copy() $sqlCred.MakeReadOnly() $conn = [System.Data.SqlClient.SqlConnection]::new($sb.ConnectionString, [System.Data.SqlClient.SqlCredential]::new($ht.Credential.UserName, $sqlCred)) } Else { $conn = [System.Data.SqlClient.SqlConnection]::new($sb.ConnectionString) } Try { $conn.Open() } Catch { $conn.Dispose() Throw $_ } return $conn } }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Classes/SqlMessage.ps1
SqlMessage.ps1
Class SqlMessage { [datetime]$Received; [string]$Message }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Classes/ProviderConfig.ps1
ProviderConfig.ps1
Class ProviderConfig { [string]$ShortDescription [string]$HelpText [scriptblock]$CreateProvider [hashtable[]]$ParameterHash [System.Management.Automation.RuntimeDefinedParameterDictionary]$Parameters = (New-Object System.Management.Automation.RuntimeDefinedParameterDictionary) ProviderConfig() {} ProviderConfig([string]$ShortDescription, [string]$HelpText, [hashtable[]]$ht, [scriptblock]$CreateProvider){ $this.ShortDescription = $ShortDescription $this.HelpText = $HelpText $this.ParameterHash = $ht $this.CreateProvider = $CreateProvider } [System.Management.Automation.RuntimeDefinedParameterDictionary] GenerateParameters() { $paramDict = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new() ForEach($ht in $this.ParameterHash) { $paramDict.Add($ht.name, (CreateParameter @ht)) } Return $ParamDict } }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Classes/ProviderBase.ps1
ProviderBase.ps1
Class ProviderBase { [string]$ConnectionName [int]$CommandTimeout = 30 [System.Data.IDbConnection]$Connection [System.Data.IDbTransaction]$Transaction [System.Collections.Generic.Queue[SqlMessage]]$Messages = (New-Object 'System.Collections.Generic.Queue[SqlMessage]') ProviderBase() { If($this.GetType().Name -eq "ProviderBase") { Throw [System.InvalidOperationException]::new("ProviderBase must be inherited!") } } [PSCustomObject] ConnectionInfo() { Throw [System.NotImplementedException]::new("ProviderBase.ConnectionInfo must be overloaded!") } [void] ChangeDatabase([string]$DatabaseName) { Throw [System.NotImplementedException]::new("ProviderBase.ChangeDatabase must be overloaded!") } [string] ProviderType() { Throw [System.NotImplementedException]::new("ProviderBase.ProviderType must be overloaded!") } [System.Data.IDbCommand] GetCommand([string]$Query, [int]$cmdTimeout, [hashtable]$Parameters) { If($cmdTimeout -lt 0) { $cmdTimeout = $this.CommandTimeout } $cmd = $this.Connection.CreateCommand() $cmd.CommandText = $Query $cmd.CommandTimeout = $cmdTimeout ForEach($de in $Parameters.GetEnumerator()) { $param = $cmd.CreateParameter() $param.ParameterName = $de.Name If($de.Value) { $param.Value = $de.Value } Else { $param.Value = [System.DBNull]::Value } $cmd.Parameters.Add($param) } Return $cmd } [System.Object] GetScalar([string]$Query, [int]$cmdTimeout, [hashtable]$Parameters) { $cmd = $this.GetCommand($Query, $cmdTimeout, $Parameters) Try { return $cmd.ExecuteScalar() } Catch { Throw $_ } Finally { $cmd.Dispose() } } [System.Data.IDataReader] GetReader([string]$Query, [int]$cmdTimeout, [hashtable]$Parameters) { Return $this.GetCommand($Query, $cmdTimeout, $Parameters).ExecuteReader() } [long] Update([string]$Query, [int]$cmdTimeout, [hashtable]$Parameters) { $cmd = $this.GetCommand($Query, $cmdTimeout, $Parameters) Try { return $cmd.ExecuteNonQuery() } Catch { Throw $_ } Finally { $cmd.Dispose() } } [System.Data.DataSet] GetDataSet([System.Data.IDbCommand]$cmd) { Throw [System.NotImplementedException]::new("ProviderBase.GetDataSet must be overloaded!") } [long] BulkLoad([System.Data.IDataReader]$DataReader , [string]$DestinationTable , [hashtable]$ColumnMap = @{} , [int]$BatchSize , [int]$BatchTimeout , [ScriptBlock]$Notify) { #Throw [System.NotImplementedException]::new("ProviderBase.BulkLoad must be overloaded!") $SchemaMap = @() [long]$batchIteration = 0 $DataReader.GetSchemaTable().Rows | ForEach-Object { $SchemaMap += [PSCustomObject]@{Ordinal = $_["ColumnOrdinal"]; SrcName = $_["ColumnName"]; DestName = $_["ColumnName"]}} If($ColumnMap -and $ColumnMap.Count -gt 0) { $SchemaMap = $SchemaMap | Where-Object SrcName -In $ColumnMap.Keys | ForEach-Object { $_.DestName = $ColumnMap[$_.SrcName]; $_ } } [string[]]$DestNames = $SchemaMap | Select-Object -ExpandProperty DestName [string]$InsertSql = "INSERT INTO {0} ({1}) VALUES (@{2})" -f $DestinationTable, ($DestNames -join ", "), ($DestNames -join ", @") $bulkCmd = $this.GetCommand($InsertSql, -1, @{}) Try { $bulkCmd.Transaction = $this.Connection.BeginTransaction() $sw = [System.Diagnostics.Stopwatch]::StartNew() [bool]$hasPrepared = $false While($DataReader.Read()) { If(-not $hasPrepared) { ForEach($sm in $SchemaMap) { $param = $bulkCmd.CreateParameter() $param.ParameterName = $sm.DestName $param.Value = $DataReader.GetValue($sm.Ordinal) $bulkCmd.Parameters.Add($param) | Out-Null } $bulkCmd.Prepare() $hasPrepared = $true } Else { ForEach($sm in $SchemaMap) { $bulkCmd.Parameters[$sm.Ordinal] = $DataReader.GetValue($sm.Ordinal) } } $batchIteration += 1 $null = $bulkCmd.ExecuteNonQuery() If($sw.Elapsed.TotalSeconds -gt $BatchTimeout) { Throw [System.TimeoutException]::new(("Batch took longer than {0} seconds to complete." -f $BatchTimeout)) } If($batchIteration % $BatchSize -eq 0) { $bulkCmd.Transaction.Commit() $bulkCmd.Transaction.Dispose() If($Notify) { $Notify.Invoke($batchIteration) } $bulkCmd.Transaction = $this.Connection.BeginTransaction() $sw.Restart() } } $bulkCmd.Transaction.Commit() $bulkCmd.Transaction.Dispose() $bulkCmd.Transaction = $null } Finally { If($bulkCmd.Transaction) { $bulkCmd.Transaction.Rollback() $bulkcmd.Transaction.Dispose() } $bulkCmd.Dispose() $DataReader.Close() $DataReader.Dispose() } Return $batchIteration } [SqlMessage] GetMessage() { Return $this.Messages.Dequeue() } [Void] ClearMessages() { $this.Messages.Clear() } [bool] HasMessages() { Return $this.Messages.Count -gt 0 } [bool] HasTransaction() { Return $this.Transaction -ne $null } [void] BeginTransaction() { If($this.Transaction) { Throw [System.InvalidOperationException]::new("Cannot BEGIN a transaction when one is already in progress.") } $this.Transaction = $this.Connection.BeginTransaction() } [void] RollbackTransaction() { If($this.Transaction) { $this.Transaction.Rollback() $this.Transaction.Dispose() $this.Transaction = $null } Else { Throw [System.InvalidOperationException]::new("Cannot ROLLBACK when there is no transaction in progress.") } } [void] CommitTransaction() { If($this.Transaction) { $this.Transaction.Commit() $this.Transaction.Dispose() $this.Transaction = $null } Else { Throw [System.InvalidOperationException]::new("Cannot COMMIT when there is no transaction in progress.") } } [void] AttachCommand([System.Data.IDbCommand]$Command) { $Command.Connection = $this.Connection If($this.Transaction) { $Command.Transaction = $this.Transaction } } static [System.Data.IDbConnection] CreateConnection([hashtable]$ht) { Throw [System.NotImplementedException]::new("ProviderBase.CreateConnection must be overloaded!") } }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Functions/CreateMapFunction.ps1
CreateMapFunction.ps1
Function CreateMapFunction { Param([Parameter(Mandatory)][System.Data.DataTable]$SchemaTable) $sb = [System.Text.StringBuilder]::new() $sb.AppendLine('Param([parameter(Mandatory)][System.Data.IDataRecord]$dr)') | Out-Null $sb.AppendLine('Return ([PSCustomObject]@{') | Out-Null ForEach($dr in $SchemaTable.Rows) { [string]$colName = $dr["ColumnName"] [int]$colOrdinal = $dr["ColumnOrdinal"] If([string]::IsNullOrWhiteSpace($colName)) { $colName = "Column{0}" -f ($colOrdinal + 1)} [string]$colFunction = Switch($dr["DataType"].Name) { "Boolean" { "GetBoolean" } "Byte" { "GetByte" } "Char" { "GetChar" } "Datetime" { "GetDateTime" } "Decimal" { "GetDecimal" } "Double" { "GetDouble" } "Single" { "GetFloat" } "Guid" { "GetGuid" } "Int16" { "GetInt16" } "Int32" { "GetInt32" } "Int64" { "GetInt64" } "String" { "GetString" } Default { "GetValue" } } If($dr["AllowDBNull"]) { $sb.AppendLine((' {0} = if($dr.IsDBNull({2})) {{$null}} else {{$dr.{1}({2})}}' -f $colName, $colFunction, $colOrdinal)) | Out-Null } Else { $sb.AppendLine((' {0} = $dr.{1}({2})' -f $colName, $colFunction, $colOrdinal)) | Out-Null } } $sb.AppendLine('})') | Out-Null Return ([scriptblock]::Create($sb.ToString())) }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Functions/CreateParameter.ps1
CreateParameter.ps1
Function CreateParameter { Param([string]$Name , [type]$Type , [System.Management.Automation.ParameterAttribute[]]$Parameters = @() , [hashtable[]]$ParameterHashes = @() , [string[]]$ValidateSet = @() , [string[]]$Alias = @() , [object]$DefaultValue) $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] $Parameters | ForEach-Object { $AttributeCollection.Add($_) } $ParameterHashes | ForEach-Object { $AttributeCollection.Add((CreateParameterAttribute @_)) } If($ValidateSet.Count -gt 0) { $AttributeCollection.Add([System.Management.Automation.ValidateSetAttribute]::new($ValidateSet)) } If($Alias.Count -gt 0) { $AttributeCollection.Add([System.Management.Automation.AliasAttribute]::new($Alias)) } $parameter = [System.Management.Automation.RuntimeDefinedParameter]::new($Name, $Type, $AttributeCollection) If($DefaultValue) { $parameter.Value = $DefaultValue } Return $parameter }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Functions/ProcessHashTable.ps1
ProcessHashTable.ps1
#dont' think this is needed anymore in PowerShell V3+ Function ProcessHashTable([parameter(Mandatory)][hashtable]$ht) { If($ht) { ForEach($key in $ht.keys){ If($ht.$key.GetType() -is [PSObject]) { $ht.$key = ([PSObject]($ht.$key)).BaseObject } } } }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Functions/TestConnectionName.ps1
TestConnectionName.ps1
Filter TestConnectionName { Param([parameter(Mandatory, ValueFromPipeline)][string]$ConnectionName , [switch]$Quiet) If(-not $Script:Connections.ContainsKey($ConnectionName)) { If(-not $Quiet.IsPresent) { If($ConnectionName -eq "Default") { Write-Warning "There is no active SQL Connection."} Else { Write-Warning "There is no active SQL connection ($ConnectionName)."} } Return $false } Else { Return $true } }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Functions/CreateParameterAttribute.ps1
CreateParameterAttribute.ps1
Function CreateParameterAttribute { Param([string]$ParameterSetName = "default" , [switch]$Mandatory , [int]$Position = 0 , [switch]$ValueFromPipeline , [switch]$ValueFromPipelineByPropertyName , [switch]$ValueFromRemainingArguments , [string]$HelpMessage) $attribute = [System.Management.Automation.ParameterAttribute]::new() $attribute.ParameterSetName = $ParameterSetName $attribute.Mandatory = $Mandatory.IsPresent $attribute.Position = $Position $attribute.ValueFromPipeline = $ValueFromPipeline.IsPresent $attribute.ValueFromPipelineByPropertyName = $ValueFromPipelineByPropertyName.IsPresent $attribute.ValueFromRemainingArguments = $ValueFromRemainingArguments.IsPresent If(-not [string]::IsNullOrWhiteSpace($HelpMessage)) { $attribute.HelpMessage = $HelpMessage } Write-Output $attribute }
PowerShellCorpus/PowerShellGallery/SimplySql/0.2.1/Functions/AddDynamicParameterDefaults.ps1
AddDynamicParameterDefaults.ps1
Function AddDynamicParameterDefaults { Param([Parameter(ValueFromPipeline)][System.Collections.Generic.Dictionary[string,object]]$Params) $Provider, $ParameterSetName = $Params.Provider, $Params.ParameterSetName ForEach($kvp in $Script:Providers.$Provider.GenerateParameters().GetEnumerator()) { If(-not $Params.ContainsKey($kvp.Key) -and $kvp.Value.IsSet) { $Params[$kvp.key] = $kvp.Value.Value } } Write-Output $Params }
PowerShellCorpus/PowerShellGallery/BaselineManagement/2.3.0/Tests/HelperFunctions.tests.ps1
HelperFunctions.tests.ps1
<############################################################################################ # File: BaselineManagement\HelperFunctions.psm1 # This suite contains Tests that are # used for validating the BaselineManagement Module. ############################################################################################> $script:TestSourceRoot = $PSScriptRoot $ModuleBase = Split-Path $script:TestSourceRoot $HelperModule = Join-Path $ModuleBase 'HelperFunctions.psm1' $SampleXML = Join-Path $ModuleBase 'Tests\Sample.XML' $SamplePOL = Join-Path $ModuleBase "Tests\Registry.Pol" $SampleGPTemp = Join-Path $ModuleBase "Tests\gptTmpl.inf" $SampleComment = Join-Path $ModuleBase "Tests\Comment.cmtx" $SampleREGXML = Join-Path $ModuleBase "Tests\Registry.xml" $JSONSample = Join-Path $ModuleBase "Tests\sample.json" Import-Module $HelperModule -Force Import-Module PSDesiredStateConfiguration -Force Import-Module Pester -Force Describe "DSC String Helper Tests" { Context "Write-DSCString" { # This only works when it feels like it. Mock Get-DSCResource -ParameterFilter { $Module -eq "TestModule_01"} -Verifiable { return [psobject]@{Name="TestResource_01";Properties=@(@{Name="Name";IsMandatory=$true}, @{Name="Value";IsMandatory=$true})}} Mock Get-DSCResource -ParameterFilter { $Module -eq "TestModule_02"} -Verifiable { return [psobject]@{Name="TestResource_02";Properties=@(@{Name="Name";IsMandatory=$true}, @{Name="Value";IsMandatory=$true})}} $CONFIG_Params = @{Configuration=$true;Name="TestConfig"} $CONFIG_ModuleParams = @{ModuleName = @("PSDesiredStateConfiguration");ModuleImport=$true} $CONFIG_Node = @{Node=$true;Name="localhost"} $CONFIG_ResourceParams = @{Resource=$true;Type="Registry";Name="Test";Parameters=@{Key="HKLM:\SOFTWARE";ValueName = "TestResource";ValueData="Test";ValueType="DWORD" }} $CONFIG_Invoke = @{InvokeConfiguration=$true;Name="TestConfig";OutputPath=$(Join-Path -Path "C:\Temp" -ChildPath Output)} It "Creates a Configuration Open Block" { Write-DSCString @CONFIG_Params | Should Match "Configuration $($CONFIG_Params.Name)`n{`n`n`t" } $CONFIG_Params.Add("Comment", "Test Comment") It "Comments a Configuration Open Block" { Write-DSCString @CONFIG_Params | Should Match "<#`n$($CONFIG_Params.Comment)`n#>" } It "Creates Module Import Strings" { Write-DSCString @CONFIG_ModuleParams | Should Match "(?s)$(($CONFIG_ModuleParams.ModuleName | %{"'$_'"}) -join ", ")" #Assert-MockCalled -CommandName Get-DscResource -Times 2 } It "Creates a Resource Block" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?m)$($CONFIG_ResourceParams.Type) '$($CONFIG_ResourceParams.Name)'.*$((($CONFIG_ResourceParams.Parameters.GetEnumerator() | %{"$($_.Key) = '$($_.Value)'"}) -join '|')*4)}" } It "Parses String Values Properly" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)'$($CONFIG_ResourceParams.Parameters.ValueData)'" } [int]$CONFIG_ResourceParams.Parameters.ValueData = 3 It "Parses Integer Values Properly" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)$($CONFIG_ResourceParams.Parameters.ValueData)" } [bool]$CONFIG_ResourceParams.Parameters.ValueData = $True It "Parses Boolean Values Properly" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)\`$$($CONFIG_ResourceParams.Parameters.ValueData)" } [string[]]$CONFIG_ResourceParams.Parameters.ValueData = "One", "Two", "Three" It "Parses Array String Values Properly" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)$(($CONFIG_ResourceParams.Parameters.ValueData | %{"'$_'"}) -join ", ")" } [int[]]$CONFIG_ResourceParams.Parameters.ValueData = 1,2,3 It "Parses Array Integer Values Properly" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)$(($CONFIG_ResourceParams.Parameters.ValueData | %{"$_"}) -join ", ")" } It "Detects Resource Conflicts" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)<#$($CONFIG_ResourceParams.Type).*}#>" } $CONFIG_ResourceParams.Add("CommentOUT", $True) It "Comments out Resources when asked" { Write-DSCString @CONFIG_ResourceParams | Should Match "(?s)<#$($CONFIG_ResourceParams.Type).*}#>" } It "Creates Node Blocks" { Write-DSCString @CONFIG_Node | Should Match "Node $($CONFIG_Node.Name)`n`t{`n" } It "Closes Configuration Blocks" { Write-DSCString -CloseConfigurationBlock | Should Match "`n}`n" } It "Closes Node Blocks" { Write-DSCString -CloseNodeBlock | Should Match "`t}" } It "Creates Invoke Configuration Strings" { Write-DSCString @CONFIG_Invoke | Should Match "$($CONFIG_Invoke.Name) -OutputPath '$($CONFIG_Invoke.OutputPath.Replace("\", "\\"))'" } } Context "Complete-Configuration" { Mock -Verifiable -CommandName Get-PSCallStack { return [psobject]@(@{Command="None"}, @{Command="PesterTest"}) } $Configuration = @" Configuration Test { Import-DSCResource -ModuleName PSDesiredStateConfiguration Node localhost { Service Spooler { Name = 'Spooler' State = 'Running' } } } Test -OutputPath $($script:TestSourceRoot) "@ $Configuration_ERROR = @" Configuration Test { Import-DSCResource -ModuleName PSDesiredStateConfiguration Node localhost { Service Spooler { State = 'Running' } } } Test -OutputPath $($script:TestSourceRoot) "@ It "Compiles a Configuration" { Complete-Configuration -ConfigString $Configuration -OutputPath $script:TestSourceRoot $MOF = (Join-Path -Path $script:TestSourceRoot -ChildPath "localhost.mof") $MOF | Should Exist Remove-Item $MOF } It "Creates Error files on Failure" { Complete-Configuration -ConfigString $Configuration_ERROR -OutputPath $script:TestSourceRoot -ErrorAction SilentlyContinue $ErrorFile = (Join-Path -Path $script:TestSourceRoot -ChildPath "WTF.ps1.error") $ErrorFile | Should Exist Remove-Item $ErrorFile } } } Describe "GPO Conversion Helper Tests" { Mock Write-DSCString -Verifiable { return @{} + $___BoundParameters___ } -ModuleName HelperFunctions Context "Comment.cmtx Data" { Write-Warning "Not Implemented Yet" } Context "Write-GPORegistryXMLData" { [xml]$RegistryXML = Get-Content $SampleREGXML $Settings = $RegistryXML.RegistrySettings.Registry It "Parses Registry XML" { $Settings | Should Not Be $Null } # Loop through every registry setting. foreach ($Setting in $Settings) { $Parameters = Write-GPORegistryXMLData -XML $Setting Write-Host $Parameters.Name It "Parses Registry XML Data" { If ($Parameters.CommentOut.IsPresent) { Write-Host -ForegroundColor Green "This Resource was commented OUT for failure to adhere to Standards: Tests are Invalid" } else { $Parameters.Type | Should Be "Registry" [string]::IsNullOrEmpty($Parameters.Parameters.ValueName) | Should Be $false Test-Path -Path $Parameters.Parameters.Key -IsValid | Should Be $true $TypeHash = @{"Binary"=[byte];"Dword"=[int];"ExpandString"=[string];"MultiString"=[string];"Qword"=[string];"String"=[string]} ($Parameters.Parameters.ValueType -in @($TypeHash.Keys)) | Should Be $true $Parameters.Parameters.ValueData | Should BeOfType $TypeHash[$Parameters.Parameters.ValueType] [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } } } Context "Write-POLRegistryData" { $registryPolicies = Read-PolFile -Path $SamplePOL It "Parses Registry Policies" { $registryPolicies | Should Not Be $Null } foreach ($Policy in $registryPolicies) { $Parameters = Write-POLRegistryData -Data $Policy Write-Host $Parameters.Name It "Parses Registry Data" { If ($Parameters.CommentOut.IsPresent) { Write-Host -ForegroundColor Green "This Resource was commented OUT for failure to adhere to Standards: Tests are Invalid" } else { $Parameters.Type | Should Be "Registry" [string]::IsNullOrEmpty($Parameters.Parameters.ValueName) | Should Be $false Test-Path -Path $Parameters.Parameters.Key -IsValid | Should Be $true $TypeHash = @{"Binary"=[byte];"Dword"=[int];"ExpandString"=[string];"MultiString"=[string];"Qword"=[string];"String"=[string]} ($Parameters.Parameters.ValueType -in @($TypeHash.Keys)) | Should Be $true $Parameters.Parameters.ValueData | Should BeOfType $TypeHash[$Parameters.Parameters.ValueType] [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } } } Context "GPtTempl.INF Data" { $ini = Get-IniContent $SampleGPTemp It "Parses INF files" { { Get-IniContent $SampleGPTemp } | Should Not Throw $ini | Should Not Be $null } # Loop through every heading. foreach ($key in $ini.Keys) { # Loop through every setting in the heading. foreach ($subKey in $ini[$key].Keys) { switch ($key) { "Service General Setting" { It "Parses Service Data" { $Parameters = Write-INFServiceData -Service $subkey -ServiceData $ini[$key][$subKey] Write-Host $Parameters.Name } } "Registry Values" { It "Parses Registry Values" { If ($Parameters.CommentOut.IsPresent) { Write-Host -ForegroundColor Green "This Resource was commented OUT for failure to adhere to Standards: Tests are Invalid" } else { $Parameters = Write-INFRegistryData -Key $subkey -ValueData $ini[$key][$subKey] Write-Host $Parameters.Name $Parameters.Type | Should Be "Registry" [string]::IsNullOrEmpty($Parameters.Parameters.ValueName) | Should Be $false Test-Path -Path $Parameters.Parameters.Key -IsValid | Should Be $true $TypeHash = @{"Binary"=[byte];"Dword"=[int];"ExpandString"=[string];"MultiString"=[string];"Qword"=[string];"String"=[string]} ($Parameters.Parameters.ValueType -in @($TypeHash.Keys)) | Should Be $true $Parameters.Parameters.ValueData | Should BeOfType $TypeHash[$Parameters.Parameters.ValueType] [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } } "File Security" { It "Parses File ACL Data" { $Parameters = Write-INFFileSecurityData -Path $subkey -ACLData $ini[$key][$subKey] Write-Host $Parameters.Name $Parameters.Type | Should Be xACL [String]::IsNullOrEmpty($Parameters.Parameters.DACLString) | Should Be $false Test-PAth -Path "$($Parameters.Parameters.Path)" -IsValid | Should Be $true [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } "Privilege Rights" { It "Parses Privilege Data" { $Parameters = Write-INFPrivilegeData -Privilege $subkey -PrivilegeData $ini[$key][$subKey] Write-Host $Parameters.Name $Parameters.Type | Should Be "UserRightsAssignment" [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false $UserRightsHash.Values -contains $Parameters.Parameters.Policy | Should Be $true } } "Kerberos Policy" { It "Parses Kerberos Data" { $Parameters = Write-INFSecuritySettingData -Key $subKey -SecurityData $ini[$key][$subkey] Write-Host $Parameters.Name $Parameters.Type | Should Be "SecuritySetting" [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false $SecuritySettings -contains $Parameters.Parameters.Name | Should Be $true $Parameters.Parameters.ContainsKey($Parameters.Parameters.Name) | Should Be $true } } "Registry Keys" { It "Parses Registry ACL Data" { $Parameters = Write-INFRegistryACLData -Path $subkey -ACLData $ini[$key][$subKey] Write-Host $Parameters.Name [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false Test-Path -Path $Parameters.Parameters.Path -IsValid | Should Be $true [string]::IsNullOrEmpty($Parameters.Parameters.DACLString) | SHould Be $false } } "System Access" { It "Parses System Access Settings" { $Parameters = Write-INFSecuritySettingData -Key $subKey -SecurityData $ini[$key][$subkey] Write-Host $Parameters.Name $Parameters.Type | Should Be "SecuritySetting" [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false $SecuritySettings -contains $Parameters.Parameters.Name | Should Be $true $Parameters.Parameters.ContainsKey($Parameters.Parameters.Name) | Should Be $true } } } } } } } Describe "XML Conversion Helper Tests" { [XML]$XML = Get-Content $SampleXML # We need to setup a namespace to properly search the XML. $namespace = @{e="http://schemas.microsoft.com/SolutionAccelerator/SecurityCompliance"} # Grab all the DiscoveryInfo objects in the XML. They determine how to find the setting in question. $results = (Select-XML -XPath "//e:SettingDiscoveryInfo" -Xml $xml -Namespace $namespace).Node Mock Write-DSCString -Verifiable { return @{} + $___BoundParameters___ } -ModuleName HelperFunctions It "Parses XML into DiscoveryInfo Objects" { $results | Should Not Be $null } Function Get-ValueNodeData { param ( [System.Xml.XmlElement]$node ) $Setting = "../.." $SettingDiscoveryInfo = ".." # Grab the ID/Name from the Setting value. $ID = $node.SelectNodes($Setting).id.Trim("{").TrimEnd("}") # Find the ValueData using the ID. $valueNodeData = (Select-XML -XPath "//e:SettingRef[@setting_ref='{$($id)}']" -Xml $xml -Namespace $namespace).Node if ($valueNodeData -eq $null) { Write-Error "Could not find ValueNodeData of $id" return $null } else { return $valueNodeData } } Context "Write-XMLRegistryData" { $SampleREG_DI = $results.Where({$_.DiscoveryType -eq "Registry" -and $_.ChildNodes.name -contains "RegistryDiscoveryInfo"}) $SampleREG_DI_Alt = $results.Where({$_.DiscoveryType -eq "Registry" -and $_.ChildNodes.name -notcontains "RegistryDiscoveryInfo"}) for ($i = 0; $i -lt $SampleREG_DI.Count;$i++) { It "Finds RegistyDiscoveryInfo" { $SampleREG_DI[$i] | Should Not Be $Null } $SampleREG_VND = Get-ValueNodeData $SampleREG_DI[$i] It "Retrieves Value Node Data" { $SampleREG_VND | Should Not Be $Null } $Parameters = Write-XMLRegistryData -DiscoveryData $SampleREG_DI[$i] -ValueData $SampleREG_VND Write-Host $Parameters.Name It "Parses Registry Data" { If ($Parameters.CommentOut.IsPresent) { Write-Host -ForegroundColor Green "This Resource was commented OUT for failure to adhere to Standards: Tests are Invalid" } else { $Parameters.Type | Should Be "Registry" [string]::IsNullOrEmpty($Parameters.Parameters.ValueName) | Should Be $false Test-Path -Path $Parameters.Parameters.Key -IsValid | Should Be $true $TypeHash = @{"Binary"=[byte];"Dword"=[int];"ExpandString"=[string];"MultiString"=[string];"Qword"=[string];"String"=[string]} ($Parameters.Parameters.ValueType -in @($TypeHash.Keys)) | Should Be $true $Parameters.Parameters.ValueData | Should BeOfType $TypeHash[$Parameters.Parameters.ValueType] [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } It "Parses Comment Data" { [string]::IsNullOrEmpty($parameters.Comment) | Should Be $false } It "Converts Comments into StringData" { { Get-NodeDataFromComments -Comments $Parameters.Comment } | Should Not Throw } } for ($i = 0; $i -lt $SampleREG_DI_Alt.Count;$i++) { It "Finds Alternate RegistryDiscoveryInfo" { $SampleREG_DI_Alt[$i] | Should Not Be $Null } $SampleREG_VND_Alt = Get-ValueNodeData $SampleREG_DI_Alt[$i] It "Retrieves Alternate Value Node Data" { $SampleREG_VND_Alt | Should Not Be $null } $Parameters_All = Write-XMLRegistryData -DiscoveryData $SampleREG_DI_Alt[$i] -ValueData $SampleREG_VND_Alt foreach ($Parameters in $Parameters_All) { Write-Host $Parameters.Name It "Parses Registry Data" { If ($Parameters.CommentOut.IsPresent) { Write-Host -ForegroundColor Green "This Resource was commented OUT for failure to adhere to Standards: Tests are Invalid" } else { $Parameters.Type | Should Be "Registry" [string]::IsNullOrEmpty($Parameters.Parameters.ValueName) | Should Be $false Test-Path -Path $Parameters.Parameters.Key -IsValid | Should Be $true $TypeHash = @{"Binary"=[byte];"Dword"=[int];"ExpandString"=[string];"MultiString"=[string];"Qword"=[string];"String"=[string]} ($Parameters.Parameters.ValueType -in @($TypeHash.Keys)) | Should Be $true $Parameters.Parameters.ValueData | Should BeOfType $TypeHash[$Parameters.Parameters.ValueType] [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } It "Parses Comment Data" { [string]::IsNullOrEmpty($parameters.Comment) | Should Be $false } It "Converts Comments into StringData" { { Get-NodeDataFromComments -Comments $Parameters.Comment } | Should Not Throw } } } } Context "Write-XMLAuditData" { $SampleAUDIT_DI = $results.Where({$_.DiscoveryType -eq "AdvancedAuditPolicy"}) for ($i = 0; $i -lt $SampleAUDIT_DI.Count;$i++) { $SampleAUDIT_VND = Get-ValueNodeData $SampleAUDIT_DI[$i] $Parameters = Write-XMLAuditData -DiscoveryData $SampleAUDIT_DI[$i] -ValueData $SampleAUDIT_VND Write-Host $Parameters.Name It "Parses AUDIT Data" { $Parameters.Type | Should BE "xAuditCategory" $AuditCategoryHash.Values -contains $Parameters.Parameters.SubCategory | Should Be $true @("Failure","NoAuditing","Success","SuccessAndFailure") -contains $Parameters.Parameters.AuditFlag | Should Be $true [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } It "Parses Comment Data" { [string]::IsNullOrEmpty($parameters.Comment) | Should Be $false } It "Converts Comments into StringData" { { Get-NodeDataFromComments -Comments $Parameters.Comment } | Should Not Throw } } } Context "Write-XMLPrivilegeData" { $SamplePRIV_DI = $results.Where({$_.DiscoveryType -eq "GeneratedScript (User Rights Assignment)"}) for ($i = 0; $i -lt $SamplePRIV_DI.Count;$i++) { $SamplePRIV_VND = Get-ValueNodeData $SamplePRIV_DI[$i] $Parameters = Write-XMLPrivilegeData -DiscoveryData $SamplePRIV_DI[$i] -ValueData $SamplePRIV_VND Write-Host $Parameters.Name It "Parses PRIVILEGE Data" { $Parameters.Type | Should Be "UserRightsAssignment" [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false $UserRightsHash.Values -contains $Parameters.Parameters.Policy | Should Be $true # Cannot parse Privilege Data without a sample because it COULD actually be Empty } It "Parses Comment Data" { [string]::IsNullOrEmpty($parameters.Comment) | Should Be $false } It "Converts Comments into StringData" { { Get-NodeDataFromComments -Comments $Parameters.Comment } | Should Not Throw } } } Context "Write-XMLWMIData" { $SampleWMI_DI = $results.Where({$_.DiscoveryType -eq "WMI"}) for ($i = 0; $i -lt $SampleWMI_DI.Count; $i++) { $SampleWMI_VND = Get-ValueNodeData $SampleWMI_DI[$i] $Parameters = Write-XMLWMIData -DiscoveryData $SampleWMI_DI[$i] -ValueData $SampleWMI_VND Write-Host $Parameters.Name It "Parses SecuritySetting Data" { $Parameters.Type | Should Be "SecuritySetting" [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false $SecuritySettings -contains $Parameters.Parameters.Name | Should Be $true $Parameters.Parameters.ContainsKey($Parameters.Parameters.Name) | Should Be $true } It "Parses Comment Data" { [string]::IsNullOrEmpty($parameters.Comment) | Should Be $false } It "Converts Comments into StringData" { { Get-NodeDataFromComments -Comments $Parameters.Comment } | Should Not Throw } } } } Describe "JSON Conversion Helper Tests" { $JSON = Get-Content -Path $JSONSample | ConvertFrom-Json $registryPolicies = $JSON.properties.RulesetsCollection.BaselineRuleset.rules.BaselineRegistryRule $AuditPolicies = $JSON.properties.RulesetsCollection.BaselineRuleset.rules.BaselineAuditPolicyRule $securityPolicies = $JSON.properties.RulesetsCollection.BaselineRuleset.rules.BaselineSecurityPolicyRule Context "Write-JSONRegistryData" { Mock Write-DSCString -Verifiable { return @{} + $___BoundParameters___ } -ModuleName HelperFunctions # Loop through all the registry settings. Foreach ($Policy in $registryPolicies) { $HiveHash = @{"LocalMachine" = "HKLM:"} $TypeHash = @{"Int"="DWORD";"String"= "String"} $Parameters = Write-JSONRegistryData -RegistryData $Policy Write-Host $Parameters.Name -ForegroundColor White It "Parses Regisry Data" { If ($Parameters.CommentOut.IsPresent) { Write-Host -ForegroundColor Green "This Resource was commented OUT for failure to adhere to Standards: Tests are Invalid" } else { $Parameters.Type | Should Be "Registry" [string]::IsNullOrEmpty($Parameters.Parameters.ValueName) | Should Be $false Test-Path -Path $Parameters.Parameters.Key -IsValid | Should Be $true $TypeHash = @{"Binary"=[byte];"Dword"=[int];"ExpandString"=[string];"MultiString"=[string];"Qword"=[string];"String"=[string]} ($Parameters.Parameters.ValueType -in @($TypeHash.Keys)) | Should Be $true $Parameters.Parameters.ValueData | Should BeOfType $TypeHash[$Parameters.Parameters.ValueType] [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } switch ($JSON_Entry) { {$_.RegValueType -eq "Int"} { It "Parses Integers Values Properly" { $Parameters.Parameters.ValueData | Should BeOfType ([int]) # Should BeOfType? } } {$_.RegValueType -eq "String"} { It "Parses String Values Properly" { $Parameters.Parameters.ValueData | Should BeOfType ([string]) # Should BeOfType? } } {$_.RegValueType -eq "Binary"} { <#It "Parses Binary Values Properly" { $Parameters = Write-JSONRegistryData -RegistryData $JSON_Sample }#> } {$_.Enabled -eq $False} { It "Respects the Enabled Flag" { $Parameters.CommentOUT | Should Be $true } } } } } Context "Write-JSONAuditData" { Mock Write-DSCString -Verifiable { return @{} + $___BoundParameters___ } -ModuleName HelperFunctions foreach ($Policy in $auditPolicies) { $Parameters = Write-JSONAuditData -AuditData $Policy Write-Host $Parameters.Name -ForegroundColor White It "Parses Audit Data" { $Parameters.Type | Should Be xAuditCategory $Parameters.Parameters.SubCategory | Should Be $AuditCategoryHash[$Policy.AuditPolicyId] $Parameters.Parameters.AuditFlag | Should Be $Policy.ExpectedValue.Trim() [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } if (!$Policy.Enabled) { It "Respects the Enabled Flag" { $Parameters.CommentOUT | Should Be $True } } } } Context "Write-JSONPrivilegeData" { Mock Write-DSCString -Verifiable { return @{} + $___BoundParameters___ } -ModuleName HelperFunctions foreach ($Policy in $securityPolicies) { $Parameters = Write-JSONPrivilegeData -PrivilegeData $Policy Write-Host $Parameters.Name switch ($Policy.SectionName) { "Service General Setting" { } "Registry Values" { } "File Security" { } "Privilege Rights" { It "Parses Privilege Data" { $Parameters.Type | Should Be "UserRightsAssignment" $Parameters.Parameters.Policy | Should Be $UserRightsHash[$Policy.SettingName] $Parameters.Parameters.Identity -join ", " | Should Match ((($Policy.ExpectedValue.Replace("No One", "") -split ", ") | %{"(?=.*$_)"}) -join "") [string]::IsNullOrEmpty($Parameters.Name) | Should Be $false } } "Kerberos Policy" { } "Registry Keys" { } "System Access" { } } if (!$Policy.Enabled) { It "Respects the Enabled Flag" { $Parameters.CommentOUT | Should be $true } } } } }
PowerShellCorpus/PowerShellGallery/xMPC/1.0.2/Example/Sample_xMPC.ps1
Sample_xMPC.ps1
# Configuration sample for xMPC. # Vasken Houdoverdov # # Each of the calls to Sample_InstallxMPC below will generate a MOF file which can then be fed into Start-DscConfiguration # # Sample_InstallxMPC -VersionNumber "1.7.9" -Architecture "x64" -LocalPath "C:\Windows\DtlDownloads\MPC-HC.1.7.9.x64.exe" # Sample_InstallxMPC -VersionNumber "1.7.9" -Architecture "x86" -LocalPath "C:\Windows\DtlDownloads\MPC-HC.1.7.9.x86.exe" # # Sample_InstallxMPC -VersionNumber "1.7.8" -Architecture "x64" -LocalPath "C:\Windows\DtlDownloads\MPC-HC.1.7.8.x64.exe" # Sample_InstallxMPC -VersionNumber "1.7.8" -Architecture "x86" -LocalPath "C:\Windows\DtlDownloads\MPC-HC.1.7.8.x86.exe" # # Sample_InstallxMPC -VersionNumber "1.7.7" -Architecture "x64" -LocalPath "C:\Windows\DtlDownloads\MPC-HC.1.7.7.x64.exe" # Sample_InstallxMPC -VersionNumber "1.7.7" -Architecture "x86" -LocalPath "C:\Windows\DtlDownloads\MPC-HC.1.7.7.x86.exe" # # Note that the silent installation for OSSEC 2.7.1 does not automatically place shortcuts to the Manage Agent utility in the start menu. Configuration Sample_InstallxMPC { param ( [Parameter(Mandatory)] $VersionNumber, [Parameter(Mandatory)] $LocalPath, [Parameter(Mandatory)] $Architecture ) Import-DscResource -module xMPC VH_xMPC mpc { VersionNumber = $VersionNumber Architecture = $Architecture LocalPath = $LocalPath } }
PowerShellCorpus/PowerShellGallery/PSWebAccessAuthorization/0.5.0.0/Tests/PSWebAccessAuthorization.tests.ps1
PSWebAccessAuthorization.tests.ps1
Return "No Pester tests have been defined" $here = Split-Path -Path $MyInvocation.MyCommand.Path $parent = Split-Path -Path $here $module = Split-Path -Path $parent -Leaf Write-Host "Importing module $module from $parent" -ForegroundColor Cyan Import-Module $parent -force InModuleScope $Module { Describe PSWebAccessAuthorization { It "does something useful" { $true | Should Be $true } } }
PowerShellCorpus/PowerShellGallery/AzurePublicIPAddresses/0.8.3/AzurePublicIPAddresses.Tests.ps1
AzurePublicIPAddresses.Tests.ps1
Import-Module $PSScriptRoot\AzurePublicIPAddresses.psm1 -Force Describe 'AzurePublicIPAddresses' { Context 'Script Analyzer' { It 'Does not have any issues with the Script Analyser - Get-MicrosoftAzureDatacenterIPRange' { Invoke-ScriptAnalyzer $PSScriptRoot\Functions\Get-MicrosoftAzureDatacenterIPRange.ps1 | Should be $null } It 'Does not have any issues with the Script Analyser - Get-MicrosoftAzureDatacenterIPRangeFile' { Invoke-ScriptAnalyzer $PSScriptRoot\Functions\Get-MicrosoftAzureDatacenterIPRangeFile.ps1 | Should be $null } } Context 'Get-MicrosoftAzureDatacenterIPRange Parameter validation' { It 'throws an error for an invalid region is specified' { {Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'nomansland'} | should throw } It 'throws an error for $null is specified for a region' { {Get-MicrosoftAzureDatacenterIPRange -AzureRegion $null} | should throw } It 'throws an error for an empty string is specified for a region' { {Get-MicrosoftAzureDatacenterIPRange -AzureRegion ''} | should throw } It 'throws an error for @() is specified for a region' { {Get-MicrosoftAzureDatacenterIPRange -AzureRegion @()} | should throw } It 'throws an error for @() is specified for a region 2' { {Get-MicrosoftAzureDatacenterIPRange -AzureRegion @('')} | should throw } It 'throws an error for $null is specified for a path' { {Get-MicrosoftAzureDatacenterIPRange -Path $null} | should throw } It 'throws an error for an empty string is specified for a path' { {Get-MicrosoftAzureDatacenterIPRange -Path ''} | should throw } It 'throws an error for an invalid path is specified for a path' { {Get-MicrosoftAzureDatacenterIPRange -Path 'C:\Windowsthisdoesnotexit\file.xml'} | should throw } It 'throws an error for an folder path is specified for a path' { {Get-MicrosoftAzureDatacenterIPRange -Path 'C:\Windows'} | should throw } } Context 'Get-MicrosoftAzureDatacenterIPRangeFile Parameter validation' { It 'throws an error for $null is specified for a path' { {Get-MicrosoftAzureDatacenterIPRangeFile -Path $null} | should throw } It 'throws an error for an empty string is specified for a path' { {Get-MicrosoftAzureDatacenterIPRangeFile -Path ''} | should throw } It 'throws an error for an invalid path is specified for a path' { {Get-MicrosoftAzureDatacenterIPRangeFile -Path 'C:\Windowsthisdoesnotexit\file.xml'} | should throw } It 'throws an error for an folder path is specified for a path' { {Get-MicrosoftAzureDatacenterIPRangeFile -Path 'C:\Windows'} | should throw } } Context 'Get-MicrosoftAzureDatacenterIPRange outputs results for each supported Azure region' { It 'returns output for West Europe' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'West Europe' | Should not be $null } It 'returns output for East US' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'East US'| Should not be $null } It 'returns output for East US 2' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'East US 2' | Should not be $null } It 'returns output for West US' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'West US' | Should not be $null } It 'returns output for North Central US' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'North Central US' | Should not be $null } It 'returns output for North Europe' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'North Europe' | Should not be $null } It 'returns output for Central US' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Central US' | Should not be $null } It 'returns output for East Asia' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'East Asia' | Should not be $null } It 'returns output for Southeast Asia' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Southeast Asia' | Should not be $null } It 'returns output for South Central US' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'South Central US' | Should not be $null } It 'returns output for Japan West' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Japan West' | Should not be $null } It 'returns output for Japan East' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Japan East' | Should not be $null } It 'returns output for Brazil South' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Brazil South' | Should not be $null } It 'returns output for Australia East' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Australia East' | Should not be $null } It 'returns output for Australia Southeast' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Australia Southeast' | Should not be $null } It 'returns output for Central India' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Central India' | Should not be $null } It 'returns output for West India' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'West India' | Should not be $null } It 'returns output for South India' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'South India' | Should not be $null } It 'returns output for Canada Central' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Canada Central' | Should not be $null } It 'returns output for Canada East' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Canada East' | Should not be $null } It 'returns output for West Central US' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'West Central US' | Should not be $null } It 'returns output for West US 2' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'West US 2' | Should not be $null } It 'returns output for UK South' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'UK South' | Should not be $null } It 'returns output for UK West' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'UK West' | Should not be $null } It 'returns output for China North' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'China North' | Should not be $null } It 'returns output for China East' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'China East' | Should not be $null } It 'returns output for Central US EUAP' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Central US EUAP' | Should not be $null } It 'returns output for East US 2 EUAP' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'East US 2 EUAP' | Should not be $null } It 'returns output for Korea South' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Korea South' | Should not be $null } It 'returns output for Korea Central' { Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'Korea Central' | Should not be $null } It 'accepts an Azure region from the pipeline' { {'West US 2' | Get-MicrosoftAzureDatacenterIPRange} | Should not be $null } It 'accepts multiple Azure regions from the pipeline' { { @('West US 2', 'Canada East') | Get-MicrosoftAzureDatacenterIPRange} | Should not be $null } It 'returns values if no region is specified' { Get-MicrosoftAzureDatacenterIPRange | Should not be $null } } Context 'File operations' { $TestPath = "TestDrive:\test.txt" It 'Get-MicrosoftAzureDatacenterIPRangeFile saves the IP range file as specified' { $Test = Get-MicrosoftAzureDatacenterIPRangeFile -Path $TestPath $Test | Should be $null Test-Path -Path $TestPath | Should be $true } It 'Get-MicrosoftAzureDatacenterIPRange reads from the IP range file if specifies' { Get-MicrosoftAzureDatacenterIPRange -Path $TestPath | should not be $null } } Context 'Get-MicrosoftAzureDatacenterIPRangeFile' { It 'outputs an xml document if no path is specified' { $null -ne (Get-MicrosoftAzureDatacenterIPRangeFile).AzurePublicIpAddresses | should be $true $null -ne (Get-MicrosoftAzureDatacenterIPRangeFile).AzurePublicIpAddresses.Region | should be $true } } }
PowerShellCorpus/PowerShellGallery/AzurePublicIPAddresses/0.8.3/functions/Get-MicrosoftAzureDatacenterIPRangeFile.ps1
Get-MicrosoftAzureDatacenterIPRangeFile.ps1
#requires -Version 3.0 function Get-MicrosoftAzureDatacenterIPRangeFile { <# .SYNOPSIS Downloads either the Microsoft Azure Datacenter IP Ranges file, or the Windows Azure Datacenter IP Ranges in China file. The file can be stored in memory or to the file system. .DESCRIPTION This CMDLet will download either of the two files: Microsoft Azure Datacenter IP Ranges (https://www.microsoft.com/en-us/download/details.aspx?id=41653) Windows Azure Datacenter IP Ranges in China (https://www.microsoft.com/en-us/download/details.aspx?id=42064) If the -ChinaRegion parameter is not specified, then Microsoft Azure Datacenter IP Ranges is downloaded. If the -ChinaRegion parameter is specified, then Windows Azure Datacenter IP Ranges in China is downloaded. It should be noted that this file is updated on a weekly basis, so if you save these file, then you should re-download them on a regular basis. This cmdlet makes use of Invoke-WebRequest. .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRangeFile Returns an XML document from the Microsoft Azure Datacenter IP Ranges file .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRangeFile -Path C:\Temp\AzureRanges.xml Dowloads the Microsoft Azure Datacenter IP Ranges file to C:\Temp\AzureRanges.xml .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRangeFile -ChinaRegion Returns an XML document from the Microsoft Azure Datacenter IP Ranges in China file .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRangeFile -ChinaRegion -Path C:\Temp\AzureRangesChina.xml Downloads the Microsoft Azure Datacenter IP Ranges in China file to C:\Temp\AzureRangesChina.xml .OUTPUTS XML document containing Azure Subnets, or Void if saving the file to the file system #> [CmdletBinding(DefaultParameterSetName = 'xml')] [OutputType([System.Xml.XmlDocument], ParameterSetName = 'path')] [OutputType([void], ParameterSetName = 'xml')] param( # Path where you want to save the XML file [Parameter(Mandatory = $false, ParameterSetName = 'path', Position = 0)] [ValidateNotNullOrEmpty()] [ValidateScript({Test-Path -Path (Split-Path -Path $_ -Parent) -PathType Container})] [String] $Path, # Download China Region File [Parameter(Mandatory = $false, Position = 1)] [Switch] $ChinaRegion ) if ($PSBoundParameters.ContainsKey('ChinaRegion') -and $ChinaRegion) { Write-Verbose -Message 'Downloading... Windows Azure Datacenter IP Ranges in China' $MicrosoftDownloadsURL = 'https://www.microsoft.com/en-us/download/confirmation.aspx?id=42064' } else { Write-Verbose -Message 'Downloading... Microsoft Azure Datacenter IP Ranges' $MicrosoftDownloadsURL = 'https://www.microsoft.com/en-us/download/confirmation.aspx?id=41653' } $DownloadPage = Invoke-WebRequest -UseBasicParsing -Uri $MicrosoftDownloadsURL $DownloadLink = ($DownloadPage.Links | Where-Object -FilterScript {$_.outerHTML -match 'Click here' -and $_.href -match '.xml'}).href[0] if ($PSCmdlet.ParameterSetName -eq 'path') { Write-Verbose -Message ('Saving file to {0}' -f $Path) Invoke-WebRequest -UseBasicParsing -Uri $DownloadLink -OutFile $Path } else { Write-Verbose -Message 'Downloading and creating XML object' $Request = Invoke-WebRequest -UseBasicParsing -Uri $DownloadLink $RequestXML = Select-Xml -Content $Request.toString() -XPath / $RequestXML.Node } }
PowerShellCorpus/PowerShellGallery/AzurePublicIPAddresses/0.8.3/functions/Get-MicrosoftAzureDatacenterIPRange.ps1
Get-MicrosoftAzureDatacenterIPRange.ps1
#requires -Version 4.0 function Get-MicrosoftAzureDatacenterIPRange { <# .SYNOPSIS Gets the IP ranges associated with Azure regions in CIDR format. .DESCRIPTION The Get-MicrosoftAzureDatacenterIPRange cmdlet gets a list of subnets in CIDR format (eg 192.168.1.0/24). You can get the ranges for a specific region, or get all subnets for all regions. There are two files that contain all the information that this CMDLet uses: Microsoft Azure Datacenter IP Ranges file (https://www.microsoft.com/en-us/download/details.aspx?id=41653) Windows Azure Datacenter IP Ranges in China (https://www.microsoft.com/en-us/download/details.aspx?id=42064) Both of these files are updated each week. If the -path parameter is omitted, then the CMDLet will download both files and store them in memory (it doesn't save them to disk). The CMDLet will not download the file upon each execution, as it checks to see if the file has already been stored in memory. If you specify -path, the CMDLet will generate warnings that not all regions will be available. This is by design. I will look at handling both files saved to the file system in a later release. .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRange -AzureRegion 'North Central US' Returns all of the subnets in the North Central US regions, will download the Microsoft Azure Datacenter IP Ranges file into memory .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRange -AzureRegion @('North Central US', 'West India') Returns all of the subnets in the North Central US and West India regions, will download the Microsoft Azure Datacenter IP Ranges file into memory .EXAMPLE C:\PS> @('Japan West', 'Japan East') | Get-MicrosoftAzureDatacenterIPRange Returns all of the subnets in the Japan West and East regions, will download the Microsoft Azure Datacenter IP Ranges file into memory .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRange -Path C:\Temp\AzureRanges.xml -AzureRegion 'North Central US' Returns all of the subnets in the North Central US region based on the specified file .EXAMPLE C:\PS> Get-MicrosoftAzureDatacenterIPRange Returns all of the subnets used by Azure, will download the Microsoft Azure Datacenter IP Ranges file into memory .INPUTS Can take Azure region names from the pipeline. .OUTPUTS Outputs objects containing each subnet and their region. #> [CmdletBinding()] [OutputType([PSCustomObject])] param( # Azure Datacenter/region [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline = $true)] [ValidateSet( 'West Europe', 'East US', 'East US 2', 'West US', 'North Central US', 'North Europe', 'Central US', 'East Asia', 'Southeast Asia', 'South Central US', 'Japan West', 'Japan East', 'Brazil South', 'Australia East', 'Australia Southeast', 'Central India', 'West India', 'South India', 'Canada Central', 'Canada East', 'West Central US', 'West US 2', 'UK South', 'UK West', 'China North', 'China East', 'Central US EUAP', 'East US 2 EUAP', 'Korea South', 'Korea Central' )] [ValidateNotNullOrEmpty()] [String[]] $AzureRegion, # Path to Microsoft Azure Datacenter IP Ranges file [Parameter(Mandatory = $false, Position = 1)] [ValidateNotNullOrEmpty()] [ValidateScript({Test-Path -Path $_ -PathType Leaf})] [String] $Path ) begin { if ($PSBoundParameters.ContainsKey('path')) { # Read the file $PublicIPXML = [xml](Get-Content -Path $Path) #Display warning stating that some regions may not be available Write-Warning -Message 'Using -Path may result in some regions being unavailable and returning no values.' if ($publicipxml.AzurePublicIpAddresses.Region.Name.Contains('chinanorth')) { Write-Warning -Message 'The file specified contains only Azure China regions (China North and China East), only these regions will return results' } else { Write-Warning -Message 'The file specified does not contain Azure China regions (China North and China East), no results will be returned for these regions' } } else { if ($null -eq $Script:PublicIPXML) { Write-Verbose -Message 'Fetching region data file' $Script:PublicIPXML = Get-MicrosoftAzureDatacenterIPRangeFile Write-Verbose -Message 'Fetching the china region file' $Script:PublicIPChinaXML = Get-MicrosoftAzureDatacenterIPRangeFile -ChinaRegion } } # Define the region mappings (What we see in the portal to the names in the file) $AzureRegions = @{ 'West Europe' = 'EuropeWest' 'East US' = 'USEast' 'East US 2' = 'USEast2' 'West US' = 'USWest' 'North Central US' = 'USNorth' 'North Europe' = 'EuropeNorth' 'Central US' = 'USCentral' 'East Asia' = 'AsiaEast' 'Southeast Asia' = 'AsiaSouthEast' 'South Central US' = 'USSouth' 'Japan West' = 'JapanWest' 'Japan East' = 'JapanEast' 'Brazil South' = 'BrazilSouth' 'Australia East' = 'AustraliaEast' 'Australia Southeast' = 'AustraliaSoutheast' 'Central India' = 'IndiaCentral' 'West India' = 'IndiaWest' 'South India' = 'IndiaSouth' 'Canada Central' = 'CanadaCentral' 'Canada East' = 'CanadaEast' 'West Central US' = 'USWestCentral' 'West US 2' = 'USWest2' 'UK South' = 'UKSouth' 'UK West' = 'UKWest' 'China North' = 'chinanorth' 'China East' = 'chinaeast' 'Central US EUAP' = 'uscentraleuap' 'East US 2 EUAP' = 'useast2euap' 'Korea South' = 'koreasouth' 'Korea Central' = 'koreacentral' } $Regions = $PublicIPXML.AzurePublicIpAddresses.Region + $PublicIPChinaXML.AzurePublicIpAddresses.Region } process { # Are we selecting a specific region or returing all subnets? if ($PSBoundParameters.ContainsKey('AzureRegion')) { #We need to process this as we may have one or many regions specified in $AzureRegion foreach ($Region in $AzureRegion) { # Translate the friendly region name to the backend names $BackendRegionName = $AzureRegions[$Region] Write-Verbose -Message "Backend region $BackendRegionName" $Subnets = ($Regions.where({$_.name -eq $BackendRegionName})).iprange.subnet foreach ($Subnet in $Subnets) { $OutputObject = [PSCustomObject]@{ Region = $Region Subnet = $Subnet } Write-Output -InputObject $OutputObject } } } else { foreach ($Region in $Regions) { $BackendRegionName = $Region.Name # Translate each region name to something friendly $AzureRegion = $AzureRegions.GetEnumerator().Where({$_.Value -eq $BackendRegionName}).Name Write-Verbose -Message "Azure Region Name $AzureRegion" # Create the output object foreach ($Subnet in $Region.IpRange) { $OutputObject = [PSCustomObject]@{ Region = $AzureRegion Subnet = $Subnet.Subnet } Write-Output -InputObject $OutputObject } } } } }
PowerShellCorpus/PowerShellGallery/Error/1.4.0.3/Resolve-Error.ps1
Resolve-Error.ps1
<# .SYNOPSIS Recurses an error record or exception object to flatten nested objects. .DESCRIPTION Loops through information caught in catch blocks; from an ErrorRecord (and its InvocationInfo), to Exception, and InnerException. .PARAMETER ErrorRecord An error record or exception. By default the last error is used. .PARAMETER AsString Return an array of strings for printable output. By default we return an array of objects. .PARAMETER Reverse Returns items from outermost to innermost. By default we return items innermost to outermost. .INPUTS By default the last error; otherwise any error record or exception can be passed in by pipeline or first parameter. .OUTPUTS An array of objects, or an array of strings. .EXAMPLE Resolve-Error Returns an array of nested objects describing the last error. .EXAMPLE $_ | Resolve-Error -AsString Returns an array of strings describing the error in $_. #> function Resolve-Error { [CmdletBinding()] param ( [Parameter(ValueFromPipeline = $true)] $ErrorRecord = $null, [switch] $AsString, [switch] $Reverse ) if (!$ErrorRecord) { # This is a bit iffy, if it's a nested module it needs $_ as $Error will not be populated yet. # If it's not a nested module then it needs a Get-Variable -Scope 2 $ErrorRecord = (Get-Variable -Name Error -Scope 2).Value | Select-Object -First 1 <# if ($Error.Count -gt 0) { $ErrorRecord = $Error[0] } else { $ErrorRecord = $_ } #> } $records = @() if ($ErrorRecord.psobject.Properties["InnerException"] -and $ErrorRecord.InnerException) { $records += Resolve-Error $ErrorRecord.InnerException } if ($ErrorRecord.psobject.Properties["Exception"] -and $ErrorRecord.Exception) { $records += Resolve-Error $ErrorRecord.Exception } if ($ErrorRecord.psobject.Properties["InvocationInfo"] -and $ErrorRecord.InvocationInfo) { $records += Resolve-Error $ErrorRecord.InvocationInfo } $records += $ErrorRecord if ($Reverse) { $records = [Array]::Reverse($records) } if (!$AsString) { $records } else { $string = @() $first = $true $records | ForEach-Object { if ($first) { $string += "=" * 40 $first = $false } else { $string += "*" * 5 } $string += $_ | Select-Object * | Out-String } $string += "" $stack = Get-PSCallStack for ($i = $stack.Count - 1; $i -ge 1; $i--) { $string += "-" * 5 $string += "Depth: $i" $string += "Function: $($stack[$i].FunctionName)" # In some highly threaded contexts this doesn't appear? if ($stack[$i].PSObject.Properties["Arguments"]) { $string += "Arguments: $($stack[$i].Arguments)" } $string += "Line: $($stack[$i].ScriptLineNumber)" $string += "Command: $($stack[$i].Position.Text)" } $string += "" $string += "" $string += "=" * 40 $string -join [System.Environment]::NewLine } }
PowerShellCorpus/PowerShellGallery/Error/1.4.0.3/Test-Error.ps1
Test-Error.ps1
<# .SYNOPSIS Recurses an error record or exception object and returns true/false if a match is found. .DESCRIPTION Loops through information caught in catch blocks; from an ErrorRecord (and its InvocationInfo), to Exception, and InnerException. These are then compared to a specific type, or, a hash table with a set of desired properties and settings. .PARAMETER ErrorRecord An error record or exception. By default the last error is used. .PARAMETER Type A type to compare against. If any item in the expanded ErrorRecord entry matches this typethen a $true result is returned. .PARAMETER Property A hash table with a series of Name/Value property pairs. If all of these exist on any object in the expanded ErrorRecord entry then a $true result is returned. .OUTPUTS $true or $false. .EXAMPLE Test-Error Microsoft.SqlServer.Management.Sdk.Sfc.InvalidVersionEnumeratorException Tests whether the ErrorRecord, Exception, InnerException, and so forth are this specific type of Exception. When providing this do not put it into string quotes. .EXAMPLE Test-Error @{ Number = 954; Class = 14; State = 1; } Tests whether the ErrorRecord, Exception, InnerException, and so forth have an item with all 3 properties which match these conditions. #> function Test-Error { [CmdletBinding(DefaultParameterSetName = "Type")] [OutputType("System.Boolean")] param ( [Parameter(ValueFromPipeline = $true, ParameterSetName = "Type")] [Parameter(ValueFromPipeline = $true, ParameterSetName = "TypeName")] [Parameter(ValueFromPipeline = $true, ParameterSetName = "Property")] $ErrorRecord = $null, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "Type")] [type] $Type, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "TypeName")] [string] $TypeName, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = "Property")] [hashtable] $Property ) if (!$ErrorRecord) { $ErrorRecord = (Get-Variable -Name Error -Scope 2).Value | Select-Object -First 1 } $expandedErrorRecord = Resolve-Error $ErrorRecord switch ($PSCmdlet.ParameterSetName) { "Type" { if ($expandedErrorRecord | Where-Object { $_ -is $Type }) { return $true } break } "TypeName" { if ($expandedErrorRecord | Where-Object { @($_.GetType(), $_.GetType().FullName) -contains $TypeName }) { return $true } break } "Property" { foreach ($record in $expandedErrorRecord) { $match = $true foreach ($thisProperty in $Property.GetEnumerator()) { if (!$record.psobject.Properties[$thisProperty.Name] -or !$record.$($thisProperty.Name) -or $record.$($thisProperty.Name).ToString() -ne $thisProperty.Value) { $match = $false break } } if ($match) { return $true } } break } } return $false }
PowerShellCorpus/PowerShellGallery/Poshjure/1.0/Poshjure.tests.ps1
Poshjure.tests.ps1
# # This is a PowerShell Unit Test file. # You need a unit test framework such as Pester to run PowerShell Unit tests. # You can download Pester from http://go.microsoft.com/fwlink/?LinkID=534084 # Describe "Get-Function" { Context "Function Exists" { It "Should Return" { } } }
PowerShellCorpus/PowerShellGallery/SonicWallVPN/1.1.1/SonicWallVpn.ps1
SonicWallVpn.ps1
$userFileName = "vpn.usr" $pwdFileName = "vpn.pwd" $nameFileName = "vpn.nme" function Enable-SonicVpn { [CmdletBinding()] Param ( ) Write-Verbose -Message "Connecting to VPN..." $name = Get-VpnName $user = Get-User $pwd = Get-Password & "C:\Program Files\Dell SonicWALL\Global VPN Client\swgvc.exe" /E $name /U $user /P $pwd } function Disable-SonicVpn { [CmdletBinding()] Param ( [string] $name = "VPN" ) Write-Verbose -Message "Disonnecting VPN..." & "C:\Program Files\Dell SonicWALL\Global VPN Client\swgvc.exe" /D $name } function Get-Password { $pwdFilePath = "$(Get-ModulePath)\$pwdFileName" if(Test-Path -Path $pwdFilePath) { $pwdFile = Get-Content -Path $pwdFilePath $secured = $pwdFile | ConvertTo-SecureString } else { $secured = Read-Host -Prompt "Enter password for VPN" -AsSecureString $secured | ConvertFrom-SecureString | Out-File -FilePath $pwdFilePath } $user=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name $creds = new-object -TypeName PSCredential -ArgumentList $user, $secured $pwd = $creds.GetNetworkCredential().Password return $pwd } function Get-User { $usrFilePath = "$(Get-ModulePath)\$userFileName" Write-Verbose -Message $usrFilePath if(Test-Path -Path $usrFilePath) { $usr = Get-Content -Path $usrFilePath } else { $usr = Read-Host -Prompt "Enter user name for VPN" $usr | Out-File -FilePath $usrFilePath } return $usr } function Get-VpnName { $nameFilePath = "$(Get-ModulePath)\$nameFileName" Write-Verbose -Message $nameFilePath if(Test-Path -Path $nameFilePath) { $name = Get-Content -Path $nameFilePath } else { $name = Read-Host -Prompt "Enter name of your VPN profile" $name | Out-File -FilePath $nameFilePath } return $name } function Reset-SonicVpnUser { Remove-Item -Path "$(Get-ModulePath)\$userFileName" } function Reset-SonicVpnPassword { Remove-Item -Path "$(Get-ModulePath)\$pwdFileName" } function Get-ModulePath { Split-Path -Path "$PSScriptRoot\SonicWallVPN\" } New-Alias -Name evpn -Value Enable-SonicVpn Export-ModuleMember -Function Enable-SonicVpn -Alias evpn New-Alias -Name dvpn -Value Disable-SonicVpn Export-ModuleMember -Function Disable-SonicVpn -Alias dvpn Export-ModuleMember -Function Reset-SonicVpnUser Export-ModuleMember -Function Reset-SonicVpnPassword
PowerShellCorpus/PowerShellGallery/PolicyFileEditor/2.0.2/Common.ps1
Common.ps1
#requires -Version 2.0 $script:MachineExtensionGuids = '[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F72-3407-48AE-BA88-E8213C6761F1}]' $script:UserExtensionGuids = '[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F73-3407-48AE-BA88-E8213C6761F1}]' function OpenPolicyFile { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Path ) $policyFile = New-Object TJX.PolFileEditor.PolFile $policyFile.FileName = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) if (Test-Path -LiteralPath $policyFile.FileName) { try { $policyFile.LoadFile() } catch [TJX.PolFileEditor.FileFormatException] { $message = "File '$Path' is not a valid POL file." $exception = New-Object System.Exception($message) $errorRecord = New-Object System.Management.Automation.ErrorRecord( $exception, 'InvalidPolFileContents', [System.Management.Automation.ErrorCategory]::InvalidData, $Path ) throw $errorRecord } catch { $errorRecord = $_ $message = "Error loading policy file at path '$Path': $($errorRecord.Exception.Message)" $exception = New-Object System.Exception($message, $errorRecord.Exception) $newErrorRecord = New-Object System.Management.Automation.ErrorRecord( $exception, 'FailedToOpenPolicyFile', [System.Management.Automation.ErrorCategory]::OperationStopped, $Path ) throw $newErrorRecord } } return $policyFile } function PolEntryToPsObject { param ( [TJX.PolFileEditor.PolEntry] $PolEntry ) $type = PolEntryTypeToRegistryValueKind $PolEntry.Type $data = GetEntryData -Entry $PolEntry -Type $type return New-Object psobject -Property @{ Key = $PolEntry.KeyName ValueName = $PolEntry.ValueName Type = $type Data = $data } } function GetEntryData { param ( [TJX.PolFileEditor.PolEntry] $Entry, [Microsoft.Win32.RegistryValueKind] $Type ) switch ($type) { ([Microsoft.Win32.RegistryValueKind]::Binary) { return $Entry.BinaryValue } ([Microsoft.Win32.RegistryValueKind]::DWord) { return $Entry.DWORDValue } ([Microsoft.Win32.RegistryValueKind]::ExpandString) { return $Entry.StringValue } ([Microsoft.Win32.RegistryValueKind]::MultiString) { return $Entry.MultiStringValue } ([Microsoft.Win32.RegistryValueKind]::QWord) { return $Entry.QWORDValue } ([Microsoft.Win32.RegistryValueKind]::String) { return $Entry.StringValue } } } function SavePolicyFile { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [TJX.PolFileEditor.PolFile] $PolicyFile, [switch] $UpdateGptIni ) if ($PSCmdlet.ShouldProcess($PolicyFile.FileName, 'Save new settings')) { $parentPath = Split-Path $PolicyFile.FileName -Parent if (-not (Test-Path -LiteralPath $parentPath -PathType Container)) { try { $null = New-Item -Path $parentPath -ItemType Directory -ErrorAction Stop -Confirm:$false -WhatIf:$false } catch { $errorRecord = $_ $message = "Error creating parent folder of path '$Path': $($errorRecord.Exception.Message)" $exception = New-Object System.Exception($message, $errorRecord.Exception) $newErrorRecord = New-Object System.Management.Automation.ErrorRecord( $exception, 'CreateParentFolderError', $errorRecord.CategoryInfo.Category, $Path ) throw $newErrorRecord } } try { $PolicyFile.SaveFile() } catch { $errorRecord = $_ $message = "Error saving policy file to path '$($PolicyFile.FileName)': $($errorRecord.Exception.Message)" $exception = New-Object System.Exception($message, $errorRecord.Exception) $newErrorRecord = New-Object System.Management.Automation.ErrorRecord( $exception, 'FailedToSavePolicyFile', [System.Management.Automation.ErrorCategory]::OperationStopped, $PolicyFile ) throw $newErrorRecord } } if ($UpdateGptIni) { if ($policyFile.FileName -match '^(.*)\\+([^\\]+)\\+[^\\]+$' -and $Matches[2] -eq 'User' -or $Matches[2] -eq 'Machine') { $iniPath = Join-Path $Matches[1] GPT.ini if (Test-Path -LiteralPath $iniPath -PathType Leaf) { if ($PSCmdlet.ShouldProcess($iniPath, 'Increment version number in INI file')) { IncrementGptIniVersion -Path $iniPath -PolicyType $Matches[2] -Confirm:$false -WhatIf:$false } } else { if ($PSCmdlet.ShouldProcess($iniPath, 'Create new gpt.ini file')) { NewGptIni -Path $iniPath -PolicyType $Matches[2] } } } } } function NewGptIni { param ( [string] $Path, [string[]] $PolicyType ) $parent = Split-Path $Path -Parent if (-not (Test-Path $parent -PathType Container)) { $null = New-Item -Path $parent -ItemType Directory -ErrorAction Stop } $version = GetNewVersionNumber -Version 0 -PolicyType $PolicyType Set-Content -Path $Path -Encoding Ascii -Value @" [General] gPCMachineExtensionNames=$script:MachineExtensionGuids Version=$version gPCUserExtensionNames=$script:UserExtensionGuids "@ } function IncrementGptIniVersion { [CmdletBinding(SupportsShouldProcess = $true)] param ( [string] $Path, [string[]] $PolicyType ) $foundVersionLine = $false $section = '' $newContents = @( foreach ($line in Get-Content $Path) { # This might not be the most unreadable regex ever, but it's trying hard to be! # It's looking for section lines: [SectionName] if ($line -match '^\s*\[([^\]]+)\]\s*$') { if ($section -eq 'General') { if (-not $foundVersionLine) { $foundVersionLine = $true $newVersion = GetNewVersionNumber -Version 0 -PolicyType $PolicyType "Version=$newVersion" } if (-not $foundMachineExtensionLine) { $foundMachineExtensionLine = $true "gPCMachineExtensionNames=$script:MachineExtensionGuids" } if (-not $foundUserExtensionLine) { $foundUserExtensionLine = $true "gPCUserExtensionNames=$script:UserExtensionGuids" } } $section = $matches[1] } elseif ($section -eq 'General' -and $line -match '^\s*Version\s*=\s*(\d+)\s*$' -and $null -ne ($version = $matches[1] -as [uint32])) { $foundVersionLine = $true $newVersion = GetNewVersionNumber -Version $version -PolicyType $PolicyType $line = "Version=$newVersion" } elseif ($section -eq 'General' -and $line -match '^\s*gPC(Machine|User)ExtensionNames\s*=') { if ($matches[1] -eq 'Machine') { $foundMachineExtensionLine = $true } else { $foundUserExtensionLine = $true } $line = EnsureAdminTemplateCseGuidsArePresent $line } $line } if ($section -eq 'General') { if (-not $foundVersionLine) { $foundVersionLine = $true $newVersion = GetNewVersionNumber -Version 0 -PolicyType $PolicyType "Version=$newVersion" } if (-not $foundMachineExtensionLine) { $foundMachineExtensionLine = $true "gPCMachineExtensionNames=$script:MachineExtensionGuids" } if (-not $foundUserExtensionLine) { $foundUserExtensionLine = $true "gPCUserExtensionNames=$script:MachineExtensionGuids" } } ) if ($PSCmdlet.ShouldProcess($Path, 'Increment Version number')) { Set-Content -Path $Path -Value $newContents -Encoding Ascii -Confirm:$false -WhatIf:$false } } function EnsureAdminTemplateCseGuidsArePresent { param ([string] $Line) # These lines contain pairs of GUIDs in "registry" format (with the curly braces), separated by nothing, with # each pair of GUIDs wrapped in square brackets. Example: # gPCMachineExtensionNames=[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F72-3407-48AE-BA88-E8213C6761F1}] # Per Darren Mar-Elia, these GUIDs must be in alphabetical order, or GP processing will have problems. if ($Line -notmatch '\s*(gPC(?:Machine|User)ExtensionNames)\s*=\s*(.*)$') { throw "Malformed gpt.ini line: $Line" } $valueName = $matches[1] $guidStrings = @($matches[2] -split '(?<=\])(?=\[)') if ($matches[1] -eq 'gPCMachineExtensionNames') { $toolExtensionGuid = $script:MachineExtensionGuids } else { $toolExtensionGuid = $script:UserExtensionGuids } $guidList = @( $guidStrings $toolExtensionGuid ) $newGuidString = ($guidList | Sort-Object -Unique) -join '' return "$valueName=$newGuidString" } function GetNewVersionNumber { param ( [UInt32] $Version, [string[]] $PolicyType ) # User version is the high 16 bits, Machine version is the low 16 bits. # Reference: http://blogs.technet.com/b/grouppolicy/archive/2007/12/14/understanding-the-gpo-version-number.aspx $pair = UInt32ToUInt16Pair -UInt32 $version if ($PolicyType -contains 'User') { $pair.HighPart++ } if ($PolicyType -contains 'Machine') { $pair.LowPart++ } return UInt16PairToUInt32 -UInt16Pair $pair } function UInt32ToUInt16Pair { param ([UInt32] $UInt32) # Deliberately avoiding bitwise shift operators here, for PowerShell v2 compatibility. $lowPart = $UInt32 -band 0xFFFF $highPart = ($UInt32 - $lowPart) / 0x10000 return New-Object psobject -Property @{ LowPart = [UInt16] $lowPart HighPart = [UInt16] $highPart } } function UInt16PairToUInt32 { param ([object] $UInt16Pair) # Deliberately avoiding bitwise shift operators here, for PowerShell v2 compatibility. return ([UInt32] $UInt16Pair.HighPart) * 0x10000 + $UInt16Pair.LowPart } function PolEntryTypeToRegistryValueKind { param ([TJX.PolFileEditor.PolEntryType] $PolEntryType) switch ($PolEntryType) { ([TJX.PolFileEditor.PolEntryType]::REG_NONE) { return [Microsoft.Win32.RegistryValueKind]::None } ([TJX.PolFileEditor.PolEntryType]::REG_DWORD) { return [Microsoft.Win32.RegistryValueKind]::DWord } ([TJX.PolFileEditor.PolEntryType]::REG_DWORD_BIG_ENDIAN) { return [Microsoft.Win32.RegistryValueKind]::DWord } ([TJX.PolFileEditor.PolEntryType]::REG_BINARY) { return [Microsoft.Win32.RegistryValueKind]::Binary } ([TJX.PolFileEditor.PolEntryType]::REG_EXPAND_SZ) { return [Microsoft.Win32.RegistryValueKind]::ExpandString } ([TJX.PolFileEditor.PolEntryType]::REG_MULTI_SZ) { return [Microsoft.Win32.RegistryValueKind]::MultiString } ([TJX.PolFileEditor.PolEntryType]::REG_QWORD) { return [Microsoft.Win32.RegistryValueKind]::QWord } ([TJX.PolFileEditor.PolEntryType]::REG_SZ) { return [Microsoft.Win32.RegistryValueKind]::String } } } function GetPolFilePath { param ( [Parameter(Mandatory = $true, ParameterSetName = 'PolicyType')] [string] $PolicyType, [Parameter(Mandatory = $true, ParameterSetName = 'Account')] [string] $Account ) if ($PolicyType) { switch ($PolicyType) { 'Machine' { return Join-Path $env:SystemRoot System32\GroupPolicy\Machine\registry.pol } 'User' { return Join-Path $env:SystemRoot System32\GroupPolicy\User\registry.pol } 'Administrators' { # BUILTIN\Administrators well-known SID return Join-Path $env:SystemRoot System32\GroupPolicyUsers\S-1-5-32-544\User\registry.pol } 'NonAdministrators' { # BUILTIN\Users well-known SID return Join-Path $env:SystemRoot System32\GroupPolicyUsers\S-1-5-32-545\User\registry.pol } } } else { try { $sid = $Account -as [System.Security.Principal.SecurityIdentifier] if ($null -eq $sid) { $sid = GetSidForAccount $Account } return Join-Path $env:SystemRoot "System32\GroupPolicyUsers\$($sid.Value)\User\registry.pol" } catch { throw } } } function GetSidForAccount($Account) { $acc = $Account if ($acc -notlike '*\*') { $acc = "$env:COMPUTERNAME\$acc" } try { $ntAccount = [System.Security.Principal.NTAccount]$acc return $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]) } catch { $message = "Could not translate account '$acc' to a security identifier." $exception = New-Object System.Exception($message, $_.Exception) $errorRecord = New-Object System.Management.Automation.ErrorRecord( $exception, 'CouldNotGetSidForAccount', [System.Management.Automation.ErrorCategory]::ObjectNotFound, $Acc ) throw $errorRecord } } function DataIsEqual { param ( [object] $First, [object] $Second, [Microsoft.Win32.RegistryValueKind] $Type ) if ($Type -eq [Microsoft.Win32.RegistryValueKind]::String -or $Type -eq [Microsoft.Win32.RegistryValueKind]::ExpandString -or $Type -eq [Microsoft.Win32.RegistryValueKind]::DWord -or $Type -eq [Microsoft.Win32.RegistryValueKind]::QWord) { return @($First)[0] -ceq @($Second)[0] } # If we get here, $Type is either MultiString or Binary, both of which need to compare arrays. # The PolicyFileEditor module never returns type Unknown or None. $First = @($First) $Second = @($Second) if ($First.Count -ne $Second.Count) { return $false } $count = $First.Count for ($i = 0; $i -lt $count; $i++) { if ($First[$i] -cne $Second[$i]) { return $false } } return $true } function ParseKeyValueName { param ([string] $KeyValueName) if ($KeyValueName.EndsWith('\')) { $key = $KeyValueName -replace '\\$' $valueName = '' } else { $key = Split-Path $KeyValueName -Parent $valueName = Split-Path $KeyValueName -Leaf } return $key, $valueName } function GetTargetResourceCommon { param ( [string] $Path, [string] $KeyValueName ) $configuration = @{ KeyValueName = $KeyValueName Ensure = 'Absent' Data = $null Type = [Microsoft.Win32.RegistryValueKind]::Unknown } if (Test-Path -LiteralPath $path -PathType Leaf) { $key, $valueName = ParseKeyValueName $KeyValueName $entry = Get-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName if ($entry) { $configuration['Ensure'] = 'Present' $configuration['Type'] = $entry.Type $configuration['Data'] = @($entry.Data) } } return $configuration } function SetTargetResourceCommon { param ( [string] $Path, [string] $KeyValueName, [string] $Ensure, [string[]] $Data, [Microsoft.Win32.RegistryValueKind] $Type ) if ($null -eq $Data) { $Data = @() } try { Assert-ValidDataAndType -Data $Data -Type $Type } catch { Write-Error -ErrorRecord $_ return } $key, $valueName = ParseKeyValueName $KeyValueName if ($Ensure -eq 'Present') { Set-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName -Data $Data -Type $Type } else { Remove-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName } } function TestTargetResourceCommon { [OutputType([bool])] param ( [string] $Path, [string] $KeyValueName, [string] $Ensure, [string[]] $Data, [Microsoft.Win32.RegistryValueKind] $Type ) if ($null -eq $Data) { $Data = @() } try { Assert-ValidDataAndType -Data $Data -Type $Type } catch { Write-Error -ErrorRecord $_ return $false } $key, $valueName = ParseKeyValueName $KeyValueName $fileExists = Test-Path -LiteralPath $Path -PathType Leaf if ($Ensure -eq 'Present') { if (-not $fileExists) { return $false } $entry = Get-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName return $null -ne $entry -and $Type -eq $entry.Type -and (DataIsEqual $entry.Data $Data -Type $Type) } else # Ensure is 'Absent' { if (-not $fileExists) { return $true } $entry = Get-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName return $null -eq $entry } } function Assert-ValidDataAndType { param ( [string[]] $Data, [Microsoft.Win32.RegistryValueKind] $Type ) if ($Type -ne [Microsoft.Win32.RegistryValueKind]::MultiString -and $Type -ne [Microsoft.Win32.RegistryValueKind]::Binary -and $Data.Count -gt 1) { $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'Do not pass arrays with multiple values to the -Data parameter when -Type is not set to either Binary or MultiString.' throw $errorRecord } } function InvalidDataTypeCombinationErrorRecord($Message) { $exception = New-Object System.Exception($Message) return New-Object System.Management.Automation.ErrorRecord( $exception, 'InvalidDataTypeCombination', [System.Management.Automation.ErrorCategory]::InvalidArgument, $null ) } # SIG # Begin signature block # MIIgQgYJKoZIhvcNAQcCoIIgMzCCIC8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBwJwFOwNQwAUL6 # rmiYVGlFFf0AkTutmiSN7DsyWKq+QaCCG0wwggO3MIICn6ADAgECAhAM5+DlF9hG # /o/lYPwb8DA5MA0GCSqGSIb3DQEBBQUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNV # BAMTG0RpZ2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBa # Fw0zMTExMTAwMDAwMDBaMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2Vy # dCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNVBAMTG0RpZ2lD # ZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC # AQoCggEBAK0OFc7kQ4BcsYfzt2D5cRKlrtwmlIiq9M71IDkoWGAM+IDaqRWVMmE8 # tbEohIqK3J8KDIMXeo+QrIrneVNcMYQq9g+YMjZ2zN7dPKii72r7IfJSYd+fINcf # 4rHZ/hhk0hJbX/lYGDW8R82hNvlrf9SwOD7BG8OMM9nYLxj+KA+zp4PWw25EwGE1 # lhb+WZyLdm3X8aJLDSv/C3LanmDQjpA1xnhVhyChz+VtCshJfDGYM2wi6YfQMlqi # uhOCEe05F52ZOnKh5vqk2dUXMXWuhX0irj8BRob2KHnIsdrkVxfEfhwOsLSSplaz # vbKX7aqn8LfF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CAfwwggH4AgEBMHYwYjELMAkGA1UEBhMC # VVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0 # LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgQXNzdXJlZCBJRCBDQS0xAhADAZoCOv9Y # sWvW1ermF/BmMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB # MBwGCSqGSIb3DQEJBTEPFw0xNjA1MDkwMzQ5MjhaMCMGCSqGSIb3DQEJBDEWBBQC # 1cE2yb41mvaAV9qB/qb6Rg3E7zANBgkqhkiG9w0BAQEFAASCAQBDRpnYNSj6dHTB # McJn1V9Ce6rdyHMYAZNEPvSkdAT9RtywxkqzxgrSMxa7adAuXOspEMINqyCUH575 # Fkxo5kgYEIYsAoDdhav9pCsSCfF8j+lARUYitYaFd+PkI1kEF+O6ML5tHG7mWXnT # ES/aRnU8G7SKUUarkSGMYIfh/ygDN1dURpFZHkwmtE61J4nH+QljcIg3CjWkpJA7 # Z3ebr+7NN5frEnln9tDrwt/r/0xr///wN1M0KgIvHs1oeIyq00I0s5zQinuPPUb1 # /mpPtT6fJlO3ogVEA1VwuxFqLPe/cInv6YOpGXt3B3kQS8oGyGot0vZuxrGrgNVK # 5P2CZxmm # SIG # End signature block
PowerShellCorpus/PowerShellGallery/PolicyFileEditor/2.0.2/Commands.ps1
Commands.ps1
#requires -Version 2.0 $scriptRoot = Split-Path $MyInvocation.MyCommand.Path . "$scriptRoot\Common.ps1" <# .SYNOPSIS Creates or modifies a value in a .pol file. .DESCRIPTION Creates or modifies a value in a .pol file. By default, also updates the version number in the policy's gpt.ini file. .PARAMETER Path Path to the .pol file that is to be modified. .PARAMETER Key The registry key inside the .pol file that you want to modify. .PARAMETER ValueName The name of the registry value. May be set to an empty string to modify the default value of a key. .PARAMETER Data The new value to assign to the registry key / value. Cannot be $null, but can be set to an empty string or empty array. .PARAMETER Type The type of registry value to set in the policy file. Cannot be set to Unknown or None, but all other values of the RegistryValueKind enum are legal. .PARAMETER NoGptIniUpdate When this switch is used, the command will not attempt to update the version number in the gpt.ini file .EXAMPLE Set-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue -Data 'Hello, World!' -Type String Assigns a value of 'Hello, World!' to the String value Software\Policies\Something\SomeValue in the local computer Machine GPO. Updates the Machine version counter in $env:systemroot\system32\GroupPolicy\gpt.ini .EXAMPLE Set-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue -Data 'Hello, World!' -Type String -NoGptIniUpdate Same as example 1, except this one does not update gpt.ini right away. This can be useful if you want to set multiple values in the policy file and only trigger a single Group Policy refresh. .EXAMPLE Set-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue -Data '0x12345' -Type DWord Example demonstrating that strings with valid numeric data (including hexadecimal strings beginning with 0x) can be assigned to the numeric types DWord, QWord and Binary. .EXAMPLE $entries = @( New-Object psobject -Property @{ ValueName = 'MaxXResolution'; Data = 1680 } New-Object psobject -Property @{ ValueName = 'MaxYResolution'; Data = 1050 } ) $entries | Set-PolicyFileEntry -Path $env:SystemRoot\system32\GroupPolicy\Machine\registry.pol ` -Key 'SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services' ` -Type DWord Example of using pipeline input to set multiple values at once. The advantage to this approach is that the .pol file on disk (and the GPT.ini file) will be updated if _any_ of the specified settings had to be modified, and will be left alone if the file already contained all of the correct values. The Key and Type properties could have also been specified via the pipeline objects instead of on the command line, but since both values shared the same Key and Type, this example shows that you can pass the values in either way. .INPUTS The Key, ValueName, Data, and Type properties may be bound via the pipeline by property name. .OUTPUTS None. This command does not generate output. .NOTES If the specified policy file already contains the correct value, the file will not be modified, and the gpt.ini file will not be updated. .LINK Get-PolicyFileEntry .LINK Remove-PolicyFileEntry .LINK Update-GptIniVersion .LINK about_RegistryValuesForAdminTemplates #> function Set-PolicyFileEntry { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true, Position = 0)] [string] $Path, [Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)] [string] $Key, [Parameter(Mandatory = $true, Position = 2, ValueFromPipelineByPropertyName = $true)] [AllowEmptyString()] [string] $ValueName, [Parameter(Mandatory = $true, Position = 3, ValueFromPipelineByPropertyName = $true)] [AllowEmptyString()] [AllowEmptyCollection()] [object] $Data, [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateScript({ if ($_ -eq [Microsoft.Win32.RegistryValueKind]::Unknown) { throw 'Unknown is not a valid value for the Type parameter' } if ($_ -eq [Microsoft.Win32.RegistryValueKind]::None) { throw 'None is not a valid value for the Type parameter' } return $true })] [Microsoft.Win32.RegistryValueKind] $Type = [Microsoft.Win32.RegistryValueKind]::String, [switch] $NoGptIniUpdate ) begin { if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) { Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState } $dirty = $false try { $policyFile = OpenPolicyFile -Path $Path -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError($_) } } process { $existingEntry = $policyFile.GetValue($Key, $ValueName) if ($null -ne $existingEntry -and $Type -eq (PolEntryTypeToRegistryValueKind $existingEntry.Type)) { $existingData = GetEntryData -Entry $existingEntry -Type $Type if (DataIsEqual $Data $existingData -Type $Type) { Write-Verbose "Policy setting '$Key\$ValueName' is already set to '$Data' of type '$Type'." return } } Write-Verbose "Configuring '$Key\$ValueName' to value '$Data' of type '$Type'." try { switch ($Type) { ([Microsoft.Win32.RegistryValueKind]::Binary) { $bytes = $Data -as [byte[]] if ($null -eq $bytes) { $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to Binary, -Data must be passed a Byte[] array.' $PSCmdlet.ThrowTerminatingError($errorRecord) } else { $policyFile.SetBinaryValue($Key, $ValueName, $bytes) } break } ([Microsoft.Win32.RegistryValueKind]::String) { $array = @($Data) if ($array.Count -ne 1) { $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to String, -Data must be passed a scalar value or single-element array.' $PSCmdlet.ThrowTerminatingError($errorRecord) } else { $policyFile.SetStringValue($Key, $ValueName, $array[0].ToString()) } break } ([Microsoft.Win32.RegistryValueKind]::ExpandString) { $array = @($Data) if ($array.Count -ne 1) { $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to ExpandString, -Data must be passed a scalar value or single-element array.' $PSCmdlet.ThrowTerminatingError($errorRecord) } else { $policyFile.SetStringValue($Key, $ValueName, $array[0].ToString(), $true) } break } ([Microsoft.Win32.RegistryValueKind]::DWord) { $array = @($Data) $dword = ($array | Select-Object -First 1) -as [UInt32] if ($null -eq $dword -or $array.Count -ne 1) { $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to DWord, -Data must be passed a valid UInt32 value.' $PSCmdlet.ThrowTerminatingError($errorRecord) } else { $policyFile.SetDWORDValue($key, $ValueName, $dword) } break } ([Microsoft.Win32.RegistryValueKind]::QWord) { $array = @($Data) $qword = ($array | Select-Object -First 1) -as [UInt64] if ($null -eq $qword -or $array.Count -ne 1) { $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to QWord, -Data must be passed a valid UInt64 value.' $PSCmdlet.ThrowTerminatingError($errorRecord) } else { $policyFile.SetQWORDValue($key, $ValueName, $qword) } break } ([Microsoft.Win32.RegistryValueKind]::MultiString) { $strings = [string[]] @( foreach ($item in @($Data)) { $item.ToString() } ) $policyFile.SetMultiStringValue($Key, $ValueName, $strings) break } } # switch ($Type) $dirty = $true } catch { throw } } end { if ($dirty) { $doUpdateGptIni = -not $NoGptIniUpdate try { # SavePolicyFile contains the calls to $PSCmdlet.ShouldProcess, and will inherit our # WhatIfPreference / ConfirmPreference values from here. SavePolicyFile -PolicyFile $policyFile -UpdateGptIni:$doUpdateGptIni -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError($_) } } } } <# .SYNOPSIS Retrieves the current setting(s) from a .pol file. .DESCRIPTION Retrieves the current setting(s) from a .pol file. .PARAMETER Path Path to the .pol file that is to be read. .PARAMETER Key The registry key inside the .pol file that you want to read. .PARAMETER ValueName The name of the registry value. May be set to an empty string to read the default value of a key. .PARAMETER All Switch indicating that all entries from the specified .pol file should be output, instead of searching for a specific key / ValueName pair. .EXAMPLE Get-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue Reads the value of Software\Policies\Something\SomeValue from the Machine admin templates of the local GPO. Either returns an object with the data and type of this registry value (if present), or returns nothing, if not found. .EXAMPLE Get-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -All Outputs all of the registry values from the local machine Administrative Templates .INPUTS None. This command does not accept pipeline input. .OUTPUTS If the specified registry value is found, the function outputs a PSCustomObject with the following properties: ValueName: The same value that was passed to the -ValueName parameter Key: The same value that was passed to the -Key parameter Data: The current value assigned to the specified Key / ValueName in the .pol file. Type: The RegistryValueKind type of the specified Key / ValueName in the .pol file. If the specified registry value is not found in the .pol file, the command returns nothing. No error is produced. .LINK Set-PolicyFileEntry .LINK Remove-PolicyFileEntry .LINK Update-GptIniVersion .LINK about_RegistryValuesForAdminTemplates #> function Get-PolicyFileEntry { [CmdletBinding(DefaultParameterSetName = 'ByKeyAndValue')] param ( [Parameter(Mandatory = $true, Position = 0)] [string] $Path, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByKeyAndValue')] [string] $Key, [Parameter(Mandatory = $true, Position = 2, ParameterSetName = 'ByKeyAndValue')] [string] $ValueName, [Parameter(Mandatory = $true, ParameterSetName = 'All')] [switch] $All ) if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) { Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState } try { $policyFile = OpenPolicyFile -Path $Path -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError($_) } if ($PSCmdlet.ParameterSetName -eq 'ByKeyAndValue') { $entry = $policyFile.GetValue($Key, $ValueName) if ($null -ne $entry) { PolEntryToPsObject -PolEntry $entry } } else { foreach ($entry in $policyFile.Entries) { PolEntryToPsObject -PolEntry $entry } } } <# .SYNOPSIS Removes a value from a .pol file. .DESCRIPTION Removes a value from a .pol file. By default, also updates the version number in the policy's gpt.ini file. .PARAMETER Path Path to the .pol file that is to be modified. .PARAMETER Key The registry key inside the .pol file from which you want to remove a value. .PARAMETER ValueName The name of the registry value to be removed. May be set to an empty string to remove the default value of a key. .PARAMETER NoGptIniUpdate When this switch is used, the command will not attempt to update the version number in the gpt.ini file .EXAMPLE Remove-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue Removes the value Software\Policies\Something\SomeValue from the local computer Machine GPO, if present. Updates the Machine version counter in $env:systemroot\system32\GroupPolicy\gpt.ini .EXAMPLE $entries = @( New-Object psobject -Property @{ ValueName = 'MaxXResolution'; Data = 1680 } New-Object psobject -Property @{ ValueName = 'MaxYResolution'; Data = 1050 } ) $entries | Remove-PolicyFileEntry -Path $env:SystemRoot\system32\GroupPolicy\Machine\registry.pol ` -Key 'SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services' Example of using pipeline input to remove multiple values at once. The advantage to this approach is that the .pol file on disk (and the GPT.ini file) will be updated if _any_ of the specified settings had to be removed, and will be left alone if the file already did not contain any of those values. The Key property could have also been specified via the pipeline objects instead of on the command line, but since both values shared the same Key, this example shows that you can pass the value in either way. .INPUTS The Key and ValueName properties may be bound via the pipeline by property name. .OUTPUTS None. This command does not generate output. .NOTES If the specified policy file is already not present in the .pol file, the file will not be modified, and the gpt.ini file will not be updated. .LINK Get-PolicyFileEntry .LINK Set-PolicyFileEntry .LINK Update-GptIniVersion .LINK about_RegistryValuesForAdminTemplates #> function Remove-PolicyFileEntry { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true, Position = 0)] [string] $Path, [Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)] [string] $Key, [Parameter(Mandatory = $true, Position = 2, ValueFromPipelineByPropertyName = $true)] [string] $ValueName, [switch] $NoGptIniUpdate ) begin { if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) { Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState } $dirty = $false try { $policyFile = OpenPolicyFile -Path $Path -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError($_) } } process { $entry = $policyFile.GetValue($Key, $ValueName) if ($null -eq $entry) { Write-Verbose "Entry '$Key\$ValueName' is already not present in file '$Path'." return } Write-Verbose "Removing entry '$Key\$ValueName' from file '$Path'" $policyFile.DeleteValue($Key, $ValueName) $dirty = $true } end { if ($dirty) { $doUpdateGptIni = -not $NoGptIniUpdate try { # SavePolicyFile contains the calls to $PSCmdlet.ShouldProcess, and will inherit our # WhatIfPreference / ConfirmPreference values from here. SavePolicyFile -PolicyFile $policyFile -UpdateGptIni:$doUpdateGptIni -ErrorAction Stop } catch { $PSCmdlet.ThrowTerminatingError($_) } } } } <# .SYNOPSIS Increments the version counter in a gpt.ini file. .DESCRIPTION Increments the version counter in a gpt.ini file. .PARAMETER Path Path to the gpt.ini file that is to be modified. .PARAMETER PolicyType Can be set to either 'Machine', 'User', or both. This affects how the value of the Version number in the ini file is changed. .EXAMPLE Update-GptIniVersion -Path $env:SystemRoot\system32\GroupPolicy\gpt.ini -PolicyType Machine Increments the Machine version counter of the local GPO. .EXAMPLE Update-GptIniVersion -Path $env:SystemRoot\system32\GroupPolicy\gpt.ini -PolicyType User Increments the User version counter of the local GPO. .EXAMPLE Update-GptIniVersion -Path $env:SystemRoot\system32\GroupPolicy\gpt.ini -PolicyType Machine,User Increments both the Machine and User version counters of the local GPO. .INPUTS None. This command does not accept pipeline input. .OUTPUTS None. This command does not generate output. .NOTES A gpt.ini file contains only a single Version value. However, this represents two separate counters, for machine and user versions. The high 16 bits of the value are the User counter, and the low 16 bits are the Machine counter. For example (on PowerShell 3.0 and later), the Version value when the Machine counter is set to 3 and the User counter is set to 5 can be found by evaluating this expression: (5 -shl 16) -bor 3 , which will show up as decimal value 327683 in the INI file. .LINK Get-PolicyFileEntry .LINK Set-PolicyFileEntry .LINK Remove-PolicyFileEntry .LINK about_RegistryValuesForAdminTemplates #> function Update-GptIniVersion { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [ValidateScript({ if (Test-Path -LiteralPath $_ -PathType Leaf) { return $true } throw "Path '$_' does not exist." })] [string] $Path, [Parameter(Mandatory = $true)] [ValidateSet('Machine', 'User')] [string[]] $PolicyType ) if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) { Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState } try { IncrementGptIniVersion @PSBoundParameters } catch { $PSCmdlet.ThrowTerminatingError($_) } } # SIG # Begin signature block # MIIgQgYJKoZIhvcNAQcCoIIgMzCCIC8CAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCNrv3Ili4LqB0u # pNUvYlI7CTyDz9cKORd2+xJF4tY7nqCCG0wwggO3MIICn6ADAgECAhAM5+DlF9hG # /o/lYPwb8DA5MA0GCSqGSIb3DQEBBQUAMGUxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xJDAiBgNV # BAMTG0RpZ2lDZXJ0IEFzc3VyZWQgSUQgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBa # Fw0zMTExMTAwMDAwMDBaMGUxCzAJBgNVBAYT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urhqEDtIAXDSDN3F9aKcXex6VEbcEZb1mBFFSdWCOIziZCQ2hNsLld6Q6un2eir # +RcOqZ0i1YX1tZ+O9LGE5Y7780GwyWcWhA/1uSTEPhf9XU/DL0EFzW3607zK6d4h # 5JZpcQ3j # SIG # End signature block
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/tests/PSPuTTY.tests.ps1
PSPuTTY.tests.ps1
<# Assuming that this module is in your $env:PSModulePath, you can invoke this Pester test script: Set-Location -Path ('{0}\Tests' -f (Get-Module -Name PSPuTTY -ListAvailable).ModuleBase); ./PSPuTTY.tests.ps1 #> $VerbosePreference = 'continue' $ErrorActionPreference = 'stop' describe -Name 'PSPuTTY PowerShell module' { $ModuleName = 'PSPuTTY' $ModulePath = Split-Path -Path $PSScriptRoot -Parent if (Get-Module -Name $ModuleName) { Remove-Module -Name $ModuleName } Import-Module -Name $ModulePath -Force Write-Verbose -Message ('Module path is: {0}' -f $ModulePath) context -Name 'Basic presence of core commands' { it 'Should have a Get-PSPuTTYSession command' { (Get-Command -Module $ModuleName -Name Get-PSPuTTYSession).Count | Should be 1 } it 'Should have a Get-PSPuTTYTheme command' { (Get-Command -Module $ModuleName -Name Get-PSPuTTYTheme).Count | Should be 1 } it 'Should have a Merge-PSPuTTYTheme command' { (Get-Command -Module $ModuleName -Name Merge-PSPuTTYTheme).Count | Should be 1 } it 'Should have a Invoke-PSPuTTYSession command' { (Get-Command -Module $ModuleName -Name Invoke-PSPuTTYSession).Count | Should be 1 } it 'Should have a New-PSPuTTYSession command' { (Get-Command -Module $ModuleName -Name New-PSPuTTYSession).Count | Should be 1 } it 'Should have a Remove-PSPuTTYSession command' { (Get-Command -Module $ModuleName -Name Remove-PSPuTTYSession).Count | Should be 1 } } context -Name 'Get-PSPuTTYTheme' { it 'Should not throw an error' { { Get-PSPuTTYTheme } | Should not throw } } context -Name 'Get-PSPuTTYSession' { it 'Should not throw an error' { { Get-PSPuTTYSession } | Should not throw } } context -Name 'Merge-PSPuTTYTheme' { it 'Should have four parameter sets' { (Get-Command -Module $ModuleName -Name Merge-PSPuTTYTheme).ParameterSets.Count | Should be 4 } } context -Name 'Remove-PSPuTTYSession' -Fixture { it 'Should require input parameters' { ${gps} | Should throw } } }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/models/PSPuTTYTheme.ps1
PSPuTTYTheme.ps1
class PSPuTTYTheme { [string] $Name [string] $Url [string] $Colour0 [string] $Colour1 [string] $Colour2 [string] $Colour3 [string] $Colour4 [string] $Colour5 [string] $Colour6 [string] $Colour7 [string] $Colour8 [string] $Colour9 [string] $Colour10 [string] $Colour11 [string] $Colour12 [string] $Colour13 [string] $Colour14 [string] $Colour15 [string] $Colour16 [string] $Colour17 [string] $Colour18 [string] $Colour19 [string] $Colour20 [string] $Colour21 PSPuTTYTheme ([object] $Theme) { try { $this.Name = $Theme.Name $this.Url = $Theme.Url $this.Colour0 = $Theme.Colors.Colour0 $this.Colour1 = $Theme.Colors.Colour1 $this.Colour2 = $Theme.Colors.Colour2 $this.Colour3 = $Theme.Colors.Colour3 $this.Colour4 = $Theme.Colors.Colour4 $this.Colour5 = $Theme.Colors.Colour5 $this.Colour6 = $Theme.Colors.Colour6 $this.Colour7 = $Theme.Colors.Colour7 $this.Colour8 = $Theme.Colors.Colour8 $this.Colour9 = $Theme.Colors.Colour9 $this.Colour10 = $Theme.Colors.Colour10 $this.Colour11 = $Theme.Colors.Colour11 $this.Colour12 = $Theme.Colors.Colour12 $this.Colour13 = $Theme.Colors.Colour13 $this.Colour14 = $Theme.Colors.Colour14 $this.Colour15 = $Theme.Colors.Colour15 $this.Colour16 = $Theme.Colors.Colour16 $this.Colour17 = $Theme.Colors.Colour17 $this.Colour18 = $Theme.Colors.Colour18 $this.Colour19 = $Theme.Colors.Colour19 $this.Colour20 = $Theme.Colors.Colour20 $this.Colour21 = $Theme.Colors.Colour21 } catch { Write-Error -Message 'Malformed theme file detected. Please ensure the format of the theme file is correct.' } } }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/models/PSPuTTYSession.ps1
PSPuTTYSession.ps1
class PSPuTTYSession { [string] $Name ### The name of the PuTTY saved session (URL-encoded). [string] $Hostname ### The hostname or IP address of the host that the PuTTY saved session will connect to. [int] $Port ### The TCP port that the PuTTY session will connect to [string] $ThemeName ### The name of the PuTTY theme that will be associated with this PuTTY saved session. [string] $RealName ### The user-friendly name (not URL encoded) of the PuTTY saved session ### Constructore intended for creating a new session with a particular theme. PSPuTTYSession ( [string] $Name, [string] $Hostname, [int] $Port, [string] $Theme) { $this.Name = $Name $this.Hostname = $Hostname $this.Port = $Port $this.Theme = $Theme } PSPuTTYSession ([string] $Name, [string] $RealName) { $this.Name = $Name $this.RealName = $RealName } ### Constructor intended for creating and writing new saved sessions. PSPuTTYSession ([string] $RealName) { } ### Writes the session to the Windows Registry [void] Write() { ### TODO: Implement } }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Private/Get-PSPuTTYRegistrySessions.ps1
Get-PSPuTTYRegistrySessions.ps1
using namespace Microsoft.Win32 function Get-PSPuTTYRegistrySessions { <# .Synopsis Obtains a connection to the PuTTY registry key for the current user's hive. #> [CmdletBinding()] param ( ) $Command = $PSCmdlet.MyInvocation.MyCommand.Name $Module = $PSCmdlet.MyInvocation.MyCommand.Module ### Get the PuTTY registry path $SessionRegPath = '{0}\Sessions' -f $Module.PrivateData['PuTTYRegPath'] ### Open the CurrentUser hive and the PuTTY subkey $RegCurrentUser = [RegistryKey]::OpenBaseKey([RegistryHive]::CurrentUser, [RegistryView]::Default) $RegCurrentUser.OpenSubKey($SessionRegPath, $true) }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Public/Remove-PSPuTTYSession.ps1
Remove-PSPuTTYSession.ps1
function Remove-PSPuTTYSession { <# .Synopsis Removes a PuTTY saved session from the user's profile. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Name ) ### TODO: Implement this function }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Public/Merge-PSPuTTYTheme.ps1
Merge-PSPuTTYTheme.ps1
using namespace System.Web function Merge-PSPuTTYTheme { <# .Synopsis Configures a PuTTY saved session with the specified theme. .Parameter SessionName The name of the PuTTY saved session that will have its theme updated. NOTE: The session name will be URL-encoded, to conform to the stored value in the registry. Make sure that you do not use the URL-encoded name of the session. Rather, use the "friendly name" of the session, that appears in the PuTTY Saved Session list. .Parameter ThemeName The name of the PuTTY theme that will be configured on the saved session. .Parameter Session The PSPuTTYSession object that will be updated with a new theme. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ParameterSetName = 'SessionNameThemeName')] [Parameter(Mandatory = $true, ParameterSetName = 'SessionNameThemeObject')] [string] $SessionName , [Parameter(Mandatory = $true, ParameterSetName = 'SessionObjectThemeName')] [Parameter(Mandatory = $true, ParameterSetName = 'SessionObjectThemeObject')] [PSPuTTYSession] $Session , [Parameter(Mandatory = $true, ParameterSetName = 'SessionObjectThemeName')] [Parameter(Mandatory = $true, ParameterSetName = 'SessionNameThemeName')] [string] $ThemeName , [Parameter(Mandatory = $true, ParameterSetName = 'SessionNameThemeObject')] [Parameter(Mandatory = $true, ParameterSetName = 'SessionObjectThemeObject')] [PSPuTTYTheme] $Theme ) Write-Verbose -Message ('Using parameter set: {0}' -f $PSCmdlet.ParameterSetName) ### If the user specifies a session name, then we need to URL encode it if ($PSCmdlet.ParameterSetName -match 'SessionName') { Write-Verbose -Message 'Caller specified session name. Obtaining session object.' $Session = Get-PSPuTTYSession -Name $SessionName } if ($PSCmdlet.ParameterSetName -match 'ThemeName') { Write-Verbose -Message 'Caller specified theme name. Obtaining theme object.' $Theme = Get-PSPuTTYTheme -Name $ThemeName } Write-Verbose -Message ($Session) Write-Verbose -Message ('Opening PuTTY session subkey: {0}' -f $Session.Name) $PuTTYSessionReg = (Get-PSPuTTYRegistrySessions).OpenSubkey($Session.Name, $true) $SessionKey = $PuTTYSessionReg.OpenSubkey($Session.Name) foreach ($Number in 0..21) { Write-Verbose -Message ('Setting Colour{0} to {1}' -f $Number, $Theme."Colour$Number") $PuTTYSessionReg.SetValue("Colour$Number", $Theme."Colour$Number", [Microsoft.Win32.RegistryValueKind]::String) } $PuTTYSessionReg.SetValue('TerminalType', 'putty-256color') }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Public/Invoke-PSPuTTYSession.ps1
Invoke-PSPuTTYSession.ps1
function Invoke-PSPuTTYSession { <# .Synopsis Invokes a new PuTTY session, with the specified saved session name. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Name ) Write-Verbose -Message ('Launching new PuTTY session named {0}' -f $Name) Start-Process -FilePath putty.exe -ArgumentList ('-load "{0}"' -f $Name) -NoNewWindow }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Public/Get-PSPuTTYTheme.ps1
Get-PSPuTTYTheme.ps1
function Get-PSPuTTYTheme { <# .Synopsis Returns a list of supported PuTTY themes that are distributed with this PowerShell module. .Outputs [PSPuTTYTheme] #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string] $Name ) $Command = $PSCmdlet.MyInvocation.MyCommand.Name $Module = $PSCmdlet.MyInvocation.MyCommand.Module $ThemeFileList = Get-ChildItem -Path ('{0}\Themes' -f $Module.ModuleBase) $ThemeList = @() foreach ($ThemeFile in $ThemeFileList) { Write-Verbose -Message ('{0}: Processing file: {1}' -f $Command, $ThemeFile.FullName) $ThemeJson = Get-Content -Path $ThemeFile.FullName -Raw | ConvertFrom-Json $ThemeList += [PSPuTTYTheme]::new($ThemeJson) } if ($PSBoundParameters.ContainsKey('Name')) { Write-Output -InputObject $ThemeList.Where({ $PSItem.Name -like $Name }) } else { Write-Output -InputObject $ThemeList } }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Public/Get-PSPuTTYSession.ps1
Get-PSPuTTYSession.ps1
using namespace Microsoft.Win32 using namespace System.Web function Get-PSPuTTYSession { <# .Synopsis Returns a list of configured PuTTY sessions. .Outputs [PSPuTTYSession] #> [CmdletBinding()] param ( [Parameter(Mandatory = $false)] [string] $Name ) $Command = $PSCmdlet.MyInvocation.MyCommand.Name $Module = $PSCmdlet.MyInvocation.MyCommand.Module ### Get a reference to the PuTTY Registry sessions subkey $PuTTYSessions = Get-PSPuTTYRegistrySessions ### List out the sessions under the PuTTY sessions subkey ### NOTE: Sessions are stored as URL-encoded names, and do not have spaces, even if the session name does have spaces. ### The PSPuTTYSession data model has properties to store both the URL encoded name, and the URL decoded (natural) session name $KeyList = $PuTTYSessions.GetSubKeyNames() ### Empty array to hold a list of sessions $SessionList = @() foreach ($Key in $KeyList) { $KeyName = [System.Web.HttpUtility]::UrlDecode($Key) Write-Verbose -Message ('Found PuTTY saved session: {0}, URL decoded: {1}' -f $Key, $KeyName) $SessionList += [PSPuTTYSession]::new($Key, $KeyName) } if ($PSBoundParameters.ContainsKey('Name')) { Write-Output -InputObject $SessionList.Where({ $PSItem.RealName -eq $Name }) } else { Write-Output -InputObject $SessionList } }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Functions/Public/New-PSPuTTYSession.ps1
New-PSPuTTYSession.ps1
function New-PSPuTTYSession { <# .Synopsis Creates a new PuTTY saved session. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Name , [Parameter(Mandatory = $true)] [string] $Hostname , [Parameter(Mandatory = $true)] [int] $Port , [Parameter(Mandatory = $true)] [string] $ThemeName , [Parameter(Mandatory = $false)] [string] $WindowTitle , [Parameter(Mandatory = $true)] [string] $TerminalType = 'putty-256color' , [Parameter(Mandatory = $true)] [string] $UserName ) $PuTTYSessionsReg = Get-PSPuTTYRegistrySessions ### Create a new, in-memory PuTTY saved session $NewSession = [PSPuTTYSession]::new() if ($WindowTitle) { $NewSession.WinTitle = $WindowTitle } if ($Port) { $NewSession.PortNumber = $Port } if ($TerminalType) { $NewSession.TerminalType = $TerminalType } ### Write the new PuTTY session to the registry $NewSession.Write() }
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Completers/PSPuTTYSession.Name.ArgumentCompletes.ps1
PSPuTTYSession.Name.ArgumentCompletes.ps1
$ScriptBlock = { <# .SYNOPSIS Auto-complete the -Name parameter value for PSPuTTY sessions. .NOTES Created by Trevor Sullivan, Founder of Art of Shell <trevor@artofshell.com> https://trevorsullivan.net https://artofshell.com #> param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $ItemList = Get-PSPuTTYSession | Where-Object { $PSItem.Name -match $wordToComplete } | ForEach-Object { $CompletionText = '''{0}''' -f $PSItem.RealName $ToolTip = 'PuTTY session: {0}.' -f $PSItem.Name $ListItemText = $PSItem.Name $CompletionResultType = [System.Management.Automation.CompletionResultType]::ParameterValue New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList @($CompletionText, $ListItemText, $CompletionResultType, $ToolTip); } return $ItemList } $ArgumentCompleter = @{ CommandName = @( 'Merge-PSPuTTYTheme' 'Invoke-PSPuTTYSession' 'New-PSPuTTYSession' 'Get-PSPuTTYSession' ); ParameterName = 'SessionName'; ScriptBlock = $ScriptBlock } Microsoft.PowerShell.Core\Register-ArgumentCompleter @ArgumentCompleter; $ArgumentCompleter = @{ CommandName = @( 'Invoke-PSPuTTYSession' 'New-PSPuTTYSession' 'Get-PSPuTTYSession' ); ParameterName = 'Name'; ScriptBlock = $ScriptBlock } Microsoft.PowerShell.Core\Register-ArgumentCompleter @ArgumentCompleter;
PowerShellCorpus/PowerShellGallery/PSPuTTY/0.1.1/Completers/PSPuTTYTheme.Name.ArgumentCompletes.1.ps1
PSPuTTYTheme.Name.ArgumentCompletes.1.ps1
$ScriptBlock = { <# .SYNOPSIS Auto-complete the -Name parameter value for PSPuTTY sessions. .NOTES Created by Trevor Sullivan, Founder of Art of Shell <trevor@artofshell.com> https://trevorsullivan.net https://artofshell.com #> param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) $ItemList = Get-PSPuTTYTheme | Where-Object { $PSItem.Name -match $wordToComplete } | ForEach-Object { $CompletionText = '''{0}''' -f $PSItem.Name $ToolTip = 'PuTTY session: {0}.' -f $PSItem.Name $ListItemText = '{0}' -f $PSItem.Name $CompletionResultType = [System.Management.Automation.CompletionResultType]::ParameterValue New-Object -TypeName System.Management.Automation.CompletionResult -ArgumentList @($CompletionText, $ListItemText, $CompletionResultType, $ToolTip); } return $ItemList } $ArgumentCompleter = @{ CommandName = @( 'Merge-PSPuTTYTheme' ); ParameterName = 'ThemeName'; ScriptBlock = $ScriptBlock } Microsoft.PowerShell.Core\Register-ArgumentCompleter @ArgumentCompleter $ArgumentCompleter = @{ CommandName = @( 'Get-PSPuTTYTheme' ); ParameterName = 'Name'; ScriptBlock = $ScriptBlock } Microsoft.PowerShell.Core\Register-ArgumentCompleter @ArgumentCompleter
PowerShellCorpus/PowerShellGallery/Pscx/3.2.2/Pscx.UserPreferences.ps1
Pscx.UserPreferences.ps1
# --------------------------------------------------------------------------- # You can override individual preferences by passing a hashtable with just those # preference defined as shown below: # # Import-Module Pscx -arg @{ModulesToImport = @{Prompt = $true}} # # Any value not specified will be retrieved from the default preferences built # into the PSCX DLL. # # If you have a sufficiently large number of altered preferences, copy this file, # modify it and pass the path to your preferences file to Import-Module e.g.: # # Import-Module Pscx -arg "$(Split-Path $profile -parent)\Pscx.UserPreferences.ps1" # # --------------------------------------------------------------------------- @{ ShowModuleLoadDetails = $false # Display module load details during Import-Module CD_GetChildItem = $false # Display the contents of new provider location after using # cd (Set-LocationEx). Mutually exclusive with CD_EchoNewLocation. CD_EchoNewLocation = $false # Display new provider location after using cd (Set-LocationEx). # Mutually exclusive with CD_GetChildItem. TextEditor = 'Notepad.exe' # Default text editor used by the Edit-File function # For Visual Studio Code use 'code.cmd' PromptTheme = 'Modern' # Prompt string and window title updates. To enable, first # set the ModulesToImport setting for Prompt below to $true. # Then set this value to one of: 'Modern', 'WinXP' or 'Jachym'. PageHelpUsingLess = $true # Pscx replaces PowerShell's More function. When this setting # is set to $true, less.exe is used to page items piped # to the More function. Less.exe is powerful paging app # that allows advanced navigation and search. Press 'h' to # access help inside less.exe and 'q' to exit less.exe. # Set this setting to $false to use more.com for paging. SmtpFrom = $null # These settings are used by the PSCX Send-SmtpMail cmdlet. SmtpHost = $null # Specify a default SMTP server. SmtpPort = $null # Specify a default port number if not specified port 25 is used. FileSizeInUnits = $false # Pscx prepends format data for display of file information. # If this value is set to $true, file sizes are displayed in # using KB,MG,GB and TB units. ModulesToImport = @{ CD = $true DirectoryServices = $false FileSystem = $false GetHelp = $false # Disabled by default due to some bugs that have to be resolved. Net = $false Prompt = $false # Disabled by default because a lot of users already have established prompt functions. TranscribeSession = $false # Disabled by default for security and privacy reasons. Utility = $true Vhd = $false Wmi = $false } }
PowerShellCorpus/PowerShellGallery/Pscx/3.2.2/Modules/Prompt/Themes/Modern.ps1
Modern.ps1
# --------------------------------------------------------------------------- # Author: Keith Hill # Desc: Prompt, colors and host window title updates suited to UAC enabled # Windows Vista and Windows 7. Elevated (admin) prompts are easy # distinguish from non-elevated prompts. # Date: Nov 07, 2009 # Site: http://pscx.codeplex.com # Usage: In your options hashtable place the following setting: # # PromptTheme = 'Modern' # --------------------------------------------------------------------------- #requires -Version 3 param([hashtable]$Theme) Set-StrictMode -Version Latest # --------------------------------------------------------------------------- # Colors # --------------------------------------------------------------------------- $Theme.HostBackgroundColor = if ($Pscx:IsAdmin) { 'DarkRed' } else { 'Black' } $Theme.HostForegroundColor = if ($Pscx:IsAdmin) { 'White' } else { 'Cyan' } $Theme.PromptForegroundColor = if ($Pscx:IsAdmin) { 'Gray' } else { 'White' } # --------------------------------------------------------------------------- # Prompt ScriptBlock # --------------------------------------------------------------------------- $Theme.PromptScriptBlock = { param($Id) if ($NestedPromptLevel) { new-object string ([char]0xB7), $NestedPromptLevel } $sepChar = '>' # [char]0xBB if ($Pscx:IsAdmin) { $sepChar = '#' } $path = '' "${Id}$path$sepChar" } # --------------------------------------------------------------------------- # Window Title Update ScriptBlock # --------------------------------------------------------------------------- $Theme.UpdateWindowTitleScriptBlock = { $adminPrefix = '' if ($Pscx:IsAdmin) { $adminPrefix = 'Admin' } $location = Get-Location $version = $PSVersionTable.PSVersion $bitness = '' if ([IntPtr]::Size -eq 8) { $bitness = ' (x64)' } elseif ($Pscx:IsWow64Process) { $bitness = ' (x86)' } "$adminPrefix $location - Windows PowerShell $version$bitness" } # --------------------------------------------------------------------------- # Startup Message ScriptBlock # --------------------------------------------------------------------------- $Theme.StartupMessageScriptBlock = { $logo = "Windows PowerShell $($PSVersionTable.PSVersion)" if ([IntPtr]::Size -eq 8) { $logo += ' (x64)' } elseif ($Pscx:IsWow64Process) { $logo += ' (x86)' } $logo $user = "`nLogged in on $([DateTime]::Now.ToString((Get-Culture))) as $($Pscx:WindowsIdentity.Name)" if ($Pscx:IsAdmin) { $user += ' (Elevated).' } else { $user += '.' } $user } # SIG # Begin signature block # MIIfUwYJKoZIhvcNAQcCoIIfRDCCH0ACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUuE6HU1EoDZbCKke9CjKjLrEd # OUigghqFMIIGajCCBVKgAwIBAgIQAwGaAjr/WLFr1tXq5hfwZjANBgkqhkiG9w0B # AQUFADBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD # VQQLExB3d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBBc3N1cmVk # IElEIENBLTEwHhcNMTQxMDIyMDAwMDAwWhcNMjQxMDIyMDAwMDAwWjBHMQswCQYD # VQQGEwJVUzERMA8GA1UEChMIRGlnaUNlcnQxJTAjBgNVBAMTHERpZ2lDZXJ0IFRp # bWVzdGFtcCBSZXNwb25kZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB # AQCjZF38fLPggj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CAg8wggILBgkqhkiG9w0BCQYxggH8MIIB+AIBATB2MGIxCzAJBgNVBAYT # AlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2Vy # dC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3VyZWQgSUQgQ0EtMQIQAwGaAjr/ # WLFr1tXq5hfwZjAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEH # ATAcBgkqhkiG9w0BCQUxDxcNMTYwNjMwMDM1OTE0WjAjBgkqhkiG9w0BCQQxFgQU # dUkLzUViUovoD0W7bubxiI4to3QwDQYJKoZIhvcNAQEBBQAEggEAP0eLuKw5F3bk # 5xvH1y0pULJGE2KuR5e7spMhLmT+Lq3VGSq27DjvcwXR1/HqOKCqonCB1h13Yiiv # 2pTt04x0lkf+i+nn98bNqXzddqrnVHEPz6MliAW0+mt5J3vaLnUMjkZq+PESjf38 # YdxI6nDXVlRJ3YG2yT7MrBb1n2c+3WJX/3mBzH5MpT6/B7im6yE7kdEOQ2njiqxz # 7y+wOFAs5mdvHYzzFP33vCl1dxY9OW/1/o2rRaI0EIhZ98GQ7URdwYtFrnrZd9mi # ek2FwVi8SWpdiTmq7pPzjdZt7WZWJywXEY6jGLZTQW+RBPPOgH4E2jKyqTxY7j5T # Rb8Bi83qpA== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Pscx/3.2.2/Modules/Prompt/Themes/WinXP.ps1
WinXP.ps1
# --------------------------------------------------------------------------- # Author: Keith Hill # Desc: Prompt, colors and host window title updates suited to Windows XP # where folks tend to run with adminstrator privileges all the time. # Date: Nov 07, 2009 # Site: http://pscx.codeplex.com # Usage: In your options hashtable place the following setting: # # PromptTheme = 'WinXP' # --------------------------------------------------------------------------- #requires -Version 3 param([hashtable]$Theme) Set-StrictMode -Version Latest # --------------------------------------------------------------------------- # Colors # --------------------------------------------------------------------------- # Configure console colors. $null signifies to use the console default color if ($Pscx:IsAdmin -and ([System.Environment]::OSVersion.Version.Major -gt 5)) { $Theme.PromptForegroundColor = 'Red' } # --------------------------------------------------------------------------- # Prompt ScriptBlock # --------------------------------------------------------------------------- $Theme.PromptScriptBlock = { param($nextCommandId) # Determine what nesting level we are at (if any) $nestingLevel = '' if ($nestedpromptlevel -ge 1) { $nestingLevel = " [Nested:${nestedpromptlevel}]" } $promptChar = '>' if ($Pscx:IsAdmin) { $promptChar = '#' } # Output prompt string "${nextCommandId}${nestingLevel}$promptChar" } # --------------------------------------------------------------------------- # Window Title Update ScriptBlock # --------------------------------------------------------------------------- $Theme.UpdateWindowTitleScriptBlock = { # Pretty much everyone runs as admin on XP and below so displaying the # admin status in the title bar is a waste of space. Only do this on Vista. $isVistaOrHigher = ([System.Environment]::OSVersion.Version.Major -gt 5) $adminStatus = '' if ($Pscx:IsAdmin -and $isVistaOrHigher) { $adminStatus = 'Admin: ' } $location = Get-Location $version = $PSVersionTable.PSVersion $bitness = '' if ([IntPtr]::Size -eq 8) { $bitness = ' (x64)' } elseif ($Pscx:IsWow64Process) { $bitness = ' (x86)' } "$adminStatus$location - Windows PowerShell $version$bitness" } # SIG # Begin signature block # MIIfUwYJKoZIhvcNAQcCoIIfRDCCH0ACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUKGzZWrx7/P0U7FApqRlzj4Bm # /FagghqFMIIGajCCBVKgAwIBAgIQAwGaAjr/WLFr1tXq5hfwZjANBgkqhkiG9w0B # AQUFADBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD # VQQLExB3d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBBc3N1cmVk # IElEIENBLTEwHhcNMTQxMDIyMDAwMDAwWhcNMjQxMDIyMDAwM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J4HGwoKcy+JrI+Ag # QCnteiD7Z4kX4LELbH/8xNa5kmeV9nluvF1IgCo2x7TdgRvJXUGMr6g5fQl+qcQm # 6SAR+qDYhDTweAKjfhV7feMewgNpqwCHNoADVZmpXkPHv8bz4YeCWIoBgbmgXmuO # EVKgc6GCAg8wggILBgkqhkiG9w0BCQYxggH8MIIB+AIBATB2MGIxCzAJBgNVBAYT # AlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2Vy # dC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3VyZWQgSUQgQ0EtMQIQAwGaAjr/ # WLFr1tXq5hfwZjAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEH # ATAcBgkqhkiG9w0BCQUxDxcNMTYwNjMwMDM1OTE0WjAjBgkqhkiG9w0BCQQxFgQU # LjQx/orAPHwsDSBnn4kPTwbJfVswDQYJKoZIhvcNAQEBBQAEggEANwgvOZ0upVDZ # zNsOhDQn3SFk5nytGfQnXfiIfKsAstXzKLzUYhv6TK9eh9xIKUZf5VJWVA8FiDGC # qJ56cv+/zajknoGYoLsSrSKnm6NcUbNRwqumHQ7I5GxIeBL2Q41Bv2YvgC2xvXPB # WYNi1LVnk+CIwx5mr/vuRCqZqUh8mF0s7YM0STKqoxKhywmaziqvsYg4CjB1ZWuE # 06ZAaZS2WYyfyiT2G5JOJvJajrPuWd95ylRkq3fkd9IsxZuRxDRLGbGViSHczKK3 # XJDjHBp/Ja40EiuZVSI7Yr/CQ3DndrVSV8PZ+SSa0OA5RmCTyiizHM6TKJq/u2cU # Rm0vClYUYQ== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Pscx/3.2.2/Modules/Prompt/Themes/Jachym.ps1
Jachym.ps1
# --------------------------------------------------------------------------- # Author: Jachymko # Desc: Jachym's prompt, colors and host window title updates. # Date: Nov 07, 2009 # Site: http://pscx.codeplex.com # Usage: In your options hashtable place the following setting: # # PromptTheme = 'Jachym' # --------------------------------------------------------------------------- #requires -Version 3 param([hashtable]$Theme) Set-StrictMode -Version Latest # --------------------------------------------------------------------------- # Colors # --------------------------------------------------------------------------- $Theme.HostBackgroundColor = if ($Pscx:IsAdmin) { 'DarkRed' } else { 'Black' } $Theme.HostForegroundColor = if ($Pscx:IsAdmin) { 'White' } else { 'Gray' } $Theme.PromptForegroundColor = if ($Pscx:IsAdmin) { 'Yellow' } else { 'White' } $Theme.PrivateData.ErrorForegroundColor = if ($Pscx:IsAdmin) { 'DarkCyan' } # --------------------------------------------------------------------------- # Prompt ScriptBlock # --------------------------------------------------------------------------- $Theme.PromptScriptBlock = { param($Id) if($NestedPromptLevel) { new-object string ([char]0xB7), $NestedPromptLevel } "[$Id] $([char]0xBB)" } # --------------------------------------------------------------------------- # Window Title Update ScriptBlock # --------------------------------------------------------------------------- $Theme.UpdateWindowTitleScriptBlock = { (Get-Location) '-' 'Windows PowerShell' if($Pscx:IsAdmin) { '(Administrator)' } if ($Pscx:IsWow64Process) { '(x86)' } } # SIG # Begin signature block # MIIfUwYJKoZIhvcNAQcCoIIfRDCCH0ACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUWoXS5jtlDks5QDPumfJJrEQo # TgSgghqFMIIGajCCBVKgAwIBAgIQAwGaAjr/WLFr1tXq5hfwZjANBgkqhkiG9w0B # AQUFADBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD # VQQLExB3d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBBc3N1cmVk # IElEIENBLTEwHhcNMTQxMDIyMDAwMDAwWhcNMjQxMDIyMDAwMDAwWjBHMQswCQYD # VQQGEwJVUzERMA8GA1UEChMIRGlnaUNlcnQxJ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7mQbXXWZkBMpO6peTwYvqOFc1z0e1zSKgcU # IKszmCrtumXu58Ujy0DLakUB/pV3GFcZmEUcb58NhhvyH/bWCbnIqmEE9vKxryJ8 # NyMUHaGCAg8wggILBgkqhkiG9w0BCQYxggH8MIIB+AIBATB2MGIxCzAJBgNVBAYT # AlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2Vy # dC5jb20xITAfBgNVBAMTGERpZ2lDZXJ0IEFzc3VyZWQgSUQgQ0EtMQIQAwGaAjr/ # WLFr1tXq5hfwZjAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEH # ATAcBgkqhkiG9w0BCQUxDxcNMTYwNjMwMDM1OTE0WjAjBgkqhkiG9w0BCQQxFgQU # G7MoU6l7B76Lozb3l0o98DmX7LgwDQYJKoZIhvcNAQEBBQAEggEAC/n8PoWkv0ip # 1UkdAvIZkjCoQufdzI/lIIP0nIL70QpuiVoCVZ7U70GIK6KIVopTrhtDPFEhwq9j # mnNoU2NKnVfzOBfw1Kjajnclxve2o9leyZEf8CdDUJRPm+trTOXdI7SsKarZsj/x # mNVEYUy+rwBCuzv9ipavni/Yoregyj8BcgJAGI126mqvwNoqFXUYTDOQWeBwtBO9 # 7EAuCGLeSOb1ZuSd/LH4HuCJ7ntkv8mKMpkH4OefjVF4UgaLG5V3tHDUYtvBRiMb # 1D940cRIaFSfNkyilsDaaw/77G9zATbOVFKNUHm8a6PAtw7aJflcPE6YyL6939Fd # FNw7OHNdgw== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Open-ROSSDatabaseConnection.ps1
Open-ROSSDatabaseConnection.ps1
function Open-ROSSDatabaseConnection { <# .SYNOPSIS Opens a RES ONE Service Store database connection. .NOTES Adapted from the VirtualEngine.Database module. #> [CmdletBinding()] param ( # Microsoft SQL server connection [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.Data.Common.DbConnection] $Connection ) process { if ($Connection.State -eq 'Closed') { Write-Debug "Connection is closed. Attempting to open.."; $Connection.Open(); } else { Write-Debug "Connection is already open."; } #end if } #end process } #end function Open-ROSSDatabaseConnection
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Disable-ROSSPerson.ps1
Disable-ROSSPerson.ps1
function Disable-ROSSPerson { <# .SYNOPSIS Sets a RES ONE Service person to inactive. .EXAMPLE Disable-ROSSPerson -PersonName 'Sales' Disables all people with a name matching 'Sales'. .EXAMPLE Get-ROSSOrganization -Path 'Departments\Sales' | Disable-ROSSPerson Disables all people in the 'Departments\Sales' organizational context. .NOTES The RES ONE Service Store API performs a wildcard search on the service name when specified. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'PersonName')] [OutputType([System.Management.Automation.PSCustomObject])] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies returning people records with the specified RES ONE Service Store name(s). [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'PersonName')] [System.String[]] $PersonName, # Specifies returning people records with the specified RES ONE Service Store idenitifier(s). [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'PersonId')] [System.String[]] $PersonId, [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject] $InputObject, # Returns the updated RES ONE Service Store service object to the pipeline. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'PersonId')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'PersonName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { if ($PSCmdlet.ParameterSetName -eq 'PersonId') { $InputObject = Get-ROSSPerson -Session $Session -PersonId $PersonId; } elseif ($PSCmdlet.ParameterSetName -eq 'PersonName') { $InputObject = Get-ROSSPerson -Session $Session -PersonName $PersonName; } foreach ($person in $InputObject) { try { if ($Force -or ($PSCmdlet.ShouldProcess($person.Name, $localizedData.ShouldProcessDisable))) { $service.Active = $false; $setROSSPersonParams = @{ Session = $Session; InputObject = $person; Force = $Force; Confirm = $false; } Set-ROSSPerson @setROSSPersonParams; if ($PassThru) { ## Set-ROSSPerson only returns the response length, so we'll have to fetch it Write-Output -InputObject (Get-ROSSPerson -Session $Session -PersonId $person.Id); } } } catch { throw $_; } } #end foreach person } #end process } #end function Disable-ROSSPerson
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Invoke-ROSSRestMethod.ps1
Invoke-ROSSRestMethod.ps1
function Invoke-ROSSRestMethod { <# .SYNOPSIS Calls a RES ONE Service Store API method. .NOTES This is an internal method and should not be called directly. #> [CmdletBinding(DefaultParameterSetName = 'DefaultHashtable')] param ( # Specifies the RES ONE Service Store API endpoint and action to call [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultObject')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultHashtable')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'LoginObject')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'LoginHashtable')] [System.Uri] $Uri, # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultHashtable')] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies the HTTP action to perform [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultObject')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultHashtable')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'LoginObject')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'LoginHashtable')] [ValidateSet('Get','Post','Put','Delete')] [System.String] $Method, # Specifies that no authorisation header should be added to the request [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'LoginObject')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'LoginHashtable')] [Alias('NoAuthorisation')] [System.Management.Automation.SwitchParameter] $NoAuthorization, # Specifies the body of the HTTP request [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'LoginObject')] [ValidateNotNullOrEmpty()] [PSCustomObject] $InputObject, # Specifies the body of the HTTP request [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultHashtable')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'LoginHashtable')] [ValidateNotNullOrEmpty()] [System.Collections.Hashtable] $Body, # Specifies the property to expand from the API response [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultHashtable')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'LoginObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'LoginHashtable')] [ValidateNotNullOrEmpty()] [System.String] $ExpandProperty, # PSCustomObject type name to apply to the object. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DefaultHashtable')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'LoginObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'LoginHashtable')] [System.String] $TypeName = 'VirtualEngine.ROSS.Object' ) begin { if ($PSCmdlet.ParameterSetName -in 'DefaultObject','DefaultHashtable') { Assert-ROSSSession -Session $Session;; } } process { $invokeRestMethodParams = @{ Uri = $Uri; } if ($PSBoundParameters.ContainsKey('InputObject')) { $invokeRestMethodParams['Body'] = ConvertTo-Json -InputObject $InputObject -Depth 100 -Compress; } elseif ($PSBoundParameters.ContainsKey('Body')) { $invokeRestMethodParams['Body'] = ConvertTo-Json -InputObject $Body -Depth 100 -Compress; } if ($Method -ne 'Get') { $invokeRestMethodParams['Method'] = $Method; $invokeRestMethodParams['ContentType'] = 'application/json'; } if ($PSCmdlet.ParameterSetName -in 'DefaultObject','DefaultHashtable') { ## Build header that contains authentication key $headers = New-Object -TypeName 'System.Collections.Generic.Dictionary[[String],[String]]'; [ref] $null = $headers.Add('Auth-Token', $Session.AuthorizationToken); $invokeRestMethodParams['Headers'] = $headers; } $response = Invoke-RestMethod @invokeRestMethodParams; if ($PSBoundParameters.ContainsKey('ExpandProperty')) { #return $response.$ExpandProperty; $response = $response.$ExpandProperty; } foreach ($object in $response) { try { if (($null -ne $script:customProperties) -and ($script:customProperties.ContainsKey($TypeName))) { foreach ($propertyName in $script:customProperties[$TypeName].Keys) { $propertyMap = $script:customProperties.$TypeName[$propertyName]; $dataSourcePropertyName = $propertyMap['DataSourceColumn']; $dataSourcePropertyValue = $object.$dataSourcePropertyName if ($propertyMap.ContainsKey('ValueMap')) { } else { $addMemberParams = @{ InputObject = $object; MemberType = 'NoteProperty'; Name = $propertyName; Value = $dataSourcePropertyValue; } Add-Member @addMemberParams; } } } $object.PSObject.TypeNames.Insert(0, $TypeName); Write-Output -InputObject $object; } catch { throw $_; } } #end foreach object } #end process } #end function Invoke-ROSSRestMethod
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Remove-ROSSOrganization.ps1
Remove-ROSSOrganization.ps1
function Remove-ROSSOrganization { <# .SYNOPSIS Deletes a RES ONE Service Store Organizational Context. .NOTES THIS IS AN UNSUPPORTED DATABASE OPERATION AND THIS METHOD SHOULD NOT BE CALLED DIRECTLY. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'InputObject')] [OutputType('VirtualEngine.ROSS.Organization')] [Alias('Remove-ROSSOrganisation')] param ( # RES ONE Service Store session connection. [Parameter(ParameterSetName = 'Name')] [Parameter(ParameterSetName = 'Path')] [Parameter(ParameterSetName = 'InputObject')] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # RES ONE Service Store organization context reference object. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject[]] $InputObject, # RES ONE Service Store organization context name. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [System.String[]] $Name, # RES ONE Service Store organization context name. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [System.String[]] $Path, # Perform a regular expression match on name or path parameter. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [System.Management.Automation.SwitchParameter] $Match, # Returns an object representing the organization context with which you are working. By default, this cmdlet does not generate any output. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $Force ) begin { Write-Warning -Message ($localizedData.UnsupportedOperationWarning -f $MyInvocation.MyCommand); Assert-ROSSSession -Session $Session -Database; } process { $typeName = 'VirtualEngine.ROSS.Organization'; if (($PSCmdlet.ParameterSetName -eq 'Name') -or ($PSCmdlet.ParameterSetName -eq 'Path')) { [ref] $null = $PSBoundParameters.Remove('PassThru'); [ref] $null = $PSBoundParameters.Remove('Force'); [ref] $null = $PSBoundParameters.Remove('WhatIf'); $InputObject = Get-ROSSOrganization @PSBoundParameters; } foreach ($organization in $InputObject) { if ($organization.PSTypeNames -notcontains $typeName) { $exceptionMessage = $localizedData.InputObjectTypeMismatchError -f $typeName; $exception = New-Object System.ArgumentException $exceptionMessage; $category = [System.Management.Automation.ErrorCategory]::InvalidData; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'TypeMismatch', $category, $organization; $psCmdlet.WriteError($errorRecord); continue; } if (($Force -and (-not $PSBoundParameters.ContainsKey('WhatIf'))) -or ($PSCmdlet.ShouldProcess($organization.Name, $localizedData.ShouldProcessDelete))) { try { ## If we called the API we'll have an OrganizationId property so prefer that $organizationId = $organization.OrganizationId; if ([System.String]::IsNullOrEmpty($organizationId)) { ## If we called Get-ROSSOrganizationDb, we'll have a Guid property so use that instead $organizationId = $organization.Guid; } $query = "DELETE FROM [OR_Objects] WHERE [Type] = 3 AND [Guid] = '{0}'" -f $organizationId; $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; Query = $query; } [ref] $null = Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams; if ($PassThru) { Write-Output -InputObject $organization; } } catch { throw $_; } } } #end foreach organization } #end process } #end function Remove-ROSSOrganization
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Disconnect-ROSSSession.ps1
Disconnect-ROSSSession.ps1
function Disconnect-ROSSSession { <# .SYNOPSIS Disconnects connections to the RES ONE Service Store API and/or database.. #> [CmdletBinding()] param ( # RES ONE Service Store session connection. [Parameter()] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession ) process { if ($null -ne $Session) { Close-ROSSDatabaseConnection -Session $Session; $Session = $null; } } #end process } #end function Disconnect-ROSSSession
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Enable-ROSSServiceWorkflowAction.ps1
Enable-ROSSServiceWorkflowAction.ps1
function Enable-ROSSServiceWorkflowAction { <# .SYNOPSIS Enables RES ONE Service Store service workflow actions. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'DeliveryName')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Collections.Hashtable] $Session = $Script:_RESONEServiceStoreSession, # Specifies to enable the workflow action in the delivery workflow [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [System.Management.Automation.SwitchParameter] $Delivery, # Specifies to enable the workflow action in the return workflow [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $Return, # Specifies the RES ONE Service Store service(s) to enable by name. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [ValidateNotNullOrEmpty()] [System.String[]] $ServiceName, # Specifies the RES ONE Service Store service(s) to enable by reference. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [ValidateNotNull()] [PSCustomObject[]] $InputObject, # Specifies the RES ONE Service Store service workflow action name(s) to enable. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [ValidateNotNullOrEmpty()] [System.String[]] $Name, # Specifies matching of the workflow action name should not be performed on the custom/friendly name. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $ExcludeFriendlyName, # Returns the updated RES ONE Service Store service object to the pipeline. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { if ($PSBoundParameters.ContainsKey('ServiceName')) { $InputObject = Get-ROSSService -Session $Session -ServiceName $ServiceName; } foreach ($service in $InputObject) { try { if ($Delivery) { $serviceWorkflowActions = $service.Workflow.Delivery.Actions; } elseif ($Return) { $serviceWorkflowActions = $service.Workflow.Return.Actions; } ## Find all matching workflow action namess $matchingWorkflowActions = @(); foreach ($workflowActionName in $Name) { if ($ExcludeFriendlyName) { $matchingWorkflowActions += $serviceWorkflowActions | Where-Object { $_.Name -match $workflowActionName } } else { $matchingWorkflowActions += $serviceWorkflowActions | Where-Object { $_.Name -match $workflowActionName -or $_.ActionFriendlyName -match $workflowActionName } } } ## Only confirm/process if we have matching action name(s) if ($matchingWorkflowActions.Count -gt 0) { if ($Force -or ($PSCmdlet.ShouldProcess($service.Name, $localizedData.ShouldProcessDisable))) { ## Now disable all matching workflow actions foreach ($workflowAction in $matchingWorkflowActions) { $workflowAction.Enabled = $true; } $setROSSServiceParams = @{ Session = $Session; InputObject = $service; Force = $true; PassThru = $PassThru; } Set-ROSSService @setROSSServiceParams; } } else { ## We have no matching workflow action Write-Warning -Message ($localizedData.NoMatchingWorkflowActionsFound -f $service.Name); } } catch { throw $_; } } #end foreach service } #end process } #end function Enable-ROSSServiceWorkflowAction
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSDataSource.ps1
Get-ROSSDataSource.ps1
function Get-ROSSDataSource { <# .SYNOPSIS Queries the RES ONE Service Store database for Data Sources. #> [CmdletBinding()] [OutputType('VirtualEngine.ROSS.DataSource')] param ( # RES ONE Service Store session connection. [Parameter()] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # RES ONE Service Store organization context name. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [System.String[]] $Name, ## RES ONE Service Store data source type. [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('CSV','ActiveDirectory','ODBC')] [System.String] $Type ) begin { Assert-ROSSSession -Session $Session -Database; } process { try { $typeName = 'VirtualEngine.ROSS.DataSource'; $query = 'SELECT * FROM [OR_Objects] WHERE [Type] = 19'; if ($PSBoundParameters.ContainsKey('Type')) { $dataConnectionType = $script:customProperties[$typeName].Type.ValueMap.Keys | ForEach-Object { if ($script:customProperties[$typeName].Type.ValueMap[$_] -eq $Type) { $_ } } $query = '{0} AND SPECIFICFLAGS = {1}' -f $query, $dataConnectionType; } $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; TypeName = $typeName; PropertyMap = $script:customProperties[$typeName]; } if ($PSBoundParameters.ContainsKey('Name')) { foreach ($dataConnectionName in $Name) { $nameQuery = "{0} AND Name = '{1}'" -f $query, $dataConnectionName; $invokeROSSDatabaseQueryParams['Query'] = $nameQuery; Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } else { $invokeROSSDatabaseQueryParams['Query'] = $query; Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } catch { throw $_; } } #end process } #end function Get-ROSSDataSource
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSResourceUri.ps1
Get-ROSSResourceUri.ps1
function Get-ROSSResourceUri { <# .SYNOPSIS Returns RES ONE Service Store API endpoint URI. .NOTES This is an internal method and should not be called directly. #> [CmdletBinding()] [OutputType([System.String])] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Service')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchService')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchServiceFilter')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchTransaction')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Person')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchPerson')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'NewPerson')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Organization')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ListOrganization')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'UploadBuildingBlock')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ImportBuildingBlock')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ExportBuildingBlock')] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Return the Service API endpoint URI [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Service')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchService')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchServiceFilter')] [System.Management.Automation.SwitchParameter] $Service, # Return the Person API endpoint URI [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Person')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchPerson')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'NewPerson')] [System.Management.Automation.SwitchParameter] $Person, # Specifies the New action on the Person API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'NewPerson')] [System.Management.Automation.SwitchParameter] $New, # Specifies the search critera on the API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchService')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchServiceFilter')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchTransaction')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchPerson')] [System.Management.Automation.SwitchParameter] $Search, # Specifies the search filter on the Search API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchServiceFilter')] [System.String] $Filter, # Return the Transaction API endpoint URI [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'SearchTransaction')] [System.Management.Automation.SwitchParameter] $Transaction, # Return the Organization API endpoint URI [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Organization')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ListOrganization')] [System.Management.Automation.SwitchParameter] $Organization, # Specifies the List action on the Organization API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ListOrganization')] [System.Management.Automation.SwitchParameter] $List, # Return the Building Block API endpoint URI [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'UploadBuildingBlock')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ImportBuildingBlock')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ExportBuildingBlock')] [System.Management.Automation.SwitchParameter] $BuildingBlock, # Specifies the Import action on the Building Block API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ImportBuildingBlock')] [System.Management.Automation.SwitchParameter] $Import, # Specifies the Upload action on the Building Block API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'UploadBuildingBlock')] [System.String] $Upload, # Specifies the Import action on the Building Block API endpoint [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ExportBuildingBlock')] [System.Management.Automation.SwitchParameter] $Export, # Return the Authentication API endpoint URI [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Authentication')] [System.Management.Automation.SwitchParameter] $Authentication, # Specifies the server hostname hosting the RES ONE Service Store API to perform the authentication action against [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Authentication')] [System.String] $Server, # Specifies connections to the RES ONE Service Store API should used an encrypted connection [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Authentication')] [System.Management.Automation.SwitchParameter] $UseHttps ) begin { if ($PSCmdlet.ParameterSetName -eq 'Authentication') { $Session = @{ Server = $Server; UseHttps = $UseHttps.ToBool(); } } else { Assert-ROSSSession -Session $Session; } } process { $fqdn = 'http://{0}' -f $Session.Server; if ($Session.UseHttps) { $fqdn = 'https://{0}' -f $Session.Server; } switch ($PSCmdlet.ParameterSetName) { Authentication { return "$fqdn/Management/PublicApi/Authentication/Login"; } Service { return "$fqdn/Management/PublicApi/Service"; } SearchService { return "$fqdn/Management/PublicApi/Service/Search"; } SearchServiceFilter { $escapedFilter = [System.Uri]::EscapeUriString($Filter); return "$fqdn/Management/PublicApi/Service/Search?request.freeTextFilter=$escapedFilter"; } ImportBuildingBlock { return "$fqdn/Management/PublicApi/BuildingBlock/Import"; } UploadBuildingBlock { $escapedFilename = [System.Uri]::EscapeUriString($Upload); return "$fqdn/Management/PublicApi/BuildingBlock/Upload?fileName=$escapedFilename"; } ExportBuildingBlock { return "$fqdn/Management/PublicApi/BuildingBlock/Export"; } SearchTransaction { return "$fqdn/Management/PublicApi/Transaction/Search"; } Person { return "$fqdn/Management/PublicApi/Person"; } SearchPerson { return "$fqdn/Management/PublicApi/Person/Search"; } NewPerson { return "$fqdn/Management/PublicApi/Person/New"; } Organization { return "$fqdn/Management/PublicApi/Organization"; } ListOrganization { return "$fqdn/Management/PublicApi/Organization/List"; } } } #end process } #end function Get-ROSSResourceUri
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Disable-ROSSService.ps1
Disable-ROSSService.ps1
function Disable-ROSSService { <# .SYNOPSIS Disables RES ONE Service Store service transactions. .EXAMPLE Disable-ROSSService -ServiceName 'Sales' Disables all services with a name matching 'Sales'. .EXAMPLE Disable-ROSSService -ServiceId 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' Disables the service with the 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' identifier. .NOTES The RES ONE Service Store API performs a wildcard search on the service name when specified. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'ServiceName')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Collections.Hashtable] $Session = $Script:_RESONEServiceStoreSession, # Specifies the RES ONE Service Store service(s) to enable by name. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [System.String[]] $ServiceName, # Specifies the RES ONE Service Store service(s) to disable by Id. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [System.String[]] $ServiceId, # Specifies the RES ONE Service Store service(s) to enable by reference. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject[]] $InputObject, # Returns the updated RES ONE Service Store service object to the pipeline. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { if ($PSCmdlet.ParameterSetName -eq 'ServiceId') { $InputObject = Get-ROSSService -Session $Session -ServiceId $ServiceId; } elseif ($PSCmdlet.ParameterSetName -eq 'ServiceName') { $InputObject = Get-ROSSService -Session $Session -ServiceName $ServiceName; } foreach ($service in $InputObject) { try { if ($Force -or ($PSCmdlet.ShouldProcess($service.Name, $localizedData.ShouldProcessDisable))) { $service.EnableTransactions = $false; $setROSSServiceParams = @{ Session = $Session; InputObject = $service; Force = $Force; Confirm = $false; } Set-ROSSService @setROSSServiceParams; if ($PassThru) { ## Set-ROSSSession only returns the Service.Id so we'll have to fetch it Write-Output -InputObject (Get-ROSSService -Session $Session -ServiceId $service.Id); } } } catch { throw $_; } } #end foreach service } #end process } #end function Disable-ROSSService
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Disable-ROSSServiceWorkflowAction.ps1
Disable-ROSSServiceWorkflowAction.ps1
function Disable-ROSSServiceWorkflowAction { <# .SYNOPSIS Disables RES ONE Service Store service workflow actions. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'DeliveryName')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Collections.Hashtable] $Session = $Script:_RESONEServiceStoreSession, # Specifies to disable the workflow action in the delivery workflow [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [System.Management.Automation.SwitchParameter] $Delivery, # Specifies to disable the workflow action in the return workflow [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $Return, # Specifies the RES ONE Service Store service(s) to disable by name. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [ValidateNotNullOrEmpty()] [System.String[]] $ServiceName, # Specifies the RES ONE Service Store service(s) to disable by reference. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [ValidateNotNull()] [PSCustomObject[]] $InputObject, # Specifies the RES ONE Service Store service workflow action name(s) to disable. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [ValidateNotNullOrEmpty()] [System.String[]] $Name, # Specifies matching of the workflow action name should not be performed on the custom/friendly name. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $ExcludeFriendlyName, # Returns the updated RES ONE Service Store service object to the pipeline. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveryInputObject')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ReturnInputObject')] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { if ($PSBoundParameters.ContainsKey('ServiceName')) { $InputObject = Get-ROSSService -Session $Session -ServiceName $ServiceName; } try { foreach ($service in $InputObject) { if ($Delivery) { $serviceWorkflowActions = $service.Workflow.Delivery.Actions; } elseif ($Return) { $serviceWorkflowActions = $service.Workflow.Return.Actions; } ## Find all matching workflow action namess $matchingWorkflowActions = @(); foreach ($workflowActionName in $Name) { if ($ExcludeFriendlyName) { $matchingWorkflowActions += $serviceWorkflowActions | Where-Object { $_.Name -match $workflowActionName } } else { $matchingWorkflowActions += $serviceWorkflowActions | Where-Object { $_.Name -match $workflowActionName -or $_.ActionFriendlyName -match $workflowActionName } } } ## Only confirm/process if we have matching action name(s) if ($matchingWorkflowActions.Count -gt 0) { if ($Force -or ($PSCmdlet.ShouldProcess($service.Name, $localizedData.ShouldProcessDisable))) { ## Now disable all matching workflow actions foreach ($workflowAction in $matchingWorkflowActions) { $workflowAction.Enabled = $false; } $setROSSServiceParams = @{ Session = $Session; InputObject = $service; Force = $true; PassThru = $PassThru; } Set-ROSSService @setROSSServiceParams; } } else { ## We have no matching workflow action Write-Warning -Message ($localizedData.NoMatchingWorkflowActionsFound -f $service.Name); } } #end foreach service } catch { throw $_; } } #end process } #end function Disable-ROSSServiceWorkflowAction
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Enable-ROSSPerson.ps1
Enable-ROSSPerson.ps1
function Enable-ROSSPerson { <# .SYNOPSIS Sets a RES ONE Service person to active. .EXAMPLE Enable-ROSSPerson -PersonName 'Sales' Enables all people with a name matching 'Sales'. .EXAMPLE Get-ROSSOrganization -Path 'Departments\Sales' | Enable-ROSSPerson Enables all people in the 'Departments\Sales' organizational context. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'PersonName')] [OutputType([System.Management.Automation.PSCustomObject])] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies returning people records with the specified RES ONE Service Store name(s). [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'PersonName')] [System.String[]] $PersonName, # Specifies returning people records with the specified RES ONE Service Store idenitifier(s). [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'PersonId')] [System.String[]] $PersonId, [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject] $InputObject, # Returns the updated RES ONE Service Store service object to the pipeline. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'PersonId')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'PersonName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { if ($PSCmdlet.ParameterSetName -eq 'PersonId') { $InputObject = Get-ROSSPerson -Session $Session -PersonId $PersonId; } elseif ($PSCmdlet.ParameterSetName -eq 'PersonName') { $InputObject = Get-ROSSPerson -Session $Session -PersonName $PersonName; } try { foreach ($person in $InputObject) { if ($Force -or ($PSCmdlet.ShouldProcess($person.Name, $localizedData.ShouldProcessDisable))) { $service.Active = $true; $setROSSPersonParams = @{ Session = $Session; InputObject = $person; Force = $Force; Confirm = $false; } Set-ROSSPerson @setROSSPersonParams; if ($PassThru) { ## Set-ROSSPerson only returns the response length, so we'll have to fetch it Write-Output -InputObject (Get-ROSSPerson -Session $Session -PersonId $person.Id); } } } } catch { throw $_; } } #end process } #end function Enable-ROSSPerson
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Set-ROSSPerson.ps1
Set-ROSSPerson.ps1
function Set-ROSSPerson { <# .SYNOPSIS Updates a RES ONE Service Store person by reference. .EXAMPLE $person = Get-ROSSPerson -PersonName 'HJohn Smith' $person.Name = 'Joe Bloggs' $person | Set-ROSSPerson Renames an existing RES ONE Service Store person from 'John Smith' to 'Joe Bloggs' #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies the RES ONE Service Store object(s) to update. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [PSCustomObject[]] $InputObject, # Returns an object representing the server with which you are working. By default, this cmdlet does not generate any output. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { foreach ($person in $InputObject) { try { if ($Force -or ($PSCmdlet.ShouldProcess($person.Name, $localizedData.ShouldProcessSet))) { $uri = '{0}/{1}' -f (Get-ROSSResourceUri -Session $Session -Person), $person.Id; $invokeROSSRestMethodParams = @{ Session = $Session; Uri = $Uri; Method = 'Put'; InputObject = $person; } $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($PassThru) { Write-Output -InputObject $response; } } } catch { throw $_; } } #end foreach person } #end process } #end function Set-ROSSService
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Close-ROSSDatabaseConnection.ps1
Close-ROSSDatabaseConnection.ps1
function Close-ROSSDatabaseConnection { <# .SYNOPSIS Closes a RES ONE Service Store database connection. .NOTES Adapted from the VirtualEngine.Database module. #> [CmdletBinding()] param ( # RES ONE Service Store session connection. [Parameter()] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession ) process { if (($null -ne $Session) -and ($null -ne $Session.DbConnection)) { if ($Session.DbConnection.State -ne 'Closed') { Write-Debug "Attempting to close connection.."; $Session.DbConnection.Close(); ## Clear the exising session $Session.DbServer = $null; $Session.DbName = $null; $Session.DbConnection = $null; } else { Write-Debug "Connection is already closed."; } } } #end process } #end function Close-ROSSDatabaseConnection
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Remove-ROSSDataConnection.ps1
Remove-ROSSDataConnection.ps1
function Remove-ROSSDataConnection { <# .SYNOPSIS Deletes a RES ONE Service Store Data Connection. .NOTES THIS IS AN UNSUPPORTED DATABASE OPERATION AND THIS METHOD SHOULD NOT BE CALLED DIRECTLY. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'InputObject')] [OutputType('VirtualEngine.ROSS.DataConnection')] param ( # RES ONE Service Store session connection. [Parameter(ParameterSetName = 'Name')] [Parameter(ParameterSetName = 'InputObject')] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # RES ONE Service Store data connection reference object. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject[]] $InputObject, # RES ONE Service Store data connection name. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [System.String[]] $Name, ## RES ONE Service Store data connection type. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [ValidateSet('CSV','ActiveDirectory','ODBC')] [System.String] $Type, # Returns an object representing the data connection with which you are working. By default, this cmdlet does not generate any output. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $Force ) begin { Write-Warning -Message ($localizedData.UnsupportedOperationWarning -f $MyInvocation.MyCommand); Assert-ROSSSession -Session $Session -Database; } process { $typeName = 'VirtualEngine.ROSS.DataConnection'; if ($PSCmdlet.ParameterSetName -eq 'Name') { [ref] $null = $PSBoundParameters.Remove('PassThru'); [ref] $null = $PSBoundParameters.Remove('Force'); [ref] $null = $PSBoundParameters.Remove('WhatIf'); $InputObject = Get-ROSSDataConnection @PSBoundParameters; } foreach ($dataConnection in $InputObject) { if ($dataConnection.PSTypeNames -notcontains $typeName) { $exceptionMessage = $localizedData.InputObjectTypeMismatchError -f $typeName; $exception = New-Object System.ArgumentException $exceptionMessage; $category = [System.Management.Automation.ErrorCategory]::InvalidData; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'TypeMismatch', $category, $dataConnection; $psCmdlet.WriteError($errorRecord); continue; } if (($Force -and (-not $PSBoundParameters.ContainsKey('WhatIf'))) -or ($PSCmdlet.ShouldProcess($dataConnection.Name, $localizedData.ShouldProcessDelete))) { try { $query = "DELETE FROM [OR_DataLinks] WHERE [Guid] = '{0}'" -f $dataConnection.Guid; $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; Query = $query; } [ref] $null = Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams; if ($PassThru) { Write-Output -InputObject $dataConnection; } } catch { throw $_; } } } #end foreach datasource } #end process } #end function Remove-ROSSDataConnection
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Export-ROSSBuildingBlock.ps1
Export-ROSSBuildingBlock.ps1
function Export-ROSSBuildingBlock { <# .SYNOPSIS Imports a RES ONE Service Store building block. #> [CmdletBinding()] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies a path to one or more locations. Wildcards are permitted. [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Path, # Specifies services should be included in the exported building block file. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Services, # Specifies organizational contexts should be included in the exported building block file. [Parameter(ValueFromPipelineByPropertyName)] [Alias('Organisations')] [System.Management.Automation.SwitchParameter] $Organizations, # Specifies data sources should be included in the exported building block file. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $DataSources, # Specifies data sources should be included in the exported building block file. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $DataConnections, # Specifies data sources should be included in the exported building block file. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Branding, # Specifies imported service objects' images should not be included. By default service images are included. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $ExcludeImages, # Specifies imported service objects should not overwrite existing objects. By default, existing objects are overwritten/merged. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $NoClobber, # Returns the RES ONE Service Store import building block API response to the pipeline. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $PassThru ) begin { Assert-ROSSSession -Session $Session; } process { $requestBody = @{ suggestedName = Split-Path -Path $Path -Leaf; includeImages = -not $ExcludeImages.ToBool(); } if ($Services) { $requestBody['rootServiceId'] = [System.Guid]::Empty.ToString(); } if ($Organizations) { $requestBody['rootOrganizationId'] = [System.Guid]::Empty.ToString(); } if ($DataSources) { $requestBody['rootDataSourceId'] = [System.Guid]::Empty.ToString(); } if ($DataConnections) { $requestBody['rootDataConnectionId'] = [System.Guid]::Empty.ToString(); } if ($Branding) { $requestBody['rootBrandingId'] = [System.Guid]::Empty.ToString(); } if ($requestBody.Keys.Count -le 2) { ## No export options provided, so add 'em all! $requestBody['rootServiceId'] = [System.Guid]::Empty.ToString(); $requestBody['rootOrganizationId'] = [System.Guid]::Empty.ToString(); $requestBody['rootDataSourceId'] = [System.Guid]::Empty.ToString(); $requestBody['rootDataConnectionId'] = [System.Guid]::Empty.ToString(); $requestBody['rootBrandingId'] = [System.Guid]::Empty.ToString(); } $invokeROSSRestMethodParams = @{ Session = $Session; Uri = Get-ROSSResourceUri -Session $Session -BuildingBlock -Export; Method = 'POST'; Body = $requestBody; ExpandProperty = 'Bytes'; } $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; ## Convert the Base64 response into a Byte[] $buildingBlockBytes = [System.Convert]::FromBase64String($response); # Modify [CmdletBinding()] to [CmdletBinding(SupportsShouldProcess=$true)] $paths = @() foreach ($filePath in $Path) { # Resolve any relative paths $paths += $psCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($filePath) } foreach ($filePath in $paths) { try { if ($NoClobber -and (Test-Path -Path $filePath -PathType Leaf)) { $exceptionMessage = $localizedData.FileAlreadyExistsError -f $filePath; $exception = New-Object System.IO.IOException $exceptionMessage; $category = [System.Management.Automation.ErrorCategory]::OpenError; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'FileExists', $category, $filePath; $psCmdlet.WriteError($errorRecord); continue; } else { [System.IO.File]::WriteAllBytes($filePath, $buildingBlockBytes); if ($PassThru) { $buildingBlockItem = Get-Item -Path $filePath; Write-Output -InputObject $buildingBlockItem; } } } catch { throw $_; } } #end foreach file path } #end process } #end function Export-ROSSBuildingBlock
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Connect-ROSSMSSQLDatabase.ps1
Connect-ROSSMSSQLDatabase.ps1
function Connect-ROSSMSSQLDatabase { <# .SYNOPSIS Creates a new RES ONE Service Store Microsoft SQL Server connection using either Windows or SQL authentication. .NOTES Adapted from the VirtualEngine.Database module. #> [CmdletBinding(DefaultParameterSetName = 'WindowsAuthentication')] [OutputType([System.Data.Common.DbConnection])] param ( # Database server to connect to [Parameter(Mandatory, ParameterSetName = 'SQLAuthentication')] [Parameter(Mandatory, ParameterSetName = 'WindowsAuthentication')] [ValidateNotNullOrEmpty()] [System.String] $DatabaseServer, # Database instance/name [Parameter(Mandatory, ParameterSetName = 'SQLAuthentication')] [Parameter(Mandatory, ParameterSetName = 'WindowsAuthentication')] [ValidateNotNullOrEmpty()] [System.String] $DatabaseName, # SQL authentication username [Parameter(Mandatory, ParameterSetName='SQLAuthentication')] [ValidateNotNull()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, # User the specified connection string [Parameter(Mandatory, ParameterSetName = 'ConnectionString')] [System.String] $ConnectionString ) begin { Write-Debug ("Using parameter set '{0}'." -f $PSCmdlet.ParameterSetName); } process { if ($PSCmdlet.ParameterSetName -ne 'ConnectionString') { $ConnectionString = 'Data Source={0};Initial Catalog={1};' -f $DatabaseServer, $DatabaseName; if ($PSCmdlet.ParameterSetName -eq 'SQLAuthentication') { $ConnectionString += 'User Id={0};Password={1};' -f $Credential.UserName, $Credential.GetNetworkCredential().Password; } else { $ConnectionString += 'Integrated Security=SSPI;'; } } Write-Debug ("Using connection string '{0}'." -f $ConnectionString); New-Object -TypeName System.Data.SqlClient.SqlConnection -Property @{ 'ConnectionString' = $ConnectionString }; } #end process } #end function Connect-ROSSMSSQLDatabase
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Remove-ROSSDataSource.ps1
Remove-ROSSDataSource.ps1
function Remove-ROSSDataSource { <# .SYNOPSIS Deletes a RES ONE Service Store Data Source. .NOTES THIS IS AN UNSUPPORTED DATABASE OPERATION AND THIS METHOD SHOULD NOT BE CALLED DIRECTLY. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'InputObject')] [OutputType('VirtualEngine.ROSS.DataSource')] param ( # RES ONE Service Store session connection. [Parameter(ParameterSetName = 'Name')] [Parameter(ParameterSetName = 'InputObject')] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # RES ONE Service Store data source reference object. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject[]] $InputObject, # RES ONE Service Store data source name. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [System.String[]] $Name, ## RES ONE Service Store data source type. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [ValidateSet('CSV','ActiveDirectory','ODBC')] [System.String] $Type, # Returns an object representing the data source with which you are working. By default, this cmdlet does not generate any output. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Name')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $Force ) begin { Write-Warning -Message ($localizedData.UnsupportedOperationWarning -f $MyInvocation.MyCommand); Assert-ROSSSession -Session $Session -Database; } process { $typeName = 'VirtualEngine.ROSS.DataSource'; if ($PSCmdlet.ParameterSetName -eq 'Name') { [ref] $null = $PSBoundParameters.Remove('PassThru'); [ref] $null = $PSBoundParameters.Remove('Force'); [ref] $null = $PSBoundParameters.Remove('WhatIf'); $InputObject = Get-ROSSDataSource @PSBoundParameters; } foreach ($dataSource in $InputObject) { if ($dataSource.PSTypeNames -notcontains $typeName) { $exceptionMessage = $localizedData.InputObjectTypeMismatchError -f $typeName; $exception = New-Object System.ArgumentException $exceptionMessage; $category = [System.Management.Automation.ErrorCategory]::InvalidData; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'TypeMismatch', $category, $dataSource; $psCmdlet.WriteError($errorRecord); continue; } if (($Force -and (-not $PSBoundParameters.ContainsKey('WhatIf'))) -or ($PSCmdlet.ShouldProcess($dataSource.Name, $localizedData.ShouldProcessDelete))) { try { $query = "DELETE FROM [OR_Objects] WHERE [Type] = 19 AND [Guid] = '{0}'" -f $dataSource.Guid; $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; Query = $query; } [ref] $null = Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams; if ($PassThru) { Write-Output -InputObject $dataSource; } } catch { throw $_; } } } #end foreach datasource } #end process } #end function Remove-ROSSDataSource
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Connect-ROSSSession.ps1
Connect-ROSSSession.ps1
function Connect-ROSSSession { <# .SYNOPSIS Authenticate and creates a connection to the RES ONE Service Store API or database. .EXAMPLE Connect-ROSSSession -Server 'servicestore.lab.local' -Credential 'LAB\Administrator' Create a RES ONE Service Store API session to server 'servicestore.lab.local' over HTTP. .EXAMPLE Connect-ROSSSession -Server 'servicestore.lab.local' -Credential 'LAB\Administrator' -UseHttps Create a RES ONE Service Store API session to server 'servicestore.lab.local' over HTTPS. .EXAMPLE Connect-ROSSSession -DatabaseServer 'controller.lab.local' -DatabaseName RESONEServiceStore Create a RES ONE Service Store MSSSQL database session to server 'controller.lab.local' using Windows authentication. .EXAMPLE Connect-ROSSSession -DatabaseServer 'controller.lab.local' -DatabaseName 'RESONEServiceStore' -Credential 'sa' Create a RES ONE Service Store MSSSQL database session to server 'controller.lab.local' using SQL authentication. #> [CmdletBinding(DefaultParameterSetName = 'RestApi')] [OutputType([System.Management.Automation.PSCustomObject])] param ( ## RES ONE Service Store server hostname [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'RestApi')] [System.String]$Server, ## RES ONE Service Store database server hostname [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Database')] [System.String] $DatabaseServer, ## RES ONE Service Store database name [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Database')] [System.String] $DatabaseName, ## RES ONE Service Store authentication credential [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'RestApi')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Database')] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, ## RES ONE Service Store database name [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Database')] [ValidateSet('MSSQL')] [System.String] $Provider = 'MSSQL', ## Use https connection [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'RestApi')] [System.Management.Automation.SwitchParameter] $UseHttps, ## Return the session hashtable to the pipeline [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'RestApi')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Database')] [System.Management.Automation.SwitchParameter] $PassThru ) process { if ($null -eq $script:_RESONEServiceStoreSession) { $script:_RESONEServiceStoreSession = @{}; } if ($PSCmdlet.ParameterSetName -eq 'RestApi') { $body = @{ username = $Credential.UserName; password = $Credential.GetNetworkCredential().Password; logintype = 'windows'; } $uri = Get-ROSSResourceUri -Server $Server -Authentication -UseHttps:$UseHttps; $response = Invoke-ROSSRestMethod -Uri $uri -Method Post -Body $body -NoAuthorization; if ($response.Success -eq $true) { $script:_RESONEServiceStoreSession['Server'] = $Server; $script:_RESONEServiceStoreSession['AuthorizationToken'] = $response.AuthorizationToken; $script:_RESONEServiceStoreSession['UseHttps'] = $UseHttps.ToBool(); } else { throw $response.Reason; } } elseif ($PSCmdlet.ParameterSetName -eq 'Database') { $script:_RESONEServiceStoreSession['DbServer'] = $DatabaseServer; $script:_RESONEServiceStoreSession['DbName'] = $DatabaseName; [ref] $null = $PSBoundParameters.Remove('PassThru'); if ($Provider -eq 'MSSQL') { $script:_RESONEServiceStoreSession['DbConnection'] = Connect-ROSSMSSQLDatabase @PSBoundParameters; } } if ($PassThru) { return $script:_RESONEServiceStoreSession; } } #end process } #end function Connect-ROSSSession
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Import-ROSSBuildingBlock.ps1
Import-ROSSBuildingBlock.ps1
function Import-ROSSBuildingBlock { <# .SYNOPSIS Imports a RES ONE Service Store building block. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'Path')] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies a path to one or more locations. Wildcards are permitted. [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [ValidateNotNullOrEmpty()] [SupportsWildcards()] [System.String[]] $Path, # Specifies a path to one or more locations. Unlike the Path parameter, 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(Mandatory, Position = 0, ValueFromPipelineByPropertyName, ParameterSetName = 'LiteralPath')] [Alias("PSPath")] [ValidateNotNullOrEmpty()] [System.String[]] $LiteralPath, # Specifies imported service objects should be enabled. By default Service objects are not enabled. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $EnableTransactions, # Specifies imported service objects' images should not be included. By default service images are included. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $ExcludeImages, # Specifies imported service objects should not overwrite existing objects. By default, existing objects are overwritten/merged. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $NoClobber, # Returns the RES ONE Service Store import building block API response to the pipeline. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $PassThru ) begin { Assert-ROSSSession -Session $Session; } process { $paths = @() if ($psCmdlet.ParameterSetName -eq 'Path') { foreach ($filePath in $Path) { if (-not (Test-Path -Path $filePath)) { $exceptionMessage = $localizedData.CannotFindFilePathError -f $filePath; $exception = New-Object System.Management.Automation.ItemNotFoundException $exceptionMessage; $category = [System.Management.Automation.ErrorCategory]::ObjectNotFound; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'PathNotFound', $category, $filePath; $psCmdlet.WriteError($errorRecord); continue; } # Resolve any wildcards that might be in the path $provider = $null; $paths += $psCmdlet.SessionState.Path.GetResolvedProviderPathFromPSPath($filePath, [ref] $provider); } } else { foreach ($filePath in $LiteralPath) { if (-not (Test-Path -LiteralPath $filePath)) { $exceptionMessage = $localizedData.CannotFindFilePathError -f $filePath; $exception = New-Object System.Management.Automation.ItemNotFoundException $exceptionMessage; $category = [System.Management.Automation.ErrorCategory]::ObjectNotFound; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, 'PathNotFound', $category, $filePath; $psCmdlet.WriteError($errorRecord); continue; } # Resolve any relative paths $paths += $psCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($filePath); } } foreach ($filePath in $paths) { if ($Force -or ($psCmdlet.ShouldProcess($filePath, $localizedData.ShouldProcessImport))) { try { ## Convert Building Block file to a Base64String - this is need for the API $buildingBlockBytes = [System.IO.File]::ReadAllBytes($filePath); $buildingBlockBase64 = [System.Convert]::ToBase64String($buildingBlockBytes); $body = @{ bytes = $buildingBlockBase64; includeImages = $true; } ## Upload Building Block first and grab response $uploadUri = Get-ROSSResourceUri -Session $Session -BuildingBlock -Upload 'RESONEServiceStore.xml'; $uploadResponse = Invoke-ROSSRestMethod -Uri $uploadUri -Method Post -Body $body; if ($PSBoundParameters.ContainsKey('EnableTransactions')) { $uploadResponse.EnableTransactions = $EnableTransactions.ToBool(); } if ($PSBoundParameters.ContainsKey('NoClobber')) { $uploadResponse.OverwriteItems = -not $NoClobber.ToBool(); } if ($PSBoundParameters.ContainsKey('ExcludeImages')) { $uploadResponse.IncludeImages = -not $ExcludeImages.ToBool(); } ## Use response from upload to import the Building Block $importUri = Get-ROSSResourceUri -Session $Session -BuildingBlock -Import; $importResponse = Invoke-ROSSRestMethod -Uri $importUri -Method Post -InputObject $uploadResponse; if ($PassThru) { Write-Output -InputObject $importResponse; } } catch { throw $_; } } #end if should process } #end foreach file path } #end process } #end function Import-ROSSBuildingBlock
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Invoke-ROSSDatabaseQuery.ps1
Invoke-ROSSDatabaseQuery.ps1
function Invoke-ROSSDatabaseQuery { <# .SYNOPSIS Executes a SQL server query against a RES ONE Service Store database. .NOTES Adapted from the VirtualEngine.Database module. #> [CmdletBinding()] [OutputType([System.Data.DataRow[]])] param ( # Database connection object. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNull()] [System.Data.Common.DbConnection] $Connection, # Transact-SQL query to run [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Query, # PSCustomObject type name to apply to the object. [Parameter(ValueFromPipelineByPropertyName)] [System.String] $TypeName = 'VirtualEngine.ROSS.Object', # Custom property map to return calculated properties. [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $PropertyMap ) process { Write-Verbose -Message ($localizedData.InvokingSQLQuery -f $Query); $sqlCommand = $Connection.CreateCommand(); $sqlCommand.CommandText = $Query; switch ($Connection.GetType().Name) { MySqlConnection { [void] [System.Reflection.Assembly]::LoadWithPartialName('MySql.Data'); $sqlDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($sqlCommand); } SqlConnection { $sqlDataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($sqlCommand); } Default { throw ($localizedData.UnsupportedDbConnectionType -f $Connection.GetType().Name); } } $dataSet = New-Object System.Data.DataSet; [ref]$null = $sqlDataAdapter.Fill($dataSet); try { $dataSet.Tables[0] | ForEach-Object { $datarow = $_; if ($datarow) { $datarowPropertyNames = Get-Member -InputObject $datarow -MemberType Property | Select-Object -ExpandProperty Name; $datarowObjectProperties = @{ } foreach ($datarowPropertyName in $datarowPropertyNames) { $datarowObjectProperties[$datarowPropertyName] = $datarow.Item($datarowPropertyName); } ## Add the calculated properties if ($PSBoundParameters.ContainsKey('PropertyMap')) { foreach ($propertyName in $PropertyMap.Keys) { $customProperty = $PropertyMap[$propertyName]; $propertyValue = $datarow.Item($customProperty['DataSourceColumn']); $datarowObjectProperties[$propertyName] = $propertyValue; if ($null -ne $customProperty.ValueMap) { $datarowObjectProperties[$propertyName] = $customProperty.ValueMap[$propertyValue]; } } } ## Add the custom type name $datarowObject = [PSCustomObject] $datarowObjectProperties; $datarowObject.PSObject.TypeNames.Insert(0, $TypeName); Write-Output -InputObject $datarowObject; } #end if datarow } } catch { throw $_; } } #end process } #end function Invoke-ROSSDatabaseQuery
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Enable-ROSSService.ps1
Enable-ROSSService.ps1
function Enable-ROSSService { <# .SYNOPSIS Enables RES ONE Service Store service transactions. .EXAMPLE Enable-ROSSService -ServiceName 'Sales' Enables all services with a name matching 'Sales'. .EXAMPLE Enable-ROSSService -ServiceId 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' Enables the service with the 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' identifier. .NOTES The RES ONE Service Store API performs a wildcard search on the service name when specified. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'Name')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Collections.Hashtable] $Session = $Script:_RESONEServiceStoreSession, # Specifies RES ONE Service Store service(s) to enable by name. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [System.String[]] $ServiceName, # Specifies RES ONE Service Store service(s) to enable by ServiceId. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [System.String[]] $ServiceId, # Specifies RES ONE Service Store service(s) to enable by reference. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [PSCustomObject[]] $InputObject, # Returns the updated RES ONE Service Store service object to the pipeline. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'InputObject')] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { if ($PSCmdlet.ParameterSetName -eq 'ServiceId') { $InputObject = Get-ROSSService -Session $Session -ServiceId $ServiceId; } elseif ($PSCmdlet.ParameterSetName -eq 'ServiceName') { $InputObject = Get-ROSSService -Session $Session -ServiceName $ServiceName; } try { foreach ($service in $InputObject) { if ($Force -or ($PSCmdlet.ShouldProcess($service.Name, $localizedData.ShouldProcessEnable))) { $service.EnableTransactions = $true; $setROSSServiceParams = @{ Session = $Session; InputObject = $service; Force = $Force; Confirm = $false; } Set-ROSSService @setROSSServiceParams; if ($PassThru) { ## Set-ROSSSession only returns the Service.ServiceId so we'll have to fetch it Write-Output -InputObject (Get-ROSSService -Session $Session -ServiceId $service.Id); } } } } catch { throw $_; } } #end process } #end function Enable-ROSSService
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSOrganizationDb.ps1
Get-ROSSOrganizationDb.ps1
function Get-ROSSOrganizationDb { <# .SYNOPSIS Queries the RES ONE Service Store database for Organizational Contexts. #> [CmdletBinding()] [OutputType('VirtualEngine.ROSS.Organization')] param ( # RES ONE Service Store session connection. [Parameter()] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # RES ONE Service Store organization context name. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [System.String[]] $Name, # Select only root organizational contexts. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Root ) begin { Assert-ROSSSession -Session $Session -Database; } process { try { $typeName = 'VirtualEngine.ROSS.Organization'; $query = "SELECT * FROM [OR_Objects] WHERE [Type] = 3"; if ($Root) { $query = "{0} AND [RootGuid] = '00000000-0000-0000-0000-000000000000'" -f $query; } if ($PSBoundParameters.ContainsKey('Name')) { foreach ($organizationName in $Name) { $nameQuery = "{0} AND Name = '{1}'" -f $query, $organizationName; $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; Query = $nameQuery; TypeName = $typeName; } Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } else { $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; Query = $query; TypeName = $typeName; } Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } catch { throw $_; } } #end process } #end function Get-ROSSOrganizationDb
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/New-ROSSPerson.ps1
New-ROSSPerson.ps1
function New-ROSSPerson { <# .SYNOPSIS Creates a new RES ONE Service Store person. .EXAMPLE $person = New-ROSSPerson -PersonName 'Joe Bloggs' Creates a new RES ONE Service Store person called 'Joe Bloggs' .EXAMPLE $person = New-ROSSPerson -PersonName 'Joe Bloggs' Creates a new RES ONE Service Store person called 'John Smith' #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Creates people records with the specified RES ONE Service Store name(s). [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [Alias('Name')] [System.String[]] $PersonName, # Specifies that the people should be activated/licensed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Active, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { foreach ($name in $PersonName) { try { if ($Force -or ($PSCmdlet.ShouldProcess($name, $localizedData.ShouldProcessNew))) { $invokeROSSRestMethodParams = @{ Session = $Session; Uri = Get-ROSSResourceUri -Session $Session -Person -New; Method = 'Get'; } $person = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; $person.Id = [System.Guid]::NewGuid().ToString(); $person.Active = $Active.ToBool(); $person.Name = $name; $invokeROSSRestMethodParams = @{ Session = $Session; Uri = Get-ROSSResourceUri -Session $Session -Person; Method = 'Post'; InputObject = $person; } $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; Write-Output -InputObject $person; } } catch { throw $_; } } #end foreach person } #end process } #end function New-ROSSPerson
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Set-ROSSService.ps1
Set-ROSSService.ps1
function Set-ROSSService { <# .SYNOPSIS Updates a RES ONE Service Store service by reference. .EXAMPLE $service = Get-ROSSService -ServiceName 'My Hidden Service' $service.ShowInStore = $false $service | Set-ROSSService Hides a service named 'My Hidden Service' from the RES ONE Service Store web portal. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies the RES ONE Service Store object(s) to update. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [PSCustomObject[]] $InputObject, # Returns an object representing the server with which you are working. By default, this cmdlet does not generate any output. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $PassThru, # Specifies any comfirmation prompts should be suppressed. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Force ) begin { Assert-ROSSSession -Session $Session; } process { foreach ($service in $InputObject) { try { if ($Force -or ($PSCmdlet.ShouldProcess($service.Name, $localizedData.ShouldProcessSet))) { $uri = '{0}/{1}' -f (Get-ROSSResourceUri -Session $Session -Service), $service.Id; $invokeROSSRestMethodParams = @{ Session = $Session; Uri = $Uri; Method = 'Put'; InputObject = $service; } $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($PassThru) { Write-Output -InputObject $response; } } } catch { throw $_; } } #end foreach service } #end process } #end function Set-ROSSService
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSPerson.ps1
Get-ROSSPerson.ps1
function Get-ROSSPerson { <# .SYNOPSIS Returns a RES ONE Service person reference. .EXAMPLE Get-ROSSPerson -PersonName 'Sales' Returns all people with a name matching 'Sales'. The RES ONE Service Store API performs a pattern match. .EXAMPLE Get-ROSSOrganization -Path 'Departments\Sales' | Get-ROSSPerson Returns all people in the 'Departments\Sales' organizational context. .EXAMPLE Get-ROSSService -ServiceName 'Name Change' | Get-ROSSPerson -Delivered Returns all people that have the the 'Name Change' service delivered. .EXAMPLE Get-ROSSService -ServiceName 'Name Change' | Get-ROSSPerson -Qualified Returns all people qualified for the 'Name Change' service. #> [CmdletBinding(DefaultParameterSetName = 'PersonName')] [OutputType([System.Management.Automation.PSCustomObject])] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies returning people records with the specified RES ONE Service Store name(s). [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'PersonName')] [System.String[]] $PersonName, # Specifies returning people records with the specified RES ONE Service Store idenitifier(s). [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'PersonId')] [System.String[]] $PersonId, ## RES ONE Service Store organizational context Id [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'OrganizationId')] [System.String[]] $OrganizationId, ## RES ONE Service Store service Id [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'QualifiedServiceId')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveredServiceId')] [System.String[]] $ServiceId, # Specifies returning people records with the specified RES ONE Service Store idenitifier(s). [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'PersonAll')] [System.Management.Automation.SwitchParameter] $All, ## Return people who qualify for the service. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'QualifiedServiceId')] [System.Management.Automation.SwitchParameter] $Qualified, ## Return people who have the service delivered. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'DeliveredServiceId')] [System.Management.Automation.SwitchParameter] $Delivered, # Filters results, returning only Unlicensed people. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Unlicensed, # Filters results, returning only inactive people. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Inactive, # Filters results, returning only people marked for deletion. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $MarkedForDeletion, # Filters results, returning only people ready for deletion. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $ReadyForDeletion, # Search page number to return. By default, search results are paginated and only the first page results are returned. [Parameter(ValueFromPipelineByPropertyName)] [System.Int32] $Page = 1, # Specifies the number of results per page. By default, search results are paginated and only the first page results are returned. [Parameter(ValueFromPipelineByPropertyName)] [ValidateRange(1,65535)] [System.Int32] $PageSize = 50 ) begin { Assert-ROSSSession -Session $Session; if (($PSBoundParameters.ContainsKey('MarkedForDeletion')) -and ($PSBoundParameters.ContainsKey('ReadyForDeletion'))) { throw 'A person cannot both be marked for deletion and ready for deletion!'; } } process { $typeName = 'VirtualEngine.ROSS.Person'; $invokeROSSRestMethodParams = @{ Session = $Session; Uri = Get-ROSSResourceUri -Session $Session -Person -Search; Method = 'Post'; Body = @{ pageSize = $PageSize; pageNumber = $Page; } } if ($PSCmdlet.ParameterSetName -ne 'PersonId') { $Id = @(); if ($PSCmdlet.ParameterSetName -eq 'PersonAll') { $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($null -ne $response.Result.Id) { $Id += $response.Result.Id; } } elseif ($PSCmdlet.ParameterSetName -eq 'PersonName') { foreach ($name in $PersonName) { $invokeROSSRestMethodParams.Body['freeTextFilter'] = $name; $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($null -ne $response.Result.Id) { $Id += $response.Result.Id; } } } elseif ($PSCmdlet.ParameterSetName -eq 'OrganizationId') { foreach ($organization in $OrganizationId) { $invokeROSSRestMethodParams.Body['filters'] = @( @{ filterType = 'organization'; values = @($organization); } ) $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($null -ne $response.Result.Id) { $Id += $response.Result.Id; } } } elseif ($PSCmdlet.ParameterSetName -eq 'QualifiedServiceId') { foreach ($service in $serviceId) { $invokeROSSRestMethodParams.Body['filters'] = @( @{ filterType = 'qualifiedFor'; values = @($service); } ) $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($null -ne $response.Result.Id) { $Id += $response.Result.Id; } } } elseif ($PSCmdlet.ParameterSetName -eq 'DeliveredServiceId') { foreach ($service in $serviceId) { $invokeROSSRestMethodParams.Body['filters'] = @( @{ filterType = 'deliveredTo'; values = @($service); } ) $response = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if ($null -ne $response.Result.Id) { $Id += $response.Result.Id; } } } } ## Search for each Person Id foreach ($personId in $Id) { if (-not ([System.String]::IsNullOrEmpty($personId))) { try { $invokeROSSRestMethodParams = @{ Session = $Session; Uri = '{0}/{1}' -f (Get-ROSSResourceUri -Session $Session -Person), ($personId -as [String]); Method = 'Get'; TypeName = $typeName; } $isPersonFiltered = $false; $person = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; if (($PSBoundParameters.ContainsKey('Unlicensed')) -and ($person.IsLicensed -eq $Unlicensed.ToBool())) { $isPersonFiltered = $true; } if (($PSBoundParameters.ContainsKey('Inactive')) -and ($person.Active -eq $Inactive.ToBool())) { $isPersonFiltered = $true; } if (($PSBoundParameters.ContainsKey('MarkedForDeletion')) -and ($person.IsMarkedForDeletion -ne $MarkedForDeletion.ToBool())) { $isPersonFiltered = $true; } if (($PSBoundParameters.ContainsKey('ReadyForDeletion')) -and ($person.IsReadyForDeletion -ne $ReadyForDeletion.ToBool())) { $isPersonFiltered = $true; } if (-not $isPersonFiltered) { Write-Output -InputObject $person; } } catch { throw $_; } } } #end foreach person id } #end process } #end function Get-ROSSPerson
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSService.ps1
Get-ROSSService.ps1
function Get-ROSSService { <# .SYNOPSIS Returns a RES ONE Service Service reference. .EXAMPLE Get-ROSSService -All Returns the first 50 RES ONE Service Store services. .EXAMPLE Get-ROSSService -All -PageSize 100 Returns the first 100 RES ONE Service Store services. .EXAMPLE Get-ROSSService -All -PageSize 25 -Page 2 Returns the second set of 25 RES ONE Service Store services. .EXAMPLE Get-ROSSService -ServiceName 'Assign' Returns all services with 'Assign Departmental Services' in their name. .EXAMPLE Get-ROSSService -ServiceId 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' Returns a single service with the specified identifier. .NOTES The RES ONE Service Store API performs a wildcard search on the service name when specified. #> [CmdletBinding(DefaultParameterSetName = 'ServiceName')] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies the name of the service(s) to return. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceName')] [System.String[]] $ServiceName, # Specifies the RES ONE Service Store Service Id(s) to return [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceId')] [System.String[]] $ServiceId, # Specifies returning all services. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'ServiceAll')] [System.Management.Automation.SwitchParameter] $All, # Search page number to return. By default, search results are paginated and only the first page results are returned. [Parameter(ValueFromPipelineByPropertyName)] [System.Int32] $Page = 1, # Specifies the number of results per page. By default, search results are paginated and only the first page results are returned. [Parameter(ValueFromPipelineByPropertyName)] [ValidateRange(1,65535)] [System.Int32] $PageSize = 50 ) begin { Assert-ROSSSession -Session $Session; } process { $typeName = 'VirtualEngine.ROSS.Service'; try { if ($PSCmdlet.ParameterSetName -ne 'ServiceId') { ## The RES ONE Service Store API returns a subset of properties when searching ## for services. Therefore, perform the search and retrieve the service Ids $ServiceId = @(); if ($PSCmdlet.ParameterSetName -eq 'ServiceAll') { $invokeROSSRestMethodParams = @{ Uri = Get-ROSSResourceUri -Session $Session -Service -Search; Method = 'Post'; Body = @{ pageNumber = $Page; pageSize = $PageSize; } ExpandProperty = 'Result'; } $services = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; $ServiceId += $services.Id; } elseif ($PSCmdlet.ParameterSetName -eq 'ServiceName') { foreach ($name in $ServiceName) { $invokeROSSRestMethodParams = @{ #Uri = Get-ROSSResourceUri -Session $Session -Service -Search -Filter $serviceName; Uri = Get-ROSSResourceUri -Session $Session -Service -Search; Method = 'Post'; Body = @{ pageNumber = $Page; pageSize = $PageSize; freeTextFilter = $name; } ExpandProperty = 'Result'; } $services = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; $ServiceId += $services.Id; } } } foreach ($id in $ServiceId) { $invokeROSSRestMethodParams = @{ Session = $Session; Uri = '{0}/{1}' -f (Get-ROSSResourceUri -Session $Session -Service), $id; Method = 'Get'; TypeName = $typeName; } Write-Output -InputObject (Invoke-ROSSRestMethod @invokeROSSRestMethodParams); } } catch { throw $_; } } #end process } #end function Get-ROSSService
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSTransaction.ps1
Get-ROSSTransaction.ps1
function Get-ROSSTransaction { <# .SYNOPSIS Returns a RES ONE Service transaction reference. .EXAMPLE Get-ROSSTransaction Returns the first 50 transactions. .EXAMPLE Get-ROSSTransaction -ServiceId 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' Returns the first 50 transactions for a service. .EXAMPLE Get-ROSSTransaction -ServiceId 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' -Count Returns the number of transactions associated with a service. .EXAMPLE Get-ROSSTransaction -ServiceId 'a13003e7-3c51-4c22-9c9e-0a8210813ed1' -State Failed Returns the first 50 failed service delivery transactions for a service. .EXAMPLE Get-ROSSTransaction -PersonId 'b6af5c3a-601c-47a3-a551-075df7f96e33' Returns the first 50 transactions for a person. .EXAMPLE Get-ROSSTransaction -PersonId 'b6af5c3a-601c-47a3-a551-075df7f96e33' -Direction Deliver Returns the first 50 service delivery transactions for a person. .EXAMPLE Get-ROSSTransaction -PersonId 'b6af5c3a-601c-47a3-a551-075df7f96e33' -Count Returns the number of transactions associated with a person. .EXAMPLE Get-ROSSTransaction -Id 'fd86f088-5105-4aab-98ed-18e56756aef7' Returns the a specific RES ONE Service transaction by its Id. .EXAMPLE Get-ROSSOrganization -Path 'Departments\Sales' | Get-ROSSPerson | Get-ROSSTransaction Returns all transactions for people classified in the 'Departments\Sales' organizational context #> [CmdletBinding(DefaultParameterSetName = 'Default')] [OutputType([System.Management.Automation.PSCustomObject], ParameterSetName = 'Default')] [OutputType([System.Management.Automation.PSCustomObject], ParameterSetName = 'Transaction')] [OutputType([System.Int32], ParameterSetName = 'Count')] param ( # RES ONE Service Store session connection [Parameter(ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies returning transactions related to a specific RES ONE Service Store service Id. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [System.String] $ServiceId, # Specifies returning transactions related to a specific RES ONE Service Store person Id. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [System.String] $PersonId, # Specifies the RES ONE Service Store transaction Id to return. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Transaction')] [System.String] $Id, # Search transactions starting on or before the specified date/time. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [System.DateTime] $StartDate, # Search transactions ending on or before the specified date/time. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [System.DateTime] $EndDate, # Transaction type. If not specified, both delivery and return transactions are returned. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [ValidateSet('Deliver','Return')] [System.String] $Direction, # Transaction state. If not specified, both delivery and return transactions are returned. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [ValidateSet('Completed','Pending','Failed','Aborted','OnHold')] [System.String] $State, # Search page number to return. By default, search results are paginated and only the first page results are returned. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [ValidateRange(1,65535)] [System.Int32] $Page = 1, # Specifies the number of results per page. By default, search results are paginated and only the first page results are returned. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [ValidateRange(1,65535)] [System.Int32] $PageSize = 50, # Specifies returning only the number of available transactions matching the search criteria. [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Count')] [System.Management.Automation.SwitchParameter] $Count ) begin { Assert-ROSSSession -Session $Session; if (($PSBoundParameters.ContainsKey('StartDate')) -and ($PSBoundParameters.ContainsKey('EndDate'))) { if ($EndDate -lt $StartDate) { throw ($localizedData.StartDateAfterEndDateError); } } } process { Write-Verbose $PSCmdlet.ParameterSetName $typeName = 'VirtualEngine.ROSS.Transaction'; $uri = Get-ROSSResourceUri -Session $Session -Transaction -Search; $requestBody = @{ filters = @{}; orderBy = @('StartDate'); } if ($PSCmdlet.ParameterSetName -eq 'Default') { $requestBody['pageNumber'] = $Page; $requestBody['pageSize'] = $PageSize; } if ($PSBoundParameters.ContainsKey('PersonId')) { $requestBody.Filters['PersonId'] = $PersonId; } if ($PSBoundParameters.ContainsKey('PersonName')) { $requestBody.Filters['PersonName'] = $PersonName; } if ($PSBoundParameters.ContainsKey('ServiceId')) { $requestBody.Filters['ServiceId'] = $ServiceId; } if ($PSBoundParameters.ContainsKey('Direction')) { $requestBody.Filters['Direction'] = if ($Direction -eq 'Deliver') { 'Provision' } else { 'Deprovision' }; } if ($PSBoundParameters.ContainsKey('State')) { $requestBody.Filters['State'] = $State; } if ($PSBoundParameters.ContainsKey('StartDate')) { $requestBody.Filters['StartDate'] = $StartDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ'); } if ($PSBoundParameters.ContainsKey('EndDate')) { $requestBody.Filters['EndDate'] = $EndDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ'); } $invokeROSSRestMethodParams = @{ Session = $Session; Uri = $uri; Method = 'Post'; Body = $requestBody; } if ($PSCmdlet.ParameterSetName -eq 'Count') { Write-Output -InputObject (Invoke-ROSSRestMethod @invokeROSSRestMethodParams).TotalCount; } else { try { Invoke-ROSSRestMethod @invokeROSSRestMethodParams -ExpandProperty 'Result' | ForEach-Object { $PSItem.PSObject.TypeNames.Insert(0, $TypeName); $startDateTime = $PSItem.UtcStartDate -as [System.DateTime]; $endDateTime = $PSItem.UtcEndDate -as [System.DateTime]; $deliveryAction = if ($PSItem.Direction -eq 'Provision') { 'Deliver' } else { 'Return ' } Add-Member -InputObject $PSItem -MemberType NoteProperty -Name Action -Value $deliveryAction; Add-Member -InputObject $PSItem -MemberType NoteProperty -Name StartDate -Value $startDateTime; Add-Member -InputObject $PSItem -MemberType NoteProperty -Name EndDate -Value $endDateTime; Write-Output -InputObject $PSItem; } } catch { throw $_; } } } #end process } #end function Get-ROSSTransaction
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSOrganization.ps1
Get-ROSSOrganization.ps1
function Get-ROSSOrganization { <# .SYNOPSIS Returns a RES ONE Service organizational context reference. #> [CmdletBinding(DefaultParameterSetName = 'OrganizationName')] [Alias('Get-ROSSOrganisation')] [OutputType('VirtualEngine.ROSS.Organization')] param ( # RES ONE Service Store session connection. [Parameter()] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # Specifies RES ONE Service Store organization context by name. Supports wildcard characters. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'OrganizationName')] [System.String[]] $OrganizationName, # Specifies RES ONE Service Store organization context by path. Supports wildcard characters. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [System.String[]] $Path, # Specifies RES ONE Service Store organization context by Id. [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'OrganizationId')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'OrganizationName')] [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [System.String[]] $Id, # Perform a regular expression match on name or path parameter. [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'OrganzationName')] [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Path')] [System.Management.Automation.SwitchParameter] $Match ) begin { Assert-ROSSSession -Session $Session; } process { $typeName = 'VirtualEngine.ROSS.Organization'; $organizations = @(); if ($PSBoundParameters.ContainsKey('Id')) { $rossOrganizationEndpointUri = Get-ROSSResourceUri -Session $Session -Organization; $invokeROSSRestMethodParams = @{ Session = $Session; Method = 'Get'; TypeName = $typeName; } foreach ($organizationId in $Id) { $invokeROSSRestMethodParams['Uri'] = '{0}/{1}' -f $rossOrganizationEndpointUri, $organizationId; $organizations += Invoke-ROSSRestMethod @invokeROSSRestMethodParams; } } else { ## Retrieve the root organizational contexts $invokeROSSRestMethodParams = @{ Session = $Session; Uri = Get-ROSSResourceUri -Session $Session -Organization -List; Method = 'Get'; TypeName = $typeName; ExpandProperty = 'Children'; } $organizations = Invoke-ROSSRestMethod @invokeROSSRestMethodParams; } foreach ($organization in $organizations) { try { $getChildROSSOrganizationParams = @{ Session = $Session; Id = $organization.Children.Id; Match = $Match.ToBool(); } if ($PSBoundParameters.ContainsKey('OrganizationName')) { foreach ($name in $OrganizationName) { $isLikeExpression = $false; if ($name.Contains('*')) { $isLikeExpression = $true; } if (($Match -and ($organization.Name -match $name)) -or ($isLikeExpression -and (-not $Match) -and ($organization.Name -like $name)) -or ((-not $Match) -and (-not $isLikeExpression) -and ($organization.Name -eq $name))) { Write-Output -InputObject $organization; } } $getChildROSSOrganizationParams['OrganizationName'] = $name; } elseif ($PSBoundParameters.ContainsKey('Path')) { foreach ($organizationPath in $Path) { $isLikeExpression = $false; if ($organizationPath.Contains('*')) { $isLikeExpression = $true; } if (($Match -and ($organization.Path -match $organizationPath)) -or ($isLikeExpression -and (-not $Match) -and ($organization.Path -like $organizationPath)) -or ((-not $Match) -and (-not $isLikeExpression) -and ($organization.Path -eq $organizationPath))) { Write-Output -InputObject $organization; } } $getChildROSSOrganizationParams['Path'] = $Path; } else { Write-Output -InputObject $organization; } ## Recursively search child organizational contexts if ($organization.Children) { Get-ROSSOrganization @getChildROSSOrganizationParams; } } catch { throw $_; } } #end foreach organization context } #end process } #end function Get-ROSSOrganization
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Assert-ROSSSession.ps1
Assert-ROSSSession.ps1
function Assert-ROSSSession { <# .SYNOPSIS Ensures there is an authenticated RES ONE Service Store session established. #> [CmdletBinding()] param ( # RES ONE Service Store session connection. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, ## Assert database connection. By default, RES ONE Service Store API session is checked. [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Database ) process { if ($null -eq $Session) { throw $localizedData.NoSessionEstablishedError; } if ($Database) { $properties = 'DbServer','DbName','DbConnection'; } else { $properties = 'Server','AuthorizationToken','UseHttps'; } ## Check each property and throw if null foreach ($property in $properties) { if ($null -eq $Session[$property]) { if ($Database) { throw $localizedData.NoDbSessionEstablishedError; } else { throw $localizedData.NoApiSessionEstablishedError; } } } } #end process } #end function Assert-ROSSSession
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Src/Get-ROSSDataConnection.ps1
Get-ROSSDataConnection.ps1
function Get-ROSSDataConnection { <# .SYNOPSIS Queries the RES ONE Service Store database for Data Connections. #> [CmdletBinding()] [OutputType('VirtualEngine.ROSS.DataConnection')] param ( # RES ONE Service Store session connection. [Parameter()] [System.Collections.Hashtable] $Session = $script:_RESONEServiceStoreSession, # RES ONE Service Store organization context name. [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [System.String[]] $Name, ## RES ONE Service Store data connection type [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Attribute','Classification','Organization','People')] [System.String] $Type ) begin { Assert-ROSSSession -Session $Session -Database; } process { try { $typeName = 'VirtualEngine.ROSS.DataConnection'; $query = 'SELECT * FROM [OR_DataLinks]'; if ($PSBoundParameters.ContainsKey('Type')) { $dataConnectionType = $script:customProperties[$typeName].Type.ValueMap.Keys | ForEach-Object { if ($script:customProperties[$typeName].Type.ValueMap[$_] -eq $Type) { $_ } } $query = '{0} WHERE TYPE = {1}' -f $query, $dataConnectionType; } $invokeROSSDatabaseQueryParams = @{ Connection = $Session.DbConnection; TypeName = $typeName; PropertyMap = $script:customProperties[$typeName]; } if (($PSBoundParameters.ContainsKey('Name')) -and ($PSBoundParameters.ContainsKey('Type'))) { foreach ($dataConnectionName in $Name) { $nameQuery = "{0} AND Name = '{1}'" -f $query, $dataConnectionName; $invokeROSSDatabaseQueryParams['Query'] = $nameQuery; Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } elseif ($PSBoundParameters.ContainsKey('Name')) { foreach ($dataConnectionName in $Name) { $nameQuery = "{0} WHERE Name = '{1}'" -f $query, $dataConnectionName; $invokeROSSDatabaseQueryParams['Query'] = $nameQuery; Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } else { $invokeROSSDatabaseQueryParams['Query'] = $query; Write-Output -InputObject (Invoke-ROSSDatabaseQuery @invokeROSSDatabaseQueryParams); } } catch { throw $_; } } #end process } #end function Get-ROSSDataConnection
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/DSCResources/ROSSCommon/Src/Get-WindowsInstallerPackageProperty.ps1
Get-WindowsInstallerPackageProperty.ps1
function Get-WindowsInstallerPackageProperty { <# .SYNOPSIS This cmdlet retrieves product name from a Windows Installer MSI database. .DESCRIPTION This function uses the WindowInstaller COM object to pull all values from the Property table from a MSI package. .NOTES Adapted from http://www.scconfigmgr.com/2014/08/22/how-to-get-msi-file-information-with-powershell/ #> [CmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName='Path')] [ValidateNotNullOrEmpty()] [Alias('PSPath','FullName')] [System.String] $Path, [Parameter(Mandatory, Position = 0, ValueFromPipelineByPropertyName, ParameterSetName = 'LiteralPath')] [ValidateNotNullOrEmpty()] [System.String] $LiteralPath, [Parameter(Position = 1, ValueFromPipelineByPropertyName)] [ValidateSet('ProductCode', 'ProductVersion', 'ProductName', 'UpgradeCode')] [System.String] $Property = 'ProductCode' ) begin { if ($PSCmdlet.ParameterSetName -eq 'Path') { $LiteralPath += $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path); } } #end begin process { $windowsInstaller = New-Object -ComObject WindowsInstaller.Installer; Write-Verbose -Message ($localizedData.OpeningMSIDatabase -f $LiteralPath); try { $msiDatabase = $windowsInstaller.GetType().InvokeMember('OpenDatabase', 'InvokeMethod', $null, $windowsInstaller, @("$LiteralPath", 0)); $query = "SELECT Value FROM Property WHERE Property = '{0}'" -f $Property; $view = $msiDatabase.GetType().InvokeMember('OpenView', 'InvokeMethod', $null, $msiDatabase, $query); $view.GetType().InvokeMember('Execute', 'InvokeMethod', $null, $view, $null); $record = $view.GetType().InvokeMember('Fetch','InvokeMethod', $null, $view, $null); $value = $record.GetType().InvokeMember('StringData', 'GetProperty', $null, $record, 1); return $value; } catch { throw $_; } } #end process } #end function Get-WindowsInstallerPackageProperty
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/DSCResources/ROSSCommon/Src/Resolve-ROSSPackagePath.ps1
Resolve-ROSSPackagePath.ps1
function Resolve-ROSSPackagePath { <# .SYNOPSIS Resolves the latest RES ONE Service Store/IT Store installation package. #> [CmdletBinding()] param ( ## The literal file path or root search path [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.String] $Path, ## Required RES ONE Service Store component [Parameter(Mandatory)] [ValidateSet('Console','CatalogServices','TransactionEngine','ManagementPortal','WebPortal','Client')] [System.String] $Component, ## RES ONE Service Store component version to be installed, i.e. 9, 8.2 or 8.2.2.0 [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.String] $Version, ## The specified Path is a literal file reference (bypasses the Version check). [Parameter()] [System.Boolean] $IsLiteralPath ) if (([System.String]::IsNullOrWhitespace($Version)) -and (-not $IsLiteralPath)) { throw ($localizedData.VersionNumberRequiredError); } elseif ($IsLiteralPath) { if ($Path -notmatch '\.msi$') { throw ($localizedData.SpecifedPathTypeError -f $Path, 'MSI'); } } elseif ($Version -notmatch '^\d\d?(\.\d\d?|\.\d\d?\.\d\d?|\.\d\d?\.\d\d?\.\d\d?)?$') { throw ($localizedData.InvalidVersionNumberFormatError -f $Version); } if ($IsLiteralPath) { $packagePath = $Path; } else { ## [System.Version] does not support just a major number and therefore, we have to roll our own.. $versionSplit = $Version.Split('.'); $productVersion = [PSCustomObject] @{ Major = $versionSplit[0] -as [System.Int32]; Minor = if ($versionSplit[1]) { $versionSplit[1] -as [System.Int32] } else { -1 } Build = if ($versionSplit[2]) { $versionSplit[2] -as [System.Int32] } else { -1 } Revision = if ($versionSplit[3]) { $versionSplit[3] -as [System.Int32] } else { -1 } } switch ($productVersion.Major) { 7 { $packageName = 'RES-ITS'; $webPortalPackageName = 'Web-Portal'; $consolePackageName = 'Console' } 8 { $packageName = 'RES-ONE-ServiceStore-2015'; $webPortalPackageName = 'WebPortal-MobileGateway'; $consolePackageName = 'Setup-Sync-Tool'; } 9 { $packageName = 'RES-ONE-ServiceStore-2016'; $webPortalPackageName = 'WebPortal-MobileGateway'; $consolePackageName = 'Setup-Sync-Tool'; } Default { throw ($localizedData.UnsupportedVersionError -f $productVersion.ToString()); } } #end switch version major ## Calculate the version search Regex if (($productVersion.Minor -eq -1) -and ($productVersion.Build -eq -1) -and ($productVersion.Revision -eq -1)) { ## We only have 'Major' $versionRegex = '{0}.\S+' -f $productVersion.Major; } elseif (($productVersion.Build -eq -1) -and ($productVersion.Revision -eq -1)) { ## We only have 'Major.Minor' $versionRegex = '{0}.{1}.\S+' -f $productVersion.Major, $productVersion.Minor; } elseif ($productVersion.Revision -eq -1) { ## We have 'Major.Minor.Build' $versionRegex = '{0}.{1}.{2}.\S+' -f $productVersion.Major, $productVersion.Minor, $productVersion.Build; } else { ## We have explicit version. $versionRegex = '{0}.{1}.{2}.{3}' -f $productVersion.Major, $productVersion.Minor, $productVersion.Build, $productVersion.Revision; } $systemArchitecture = 'x86'; if ([System.Environment]::Is64BitOperatingSystem) { $systemArchitecture = 'x64'; } switch ($Component) { 'TransactionEngine' { ## RES-ITS-Transaction-Engine(x64)-7.3.0.0.msi ## RES-ONE-ServiceStore-2015-Transaction-Engine(x64)-8.2.2.0.msi ## RES-ONE-ServiceStore-2016-Transaction-Engine(x64)-9.0.1.0.msi $regex = '{0}-Transaction-Engine\({1}\)-{2}.msi' -f $packageName, $systemArchitecture, $versionRegex; } 'CatalogServices' { ## RES-ITS-Catalog-Services(x64)-7.3.0.0.msi ## RES-ONE-ServiceStore-2015-Catalog-Services(x64)-8.2.2.0.msi ## RES-ONE-ServiceStore-2015-Catalog-Services(x64)-9.0.1.0.msi $regex = '{0}-Catalog-Services\({1}\)-{2}.msi' -f $packageName, $systemArchitecture, $versionRegex; } 'ManagementPortal' { ## Not applicable to IT Store 2014 ## RES-ONE-ServiceStore-2015-Management-Portal-8.2.2.0.msi ## RES-ONE-ServiceStore-2016-Management-Portal-9.0.1.0.msi $regex = '{0}-Management-Portal-{1}.msi' -f $packageName, $versionRegex; } 'WebPortal' { ## RES-ITS-Web-Portal-7.3.0.0.msi ## RES-ONE-ServiceStore-2015-WebPortal-MobileGateway-8.2.2.0.msi ## RES-ONE-ServiceStore-2016-WebPortal-MobileGateway-9.0.1.0.msi $regex = '{0}-{1}-{2}.msi' -f $packageName, $webPortalPackageName, $versionRegex; } 'Client' { ## RES-ITS-Client(x64)-7.3.0.0.msi ## RES-ONE-ServiceStore-2015-Client(x64)-8.2.2.0.msi ## RES-ONE-ServiceStore-2016-Client(x64)-9.0.1.0.msi $regex = '{0}-Client\({1}\)-{2}.msi' -f $packageName, $systemArchitecture, $versionRegex; } Default { ## RES-ITS-Console(x64)-7.3.0.0.msi ## RES-ONE-ServiceStore-2015-Setup-Sync-Tool(x64)-8.2.2.0.msi ## RES-ONE-ServiceStore-2016-Setup-Sync-Tool(x64)-9.0.1.0.msi $regex = '{0}-{1}\({2}\)-{3}.msi' -f $packageName, $consolePackageName, $systemArchitecture, $versionRegex; } } #end switch component Write-Verbose -Message ($localizedData.SearchFilePatternMatch -f $regex); $packagePath = Get-ChildItem -Path $Path -Recurse | Where-Object { $_.Name -imatch $regex } | Sort-Object -Property Name -Descending | Select-Object -ExpandProperty FullName -First 1; if ((-not $IsLiteralPath) -and (-not [System.String]::IsNullOrEmpty($packagePath))) { Write-Verbose ($localizedData.LocatedPackagePath -f $packagePath); return $packagePath; } elseif ([System.String]::IsNullOrEmpty($packagePath)) { throw ($localizedData.UnableToLocatePackageError -f $Component); } } #end if } #end function Resolve-ROSSPackagePath
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/DSCResources/ROSSCommon/Src/Start-WaitProcess.ps1
Start-WaitProcess.ps1
function Start-WaitProcess { <# .SYNOPSIS Starts and waits for a process to exit. .NOTES This is an internal function and shouldn't be called from outside. #> [CmdletBinding(SupportsShouldProcess)] [OutputType([System.Int32])] param ( # Path to process to start. [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.String] $FilePath, # Arguments (if any) to apply to the process. [Parameter()] [AllowNull()] [System.String[]] $ArgumentList, # Credential to start the process as. [Parameter()] [AllowNull()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, # Working directory [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $WorkingDirectory = (Split-Path -Path $FilePath -Parent) ) process { $startProcessParams = @{ FilePath = $FilePath; WorkingDirectory = $WorkingDirectory; NoNewWindow = $true; PassThru = $true; }; $displayParams = '<None>'; if ($ArgumentList) { $displayParams = [System.String]::Join(' ', $ArgumentList); $startProcessParams['ArgumentList'] = $ArgumentList; } Write-Verbose ($localizedData.StartingProcess -f $FilePath, $displayParams); if ($Credential) { Write-Verbose ($localizedData.StartingProcessAs -f $Credential.UserName); $startProcessParams['Credential'] = $Credential; } if ($PSCmdlet.ShouldProcess($FilePath, 'Start Process')) { $process = Start-Process @startProcessParams -ErrorAction Stop; } if ($PSCmdlet.ShouldProcess($FilePath, 'Wait Process')) { Write-Verbose ($localizedData.ProcessLaunched -f $process.Id); Write-Verbose ($localizedData.WaitingForProcessToExit -f $process.Id); $process.WaitForExit(); $exitCode = [System.Convert]::ToInt32($process.ExitCode); Write-Verbose ($localizedData.ProcessExited -f $process.Id, $exitCode); } return $exitCode; } #end process } #end function Start-WaitProcess
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/DSCResources/ROSSCommon/Src/Get-InstalledProductEntry.ps1
Get-InstalledProductEntry.ps1
function Get-InstalledProductEntry { <# .NOTES https://github.com/PowerShell/xPSDesiredStateConfiguration/blob/dev/DSCResources/MSFT_xPackageResource/MSFT_xPackageResource.psm1 #> [CmdletBinding()] param ( [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $Name, [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $IdentifyingNumber, [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $InstalledCheckRegHive = 'LocalMachine', [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $InstalledCheckRegKey, [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $InstalledCheckRegValueName, [Parameter()] [ValidateNotNullOrEmpty()] [System.String] $InstalledCheckRegValueData ) process { $uninstallKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'; $uninstallKeyWow64 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'; if ($IdentifyingNumber) { $keyLocation = '{0}\{1}' -f $uninstallKey, $identifyingNumber; $item = Get-Item -Path $keyLocation -ErrorAction SilentlyContinue; if (-not $item) { $keyLocation = '{0}\{1}' -f $uninstallKeyWow64, $identifyingNumber; $item = Get-Item -Path $keyLocation -ErrorAction SilentlyContinue; } return $item; } foreach ($item in (Get-ChildItem -Path $uninstallKey, $uninstallKeyWow64 -ErrorAction Ignore)) { $installedProduct = Get-LocalizableRegistryKeyValue -RegistryKey $item -ValueName 'DisplayName'; if ($installedProduct) { $installedProduct = $installedProduct.Trim(); } if ($Name -eq $installedProduct) { return $item; } } if ($InstalledCheckRegKey -and ($InstalledCheckRegValueName -and $InstalledCheckRegValueData)) { $installValue = $null; $getRegistryValueIgnoreErrorParams = @{ RegistryHive = $InstalledCheckRegHive; Key = $InstalledCheckRegKey; Value = $InstalledCheckRegValueName; } #if 64bit OS, check 64bit registry view first if ([System.Environment]::Is64BitOperatingSystem) { $getRegistryValueIgnoreErrorParams['RegistryView'] = [Microsoft.Win32.RegistryView]::Registry64; $installValue = Get-RegistryValueIgnoreError @getRegistryValueIgnoreErrorParams; } if ($null -eq $installValue) { $getRegistryValueIgnoreErrorParams['RegistryView'] = [Microsoft.Win32.RegistryView]::Registry32; $installValue = Get-RegistryValueIgnoreError @getRegistryValueIgnoreErrorParams; } if ($installValue) { if ($InstalledCheckRegValueData -and ($installValue -eq $InstalledCheckRegValueData)) { return @{ Installed = $true; } } } } return $null; } #end process } #end function Get-InstalledProductEntry
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/DSCResources/ROSSCommon/Src/Get-RegistryValueIgnoreError.ps1
Get-RegistryValueIgnoreError.ps1
function Get-RegistryValueIgnoreError { <# .NOTES https://github.com/PowerShell/xPSDesiredStateConfiguration/blob/dev/DSCResources/MSFT_xPackageResource/MSFT_xPackageResource.psm1 #> param ( [Parameter(Mandatory)] [Microsoft.Win32.RegistryHive] $RegistryHive, [Parameter(Mandatory)] [System.String] $Key, [Parameter(Mandatory)] [System.String] $Value, [Parameter(Mandatory)] [Microsoft.Win32.RegistryView] $RegistryView ) process { try { $baseKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey($RegistryHive, $RegistryView); $subKey = $baseKey.OpenSubKey($Key); if ($null -ne $subKey) { return $subKey.GetValue($Value); } } catch { $exceptionText = ($_ | Out-String).Trim(); Write-Verbose "Exception occured in Get-RegistryValueIgnoreError: $exceptionText"; } return $null; } #end process } #end function Get-RegistryValueIgnoreError
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/DSCResources/ROSSCommon/Src/Get-LocalizableRegistryKeyValue.ps1
Get-LocalizableRegistryKeyValue.ps1
function Get-LocalizableRegistryKeyValue { <# .NOTES https://github.com/PowerShell/xPSDesiredStateConfiguration/blob/dev/DSCResources/MSFT_xPackageResource/MSFT_xPackageResource.psm1 #> [CmdletBinding()] param ( [Parameter(Mandatory)] [System.Object] $RegistryKey, [Parameter(Mandatory)] [System.String] $ValueName ) process { $result = $RegistryKey.GetValue("{0}_Localized" -f $ValueName); if (-not $result) { $result = $RegistryKey.GetValue($ValueName); } return $result; } } #end function Get-LocalizableRegistryKeyValue
PowerShellCorpus/PowerShellGallery/RESONEServiceStore/2.3.0/Examples/RESONEServiceStoreLabExample.ps1
RESONEServiceStoreLabExample.ps1
$config = @{ AllNodes = @( @{ NodeName = 'localhost'; PSDSCAllowPlainTextPassword = $true; ROSSDatabaseServer = 'controller.lab.local'; ROSSDatabaseName = 'RESONEServiceStore'; ROSSBinariesFolder = 'C:\SharedData\Software\RES\ONE Service Store 2015\FR2'; ROSSBinariesVersion = '8.0'; ROSSHostHeader = 'itstore.lab.local'; ROSSDefaultDomain = 'LAB'; } ) } configuration RESONEServiceStoreLabExample { param ( ## RES ONE Service Store SQL database/user credential [Parameter(Mandatory)] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, ## Microsoft SQL Server credentials used to create the RES ONE Service Store database/user [Parameter(Mandatory)] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $SQLCredential ) Import-DscResource -ModuleName RESONEServiceStore, xWebAdministration; node 'localhost' { ROSSLab 'ROSSLab' { DatabaseServer = $node.ROSSDatabaseServer; DatabaseName = $node.ROSSDatabaseName; Credential = $Credential; SQLCredential = $SQLCredential; CatalogServicesCredential = $Credential; Path = $node.ROSSBinariesFolder; Version = $node.ROSSBinariesVersion; HostHeader = $node.ROSSHostHeader; DefaultDomain = $node.ROSSDefaultDomain; } xWebAppPool 'ITStoreMangementWebAppPool' { Name = 'IT Store Management'; IdentityType = 'LocalSystem'; DependsOn = '[ROSSLab]ROSSLab'; } } } #end configuration RESONEServiceStoreLabExample if (-not $cred) { $cred = Get-Credential -UserName 'RESONEWorkspace' -Message 'RES ONE Service Store SQL account credential'; } if (-not $sqlCred) { $sqlCred = Get-Credential -UserName 'sa' -Message 'Existing SQL account for database creation'; } RESONEServiceStoreLabExample -OutputPath ~\Documents -ConfigurationData $config -Credential $cred -SQLCredential $sqlCred;