full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSIoTTopicRuleDynamoDBAction.ps1
Add-VSIoTTopicRuleDynamoDBAction.ps1
function Add-VSIoTTopicRuleDynamoDBAction { <# .SYNOPSIS Adds an AWS::IoT::TopicRule.DynamoDBAction resource property to the template .DESCRIPTION Adds an AWS::IoT::TopicRule.DynamoDBAction resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html .PARAMETER HashKeyField Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-hashkeyfield PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER HashKeyValue Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-hashkeyvalue PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER PayloadField Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-payloadfield PrimitiveType: String Required: False UpdateType: Mutable .PARAMETER RangeKeyField Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-rangekeyfield PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER RangeKeyValue Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-rangekeyvalue PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER RoleArn Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-rolearn PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER TableName Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-dynamodb.html#cfn-iot-dynamodb-tablename PrimitiveType: String Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.IoT.TopicRule.DynamoDBAction')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $HashKeyField, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $HashKeyValue, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $PayloadField, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $RangeKeyField, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $RangeKeyValue, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $RoleArn, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $TableName ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.IoT.TopicRule.DynamoDBAction' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSEMRInstanceGroupConfigScalingConstraints.ps1
Add-VSEMRInstanceGroupConfigScalingConstraints.ps1
function Add-VSEMRInstanceGroupConfigScalingConstraints { <# .SYNOPSIS Adds an AWS::EMR::InstanceGroupConfig.ScalingConstraints resource property to the template .DESCRIPTION Adds an AWS::EMR::InstanceGroupConfig.ScalingConstraints resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingconstraints.html .PARAMETER MaxCapacity Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingconstraints.html#cfn-elasticmapreduce-instancegroupconfig-scalingconstraints-maxcapacity PrimitiveType: Integer Required: True UpdateType: Mutable .PARAMETER MinCapacity Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingconstraints.html#cfn-elasticmapreduce-instancegroupconfig-scalingconstraints-mincapacity PrimitiveType: Integer Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.EMR.InstanceGroupConfig.ScalingConstraints')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [Int] $MaxCapacity, [parameter(Mandatory = $true)] [Int] $MinCapacity ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.EMR.InstanceGroupConfig.ScalingConstraints' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSOpsWorksAppEnvironmentVariable.ps1
Add-VSOpsWorksAppEnvironmentVariable.ps1
function Add-VSOpsWorksAppEnvironmentVariable { <# .SYNOPSIS Adds an AWS::OpsWorks::App.EnvironmentVariable resource property to the template .DESCRIPTION Adds an AWS::OpsWorks::App.EnvironmentVariable resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html .PARAMETER Key Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html#cfn-opsworks-app-environment-key PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER Secure Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html#cfn-opsworks-app-environment-secure PrimitiveType: Boolean Required: False UpdateType: Mutable .PARAMETER Value Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html#value PrimitiveType: String Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.OpsWorks.App.EnvironmentVariable')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Key, [parameter(Mandatory = $false)] [System.Boolean] $Secure, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Value ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.OpsWorks.App.EnvironmentVariable' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSDataPipelinePipelineParameterObject.ps1
Add-VSDataPipelinePipelineParameterObject.ps1
function Add-VSDataPipelinePipelineParameterObject { <# .SYNOPSIS Adds an AWS::DataPipeline::Pipeline.ParameterObject resource property to the template .DESCRIPTION Adds an AWS::DataPipeline::Pipeline.ParameterObject resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html .PARAMETER Attributes Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html#cfn-datapipeline-pipeline-parameterobjects-attributes DuplicatesAllowed: True ItemType: ParameterAttribute Required: True Type: List UpdateType: Mutable .PARAMETER Id Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html#cfn-datapipeline-pipeline-parameterobject-id PrimitiveType: String Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.DataPipeline.Pipeline.ParameterObject')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "Vaporshell.Resource.DataPipeline.Pipeline.ParameterAttribute" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Attributes, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Id ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.DataPipeline.Pipeline.ParameterObject' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSDirectoryServiceMicrosoftADVpcSettings.ps1
Add-VSDirectoryServiceMicrosoftADVpcSettings.ps1
function Add-VSDirectoryServiceMicrosoftADVpcSettings { <# .SYNOPSIS Adds an AWS::DirectoryService::MicrosoftAD.VpcSettings resource property to the template .DESCRIPTION Adds an AWS::DirectoryService::MicrosoftAD.VpcSettings resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-microsoftad-vpcsettings.html .PARAMETER SubnetIds Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-microsoftad-vpcsettings.html#cfn-directoryservice-microsoftad-vpcsettings-subnetids DuplicatesAllowed: False PrimitiveItemType: String Required: True Type: List UpdateType: Mutable .PARAMETER VpcId Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-microsoftad-vpcsettings.html#cfn-directoryservice-microsoftad-vpcsettings-vpcid PrimitiveType: String Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.DirectoryService.MicrosoftAD.VpcSettings')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] $SubnetIds, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $VpcId ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.DirectoryService.MicrosoftAD.VpcSettings' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSWAFRegionalWebACLRule.ps1
Add-VSWAFRegionalWebACLRule.ps1
function Add-VSWAFRegionalWebACLRule { <# .SYNOPSIS Adds an AWS::WAFRegional::WebACL.Rule resource property to the template .DESCRIPTION Adds an AWS::WAFRegional::WebACL.Rule resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html .PARAMETER Action Type: Action Required: True Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html#cfn-wafregional-webacl-rule-action UpdateType: Mutable .PARAMETER Priority Required: True Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html#cfn-wafregional-webacl-rule-priority PrimitiveType: Integer UpdateType: Mutable .PARAMETER RuleId Required: True Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html#cfn-wafregional-webacl-rule-ruleid PrimitiveType: String UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.WAFRegional.WebACL.Rule')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] $Action, [parameter(Mandatory = $true)] [Int] $Priority, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $RuleId ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.WAFRegional.WebACL.Rule' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSCodeBuildProjectSourceAuth.ps1
Add-VSCodeBuildProjectSourceAuth.ps1
function Add-VSCodeBuildProjectSourceAuth { <# .SYNOPSIS Adds an AWS::CodeBuild::Project.SourceAuth resource property to the template .DESCRIPTION Adds an AWS::CodeBuild::Project.SourceAuth resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html .PARAMETER Type Required: False Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html#cfn-codebuild-project-sourceauth-type PrimitiveType: String UpdateType: Mutable .PARAMETER Resource Required: False Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html#cfn-codebuild-project-sourceauth-resource PrimitiveType: String UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.CodeBuild.Project.SourceAuth')] [cmdletbinding()] Param ( [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Type, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Resource ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.CodeBuild.Project.SourceAuth' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSEMRInstanceGroupConfigSimpleScalingPolicyConfiguration.ps1
Add-VSEMRInstanceGroupConfigSimpleScalingPolicyConfiguration.ps1
function Add-VSEMRInstanceGroupConfigSimpleScalingPolicyConfiguration { <# .SYNOPSIS Adds an AWS::EMR::InstanceGroupConfig.SimpleScalingPolicyConfiguration resource property to the template .DESCRIPTION Adds an AWS::EMR::InstanceGroupConfig.SimpleScalingPolicyConfiguration resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html .PARAMETER AdjustmentType Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration-adjustmenttype PrimitiveType: String Required: False UpdateType: Mutable .PARAMETER CoolDown Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration-cooldown PrimitiveType: Integer Required: False UpdateType: Mutable .PARAMETER ScalingAdjustment Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration-scalingadjustment PrimitiveType: Integer Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.EMR.InstanceGroupConfig.SimpleScalingPolicyConfiguration')] [cmdletbinding()] Param ( [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $AdjustmentType, [parameter(Mandatory = $false)] [Int] $CoolDown, [parameter(Mandatory = $true)] [Int] $ScalingAdjustment ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.EMR.InstanceGroupConfig.SimpleScalingPolicyConfiguration' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSEC2SpotFleetBlockDeviceMappings.ps1
Add-VSEC2SpotFleetBlockDeviceMappings.ps1
function Add-VSEC2SpotFleetBlockDeviceMappings { <# .SYNOPSIS Adds an AWS::EC2::SpotFleet.BlockDeviceMappings resource property to the template .DESCRIPTION Adds an AWS::EC2::SpotFleet.BlockDeviceMappings resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html .PARAMETER DeviceName Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemappings-devicename PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER Ebs Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemappings-ebs Required: False Type: Ebs UpdateType: Mutable .PARAMETER NoDevice Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemappings-nodevice PrimitiveType: Boolean Required: False UpdateType: Mutable .PARAMETER VirtualName Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemappings-virtualname PrimitiveType: String Required: False UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.EC2.SpotFleet.BlockDeviceMappings')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $DeviceName, [parameter(Mandatory = $false)] $Ebs, [parameter(Mandatory = $false)] [System.Boolean] $NoDevice, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $VirtualName ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.EC2.SpotFleet.BlockDeviceMappings' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSOpsWorksStackElasticIp.ps1
Add-VSOpsWorksStackElasticIp.ps1
function Add-VSOpsWorksStackElasticIp { <# .SYNOPSIS Adds an AWS::OpsWorks::Stack.ElasticIp resource property to the template .DESCRIPTION Adds an AWS::OpsWorks::Stack.ElasticIp resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-elasticip.html .PARAMETER Ip Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-elasticip.html#cfn-opsworks-stack-elasticip-ip PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER Name Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-elasticip.html#cfn-opsworks-stack-elasticip-name PrimitiveType: String Required: False UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.OpsWorks.Stack.ElasticIp')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Ip, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Name ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.OpsWorks.Stack.ElasticIp' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSEMRClusterVolumeSpecification.ps1
Add-VSEMRClusterVolumeSpecification.ps1
function Add-VSEMRClusterVolumeSpecification { <# .SYNOPSIS Adds an AWS::EMR::Cluster.VolumeSpecification resource property to the template .DESCRIPTION Adds an AWS::EMR::Cluster.VolumeSpecification resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html .PARAMETER Iops Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification-iops PrimitiveType: Integer Required: False UpdateType: Mutable .PARAMETER SizeInGB Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification-sizeingb PrimitiveType: Integer Required: True UpdateType: Mutable .PARAMETER VolumeType Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification-volumetype PrimitiveType: String Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.EMR.Cluster.VolumeSpecification')] [cmdletbinding()] Param ( [parameter(Mandatory = $false)] [Int] $Iops, [parameter(Mandatory = $true)] [Int] $SizeInGB, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $VolumeType ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.EMR.Cluster.VolumeSpecification' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSDynamoDBTableAttributeDefinition.ps1
Add-VSDynamoDBTableAttributeDefinition.ps1
function Add-VSDynamoDBTableAttributeDefinition { <# .SYNOPSIS Adds an AWS::DynamoDB::Table.AttributeDefinition resource property to the template .DESCRIPTION Adds an AWS::DynamoDB::Table.AttributeDefinition resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html .PARAMETER AttributeName Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html#cfn-dynamodb-attributedef-attributename PrimitiveType: String Required: True UpdateType: Mutable .PARAMETER AttributeType Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html#cfn-dynamodb-attributedef-attributename-attributetype PrimitiveType: String Required: True UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.DynamoDB.Table.AttributeDefinition')] [cmdletbinding()] Param ( [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $AttributeName, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $AttributeType ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.DynamoDB.Table.AttributeDefinition' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Resource Property Types/Add-VSEC2SpotFleetSpotPlacement.ps1
Add-VSEC2SpotFleetSpotPlacement.ps1
function Add-VSEC2SpotFleetSpotPlacement { <# .SYNOPSIS Adds an AWS::EC2::SpotFleet.SpotPlacement resource property to the template .DESCRIPTION Adds an AWS::EC2::SpotFleet.SpotPlacement resource property to the template .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html .PARAMETER AvailabilityZone Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-availabilityzone PrimitiveType: String Required: False UpdateType: Mutable .PARAMETER GroupName Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-groupname PrimitiveType: String Required: False UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.EC2.SpotFleet.SpotPlacement')] [cmdletbinding()] Param ( [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $AvailabilityZone, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $GroupName ) Begin { $obj = [PSCustomObject]@{} } Process { foreach ($key in $PSBoundParameters.Keys) { $val = $((Get-Variable $key).Value) if ($val -eq "True") { $val = "true" } elseif ($val -eq "False") { $val = "false" } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $val } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.EC2.SpotFleet.SpotPlacement' } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Primary Functions/New-VaporCondition.ps1
New-VaporCondition.ps1
function New-VaporCondition { <# .SYNOPSIS Adds a Condition object to the template .DESCRIPTION The optional Conditions section includes statements that define when a resource is created or when a property is defined. For example, you can compare whether a value is equal to another value. Based on the result of that condition, you can conditionally create resources. If you have multiple conditions, separate them with commas. You might use conditions when you want to reuse a template that can create resources in different contexts, such as a test environment versus a production environment. In your template, you can add an EnvironmentType input parameter, which accepts either prod or test as inputs. For the production environment, you might include Amazon EC2 instances with certain capabilities; however, for the test environment, you want to use reduced capabilities to save money. With conditions, you can define which resources are created and how they're configured for each environment type. Conditions are evaluated based on input parameter values that you specify when you create or update a stack. Within each condition, you can reference another condition, a parameter value, or a mapping. After you define all your conditions, you can associate them with resources and resource properties in the Resources and Outputs sections of a template. At stack creation or stack update, AWS CloudFormation evaluates all the conditions in your template before creating any resources. Any resources that are associated with a true condition are created. Any resources that are associated with a false condition are ignored. ** Important ** During a stack update, you cannot update conditions by themselves. You can update conditions only when you include changes that add, modify, or delete resources. To conditionally create resources, you must include statements in at least three different sections of a template: Parameters section Define the input values that you want to evaluate in your conditions. Conditions will result in true or false based on values from these input parameter. Conditions section Define conditions by using the intrinsic condition functions. These conditions determine when AWS CloudFormation creates the associated resources. Resources and Outputs sections Associate conditions with the resources or outputs that you want to conditionally create. AWS CloudFormation creates entities that are associated with a true condition and ignores entities that are associated with a false condition. Use the Condition key and a condition's logical ID to associate it with a resource or output. To conditionally specify a property, use the Fn::If function. For more information, see Condition Functions. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html .PARAMETER LogicalId An identifier for the current condition. The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template. .PARAMETER Condition Logical ID of the condition that this resource needs to be true in order to be provisioned. .EXAMPLE $template = Initialize-Vaporshell -Description "Testing Condition addition" $template.AddResource(( New-VaporCondition -LogicalId "CreateProdResources" -Condition (Add-ConEquals -FirstValue (Add-FnRef -Ref "EnvType") -SecondValue "prod") )) When the template is exported, this will convert to: { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Testing Condition addition", "Conditions": { "CreateProdResources": { "Fn::Equals": [ { "Ref": "EnvType" }, "prod" ] } } } .NOTES You can use the following intrinsic functions to define conditions: Fn::And Fn::Equals Fn::If Fn::Not Fn::Or .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Condition')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { throw 'The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.' } })] [System.String] $LogicalId, [parameter(Mandatory = $true,Position = 1)] [ValidateScript( { $allowedTypes = "Vaporshell.Condition.And","Vaporshell.Condition.Equals","Vaporshell.Condition.If","Vaporshell.Condition.Not","Vaporshell.Condition.Or" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "The Condition parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Condition ) $obj = [PSCustomObject][Ordered]@{ "LogicalId" = $LogicalId "Props" = $Condition } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Condition' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n`t$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5 -Compress)`n" }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Primary Functions/New-VaporOutput.ps1
New-VaporOutput.ps1
function New-VaporOutput { <# .SYNOPSIS Adds an Output object to the template .DESCRIPTION The optional Outputs section declares output values that you can import into other stacks (to create cross-stack references), return in response (to describe stack calls), or view on the AWS CloudFormation console. For example, you can output the S3 bucket name for a stack to make the bucket easier to find. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html .PARAMETER LogicalId An identifier for the current output. The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template. .PARAMETER Description A String type that describes the output value. The description can be a maximum of 4 K in length. .PARAMETER Value The value of the property returned by the aws cloudformation describe-stacks command. The value of an output can include literals, parameter references, pseudo-parameters, a mapping value, or intrinsic functions. .PARAMETER Export The name of the resource output to be exported for a cross-stack reference. Note The following restrictions apply to cross-stack references: * For each AWS account, Export names must be unique within a region. * You can't create cross-stack references across regions. You can use the intrinsic function Fn::ImportValue to import only values that have been exported within the same region. * For outputs, the value of the Name property of an Export can't use Ref or GetAtt functions that depend on a resource. * Similarly, the ImportValue function can't include Ref or GetAtt functions that depend on a resource. * You can't delete a stack if another stack references one of its outputs. * You can't modify or remove an output value that is referenced by another stack. * You can use intrinsic functions to customize the Name value of an export. .PARAMETER Condition Logical ID of the condition that this output needs to be true in order to be provisioned. .EXAMPLE $template = Initialize-Vaporshell -Description "Testing Output" $template.AddOutput( ( New-VaporOutput -LogicalId "BackupLoadBalancerDNSName" -Description "The DNSName of the backup load balancer" -Value (Add-FnGetAtt -LogicalNameOfResource "BackupLoadBalancer" -AttributeName "DNSName") -Condition "CreateProdResources" ) ) When the template is exported, this will convert to: { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Testing Output", "Outputs": { "BackupLoadBalancerDNSName": { "Description": "The DNSName of the backup load balancer", "Value": { "Fn::GetAtt": [ "BackupLoadBalancer", "DNSName" ] }, "Condition": "CreateProdResources" } } } .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Output')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { throw 'The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.' } })] [System.String] $LogicalId, [parameter(Mandatory = $false,Position = 1)] [System.String] $Description, [parameter(Mandatory = $true,Position = 2)] $Value, [parameter(Mandatory = $false,Position = 3)] $Export, [parameter(Mandatory = $false,Position = 4)] $Condition ) if ($Description) { $Properties = [PSCustomObject][Ordered]@{ "Description" = "$Description" "Value" = $Value } } else { $Properties = [PSCustomObject][Ordered]@{ "Value" = $Value } } if ($Export) { $Properties | Add-Member -MemberType NoteProperty -Name "Export" -Value $Export } if ($Condition) { $Properties | Add-Member -MemberType NoteProperty -Name "Condition" -Value $Condition } $obj = [PSCustomObject][Ordered]@{ "LogicalId" = $LogicalId "Props" = $Properties } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Output' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n`t$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5 -Compress)`n" }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Primary Functions/New-VaporMapping.ps1
New-VaporMapping.ps1
function New-VaporMapping { <# .SYNOPSIS Adds a Mapping object to the template .DESCRIPTION The optional Mappings section matches a key to a corresponding set of named values. For example, if you want to set values based on a region, you can create a mapping that uses the region name as a key and contains the values you want to specify for each specific region. You use the Fn::FindInMap intrinsic function to retrieve values in a map. You cannot include parameters, pseudo parameters, or intrinsic functions in the Mappings section. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html .PARAMETER LogicalId An identifier for the current condition. The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template. .PARAMETER Map A 2 level collection of key/value pairs. If you would like your collection to remain ordered the same as called, use an ordered PSCustomObject, otherwise a hashtable is fine. You can use any of these 3 types for this parameter; "System.Collections.Hashtable","System.Management.Automation.PSCustomObject","Vaporshell.Mapping.Map" .EXAMPLE $template = Initialize-Vaporshell -Description "Testing Mapping addition" $template.AddMapping(( New-VaporMapping -LogicalId "RegionMap" -Map ([PSCustomObject][Ordered]@{ "us-east-1" = [PSCustomObject][Ordered]@{ "32" = "ami-6411e20d" "64" = "ami-7a11e213" } "us-west-1" = [PSCustomObject][Ordered]@{ "32" = "ami-c9c7978c" "64" = "ami-cfc7978a" } "eu-west-1" = [PSCustomObject][Ordered]@{ "32" = "ami-37c2f643" "64" = "ami-31c2f645" } "ap-southeast-1" = [PSCustomObject][Ordered]@{ "32" = "ami-66f28c34" "64" = "ami-60f28c32" } "ap-northeast-1" = [PSCustomObject][Ordered]@{ "32" = "ami-9c03a89d" "64" = "ami-a003a8a1" } }) )) When the template is exported, this will convert to: { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Testing Mapping addition", "Mappings": { "RegionMap": { "us-east-1": { "32": "ami-6411e20d", "64": "ami-7a11e213" }, "us-west-1": { "32": "ami-c9c7978c", "64": "ami-cfc7978a" }, "eu-west-1": { "32": "ami-37c2f643", "64": "ami-31c2f645" }, "ap-southeast-1": { "32": "ami-66f28c34", "64": "ami-60f28c32" }, "ap-northeast-1": { "32": "ami-9c03a89d", "64": "ami-a003a8a1" } } } } .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Mapping')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { throw 'The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.' } })] [System.String] $LogicalId, [parameter(Mandatory = $true,Position = 1)] [ValidateScript( { $allowedTypes = "System.Collections.Hashtable","System.Management.Automation.PSCustomObject","Vaporshell.Mapping.Map" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "The Map parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Map ) $obj = [PSCustomObject][Ordered]@{ "LogicalId" = $LogicalId "Props" = $Map } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Mapping' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n`t$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5 -Compress)`n" }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Primary Functions/New-VaporMetadata.ps1
New-VaporMetadata.ps1
function New-VaporMetadata { <# .SYNOPSIS Adds a Metadata object to the template .DESCRIPTION You can use the optional Metadata section to include arbitrary JSON or YAML objects that provide details about the template. ** Important ** During a stack update, you cannot update the Metadata section by itself. You can update it only when you include changes that add, modify, or delete resources. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html .PARAMETER LogicalId An identifier for the current condition. The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template. .PARAMETER Metadata Key/Value pair. You can use any of these 3 types for this parameter; "System.Collections.Hashtable","System.Management.Automation.PSCustomObject","Vaporshell.Metadata.Data" .PARAMETER NoEcho Whether to mask the parameter value whenever anyone makes a call that describes the stack. If you set the value to true, the parameter value is masked with asterisks (*****). .EXAMPLE $template = Initialize-Vaporshell -Description "Testing Metadata addition" $template.AddMetadata( (New-VaporMetadata -LogicalId "Instances" -Metadata [PSCustomObject]@{"Description" = "Information about the instances"}), (New-VaporMetadata -LogicalId "Databases" -Metadata [PSCustomObject]@{"Description" = "Information about the databases"}) ) When the template is exported, this will convert to: { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Testing Metadata addition", "Metadata": { "Instances": { "Description": "Information about the instances" }, "Databases": { "Description": "Information about the databases" } } } .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Metadata')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { throw 'The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.' } })] [System.String] $LogicalId, [parameter(Mandatory = $true,Position = 1)] [ValidateScript( { $allowedTypes = "System.Collections.Hashtable","System.Management.Automation.PSCustomObject","Vaporshell.Metadata.Data" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "The Metadata parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Metadata ) $obj = [PSCustomObject][Ordered]@{ "LogicalId" = $LogicalId "Props" = $Metadata } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Metadata' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n`t$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5 -Compress)`n" }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Primary Functions/New-VaporParameter.ps1
New-VaporParameter.ps1
function New-VaporParameter { <# .SYNOPSIS Adds a Parameter object to the template .DESCRIPTION You can use the optional Parameters section to pass values into your template when you create a stack. With parameters, you can create templates that are customized each time you create a stack. Each parameter must contain a value when you create a stack. You can specify a default value to make the parameter optional so that you don't need to pass in a value when creating a stack. AWS CloudFormation will use the default value. For more information about creating stacks, see Working with Stacks. The Parameters section consists of the key name Parameters. You can have a maximum of 60 parameters in an AWS CloudFormation template. For each parameter, you must declare a logical name, which must be alphanumeric and unique among all logical names within the template. After you declare the parameter's logical name, you can specify the parameter's properties. You must declare parameters as one of following types: String, Number, CommaDelimitedList, or an AWS-specific type. For String, Number, and AWS-specific parameter types, you can define constraints that AWS CloudFormation uses to validate the value of the parameter. AWS-specific parameter types are AWS values such as Amazon EC2 key pair names and VPC IDs. AWS CloudFormation validates these parameter values against existing values in users' AWS accounts. AWS-specific parameter types are helpful in catching invalid values at the start of creating or updating a stack. ** Important ** For sensitive parameter values (such as passwords), set the NoEcho property to true. That way, whenever anyone describes your stack, the parameter value is shown as asterisks (*****). .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html .PARAMETER LogicalId An identifier for the current condition. The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template. .PARAMETER Type The Properties type for the parameter (PropertiesType). Required: Yes You can specify the following values for the Type property: String A literal string. For example, users could specify "MyUserName". Number An integer or float. AWS CloudFormation validates the parameter value as a number; however, when you use the parameter elsewhere in your template (for example, by using the Ref intrinsic function), the parameter value becomes a string. For example, users could specify "8888". List<Number> An array of integers or floats that are separated by commas. AWS CloudFormation validates the parameter value as numbers; however, when you use the parameter elsewhere in your template (for example, by using the Ref intrinsic function), the parameter value becomes a list of strings. For example, users could specify "80,20", and a Ref will result in ["80","20"]. CommaDelimitedList An array of literal strings that are separated by commas. The total number of strings should be one more than the total number of commas. Also, each member string is space trimmed. For example, users could specify "test,dev,prod", and a Ref will result in ["test","dev","prod"]. AWS-Specific Parameter Types For AWS-specific parameter types, template users must specify existing AWS values that are in their account. AWS CloudFormation supports the following AWS-specific types: AWS::EC2::AvailabilityZone::Name An Availability Zone, such as us-west-2a. AWS::EC2::Image::Id An Amazon EC2 image ID, such as ami-ff527ecf. Note that the AWS CloudFormation console won't show a drop-down list of values for this parameter type. AWS::EC2::Instance::Id An Amazon EC2 instance ID, such as i-1e731a32. AWS::EC2::KeyPair::KeyName An Amazon EC2 key pair name. AWS::EC2::SecurityGroup::GroupName An EC2-Classic or default VPC security group name, such as my-sg-abc. AWS::EC2::SecurityGroup::Id A security group ID, such as sg-a123fd85. AWS::EC2::Subnet::Id A subnet ID, such as subnet-123a351e. AWS::EC2::Volume::Id An Amazon EBS volume ID, such as vol-3cdd3f56. AWS::EC2::VPC::Id A VPC ID, such as vpc-a123baa3. AWS::Route53::HostedZone::Id An Amazon Route 53 hosted zone ID, such as Z23YXV4OVPL04A. List<AWS::EC2::AvailabilityZone::Name> An array of Availability Zones for a region, such as us-west-2a, us-west-2b. List<AWS::EC2::Image::Id> An array of Amazon EC2 image IDs, such as ami-ff527ecf, ami-e7527ed7. Note that the AWS CloudFormation console won't show a drop-down list of values for this parameter type. List<AWS::EC2::Instance::Id> An array of Amazon EC2 instance IDs, such as i-1e731a32, i-1e731a34. List<AWS::EC2::SecurityGroup::GroupName> An array of EC2-Classic or default VPC security group names, such as my-sg-abc, my-sg-def. List<AWS::EC2::SecurityGroup::Id> An array of security group IDs, such as sg-a123fd85, sg-b456fd85. List<AWS::EC2::Subnet::Id> An array of subnet IDs, such as subnet-123a351e, subnet-456b351e. List<AWS::EC2::Volume::Id> An array of Amazon EBS volume IDs, such as vol-3cdd3f56, vol-4cdd3f56. List<AWS::EC2::VPC::Id> An array of VPC IDs, such as vpc-a123baa3, vpc-b456baa3. List<AWS::Route53::HostedZone::Id> An array of Amazon Route 53 hosted zone IDs, such as Z23YXV4OVPL04A, Z23YXV4OVPL04B. AWS CloudFormation validates input values for these types against existing values in a user's account. For example, with the AWS::EC2::VPC::Id type, a user must enter an existing VPC ID that is in her account and in the region in which she is creating the stack. Group and Sort Parameters in the AWS CloudFormation Console When you use the AWS CloudFormation console to create or update a stack, the console alphabetically lists input parameters by their logical ID. To override the default ordering, you can use the AWS::CloudFormation::Interface metaProperties key. By grouping and ordering parameters, you make it easier for users to specify parameter values. For example, you could group all VPC-related parameters so that they aren't scattered throughout an alphabetical list. In the metaProperties key, you can specify the groups to create, the parameters to include in each group, and the order in which the console shows each parameter within its group. You can also define friendly parameter names so that the console shows descriptive names instead of logical IDs. All parameters that you reference in the metaProperties key must be declared in the Parameters section of the template. .PARAMETER Default A value of the appropriate type for the template to use if no value is specified when a stack is created. If you define constraints for the parameter, you must specify a value that adheres to those constraints. .PARAMETER NoEcho Whether to mask the parameter value whenever anyone makes a call that describes the stack. If you set the value to true, the parameter value is masked with asterisks (*****). .PARAMETER AllowedPattern A regular expression that represents the patterns you want to allow for String types. .PARAMETER AllowedValues An array containing the list of values allowed for the parameter. .PARAMETER ConstraintDescription A string that explains the constraint when the constraint is violated. .PARAMETER Description A string of up to 4000 characters that describes the parameter. .PARAMETER MaxLength An integer value that determines the largest number of characters you want to allow for String types. .PARAMETER MaxValue A numeric value that determines the largest numeric value you want to allow for Number types. .PARAMETER MinLength An integer value that determines the smallest number of characters you want to allow for String types. .PARAMETER MinValue A numeric value that determines the smallest numeric value you want to allow for Number types. .EXAMPLE $template = Initialize-Vaporshell -Description "Testing Mapping addition" $template.AddParameter( (New-VaporParameter -LogicalId "DBPort" -Default 3306 -Description "TCP/IP port for the Propertiesbase" -Type "Number" -MinValue 1150 -MaxValue 65535), (New-VaporParameter -LogicalId "DBPwd" -NoEcho -Description "The Propertiesbase admin account password" -Type "String" -MinLength 1 -MaxLength 41 -AllowedPattern "^[a-zA-Z0-9]*$") ) When the template is exported, this will convert to: { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Testing Mapping addition", "Parameters": { "DBPwd": { "Type": "String", "NoEcho": { "IsPresent": true }, "Description": "The Propertiesbase admin account password", "MinLength": 1, "MaxLength": 41, "AllowedPattern": "^[a-zA-Z0-9]*$" }, "DBPort": { "Type": "Number", "Default": "3306", "Description": "TCP/IP port for the Propertiesbase", "MinValue": 1150, "MaxValue": 65535 } } } .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Parameter')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { throw 'The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.' } })] [System.String] $LogicalId, [parameter(Mandatory = $true,Position = 1)] [ValidateSet("String","Number","List<Number>","CommaDelimitedList","AWS::EC2::AvailabilityZone::Name","AWS::EC2::Image::Id","AWS::EC2::Instance::Id","AWS::EC2::KeyPair::KeyName","AWS::EC2::SecurityGroup::GroupName","AWS::EC2::SecurityGroup::Id","AWS::EC2::Subnet::Id","AWS::EC2::Volume::Id","AWS::EC2::VPC::Id","AWS::Route53::HostedZone::Id","List<AWS::EC2::AvailabilityZone::Name>","List<AWS::EC2::Image::Id>","List<AWS::EC2::Instance::Id>","List<AWS::EC2::SecurityGroup::GroupName>","List<AWS::EC2::SecurityGroup::Id>","List<AWS::EC2::Subnet::Id>","List<AWS::EC2::Volume::Id>","List<AWS::EC2::VPC::Id>","List<AWS::Route53::HostedZone::Id>")] [System.String] $Type, [parameter(Mandatory = $false,Position = 2)] [System.String] $Default, [parameter(Mandatory = $false,Position = 3)] [Switch] $NoEcho, [parameter(Mandatory = $false,Position = 4)] [System.String] $AllowedPattern, [parameter(Mandatory = $false,Position = 5)] [System.String[]] $AllowedValues, [parameter(Mandatory = $false,Position = 6)] [System.String] $ConstraintDescription, [parameter(Mandatory = $false,Position = 7)] [ValidateScript( { if ($_.Length -le 4000) { $true } else { throw "The description length needs to be less than 4000 characters long." } })] [System.String] $Description, [parameter(Mandatory = $false,Position = 8)] [Int] $MaxLength, [parameter(Mandatory = $false,Position = 9)] [Int] $MaxValue, [parameter(Mandatory = $false,Position = 10)] [Int] $MinLength, [parameter(Mandatory = $false,Position = 11)] [Int] $MinValue ) Begin { $Properties = [PSCustomObject][Ordered]@{ "Type" = $Type } } Process { switch ($PSBoundParameters.Keys) { 'Default' { $Properties | Add-Member -MemberType NoteProperty -Name Default -Value $Default } 'NoEcho' { $Properties | Add-Member -MemberType NoteProperty -Name NoEcho -Value ([string]$NoEcho).ToLower() } 'AllowedPattern' { $Properties | Add-Member -MemberType NoteProperty -Name AllowedPattern -Value $AllowedPattern } 'AllowedValues' { $Properties | Add-Member -MemberType NoteProperty -Name AllowedValues -Value @($AllowedValues) } 'ConstraintDescription' { $Properties | Add-Member -MemberType NoteProperty -Name ConstraintDescription -Value $ConstraintDescription } 'Description' { $Properties | Add-Member -MemberType NoteProperty -Name Description -Value $Description } 'MaxLength' { $Properties | Add-Member -MemberType NoteProperty -Name MaxLength -Value $MaxLength } 'MaxValue' { $Properties | Add-Member -MemberType NoteProperty -Name MaxValue -Value $MaxValue } 'MinLength' { $Properties | Add-Member -MemberType NoteProperty -Name MinLength -Value $MinLength } 'MinValue' { $Properties | Add-Member -MemberType NoteProperty -Name MinValue -Value $MinValue } } } End { $obj = [PSCustomObject][Ordered]@{ "LogicalId" = $LogicalId "Props" = $Properties } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Parameter' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n`t$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5 -Compress)`n" } }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Primary Functions/New-VaporResource.ps1
New-VaporResource.ps1
function New-VaporResource { <# .SYNOPSIS Adds a Resource object to the template .DESCRIPTION The required Resources section declares the AWS resources that you want to include in the stack, such as an Amazon EC2 instance or an Amazon S3 bucket. You must declare each resource separately; however, if you have multiple resources of the same type, you can declare them together by separating them with commas. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html .PARAMETER LogicalId The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template. Use the logical name to reference the resource in other parts of the template. For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance. In addition to the logical ID, certain resources also have a physical ID, which is the actual assigned name for that resource, such as an EC2 instance ID or an S3 bucket name. Use the physical IDs to identify resources outside of AWS CloudFormation templates, but only after the resources have been created. For example, you might give an EC2 instance resource a logical ID of MyEC2Instance; but when AWS CloudFormation creates the instance, AWS CloudFormation automatically generates and assigns a physical ID (such as i-28f9ba55) to the instance. You can use this physical ID to identify the instance and view its properties (such as the DNS name) by using the Amazon EC2 console. For resources that support custom names, you can assign your own names (physical IDs) to help you quickly identify resources. For example, you can name an S3 bucket that stores logs as MyPerformanceLogs. .PARAMETER Type The resource type identifies the type of resource that you are declaring. For example, AWS::EC2::Instance declares an EC2 instance. For a list of all of the resource types, see AWS Resource Types Reference. .PARAMETER Properties This is a collection of Resource properties are additional options that you can specify for a resource. For example, for each EC2 instance, you must specify an Amazon Machine Image (AMI) ID for that instance. You can use any of these 3 types for this parameter; "System.Collections.Hashtable","System.Management.Automation.PSCustomObject","Vaporshell.Resource.Properties" .PARAMETER CreationPolicy Use the CreationPolicy attribute when you want to wait on resource configuration actions before stack creation proceeds. For example, if you install and configure software applications on an EC2 instance, you might want those applications to be running before proceeding. In such cases, you can add a CreationPolicy attribute to the instance, and then send a success signal to the instance after the applications are installed and configured. You must use the "Add-CreationPolicy" function here. .PARAMETER DeletionPolicy With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted. You specify a DeletionPolicy attribute for each resource that you want to control. If a resource has no DeletionPolicy attribute, AWS CloudFormation deletes the resource by default. To keep a resource when its stack is deleted, specify Retain for that resource. You can use retain for any resource. For example, you can retain a nested stack, S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks. You must use one of the following options: "Delete","Retain","Snapshot" .PARAMETER DependsOn With the DependsOn attribute you can specify that the creation of a specific resource follows another. When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute. This parameter takes a string or list of strings representing Logical IDs of resources that must be created prior to this resource being created. .PARAMETER Metadata The Metadata attribute enables you to associate structured data with a resource. By adding a Metadata attribute to a resource, you can add data in JSON or YAML to the resource declaration. In addition, you can use intrinsic functions (such as GetAtt and Ref), parameters, and pseudo parameters within the Metadata attribute to add those interpreted values. You must use a PSCustomObject containing key/value pairs here. This will be returned when describing the resource using AWS CLI. .PARAMETER UpdatePolicy Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource. AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group. You must use the "Add-UpdatePolicy" function here. .PARAMETER Condition Logical ID of the condition that this resource needs to be true in order for this resource to be provisioned. .EXAMPLE $template = Initialize-Vaporshell -Description "Testing Resource addition" $template.AddResource(( New-VaporResource -LogicalId "MyInstance" -Type "AWS::EC2::Instance" -Properties [PSCustomObject]@{ "UserProperties" = (Add-FnBase64 -ValueToEncode (Add-FnJoin -ListOfValues "Queue=",(Add-FnRef -Ref "MyQueue"))) "AvailabilityZone" = "us-east-1a" "ImageId" = "ami-20b65349" } )) When the template is exported, this will convert to: ```json { "AWSTemplateFormatVersion": "2010-09-09", "Description": "Testing Resource addition", "Resources": { "MyInstance": { "Type": "AWS::EC2::Instance", "Properties": { "UserProperties": { "Fn::Base64": { "Fn::Join": [ "", [ "Queue=", { "Ref": "MyQueue" } ] ] } }, "AvailabilityZone": "us-east-1a", "ImageId": "ami-20b65349" } } } } ``` .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { throw 'The logical ID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.' } })] [System.String] $LogicalId, [parameter(Mandatory = $true,Position = 1)] [System.String] $Type, [parameter(Mandatory = $false,Position = 2)] [ValidateScript( { $allowedTypes = "System.Management.Automation.PSCustomObject","Vaporshell.Resource.Properties" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "The Properties parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $Properties, [parameter(Mandatory = $false,Position = 3)] [ValidateScript( { $allowedTypes = "Vaporshell.Resource.CreationPolicy" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "The CreationPolicy parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $CreationPolicy, [parameter(Mandatory = $false,Position = 4)] [ValidateSet("Delete","Retain","Snapshot")] [System.String] $DeletionPolicy, [parameter(Mandatory = $false,Position = 5)] [System.String[]] $DependsOn, [parameter(Mandatory = $false,Position = 6)] [System.Management.Automation.PSCustomObject] $Metadata, [parameter(Mandatory = $false,Position = 7)] [ValidateScript( { $allowedTypes = "Vaporshell.Resource.UpdatePolicy" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { throw "The UpdatePolicy parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")." } })] $UpdatePolicy, [parameter(Mandatory = $false,Position = 8)] $Condition ) $obj = [PSCustomObject][Ordered]@{ "LogicalId" = $LogicalId "Props" = [PSCustomObject][Ordered]@{ "Type" = $Type } } if ($Condition) { $obj.Props | Add-Member -MemberType NoteProperty -Name "Condition" -Value $Condition -Force } if ($Properties) { $obj.Props | Add-Member -MemberType NoteProperty -Name "Properties" -Value $Properties -Force } if ($CreationPolicy) { $obj.Props | Add-Member -MemberType NoteProperty -Name "CreationPolicy" -Value $CreationPolicy } if ($DeletionPolicy) { $obj.Props | Add-Member -MemberType NoteProperty -Name "DeletionPolicy" -Value $DeletionPolicy } if ($DependsOn) { $obj.Props | Add-Member -MemberType NoteProperty -Name "DependsOn" -Value $DependsOn } if ($Metadata) { $obj.Props | Add-Member -MemberType NoteProperty -Name "Metadata" -Value $Metadata } if ($UpdatePolicy) { $obj.Props | Add-Member -MemberType NoteProperty -Name "UpdatePolicy" -Value $UpdatePolicy } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5)`n" }
PowerShellCorpus/PowerShellGallery/Vaporshell/0.7.3/Public/Helpers/Add-Variable.ps1
Add-Variable.ps1
function Add-Variable { [OutputType('Vaporshell.Helper.Variable')] [cmdletbinding()] Param ( [parameter(Mandatory=$true,Position=0)] [ValidatePattern("[A-Za-z0-9-._~:/?#&amp;=,]+")] [String] $Name, [parameter(Mandatory=$true,Position=1)] [String] $Value ) $obj = [PSCustomObject]@{ "$Name" = "$Value" } $obj | Add-ObjectDetail -TypeName 'Vaporshell.Helper.Variable' }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/SwitchEmbeddedTeamingWithHostNetworkAdapter/SETTeamWithHostNetworkAdapters.Example.ps1
SETTeamWithHostNetworkAdapters.Example.ps1
Configuration SETTeam { param ( [String] $SwitchName, [String[]] $NetAdapterName, [Int] $ManagementVlan, [Int] $ManagementBandwidthWeight, [String] $ClusterAdapterName, [Int] $ClusterVlan, [Int] $ClusterBandwidthWeight, [String] $LiveMigrationAdapterName, [Int] $LiveMigrationVlan, [Int] $LiveMigrationBandwidthWeight ) Import-DscResource -ModuleName cHyper-V cVMSwitch $SwitchName { Name = $SwitchName NetAdapterName = $NetAdapterName Type = 'External' MinimumBandwidthMode = 'Weight' TeamingMode = 'SwitchIndependent' LoadBalancingAlgorithm = 'Dynamic' Ensure = 'Present' } cVMNetworkAdapterVlan $SwitchName { Id = 'Mgmt-NIC' Name = $SwitchName AdapterMode = 'Access' VlanId = $ManagementVlan VMName = 'ManagementOS' DependsOn = "[cVMSwitch]$SwitchName" } cVMNetworkAdapterSettings $SwitchName { Id = 'Mgmt-NIC' Name = $SwitchName VMName = 'ManagementOS' SwitchName = $SwitchName MinimumBandwidthWeight = $ManagementBandwidthWeight DependsOn = "[cVMSwitch]$SwitchName" } cVMNetworkAdapter $ClusterAdapterName { Id = 'Cluster-NIC' Name = $ClusterAdapterName VMName = 'ManagementOS' SwitchName = $SwitchName DependsOn = "[cVMSwitch]$SwitchName" } cVMNetworkAdapterVlan $ClusterAdapterName { Id = 'Cluster-NIC' Name = $ClusterAdapterName AdapterMode = 'Access' VlanId = $ClusterVlan VMName = 'ManagementOS' DependsOn = "[cVMNetworkAdapter]$ClusterAdapterName" } cVMNetworkAdapterSettings $ClusterAdapterName { Id = 'Cluster-NIC' Name = $ClusterAdapterName VMName = 'ManagementOS' SwitchName = $SwitchName MinimumBandwidthWeight = $ClusterBandwidthWeight DependsOn = "[cVMNetworkAdapter]$ClusterAdapterName" } cVMNetworkAdapter $LiveMigrationAdapterName { Id = 'LM-NIC' Name = $LiveMigrationAdapterName VMName = 'ManagementOS' SwitchName = $SwitchName DependsOn = "[cVMSwitch]$SwitchName" } cVMNetworkAdapterVlan $LiveMigrationAdapterName { Id = 'LM-NIC' Name = $LiveMigrationAdapterName AdapterMode = 'Access' VlanId = $LiveMigrationVlan VMName = 'ManagementOS' DependsOn = "[cVMNetworkAdapter]$LiveMigrationAdapterName" } cVMNetworkAdapterSettings $LiveMigrationAdapterName { Id = 'LM-NIC' Name = $LiveMigrationAdapterName VMName = 'ManagementOS' SwitchName = $SwitchName MinimumBandwidthWeight = $LiveMigrationBandwidthWeight DependsOn = "[cVMNetworkAdapter]$LiveMigrationAdapterName" } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMSwitch/PrivateSwitch.Example.ps1
PrivateSwitch.Example.ps1
Configuration PrivateSwitch { Import-DscResource -ModuleName cHyper-V -Name cVMSwitch Import-DscResource -ModuleName PSDesiredStateConfiguration cVMSwitch HostSwitch { Name = 'HostSwitch' Type = 'Private' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMSwitch/SETTeamSwitch.Example.ps1
SETTeamSwitch.Example.ps1
Configuration SETTeamSwitch { Import-DscResource -ModuleName cHyper-V -Name cVMSwitch Import-DscResource -ModuleName PSDesiredStateConfiguration cVMSwitch HostSwitch { Name = 'HostSwitch' Type = 'External' AllowManagementOS = $true MinimumBandwidthMode = 'Weight' TeamingMode = 'SwitchIndependent' LoadBalancingAlgorithm = 'HyperVPort' NetAdapterName = 'NIC1','NIC2','NIC3','NIC4' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMSwitch/HostTeamSwitch.Example.ps1
HostTeamSwitch.Example.ps1
Configuration SimpleHostTeamvSwitch { Import-DscResource -ModuleName cHyper-V -Name cVMSwitch Import-DscResource -ModuleName PSDesiredStateConfiguration cVMSwitch HostSwitch { Name = 'HostSwitch' Type = 'External' AllowManagementOS = $true MinimumBandwidthMode = 'Weight' NetAdapterName = 'HostTeam' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMSwitch/InternalSwitch.Example.ps1
InternalSwitch.Example.ps1
Configuration InternalSwitch { Import-DscResource -ModuleName cHyper-V -Name cVMSwitch Import-DscResource -ModuleName PSDesiredStateConfiguration cVMSwitch HostSwitch { Name = 'HostSwitch' Type = 'Internal' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMSwitch/NetAdapterSwitch.Example.ps1
NetAdapterSwitch.Example.ps1
Configuration SimpleNetAdaptervSwitch { Import-DscResource -ModuleName cHyper-V -Name cVMSwitch Import-DscResource -ModuleName PSDesiredStateConfiguration cVMSwitch HostSwitch { Name = 'HostSwitch' Type = 'External' AllowManagementOS = $true NetAdapterName = 'NIC1' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cWaitForVMIntegrationComponent/WaitForIntegrationComponentDefault.Example.ps1
WaitForIntegrationComponentDefault.Example.ps1
Configuration WaitForIC { Import-DscResource -Name cWaitForVMGuestIntegration -ModuleName cHyper-V cWaitForVMGuestIntegration VM01 { Id = 'VM01-IC01' VMName = 'VM01' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cWaitForVMIntegrationComponent/WaitForIntegrationComponentCustom.Example.ps1
WaitForIntegrationComponentCustom.Example.ps1
Configuration WaitForIC { Import-DscResource -Name cWaitForVMGuestIntegration -ModuleName cHyper-V cWaitForVMGuestIntegration VM01 { Id = 'VM01-IC01' VMName = 'VM01' RetryIntervalSec = 20 RetryCount = 10 } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMIPAddress/ResetIPAddress.Example.ps1
ResetIPAddress.Example.ps1
Configuration VMIPAddress { Import-DscResource -ModuleName cHyper-V -Name cVMIPAddress Import-DscResource -ModuleName PSDesiredStateConfiguration cVMIPAddress VMAdapter1IPAddress { Id = 'VMMgmt-NIC' NetAdapterName = 'VMMgmt-NIC' VMName = 'SQLVM01' IPAddress = 'DHCP' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMIPAddress/SetIPAddress.Example.ps1
SetIPAddress.Example.ps1
Configuration VMIPAddress { Import-DscResource -ModuleName cHyper-V -Name cVMIPAddress Import-DscResource -ModuleName PSDesiredStateConfiguration cVMIPAddress VMAdapter1IPAddress { Id = 'VMMgmt-NIC' NetAdapterName = 'VMMgmt-NIC' VMName = 'SQLVM01' IPAddress = '172.16.101.101' DefaultGateway = '172.16.101.1' Subnet = '255.255.255.0' DnsServer = '172.16.101.2' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapter/CreateVMNetworkAdapterMultipleVM.Example.ps1
CreateVMNetworkAdapterMultipleVM.Example.ps1
Configuration VMAdapter { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapter Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapter MyVM01NIC { Id = 'MyVM01-NIC' Name = 'MyVM01-NIC' SwitchName = 'SETSwitch' VMName = 'MyVM01' Ensure = 'Present' } cVMNetworkAdapter MyVM02NIC { Id = 'MyVM02-NIC' Name = 'NetAdapter' SwitchName = 'SETSwitch' VMName = 'MyVM02' Ensure = 'Present' } cVMNetworkAdapter MyVM03NIC { Id = 'MyVM03-NIC' Name = 'NetAdapter' SwitchName = 'SETSwitch' VMName = 'MyVM03' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapter/CreateVMNetworkAdapterManagementOS.Example.ps1
CreateVMNetworkAdapterManagementOS.Example.ps1
Configuration HostOSAdapter { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapter Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapter HostOSAdapter { Id = 'Management-NIC' Name = 'Management-NIC' SwitchName = 'SETSwitch' VMName = 'ManagementOS' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapter/CreateVMNetworkAdapterMultipleVMMACAddress.Example.ps1
CreateVMNetworkAdapterMultipleVMMACAddress.Example.ps1
Configuration VMAdapter { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapter Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapter MyVM01NIC { Id = 'MyVM01-NIC' Name = 'MyVM01-NIC' SwitchName = 'SETSwitch' MacAddress = '001523be0c' VMName = 'MyVM01' Ensure = 'Present' } cVMNetworkAdapter MyVM02NIC { Id = 'MyVM02-NIC' Name = 'MyVM02-NIC' SwitchName = 'SETSwitch' MacAddress = '001523be0d' VMName = 'MyVM02' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapter/CreateVMNetworkAdapterMultipleManagementOS.Example.ps1
CreateVMNetworkAdapterMultipleManagementOS.Example.ps1
Configuration HostOSAdapter { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapter Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapter ManagementAdapter { Id = 'Management-NIC' Name = 'Management-NIC' SwitchName = 'SETSwitch' VMName = 'ManagementOS' Ensure = 'Present' } cVMNetworkAdapter ClusterAdapter { Id = 'Cluster-NIC' Name = 'Cluster-NIC' SwitchName = 'SETSwitch' VMName = 'ManagementOS' Ensure = 'Present' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapterVlan/VMNetworkAdapterVlanManagementOS.Example.ps1
VMNetworkAdapterVlanManagementOS.Example.ps1
Configuration HostOSAdapterVlan { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapterVlan Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapterVlan HostOSAdapterVlan { Id = 'Management-NIC' Name = 'Management-NIC' VMName = 'ManagementOS' AdapterMode = 'Access' VlanId = 10 } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapterVlan/VMNetworkAdapterVlanMultipleVM.Example.ps1
VMNetworkAdapterVlanMultipleVM.Example.ps1
Configuration HostOSAdapterVlan { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapterVlan Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapterVlan VMMgmtAdapterVlan { Id = 'VMManagement-NIC' Name = 'VMManagement-NIC' VMName = 'SQLVM01' AdapterMode = 'Access' VlanId = 10 } cVMNetworkAdapterVlan VMiSCSIAdapterVlan { Id = 'VMiSCSI-NIC' Name = 'VMiSCSI-NIC' VMName = 'SQLVM01' AdapterMode = 'Untagged' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapterVlan/VMNetworkAdapterVlanMultipleManagementOS.Example.ps1
VMNetworkAdapterVlanMultipleManagementOS.Example.ps1
Configuration HostOSAdapterVlan { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapterVlan Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapterVlan HostOSAdapterVlan { Id = 'Management-NIC' Name = 'Management-NIC' VMName = 'ManagementOS' AdapterMode = 'Access' VlanId = 10 } cVMNetworkAdapterVlan ClusterAdapterVlan { Id = 'Cluster-NIC' Name = 'Cluster-NIC' VMName = 'ManagementOS' AdapterMode = 'Access' VlanId = 20 } #The following configuration removes any VLAN setting, if present. cVMNetworkAdapterVlan JustAnotherAdapterVlan { Id = 'JustAnother-NIC' Name = 'JustAnother-NIC' VMName = 'ManagementOS' AdapterMode = 'Untagged' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapterSettings/VMNetworkAdapterSettingsVMMultiple.Example.ps1
VMNetworkAdapterSettingsVMMultiple.Example.ps1
Configuration VMAdapterSettings { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapterSettings Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapterSettings VMAdapterSettings01 { Id = 'Management-NIC' Name = 'Management-NIC' VMName = 'DHCPVM01' SwitchName = 'SETSwitch' DhcpGuard = 'On' DeviceNaming = 'On' } cVMNetworkAdapterSettings VMAdapterSettings02 { Id = 'App-NIC' Name = 'App-NIC' VMName = 'DHCPVM01' SwitchName = 'SETSwitch' DeviceNaming = 'On' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapterSettings/VMNetworkAdapterSettingsVMSimple.Example.ps1
VMNetworkAdapterSettingsVMSimple.Example.ps1
Configuration VMAdapterSettings { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapterSettings Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapterSettings VMAdapterSettings { Id = 'Management-NIC' Name = 'Management-NIC' VMName = 'DHCPVM01' SwitchName = 'SETSwitch' DhcpGuard = 'On' } }
PowerShellCorpus/PowerShellGallery/cHyper-V/3.0.0.0/Examples/Resources/cVMNetworkAdapterSettings/VMNetworkAdapterSettingsManagementOS.Example.ps1
VMNetworkAdapterSettingsManagementOS.Example.ps1
Configuration HostOSAdapterSettings { Import-DscResource -ModuleName cHyper-V -Name cVMNetworkAdapterSettings Import-DscResource -ModuleName PSDesiredStateConfiguration cVMNetworkAdapterSettings HostOSAdapterSettings { Id = 'Management-NIC' Name = 'Management-NIC' VMName = 'ManagementOS' SwitchName = 'SETSwitch' MinimumBandwidthWeight = 20 } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/_scriptAnalyer.tests.ps1
_scriptAnalyer.tests.ps1
$here = (Split-Path -Parent $MyInvocation.MyCommand.Path).Replace('tests', '') $scriptsModules = Get-ChildItem $here -Include *.psd1, *.psm1, *.ps1 -Exclude *.tests.ps1 -Recurse if(($scriptsModules.count -ne 0) -and (Get-Command Invoke-ScriptAnalyzer -errorAction SilentlyContinue)) { $scriptAnalyzerRules = Get-ScriptAnalyzerRule Describe 'INFO: General - Testing all scripts and modules conform to the Script Analyzer Rules' { forEach ($scriptModule in $scriptsModules) { switch ($scriptModule) { '*.psm1' { $typeTesting = 'Module' } '*.ps1' { $typeTesting = 'Script' } '*.psd1' { $typeTesting = 'Manifest' } } Context "INFO: Checking $typeTesting – $($module.BaseName) conforms to Script Analyzer Rules" { forEach ($scriptAnalyzerRule in $scriptAnalyzerRules) { It "INFO: It passes Script Analyzer Rule: $scriptAnalyzerRule" { (Invoke-ScriptAnalyzer -Path $scriptModule.fullName -IncludeRule $scriptAnalyzerRule.ruleName ).Count | Should Be 0 } } } } } } else { Write-Error -Message 'ERROR: No files found to test or Invoke-ScriptAnalyzer not installed.' }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Add-omsAgentWorkSpace.tests.ps1
Add-omsAgentWorkSpace.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Add-omsAgentWorkSpace' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { it 'Parameters' { {Add-omsAgentWorkSpace -workspaceid 'test' -workspacekey 'test' -ErrorAction Stop} | Should Not Throw {Add-omsAgentWorkSpace -workspa 'test' -workssey 'test' -ErrorAction Stop} | Should Throw } it 'WorkSpace Does Not Exist' { Mock Get-omsAgentWorkSpaceInternal { $null } Add-omsAgentWorkSpace -workspaceid 'test' -workspacekey 'test' -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled Invoke-Command -Exactly 1 -Scope It } it 'WorkSpace Does Exists' { Mock Get-omsAgentWorkSpaceInternal { $true } Add-omsAgentWorkSpace -workspaceid 'test' -workspacekey 'test' -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled Invoke-Command -Exactly 0 -Scope It } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentWorkSpaceInternal { $null } Add-omsAgentWorkSpace -workspaceid 'test' -workspacekey 'test' -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Get-omsAgentProxy.tests.ps1
Get-omsAgentProxy.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Get-omsAgentProxy' { Context 'Logic' { it 'Parameters' { {Get-omsAgentProxy -ErrorAction Stop} | Should Not Throw {Get-omsAgentProxy -compName -ErrorAction Stop} | Should Throw } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Get-omsAgentProxy -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Install-omsAgent.tests.ps1
Install-omsAgent.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Install-omsAgent' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { it 'Parameters' { {Install-omsAgent -workspa 'test' -ErrorAction Stop -WhatIf:$false -Confirm:$false} | Should Throw } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentInternal { $null } Install-omsAgent -workspaceid '34434343' -workspacekey 'dfdfdf' -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Uninstall-omsAgent.tests.ps1
Uninstall-omsAgent.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Uninstall-omsAgent' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { it 'Parameters' { {Uninstall-omsAgent -workspa 'test' -ErrorAction Stop -WhatIf:$false -Confirm:$false} | Should Throw } it 'Agent Is Installed' { Mock Get-omsAgentInternal { $true } Uninstall-omsAgent -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 1 -Scope It } it 'Agent Is Not Installed' { Mock Get-omsAgentInternal { $false } Uninstall-omsAgent -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 0 -Scope It } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentInternal { $null } Uninstall-omsAgent -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Get-omsAgentWorkSpace.tests.ps1
Get-omsAgentWorkSpace.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Get-omsAgentWorkSpace' { Context 'Logic' { it 'Parameters' { {Get-omsAgentWorkSpace -ErrorAction Stop} | Should Not Throw {Get-omsAgentWorkSpace -compName -ErrorAction Stop} | Should Throw } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentWorkSpaceInternal { $null } Get-omsAgentWorkSpace -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Get-omsAgent.tests.ps1
Get-omsAgent.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Get-omsAgent' { Context 'Logic' { it 'Parameters' { {Get-omsAgent -ErrorAction Stop} | Should Not Throw {Get-omsAgent -compName -ErrorAction Stop} | Should Throw } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentInternal { $null } Get-omsAgent -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Remove-omsAgentProxy.tests.ps1
Remove-omsAgentProxy.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Remove-omsAgentProxy' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { it 'Parameters' { {Remove-omsAgentProxy -comt -ErrorAction Stop -WhatIf:$false -Confirm:$false} | Should Throw } it 'Proxy Does Not Exist' { Mock Get-omsAgentProxyInternal { $null } Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 0 -Scope It } it 'Proxy Does Exists - No Workspaces' { Mock Get-omsAgentProxyInternal { $true } Mock Get-omsAgentWorkSpaceInternal { $null } Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 1 -Scope It } it 'Proxy Does Exists - Workspace Exists' { Mock Get-omsAgentProxyInternal { $true } Mock Get-omsAgentWorkSpaceInternal { $true } Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 2 -Scope It } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentProxyInternal { $null } Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Update-omsAgentWorkSpaceKey.tests.ps1
Update-omsAgentWorkSpaceKey.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Update-omsAgentWorkSpaceKey' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { it 'Parameters' { {Update-omsAgentWorkSpaceKey -workspa 'test' -workssey 'test' -ErrorAction Stop} | Should Throw } it 'WorkSpace Does Not Exist' { Mock Get-omsAgentWorkSpaceInternal { $null } Update-omsAgentWorkSpaceKey -workspaceid 'test' -workspacekey 'test' -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled Invoke-Command -Exactly 0 -Scope It } it 'WorkSpace Does Exists' { Mock Get-omsAgentWorkSpaceInternal { $true } Update-omsAgentWorkSpaceKey -workspaceid 'test' -workspacekey 'test' -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled Invoke-Command -Exactly 1 -Scope It } it 'Creates\Removes A PsSession Without Whatif' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentWorkSpaceInternal { $null } Update-omsAgentWorkSpaceKey -workspaceid 'test' -workspacekey 'test' -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Add-omsAgentProxy.tests.ps1
Add-omsAgentProxy.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Add-omsAgentProxy' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { Mock Get-omsAgentWorkSpaceInternal { $null } it 'Parameters' { {Add-omsAgentProxy -proxyUrl test.local -ErrorAction Stop} | Should Not Throw {Add-omsAgentProxy -workspa 'test' -workssey 'test' -ErrorAction Stop} | Should Throw } it 'Proxy Does Not Exist' { Mock Get-omsAgentProxyInternal { $null } Add-omsAgentProxy -proxyUrl test.local -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled Invoke-Command -Exactly 1 -Scope It } it 'Proxy Does Exists' { Mock Get-omsAgentProxyInternal { $true } Add-omsAgentProxy -proxyUrl test.proxy -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled Invoke-Command -Exactly 0 -Scope It } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentProxyInternal { $null } Add-omsAgentProxy -proxyUrl test.local -ErrorAction SilentlyContinue | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/tests/functions/public/Remove-omsAgentWorkSpace.tests.ps1
Remove-omsAgentWorkSpace.tests.ps1
InModuleScope -moduleName omsAgent { Describe 'Remove-omsAgentWorkSpace' { BeforeAll { Mock Invoke-Command {} } Context 'Logic' { it 'Parameters' { {Remove-omsAgentWorkSpace -workspa 'test' -ErrorAction Stop -WhatIf:$false -Confirm:$false} | Should Throw } it 'WorkSpace Does Not Exist' { Mock Get-omsAgentWorkSpaceInternal { $null } Remove-omsAgentWorkSpace -workspaceid 'test' -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 0 -Scope It } it 'One Workspace - WorkSpace Does Exists' { $script:i = 1 Mock Get-omsAgentWorkSpaceInternal { if ($script:i -ge 2) { $null } else { $true } $script:i++ } Remove-omsAgentWorkSpace -workspaceid 'test' -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 1 -Scope It } it 'Two Workspaces - WorkSpace Does Exists' { Mock Get-omsAgentWorkSpaceInternal { $true } Remove-omsAgentWorkSpace -workspaceid 'test' -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled Invoke-Command -Exactly 2 -Scope It } it 'Creates\Removes A PsSession' { Mock New-PSSession { 'sessionData' } Mock Remove-PSSession {} Mock Get-omsAgentWorkSpaceInternal { $null } Remove-omsAgentWorkSpace -workspaceid 'test' -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null Assert-MockCalled New-PSSession -Exactly 1 -Scope It Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/private/Get-omsAgentWorkSpaceInternal.ps1
Get-omsAgentWorkSpaceInternal.ps1
function Get-omsAgentWorkSpaceInternal { [CmdletBinding()] [OutputType()] param ( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$computerName, [Parameter(Mandatory=$true)] [object]$session, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string]$workspaceid ) try { Invoke-Command -Session $session -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop if($USING:PSBoundParameters['workspaceid']) { $omsAgent = $omsObj.GetCloudWorkspace($USING:workspaceid) } else { $omsAgent = $omsObj.GetCloudWorkspaces() } $omsAgent | Add-Member -NotePropertyName 'computerName' -NotePropertyValue $USING:computerName $omsAgent } -ErrorAction Stop } catch { $null } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/private/Convert-CredentialToPlainText.ps1
Convert-CredentialToPlainText.ps1
function Convert-CredentialToPlainText { <# .SYNOPSIS Converts a credential to a plain text username and password. .NOTES Written by Ben Taylor Version 1.0, 05.01.2017 #> [CmdletBinding()] [OutputType('System.Collections.Hashtable')] param ( [Parameter(Mandatory=$true)] [pscredential] [System.Management.Automation.Credential()] $credential ) @{ userName = $credential.UserName passWord = $credential.GetNetworkCredential().Password } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/private/Get-omsAgentInternal.ps1
Get-omsAgentInternal.ps1
function Get-omsAgentInternal { [CmdletBinding()] [OutputType('omsAgent')] param ( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$computerName, [Parameter(Mandatory=$true)] [object]$session ) try { Invoke-Command -Session $session -ScriptBlock { $oms = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object { $_.displayName -eq 'Microsoft Monitoring Agent' } if($oms) { $omsInfo = @{ PSTypeName = 'omsAgent' computerName = $USING:computerName DisplayName = $oms.DisplayName Version = $oms.Version DisplayVersion = $oms.DisplayVersion UninstallString = $oms.UninstallString } try { New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop | Out-Null $omsInfo.comObjectAvailable = $true } catch { $omsInfo.comObjectAvailable = $false } New-Object -TypeName PSObject -Property $omsInfo } } -ErrorAction Stop } catch { Throw $_ } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/private/Get-omsAgentProxyInternal.ps1
Get-omsAgentProxyInternal.ps1
function Get-omsAgentProxyInternal { [CmdletBinding()] [OutputType('omsAgentProxy')] param ( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$computerName, [Parameter(Mandatory=$true)] [object]$session ) try { Invoke-Command -Session $session -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop if($omsObj.proxyURL) { $omsProxyInfo = @{ PSTypeName = 'omsAgentProxy' computerName = $USING:computerName proxyURL = $omsObj.proxyURL proxyUsername = $omsObj.proxyUserName } New-Object -TypeName PSObject -Property $omsProxyInfo } } -ErrorAction Stop } catch { Throw $_ } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Add-omsAgentProxy.ps1
Add-omsAgentProxy.ps1
function Add-omsAgentProxy { <# .SYNOPSIS Adds a OMS Agent Proxy to remote computers. .EXAMPLE Add-omsAgentProxy -computerName 'computer1', 'computer2' -proxyURL 'proxy.local:443' .EXAMPLE $proxyCredential = Get-Credential Add-omsAgentProxy -computerName 'computer1', 'computer2' -proxyURL 'proxy.local:443' -proxyCredential $proxyCredential .NOTES Written by Ben Taylor Version 1.0, 06.03.2017 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')] [OutputType()] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $proxyURL, [Parameter(Mandatory=$false)] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $proxyCredential ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } If ($PSBoundParameters['proxyCredential']) { $proxyUserName = (Convert-CredentialToPlainText -credential $proxyCredential).userName $proxyPassword = (Convert-CredentialToPlainText -credential $proxyCredential).passWord } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams If(-not(Get-omsAgentProxyInternal -computerName $computer -session $psSession)) { If ($Pscmdlet.ShouldProcess($computer, 'Add OMS Agent Proxy')) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Adding OMS Agent Proxy" Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.setProxyUrl($USING:proxyURL) } -ErrorAction Stop If ($PSBoundParameters['proxyCredential']) { Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.SetProxyCredentials($USING:proxyUserName, $USING:proxyPassword) } -ErrorAction Stop } if(Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession) { Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.ReloadConfiguration() } -ErrorAction Stop } } } else { Write-Error "[$(Get-Date -Format G)] - $computer - OMS Proxy all ready found" } } catch { Write-Error $_ } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession -WhatIf:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Get-omsAgent.ps1
Get-omsAgent.ps1
function Get-omsAgent { <# .SYNOPSIS Gets OMS workspace details from remote computers .EXAMPLE Get-omsAgent -computerName 'computer1', 'computer2' .NOTES Written by Ben Taylor Version 1.1, 08.02.2016 #> [CmdletBinding()] [OutputType('omsAgent')] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams Write-Verbose "[$(Get-Date -Format G)] - $computer - Trying to find Agent Version" Get-omsAgentInternal -computerName $computer -session $psSession } catch { Write-Error "[$(Get-Date -Format G)] - $computer - $_" } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Remove-omsAgentWorkSpace.ps1
Remove-omsAgentWorkSpace.ps1
function Remove-omsAgentWorkSpace { <# .SYNOPSIS Removes OMS workspace details to remote computers .EXAMPLE Remove-omsAgentWorkSpace -computerName 'computer1', 'computer2' -workspaceid '<workspaceid>' .NOTES Written by Ben Taylor Version 1.1, 08.02.2017 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] [OutputType()] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $workspaceid ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } $omsSessionParams = @{} If ($PSBoundParameters['workspaceid']) { $omsSessionParams.workspaceid = $workspaceid } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams If(Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession @omsSessionParams) { If ($Pscmdlet.ShouldProcess($computer, 'Remove OMS Work Space')) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Removing OMS Workspace - $workspaceid" Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.RemoveCloudWorkspace($USING:workspaceId) } -ErrorAction Stop if(Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession) { Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.ReloadConfiguration() } -ErrorAction Stop } } } else { Write-Error "[$(Get-Date -Format G)] - $computer - No OMS workspace with that ID could be found to remove" } } catch { Write-Error $_ } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession -WhatIf:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Remove-omsAgentProxy.ps1
Remove-omsAgentProxy.ps1
function Remove-omsAgentProxy { <# .SYNOPSIS Removes OMS Proxy to remote computers .EXAMPLE Remove-omsAgentProxy -computerName 'computer1', 'computer2' .NOTES Written by Ben Taylor Version 1.0, 06.03.2017 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] [OutputType()] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams If(Get-omsAgentProxyInternal -computerName $computer -session $psSession) { If ($Pscmdlet.ShouldProcess($computer, 'Remove OMS Proxy')) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Removing OMS Proxy" Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.SetProxyInfo('', '', '') } -ErrorAction Stop if(Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession) { Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.ReloadConfiguration() } -ErrorAction Stop } } } else { Write-Error "[$(Get-Date -Format G)] - $computer - No proxy could be found to remove." } } catch { Write-Error $_ } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession -WhatIf:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Get-omsAgentWorkSpace.ps1
Get-omsAgentWorkSpace.ps1
function Get-omsAgentWorkSpace { <# .SYNOPSIS Gets OMS workspace details from remote computers .EXAMPLE Get-omsAgentWorkSpace -computerName 'computer1', 'computer2' .EXAMPLE Get-omsAgentWorkSpace -computerName 'computer1', 'computer2' -workSpaceId '<workSpaceId>' .NOTES Written by Ben Taylor Version 1.1, 08.02.2017 #> [CmdletBinding()] [OutputType([System.Collections.ArrayList])] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [string] $workspaceid ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } $omsSessionParams = @{} If ($PSBoundParameters['workspaceid']) { $omsSessionParams.workspaceid = $workspaceid } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams Write-Verbose "[$(Get-Date -Format G)] - $computer - Trying to find workspace" Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession @omsSessionParams } catch { Write-Error "[$(Get-Date -Format G)] - $computer - $_" } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Get-omsAgentProxy.ps1
Get-omsAgentProxy.ps1
function Get-omsAgentProxy { <# .SYNOPSIS Gets OMS proxy details from remote computers .EXAMPLE Get-omsAgentProxy -computerName 'computer1', 'computer2' .NOTES Written by Ben Taylor Version 1.0, 06.03.2017 #> [CmdletBinding()] [OutputType([System.Collections.ArrayList])] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams Write-Verbose "[$(Get-Date -Format G)] - $computer - Trying to find workspace" Get-omsAgentProxyInternal -computerName $computer -session $psSession } catch { Write-Error "[$(Get-Date -Format G)] - $computer - $_" } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Add-omsAgentWorkSpace.ps1
Add-omsAgentWorkSpace.ps1
function Add-omsAgentWorkSpace { <# .SYNOPSIS Adds a OMS workspace to remote computers. .EXAMPLE Add-omsAgentWorkSpace -computerName 'computer1', 'computer2' -workSpaceId '<workSpace>' -workSpaceKey '<workSpaceKey>' .EXAMPLE $workSpace = Get-Credential Add-omsAgentWorkSpace -computerName 'computer1', 'computer2' -workSpace $workSpace .NOTES Written by Ben Taylor Version 1.1, 09.01.2017 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')] [OutputType()] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter(Mandatory=$true, ParameterSetName='workSpaceClearText')] [ValidateNotNullOrEmpty()] [string] $workspaceid, [Parameter(Mandatory=$true, ParameterSetName='workSpaceClearText')] [ValidateNotNullOrEmpty()] [string] $workspacekey, [Parameter(Mandatory=$true, ParameterSetName='workSpaceEncrypt')] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $workSpace ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } If ($PSBoundParameters['workspace']) { $workspaceid = (Convert-CredentialToPlainText -credential $workSpace).userName $workspacekey = (Convert-CredentialToPlainText -credential $workSpace).passWord } $omsSessionParams = @{ workspaceid = $workspaceid } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams If(-not(Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession @omsSessionParams)) { If ($Pscmdlet.ShouldProcess($computer, 'Add OMS Agent Work Space')) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Adding OMS Workspace" Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.AddCloudWorkspace($USING:workspaceId, $USING:workspaceKey) $omsObj.ReloadConfiguration() } -ErrorAction Stop } } else { Write-Error "[$(Get-Date -Format G)] - $computer - OMS workspace with that ID found - please use Update-omsAgentWorkSpace" } } catch { Write-Error $_ } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession -WhatIf:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Update-omsAgentWorkSpaceKey.ps1
Update-omsAgentWorkSpaceKey.ps1
function Update-omsAgentWorkSpaceKey { <# .SYNOPSIS Updates the OMS workspace key on remote computers. .EXAMPLE Update-omsAgwentWorkSpacekey -computerName 'computer1', 'computer2' -workspaceid '<workSpaceId>' -workspacekey '<workSpaceKey>' .EXAMPLE $workSpace = Get-Credential Update-omsAgwentWorkSpacekey -computerName 'computer1', 'computer2' -workSpace $workSpace .NOTES Written by Ben Taylor Version 1.1, 09.01.2017 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low')] [OutputType()] param ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter(Mandatory=$true, ParameterSetName='workSpaceClearText')] [ValidateNotNullOrEmpty()] [string] $workspaceid, [Parameter(Mandatory=$true, ParameterSetName='workSpaceClearText')] [ValidateNotNullOrEmpty()] [string] $workspacekey, [Parameter(Mandatory=$true, ParameterSetName='workSpaceEncrypt')] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $workSpace ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } If ($PSBoundParameters['workspace']) { $workspaceid = (Convert-CredentialToPlainText -credential $workSpace).userName $workspacekey = (Convert-CredentialToPlainText -credential $workSpace).passWord } $omsSessionParams = @{ workspaceid = $workspaceid } } Process { forEach($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams If(Get-omsAgentWorkSpaceInternal -computerName $computer -session $psSession @omsSessionParams) { If ($Pscmdlet.ShouldProcess($computer, 'Update OMS Work Space Key')) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Updating OMS Workspace" Invoke-Command -Session $psSession -ScriptBlock { $omsObj = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg' -ErrorAction Stop $omsObj.GetCloudWorkspace($USING:workspaceId).updateWorkSpaceKey($USING:workspaceKey) $omsObj.ReloadConfiguration() } -ErrorAction Stop } } else { Write-Error "[$(Get-Date -Format G)] - $computer - No OMS workspace with that ID could be found to update" } } catch { Write-Error $_ } finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession -WhatIf:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Install-omsAgent.ps1
Install-omsAgent.ps1
#Requires -Version 5.0 function Install-OmsAgent { <# .Synopsis Installs the OMS agent on remote computers. .DESCRIPTION Either downloads the installer from a URL or copies the installer via the powershell session. Can detected if a previous version is installed and skip if so. If allready installed WorkSpaceId and WorkSpaceKey added to previous install. Doesn't detect invalid workspace IDs or Keys. .EXAMPLE Install-OmsAgent -sourcePath 'c:\MMASetup-AMD64.exe' -workspaceID '<workSpaceID>' -workspaceKey '<workSpaceKey>' -Verbose .EXAMPLE Install-OmsAgent -computerName <computerName> -workspaceID '<workSpaceID>' -workspaceKey '<workSpaceKey>' -Verbose .EXAMPLE $workSpace = Get-Credential Install-OmsAgent -computerName 'computerOne' -workspace $workSpace -verbose .NOTES Written by Ben Taylor Version 1.1, 08.02.2017 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Low', DefaultParameterSetName='downloadOMS')] [OutputType([String])] Param ( [Parameter(Mandatory = $false, Position = 0, ValueFromPipeline=$True, valuefrompipelinebypropertyname=$true)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter(Mandatory=$true, ParameterSetName='workSpaceClearText')] [ValidateNotNullOrEmpty()] [string] $workspaceid, [Parameter(Mandatory=$true, ParameterSetName='workSpaceClearText')] [ValidateNotNullOrEmpty()] [string] $workspacekey, [Parameter(Mandatory=$true, ParameterSetName='workSpaceEncrypt')] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $workSpace, [Parameter(ParameterSetName='downloadOMS')] [ValidateNotNullOrEmpty()] [string] $downloadURL = 'http://download.microsoft.com/download/0/C/0/0C072D6E-F418-4AD4-BCB2-A362624F400A/MMASetup-AMD64.exe', [Parameter(ParameterSetName='localOMS')] [ValidateScript({Test-Path $_ })] [string] $sourcePath, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } If ($PSBoundParameters['workspace']) { $workspaceid = (Convert-CredentialToPlainText -credential $workSpace).userName $workspacekey = (Convert-CredentialToPlainText -credential $workSpace).passWord } } Process { forEach ($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams Write-Verbose "[$(Get-Date -Format G)] - $computer - Checking if OMS is Installed" if(-not (Get-omsAgentInternal -computerName $computer -session $psSession)) { If ($Pscmdlet.ShouldProcess($computer, 'Install OMS Agent')) { $path = Invoke-Command -Session $pssession -ScriptBlock { $path = Join-Path $ENV:temp "MMASetup-AMD64.exe" # Check if file exists and if so remove if(Test-Path $path) { Remove-Item $path -force -Confirm:$false } $path } if($PSBoundParameters.sourcePath -eq $true) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Copying files over powershell session" Copy-Item -Path $sourcePath -Destination (Split-path $path) -ToSession $psSession -Force } else { Write-Verbose "[$(Get-Date -Format G)] - $computer - Trying to download installer from URL - $downloadURL" Invoke-Command -Session $psSession -ScriptBlock { Invoke-WebRequest $USING:downloadURL -OutFile $USING:path -ErrorAction Stop | Out-Null } -ErrorAction Stop } Write-Verbose "$computer - Trying to install OMS..." $installString = $path + ' /C:"setup.exe /qn ADD_OPINSIGHTS_WORKSPACE=1 ' + "OPINSIGHTS_WORKSPACE_ID=$workspaceID " + "OPINSIGHTS_WORKSPACE_KEY=$workSpaceKey " +'AcceptEndUserLicenseAgreement=1"' $installSuccess = Invoke-Command -Session $psSession -ScriptBlock { cmd.exe /C $USING:installString $LASTEXITCODE } -ErrorAction Stop if($installSuccess -ne 0) { Write-Error "$computer - OMS didn't install correctly based on the exit code" } else { if(Get-omsAgentInternal -computerName $computer -session $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS installed correctly" } else { Write-Error "[$(Get-Date -Format G)] - $computer - OMS didn't install correctly based on the exit code" } } } } else { Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS Agent allready installed so skipping." } } catch { Write-Error $_ } Finally { Write-Verbose "[$(Get-Date -Format G)] - $computer - Tidying up install files\sessions if needed" if($null -ne $psSession) { try { Invoke-Command -Session $pssession -ScriptBlock { if(Test-Path $USING:path) { Remove-Item $USING:path -force -Confirm:$false } } -ErrorAction Stop } catch { Write-Verbose "[$(Get-Date -Format G)] - $computer - Nothing to tidy up" } Remove-PSSession $psSession -whatif:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/omsAgent/1.2/functions/public/Uninstall-omsAgent.ps1
Uninstall-omsAgent.ps1
function Uninstall-OmsAgent { <# .Synopsis Un-installs the OMS agent on remote computers. .DESCRIPTION Un-installs the OMS agent on remote computers. .EXAMPLE Uninstall-OmsAgent -computerName 'computer1', 'computer2' -Verbose .NOTES Written by Ben Taylor Version 1.0, 31.07.2016 #> [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'High')] [OutputType()] Param ( [Parameter(Mandatory = $false, ValueFromPipeline=$True, valuefrompipelinebypropertyname=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias('IPAddress', 'Name')] [string[]] $computerName = $env:COMPUTERNAME, [Parameter()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) Begin { $commonSessionParams = @{ ErrorAction = 'Stop' } If ($PSBoundParameters['Credential']) { $commonSessionParams.Credential = $Credential } } Process { forEach ($computer in $computerName) { try { Write-Verbose "[$(Get-Date -Format G)] - $computer - Creating Remote PS Session" $psSession = New-PSSession -ComputerName $computer @commonSessionParams Write-Verbose "[$(Get-Date -Format G)] - $computer - Checking if OMS is Installed" $omsInstall = Get-omsAgentInternal -computerName $computer -session $psSession if($omsInstall) { If ($Pscmdlet.ShouldProcess($computer, 'Uninstall OMS Agent')) { Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS is installed so will try to uninstall" Invoke-Command -Session $psSession -ScriptBlock { $uninstallString = ($USING:omsInstall.UninstallString).ToLower().Replace("/i", "").Replace("msiexec.exe", "") Start-Process "msiexec.exe" -arg "/X $uninstallString /qn" -Wait } -ErrorAction Stop $omsInstallStatus = Get-omsAgentInternal -computerName $computer -session $psSession -ErrorAction SilentlyContinue if(-not($omsInstallStatus)) { Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS uninstalled correctly" } else { Write-Error "[$(Get-Date -Format G)] - $computer - OMS didn't uninstall correctly based registry check" } } } else { Write-Verbose "[$(Get-Date -Format G)] - $computer - OMS not installed so skipping uninstall process" } } catch { Write-Error $_ } Finally { if($null -ne $psSession) { Write-Verbose "[$(Get-Date -Format G)] - $computer - Closing Remote PS Session" Remove-PSSession $psSession -WhatIf:$false -Confirm:$false } } } } }
PowerShellCorpus/PowerShellGallery/DevTools/1.1.8/Examples/API.ps1
API.ps1
using module DevTools param ($action = [DevTools.Action]::Development) [DevTools.Action]$action = $action $provision = [DevTools.ProvisionManager]@{ root = $PSScriptRoot } $version = [DevTools.VersionManager]@{ psd = $provision.psd } $projectConfig = Import-PowerShellDataFile $provision.psd $provision.dependencies = ( @{ deploy = $true name = $provision.projectName } ) $provision.dependencies += $projectConfig.PrivateData.DevTools.Dependencies $provision.report('Version:{0}' -f [String]$version.version) $provision.report('Action:{0}' -f $action) $nextVersion = $version.next([DevTools.VersionComponent]::Build) switch ($action) { ([DevTools.Action]::Cleanup) { $provision.cleanup() } ([DevTools.Action]::Shortcuts) { $provision.shortcuts() } ([DevTools.Action]::Copy) { $provision.copy() } ([DevTools.Action]::BumpVersion) { $provision.bumpVersion($version, $nextVersion) } ([DevTools.Action]::Publish) { $provision.publish() } ([DevTools.Action]::Deploy) { $provision.bumpVersion($version, $nextVersion) $provision.publish() } default { } } if ($action -ne [DevTools.Action]::Development) { return } $provision.report('The Test Environment is redy.') . $provision.entryPoint
PowerShellCorpus/PowerShellGallery/DevTools/1.1.8/Tests/EntyPoint.ps1
EntyPoint.ps1
# Expose some globals. $provision = $global:devTools.provision $version = $global:devTools.version $appVeyor = $global:devTools.appVeyor $pesterConfig = switch ([Boolean]$appVeyor) { $true { $appVeyor.getPesterDefaultConfig($provision, $version.version) } $false { @{ path = $provision.tests } } } # Disabling Pester progress output $global:ProgressPreference = 'SilentlyContinue' $test = Invoke-Pester @pesterConfig if (!$appVeyor) { return } $appVeyor.uploadTestsFile($provision, $pesterConfig) $appVeyor.throwOnFail($provision, $test.FailedCount)
PowerShellCorpus/PowerShellGallery/DevTools/1.1.8/Tests/Unit/SuiteTwo.Tests.ps1
SuiteTwo.Tests.ps1
Describe "Tests Suit 2" { Context "Context 2" { $result = 1 It "Test 1" { $result | Should Be 1 } It "Test 2" { $result | Should Not Be 0 } It "Test 3" { $result | Should Be 1 } } }
PowerShellCorpus/PowerShellGallery/DevTools/1.1.8/Tests/Unit/SuiteOne.Tests.ps1
SuiteOne.Tests.ps1
Describe 'Tests Suit 1' { Context 'Strict mode' { Set-StrictMode -Version latest It 'Should succeed on event' { $null | Should BeNullOrEmpty $true | Should be $true } It 'Should error on event without parameter' { { throw "hello" } | Should Throw } It 'Should not error on event with parameter' { { } | Should Not Throw } It 'Should return true when event exists and parameter is used' { $true | Should be $True } It "Should return false when event doesn't exist or we time out and parameter is used" { $false | Should be $False } } }
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Import-VisualStudioEnvironment.ps1
Import-VisualStudioEnvironment.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Import-VisualStudioEnvironment { <# .SYNOPSIS Sets up the current PowerShell instance with the Visual Studio environment variables so you can use those tools at the command line. .DESCRIPTION Command line usage is the way to go, but Visual Studio requires numerous environment variables set in order to properly work. Since those are controlled by the vcvarsall.bat or VSDEVCMD.cmd cmd scripts, it's a pain to get working. This cmdlet does the work of calling the specific vcvarsall.bat/VSDEVCMD.CMD file for the specific version of Visual Studio you want to use. On VS 2015 and prior if the vcvarsall.bat file does not exist, which happens if you do not install the C++ tools, this cmdlet will use vsdevcmd.bat instead. This implementation uses the registry to look up the installed Visual Studio versions and does not rely on any preset environment variables such as VS110COMNTOOLS. .PARAMETER VSVersion The version of Visual Studio you want to use. If left to the default, Latest, the script will look for the latest version of Visual Studio installed on the computer as the tools to use. Specify 2013, 2015, or 2017 for a specific version. .PARAMETER Architecture The tools architecture to use. This defaults to the $env:PROCESSOR_ARCHITECTURE environment variable so x86 and x64 are automatically handled. The valid architecture values are x86, amd64, and arm. If the C++ tools were not installed, this parameter is ignored for VS 2015 and prior because their vsdevcmd.bat only sets the environment for 32-bit tools. .PARAMETER AdditionalOptions Starting with VS 2017, there are additional options such as -app_platform and -winsdk. If you want to set those options add them here. The string value is passed directly to the VS 2017+ VSDEVCMD.CMD with no checking. .NOTES There is a bug in the VS 2017 RC environment batch files. If you used this cmdlet to import the VS 2015 environment and then attempt to import the VS 2017 environment in the same shell, the VS 2017 batch files fail because of an improperly formed command. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> # This triggers on $vsDirectory even though it is used everywhere. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "", Scope="Function")] param ( [Parameter(Position=0)] [ValidateSet("Latest", "2013", "2015", "2017")] [string] $VSVersion = "Latest", [Parameter(Position=1)] [ValidateSet("x86", "amd64", "arm")] [string] $Architecture = ($Env:PROCESSOR_ARCHITECTURE).ToLower(), [string]$AdditionalOptions = "" ) $versionSearchKey = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" if ([IntPtr]::size -ne 8) { $versionSearchKey = "HKLM:\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" } $vsDirectory = "" # The saved off version number as I'll need it later to determine if this is VS 2017 or higher. $usingVersion = 0.0 if ($VSVersion -eq 'Latest') { # Find the largest number in the install lookup directory and that will # be the latest version. $biggest = 0.0 Get-RegistryKeyPropertiesAndValues $versionSearchKey | ForEach-Object { if ([System.Convert]::ToDecimal($_.Property, [CultureInfo]::InvariantCulture) -gt ` [System.Convert]::ToDecimal($biggest, [CultureInfo]::InvariantCulture)) { $biggest = $_.Property $vsDirectory = $_.Value } } $usingVersion = $biggest } else { $propVal = switch($VSVersion) { "2013" { "12.0" } "2015" { "14.0" } "2017" { "15.0" } default { throw "Unknown version of Visual Studio!" } } $usingVersion = [System.Convert]::ToDecimal($propVal, [CultureInfo]::InvariantCulture) if (Test-PathReg -Path $versionSearchKey -Property $propVal) { $vsDirectory = (Get-ItemProperty -Path $versionSearchKey -WarningAction SilentlyContinue).$propVal } else { $vsDirectory = $null } } if ([String]::IsNullOrEmpty($vsDirectory)) { throw "The requested Visual Studio version is not installed" } # Turns out some people install VS without the C++ tools. Crazy, I know! # This check works for VS 2105 and prior. if (Test-Path -Path "$vsDirectory\vc\vcvarsall.bat") { # Got the VS directory, now setup to make the call. Invoke-CmdScript -script "$vsDirectory\vc\vcvarsall.bat" -parameters "$Architecture" } else { # Have to do another check here. VSDEVCMD.BAT has changed with VS 2017+ It # supports parameters and is the main file. if ($usingVersion -lt 15.0) { Write-Verbose -Message "Falling back to VSDEVCMD.BAT for VS 2015 and prior, which only supports the 32-bit tools." # Use VsDevCmd.bat instead. Invoke-CmdScript -script "$vsDirectory\Common7\Tools\VsDevCmd.bat" } else { # This is VS 2017+ so poke on the architecture value. $parameters = "-no_logo -arch=$Architecture -host_arch=$Architecture" if ($AdditionalOptions -ne "") { $parameters += " $AdditionalOptions" } Invoke-CmdScript -script "$vsDirectory\Common7\Tools\VsDevCmd.bat" -parameters $parameters } } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU3a25s3h95HBDVr0Y7WPwxyF6 # Kq2ggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkw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ABIIBAN9wHC6U6G01RjwlRrr0XP3o # xJVkFvi/x+sL8XsmV3ckoZ5hriUL3wuCLB+LeyuQWhqKtwB03pLbR4KrR8X2PaOh # 0kCE0rPgOJ21yOD/b6MK21ivU2V/9iKjsLXisWmrW+9natXwXw+6WJbtgUZiH4XI # 7bV3JXHycWomu/YUFjYSWRbugmavqFRIOTQuKP1NvbVf9dB9sxdYPA7WnhoJ5Ekc # paddIGgYjuFebh+S/W8L2KIH90KxGXS1PikQpttcnvwukQoNNO0L4AmxPrpf3KA8 # CzOSG3W8lB1Hd3OQ9OxqZ9SrwjBsi6Yw6LApe+S3AoxTDhVyWy0D/2W45xqpwdM= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Get-DumpAnalysis.ps1
Get-DumpAnalysis.ps1
############################################################################### # WintellectPowerShell Module # Copyright (c) 2015-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest function Get-DumpAnalysis { <# .SYNOPSIS Automates minidump analysis. .DESCRIPTION The CDB $< command allows you read in a text file and each line be executed in the CDB command line. When you start CDB with the -c command line switch you can tell it to execute specific commands. Thus if you use the following -c option, you can script CDB. cdb.exe -c "$$<Commands.txt" This script wraps up the CDB -c trick to let you pipe in a bunch of files and have the same commands run on all individual files. All output is TEE'd to the screen and to a file. The log file written will be named <minidump name>-<debugscriptname>.log .PARAMETER Files The minidump files to process. .PARAMETER DebuggingScript The script file to pass to CDB. You specify the CDB commands in this file one line at a time. For comments, CDB supports using the "*" character at the start of the line. .PARAMETER CdbProgramPath By default this script assumes that CDB is the PATH environment variable. If you would like to specify the particular CDB to run, put the full path and CDB.EXE into this parameter. .EXAMPLE Get-DumpAnalysis -Files .\MyMiniDump.dmp -DebuggingScript .\BasicAnalysis.txt This will run the commands in BasicAnalysis.txt on MyMiniDump.dmp and the output will be writting to MyMiniDump.dmp-BasicAnalysis.txt.log .EXAMPLE Get-ChildItem *.dmp | Get-DumpAnalsys -DebuggingScript .\MoreStuff.txt For all mini dump files will be piped to Get-DumpAnalysis and have the debug script MoreStuff.txt run on each one. .NOTES Here is an example of a debugging script. Note that asterisks are treated as comments by CDB but are output to the log. It's a good idea to use comments so you can identify where different commands run so you can use a regular expression to pull them out. * Do the basic analysis !analyze -v * Get all the loaded modules lmv .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> [CmdletBinding(SupportsShouldProcess=$true)] param ( [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Mandatory=$true, HelpMessage="Please enter the minidump file to process")] [Alias('FullName')] [string]$Files, [Parameter(Mandatory=$true, HelpMessage="Please enter WinDBG script file to use")] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [string]$DebuggingScript, [AllowEmptyString()] [string]$CdbProgramPath="" ) begin { Set-StrictMode -Version Latest # If the path to the version of cdb is null, use the first one # found in the path. if ($CdbProgramPath.Length -eq 0) { $CdbProgramPath = (Get-Command -Name "cdb.exe" -ErrorAction Stop).Source } Test-Path -Path $CdbProgramPath -ErrorAction Stop | Out-Null Write-Verbose -Message "Using cdb from $CdbProgramPath" } process { foreach ($file in $Files) { $scriptName = [System.IO.Path]::GetFileName($DebuggingScript) $fullScriptPath = (Resolve-Path -Path $DebuggingScript).Path $file = (Resolve-Path -Path $file).Path $logFile = $file + "-" + $scriptName + ".log" Write-Verbose -Message "Logging to file $logFile" if ($PSCmdlet.ShouldProcess("$CdbProgramPath -z $file -c `"`$$<$fullScriptPath;q`"", "Executing")) { &$CdbProgramPath -z $file -c "`$`$<$fullScriptPath;Q" | Tee-Object -FilePath $logFile } } } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgE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AlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVT # RVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5j # b20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3QtT2JqZWN0Ag8WiPA5JV5jjmkUOQfm # MwswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI # hvcNAQkFMQ8XDTE3MDExMjIzMDcwMVowIwYJKoZIhvcNAQkEMRYEFISPkeuhlZVK # YnJw1CX6Tw2k5h/SMA0GCSqGSIb3DQEBAQUABIIBACX2m6QxlEo7fb7nbWD9ObYt # LVZDrri+PF5snWr56nRQnRRvprLTiBNuXPr9yhiKeGduUGdx5E1RLpWQ/5hj5puG # nakYbyrH0OKt/gYrWvlvqdpSxXGt+luMbrjh8I4j8TarvYlX8uM4M8irQ+O5Hrtq # L6t/VKQHJRWzN4+JAnX8b5gmfB1cNH7FkuidV12HwKSW6cu40AsfK31Cvr6xiRA2 # UsGcALCiuBpYZw3SwC9gyiXngqMohogeF9uJQxGSHVa2bisbFy6pmRXmRO4frMhF # Lf1eJQOc9w1a2CfCmM8SSHhOt/GR1MK0mvfNmbx19S25Rgwft/a06Ll+3qO+Kw4= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Invoke-CmdScript.ps1
Invoke-CmdScript.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest function Invoke-CmdScript { <# .SYNOPSIS Executes the specified command script and imports the environment into current PowerShell instance. .DESCRIPTION Running development tools at the command line in PowerShell can be a hassle since they rely on environment varibles and those are set through batch files. This cmdlet runs those batch files and imports any set environment variables into the running PowerShell instance. .PARAMETER script The required batch file to run. .PARAMETER parameters The optional parameters to pass to the batch file. .NOTES The original script is by Lee Holmes. I updated the script to make removing environment variables work. .LINK http://www.leeholmes.com/blog/2006/05/11/nothing-solves-everything-%e2%80%93-powershell-and-other-technologies/ https://github.com/Wintellect/WintellectPowerShell #> param ( [Parameter(Mandatory=$true, Position=0, HelpMessage="Please specify the command script to execute.")] [string] $script, [Parameter(Position=1)] [string] $parameters="" ) # Save off the current environment variables in case there's an issue $oldVars = $(Get-ChildItem -Path env:\) $tempFile = [IO.Path]::GetTempFileName() try { ## Store the output of cmd.exe. We also ask cmd.exe to output ## the environment table after the batch file completes cmd /c " `"$script`" $parameters && set > `"$tempFile`" " if ($LASTEXITCODE -ne 0) { throw "Error executing CMD.EXE: $LASTEXITCODE" } # Before we delete the environment variables get the output into a string # array. $vars = Get-Content -Path $tempFile # Clear out all current environment variables in PowerShell. Get-ChildItem -Path env:\ | Foreach-Object { set-item -force -path "ENV:\$($_.Name)" -value "" } ## Go through the environment variables in the temp file. ## For each of them, set the variable in our local environment. $vars | Foreach-Object { if($_ -match "^(.*?)=(.*)$") { Set-Content -Path "env:\$($matches[1])" -Value $matches[2] } } } catch { "ERROR: $_" # Any problems, restore the old environment variables. $oldVars | ForEach-Object { Set-Item -Force -Path "ENV:\$($_.Name)" -value $_.Value } } finally { Remove-Item -Path $tempFile -Force -ErrorAction SilentlyContinue } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUlhxOeyiqn+j3naljdmd2FjUx # okCggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNh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jjmkUOQfm # MwswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI # hvcNAQkFMQ8XDTE3MDExMjIzMDcxNlowIwYJKoZIhvcNAQkEMRYEFAPoxifmSmGt # xpYtKjQRTV8xNHPoMA0GCSqGSIb3DQEBAQUABIIBALUKY/dOOOkcih/jiTXaUk5V # II5IZbX+WcMupkgI9gd2T4HuwA3waUec3kzNPlawo9qjoImMdqRFiAozm34Cwo8V # 22Mc8OwRwwr8hfKDa7/UFt//0FWYEQ8ULs/VTeF3LzMapzATtCCmejYcscm2QRJ1 # GSD241DAIl5sS8HAeEGO0c0ncu/BYJ3wToV2X2J8Enx6hJC+dEmngAQNcySyb7kl # fVbAJY8XWMgsJam1efdWJ2fG/Sr3eyCbNRaHYJXlI29xVgwU+PopWljuff8YHu7s # QG1Wor9Lr2lW26sQEPr9X0YNkaAmAO00eqXy0cw1cw9WDJzwmQskkk58QCKsS1o= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/SymbolsSource.ps1
SymbolsSource.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Script Global Variables ############################################################################### # The array that contains all the versions. $script:vsVersionArray = "2012", "2013", "2015", "2017" ############################################################################### # Module Only Functions ############################################################################### # Does the lookups and builds the hash tables for Get-SourceServer, Get-SymbolServer function GetCommonSettings($propertyValue="", $envVariable="") { $returnHash = [ordered]@{} # The XPath to look for. $xPathLookup = $script:dbgPropertyXPath -f $propertyValue # Loop through all the VS versions. for ($i = 0; $i -lt $script:vsVersionArray.Length; $i++) { [xml]$settings = OpenSettingsFile $script:vsVersionArray[$i] if ($null -ne $settings) { # Look for the property itself. $propNode = $settings | Select-Xml -XPath $xPathLookup # Add the value to the hash table. $returnHash["VS " + $script:vsVersionArray[$i]] = $propNode.Node.InnerText } } # Do the environment variable, too. if ($envVariable -ne "") { $envVal = Get-ItemProperty -Path HKCU:\Environment -Name $envVariable -ErrorAction SilentlyContinue if ($null -ne $envVal) { $returnHash[$envVariable] = $envVal.$envVariable } } return $returnHash } function CreateDirectoryIfNeeded { [CmdletBinding(SupportsShouldProcess=$true)] param ( [string] $directory="" ) if ($PSCmdlet.ShouldProcess($directory,"Creating directory")) { if ( ! (Test-Path -Path $directory -type "Container")) { New-Item -type directory -Path $directory > $null } } } # Makes doing ShouldProcess easier. function Set-ItemPropertyScript { [CmdletBinding(SupportsShouldProcess=$true)] param ( [Parameter(Mandatory=$true)] $path, [Parameter(Mandatory=$true)] $name, [Parameter(Mandatory=$true)] $value, $type=$null ) $propString = "Item: " + $path.ToString() + " Property: " + $name if ($PSCmdLet.ShouldProcess($propString ,"Set Property")) { if ($null -eq $type) { Set-ItemProperty -Path $path -Name $name -Value $value } else { Set-ItemProperty -Path $path -Name $name -Value $value -Type $type } } } function SetInternalSymbolServer([xml]$settings, $cacheDirectory, $symPath) { CreateDirectoryIfNeeded -directory $CacheDirectory # Turn off Just My Code. $xPathLookup = $script:dbgPropertyXPath -f "JustMyCode" $justMyCode = $settings | Select-Xml -XPath $xPathLookup $justMyCode.Node.InnerText = "0" # Turn on Source Server Diagnostics as that's a good thing. :) $xPathLookup = $script:dbgPropertyXPath -f "ShowSourceServerDiagnostics" $ssDiag = $settings | Select-Xml -XPath $xPathLookup $ssDiag.Node.InnerText = "1" # Turn off .NET Framework Source stepping. $xPathLookup = $script:dbgPropertyXPath -f "FrameworkSourceStepping" $noFramework = $settings | Select-Xml -XPath $xPathLookup $noFramework.Node.InnerText = "0" # Turn off using the Microsoft symbol servers. $xPathLookup = $script:dbgPropertyXPath -f "SymbolUseMSSymbolServers" $noMSSymServers = $settings | Select-Xml -XPath $xPathLookup $noMSSymServers.Node.InnerText = "0" # Set the symbol cache dir to the same value as used in the environment # variable. $xPathLookup = $script:dbgPropertyXPath -f "SymbolCacheDir" $cacheDir = $settings | Select-Xml -XPath $xPathLookup $cacheDir.Node.InnerText = $CacheDirectory } function SetPublicSymbolServer([xml]$settings, $cacheDirectory, $symPath) { CreateDirectoryIfNeeded -directory $CacheDirectory # Turn off Just My Code. $xPathLookup = $script:dbgPropertyXPath -f "JustMyCode" $justMyCode = $settings | Select-Xml -XPath $xPathLookup $justMyCode.Node.InnerText = "0" # Turn on .NET Framework Source stepping. $xPathLookup = $script:dbgPropertyXPath -f "FrameworkSourceStepping" $noFramework = $settings | Select-Xml -XPath $xPathLookup $noFramework.Node.InnerText = "1" # Turn on Source Server Support. $xPathLookup = $script:dbgPropertyXPath -f "UseSourceServer" $useSS = $settings | Select-Xml -XPath $xPathLookup $useSS.Node.InnerText = "1" # Turn on Source Server Diagnostics as that's a good thing. :) $xPathLookup = $script:dbgPropertyXPath -f "ShowSourceServerDiagnostics" $ssDiag = $settings | Select-Xml -XPath $xPathLookup $ssDiag.Node.InnerText = "1" # It's very important to turn off requiring the source to match exactly. # With this flag on, .NET Reference Source Stepping doesn't work. $xPathLookup = $script:dbgPropertyXPath -f "UseDocumentChecksum" $noDoc = $settings | Select-Xml -XPath $xPathLookup $noDoc.Node.InnerText = "0" # Turn off using the Microsoft symbol servers. $xPathLookup = $script:dbgPropertyXPath -f "SymbolUseMSSymbolServers" $noMSSymServers = $settings | Select-Xml -XPath $xPathLookup $noMSSymServers.Node.InnerText = "0" # Set the VS SymbolPath setting. $xPathLookup = $script:dbgPropertyXPath -f "SymbolPath" $symPath = $settings | Select-Xml -XPath $xPathLookup $symPath.Node.IsEmpty = $true # Tell VS that all paths are empty. $xPathLookup = $script:dbgPropertyXPath -f "SymbolPathState" $symPathState = $settings | Select-Xml -XPath $xPathLookup $symPathState.Node.IsEmpty = $true # Set the symbol cache dir to the same value as used in the environment # variable. $xPathLookup = $script:dbgPropertyXPath -f "SymbolCacheDir" $cacheDir = $settings | Select-Xml -XPath $xPathLookup $cacheDir.Node.InnerText = $CacheDirectory } ############################################################################### # Public Cmdlets ############################################################################### function Get-SourceServer { <# .SYNOPSIS Returns a hashtable of the current source server settings. .DESCRIPTION Returns a hashtable with the current source server directories settings for VS 2012-2017, and the _NT_SOURCE_PATH enviroment variable used by WinDBG. .OUTPUTS HashTable The keys are, if all present, VS 2012-2017, and WinDBG. The values are those set for each debugger. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> GetCommonSettings SourceServerExtractToDirectory _NT_SOURCE_PATH } ############################################################################### function Get-SymbolServer { <# .SYNOPSIS Returns a hashtable of the current symbol server settings. .DESCRIPTION Returns a hashtable with the current source server directories settings for VS 2012-2017, and the _NT_SYMBOL_PATH enviroment variable. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> GetCommonSettings SymbolCacheDir _NT_SYMBOL_PATH } ############################################################################### function Set-SourceServer { <# .SYNOPSIS Sets the source server directory. .DESCRIPTION Sets the source server cache directory for VS 2012-2017, and WinDBG through the _NT_SOURCE_PATH environment variable to all reference the same location. This ensures you only download the file once no matter which debugger you use. Because this cmdlet sets an environment variable you need to log off to ensure it's properly set. .PARAMETER CacheDirectory The directory to use. If the directory does not exist, it will be created. .PARAMETER CurrentEnvironmentOnly If specified will only set the current PowerShell window _NT_SOURCE_PATH environment variable and not overwrite the global settings. This is primarily for use with WinDBG as Visual Studio does not use this environment variable. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> [CmdletBinding(SupportsShouldProcess=$true)] # This triggers on the environment variable setting ($env:_NT_SOURCE_PATH = "SRV*" + $CacheDirectory) # That seems like an issue in the rule. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "", Scope="Function")] param ( [Parameter(Mandatory=$true, HelpMessage="Please specify the source server cache directory")] [string] $CacheDirectory, [switch] $CurrentEnvironmentOnly ) # Check if VS is running if we are going to be setting the global stuff. if (($CurrentEnvironmentOnly -eq $false) -and (Get-Process -Name 'devenv' -ErrorAction SilentlyContinue)) { throw "Visual Studio is running. Please close all instances before executing Set-SourceServer" } # Does the cache directory exist or need to be created? CreateDirectoryIfNeeded $CacheDirectory # If just setting the current environment, that's easy. if ($CurrentEnvironmentOnly) { $env:_NT_SOURCE_PATH = "SRV*" + $CacheDirectory } else { # The XPath to look for. $xPathLookup = $script:dbgPropertyXPath -f "SourceServerExtractToDirectory" # Loop through all VS versions. for ($i = 0; $i -lt $script:vsVersionArray.Length; $i++) { [xml]$settings = OpenSettingsFile $script:vsVersionArray[$i] if ($null -ne $settings) { if ($PSCmdlet.ShouldProcess("VS " + $script:vsVersionArray[$i], "Setting Source Server")) { # Grab the SourceServerExtractToDirectory element $extractDirNode = $settings | Select-Xml -XPath $xPathLookup # Set it. $extractDirNode.Node.InnerXml = $CacheDirectory WriteSettingsFile $script:vsVersionArray[$i] $settings } } } # Always set the _NT_SOURCE_PATH value for WinDBG. Set-ItemProperty -Path HKCU:\Environment -Name _NT_SOURCE_PATH -Value "SRV*$CacheDirectory" } if ($CurrentEnvironmentOnly) { Write-Verbose -Message "`nThe _NT_SOURCE_PATH environment variable was updated for this window only`n" } else { Write-Verbose -Message "`nPlease log out to activate the new source server settings`n" } } ############################################################################### function Set-SymbolServer { <# .SYNOPSIS Sets up a computer to use a symbol server. DESCRIPTION Sets up both the _NT_SYMBOL_PATH environment variable as well as VS 2012-2017, (for all installed) to use a common symbol cache directory as well as common symbol servers. Optionally can be used to only set _NT_SYMBOL_PATH for an individual PowerShell window. .PARAMETER Internal Sets the symbol server to use to http://SymWeb. Visual Studio will not use the public symbol servers. This will turn off the .NET Framework Source Stepping. This switch is intended for internal Microsoft use only. You must specify either -Internal or -Public to the script. .PARAMETER Public Sets the symbol server to use as the two public symbol servers from Microsoft. All the appropriate settings are configured to properly have .NET Reference Source stepping working. .PARAMETER CacheDirectory Defaults to C:\SYMBOLS\PUBLIC for -Public and C:\SYMBOLS\INTERNAL for -Internal. .PARAMETER SymbolServers A string array of additional symbol servers to use. If -Internal is set, these additional symbol servers will appear before HTTP://SYMWEB. If -Public is set, these symbol servers will appear before the public symbol servers so both the environment variable and Visual Studio have the same search order. .PARAMETER CurrentEnvironmentOnly If specified will only set the current PowerShell window _NT_SYMBOL_PATH environment variable and not overwrite the global settings. This is primarily for use with WinDBG as Visual Studio requires registry settings for the cache directory. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> [CmdLetBinding(SupportsShouldProcess=$true)] param ( [switch] $Internal, [switch] $Public, [string] $CacheDirectory="", [string[]] $SymbolServers=@(), [switch] $CurrentEnvironmentOnly) # Do the parameter checking. if ($Internal -eq $Public) { throw "You must specify either -Internal or -Public" } # Check if VS is running if we are going to be setting the global stuff. if (($CurrentEnvironmentOnly -eq $false) -and (Get-Process -Name 'devenv' -ErrorAction SilentlyContinue)) { throw "Visual Studio is running. Please close all instances before running Set-SymbolServer" } if ($Internal) { if ($CacheDirectory.Length -eq 0) { $CacheDirectory = "C:\SYMBOLS\INTERNAL" } $symPath = "" for ($i = 0 ; $i -lt $SymbolServers.Length ; $i++) { $symPath += "SRV*$CacheDirectory*" $symPath += $SymbolServers[$i] $symPath += ";" } $symPath += "SRV*$CacheDirectory*http://SYMWEB" if ($CurrentEnvironmentOnly) { CreateDirectoryIfNeeded -directory $CacheDirectory $env:_NT_SYMBOL_PATH = $symPath } else { # Set the environment variable. Set-ItemPropertyScript HKCU:\Environment _NT_SYMBOL_PATH $symPath for ($i = 0; $i -lt $script:vsVersionArray.Length; $i++) { [xml]$settings = OpenSettingsFile $script:vsVersionArray[$i] if ($null -ne $settings) { if ($PSCmdlet.ShouldProcess("VS "+ $script:vsVersionArray[$i], "Symbol Server settings for internal usage")) { SetInternalSymbolServer $settings $CacheDirectory $symPath WriteSettingsFile $script:vsVersionArray[$i] $settings } } } } } else { if ($CacheDirectory.Length -eq 0) { $CacheDirectory = "C:\SYMBOLS\PUBLIC" } # It's public so we have a little different processing to do as there are # two public symbol servers where MSFT provides symbols. $refSrcPath = "$CacheDirectory*http://referencesource.microsoft.com/symbols" $msdlPath = "$CacheDirectory*https://msdl.microsoft.com/download/symbols" $extraPaths = "" # Poke on any additional symbol servers. I've keeping everything the # same between VS as WinDBG. for ($i = 0 ; $i -lt $SymbolServers.Length ; $i++) { $extraPaths += "SRV*$CacheDirectory*" $extraPaths += $SymbolServers[$i] $extraPaths += ";" } $envPath = "$extraPaths" + "SRV*$refSrcPath;SRV*$msdlPath" if ($CurrentEnvironmentOnly) { CreateDirectoryIfNeeded -directory $CacheDirectory $env:_NT_SYMBOL_PATH = $envPath } else { Set-ItemPropertyScript HKCU:\Environment _NT_SYMBOL_PATH $envPath for ($i = 0; $i -lt $script:vsVersionArray.Length; $i++) { [xml]$settings = OpenSettingsFile $script:vsVersionArray[$i] if ($null -ne $settings) { if ($PSCmdlet.ShouldProcess("VS "+ $script:vsVersionArray[$i], "Symbol Server settings for public usage")) { SetPublicSymbolServer $settings $CacheDirectory $envPath WriteSettingsFile $script:vsVersionArray[$i] $settings } } } } } if ($CurrentEnvironmentOnly) { Write-Verbose -Message "`nThe _NT_SYMBOL_PATH environment variable was updated for this window only`n" } else { Write-Verbose -Message "`nPlease log out to activate the new symbol server settings`n" } } ############################################################################### function Get-SourceServerFiles { <# .SYNOPSIS Prepopulate your symbol cache with all your Source Server extracted source code. .DESCRIPTION Recurses the specified symbol cache directory for PDB files with Source Server sections and extracts the source code. This script is a simple wrapper around SRCTOOl.EXE from the Debugging Tools for Windows (AKA WinDBG). If WinDBG is in the PATH this script will find SRCTOOL.EXE. If WinDBG is not in your path, use the SrcTool parameter to specify the complete path to the tool. .PARAMETER CacheDirectory The required cache directory for the local machine. .PARAMETER SrcTool The optional parameter to specify where SRCTOOL.EXE resides. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] param ( [Parameter(Mandatory=$true, HelpMessage="Please specify the source server directory")] [string] $CacheDirectory , [Parameter(HelpMessage="The optional full path to SCRTOOL.EXE")] [string] $SrcTool = "" ) if ($SrcTool -eq "") { # Go with the default of looking up WinDBG in the path. $windbg = Get-Command -Name windbg.exe -ErrorAction SilentlyContinue if ($null -eq $windbg) { throw "Please use the -SrcTool parameter or have WinDBG in the path" } $windbgPath = Split-Path -Path ($windbg.Definition) $SrcTool = $windbgPath + "\SRCSRV\SRCTOOL.EXE" } if ($null -eq (Get-Command -Name $SrcTool -ErrorAction SilentlyContinue)) { throw "SRCTOOL.EXE does not exist." } if ((Test-Path -Path $CacheDirectory) -eq $false) { throw "The specified cache directory does not exist." } # Get all the PDB files, execute SRCTOOL.EXE on each one. Get-ChildItem -Recurse -Include *.pdb -Path $cacheDirectory | ` ForEach-Object { &$SrcTool -d:$CacheDirectory -x $_.FullName } } ############################################################################### function Set-SymbolAndSourceServer { <# .SYNOPSIS Sets up a computer to use a symbol and source server. .DESCRIPTION Sets up both the _NT_SYMBOL_PATH and _NT_SOURCE_PATH environment variable as well as VS 2012-2017 (for each installed) to use a common symbol and source cache directory as well as common symbol servers. Optionally can be used to only set _NT_SYMBOL_PATH and _NT_SOURCE_PATH for an individual PowerShell window. This is a wrapper around Set-SymbolServer and Set-SourceServer. These have been a single command anyway. .PARAMETER Internal Sets the symbol server to use to http://SymWeb. Visual Studio will not use the public symbol servers. This will turn off the .NET Framework Source Stepping. This switch is intended for internal Microsoft use only. You must specify either -Internal or -Public to the script. .PARAMETER Public Sets the symbol server to use as the two public symbol servers from Microsoft. All the appropriate settings are configured to properly have .NET Reference Source stepping working. .PARAMETER CacheDirectory Defaults to C:\SYMBOLS\PUBLIC for -Public and C:\SYMBOLS\INTERNAL for -Internal. .PARAMETER SymbolServers A string array of additional symbol servers to use. If -Internal is set, these additional symbol servers will appear before HTTP://SYMWEB. If -Public is set, these symbol servers will appear before the public symbol servers so both the environment variable and Visual Studio have the same search order. .PARAMETER CurrentEnvironmentOnly If specified will only set the current PowerShell window _NT_SYMBOL_PATH and _NT_SOURCE_PATH environment variable and not overwrite the global settings. This is primarily for use with WinDBG as Visual Studio requires settings files for the cache directory and other settings. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> [CmdLetBinding(SupportsShouldProcess=$true)] param ( [switch] $Internal, [switch] $Public, [string] $CacheDirectory="", [string[]] $SymbolServers=@(), [switch] $CurrentEnvironmentOnly) # Splatting is just so cool... Set-SymbolServer @psBoundParameters if ($CacheDirectory.Length -eq 0) { if ($Public) { $CacheDirectory = "C:\SYMBOLS\PUBLIC" } else { $CacheDirectory = "C:\SYMBOLS\INTERNAL" } } Set-SourceServer -CacheDirectory $CacheDirectory } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU4m79foyVB9Hi5lhVBYufkts5 # Ctaggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3R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uTkxbg6SXy/QsWomO7J3YI0yL2doweH # fWoMp7BrkboLtnJSsDsnO4o60ZXCV4svo1nAD5FyXckgoAyBdI3wv14Zk5BdI3xJ # VIWtPrJLsJ+JMTYRBddEOiUw2y+sSHCxOYQTCt7xrLYzImkDuaFkxr9bcvfosx6r # GyTMcL35xLLC91LjeLWzMx7BEjqkspP8z5T/hq6xLDDzSnvA7xsi41cN5MtBlEyL # Uxn+lSXH7nS20knS1qjkcwz8/pQNPetAroHkLokMmJWKdIMwnsmeWjBwjkrXyfI= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Set-Signatures.ps1
Set-Signatures.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2014-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest function Set-Signatures { <# .SYNOPSIS Simple wrapper script for digitally signing files .DESCRIPTION Automatically grabs the first code signing certificate in CurrentUser\My and uses the Comodo time stamp server so you just have to worry about the files. .PARAMETER Files The files to digitally sign. Any files that can be normally digitally signed can be passed here. .PARAMETER Certificate Defaults to first code signing certificate in the cert:\CurrentUser\My certificate storage that does not have Azure in the name. .PARAMETER TimeStampServer The timestamp server to use. Defaults to http://timestamp.comodoca.com/authenticode .LINK http://www.wintellectnow.com http://www.wintellect.com/devcenter/author/jrobbins #> # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] [CmdletBinding(SupportsShouldProcess=$true)] param ( [Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Mandatory=$true, HelpMessage="Please enter the PowerShell files to sign")] [Alias('FullName')] $Files, [ValidateNotNull()] $Certificate = @(Get-ChildItem -Path cert:\CurrentUser\My -CodeSigning | Where-Object { $_.Subject -notlike "*Azure*" } | Select-Object -First 1)[0], [ValidateNotNull()] $TimeStampServer = "http://timestamp.comodoca.com/authenticode" ) begin { # Because this is a script file, nothing can come between the params # and begin statements. Interestingly, if something does PowerShell # ignores the begin and when it hits the process, treats it as the # alias Get-Process. :) Set-StrictMode -Version Latest } process { foreach ($file in $Files) { # Always support -whatif if ($PSCmdlet.ShouldProcess("$_", "Set-AuthenticodeSignature")) { Set-AuthenticodeSignature -FilePath $file ` -Certificate $Certificate ` -TimestampServer $TimeStampServer } } } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUAzgWOPFu1fk3xov62Ov/YjTF # BMOggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE # BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKjAoBgNVBAMT # IUNPTU9ETyBTSEEtMSBUaW1lIFN0YW1waW5nIFNpZ25lcjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBAOnpPd/XNwjJHjiyUlNCbSLxscQGBGue/YJ0UEN9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# aO17sczBlCusMBm6xRnMi9ive9mr0cBxe2hF0GE8Og59ma8PsOJyi+vEzCelSEQ= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Set-ProjectProperties.ps1
Set-ProjectProperties.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -Version Latest ############################################################################### # Script Global Variables ############################################################################### # The namespace for everything in a VS project file. $script:BuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003" # These are the settings used as the defaults for the general property group. $script:DefaultDotNetGeneralProperties = @{ } # The default properties for both debug and release builds. $script:DefaultDotNetConfigProperties = @{ # Stop the build on any compilation warnings. "TreatWarningsAsErrors" = "true"; # Always check for numeric wrapping. Does not cause perf issues. "CheckForOverflowUnderflow" = "true"; # Always run code analysis. This will set the Microsoft minimum rules if the CodeAnalysisRuleSet # property is not specified. "RunCodeAnalysis" = "true"; # Always produce an XML document file. This script block gets the binary output directory and # puts the doc comment file there as well. "DocumentationFile" = { # The configuration to add the DocumentationFile element into. param($config) # Go find the main property group to get the name of the assembly. $assemblyName = $config.ParentNode.GetElementsByTagName("AssemblyName")[0].InnerText # Set the output name to be the path. This works in both C# and VB. $valueName = Join-Path -Path $config.OutputPath -ChildPath "$assemblyName.XML" ReplaceNode -document $config.ParentNode.ParentNode ` -topElement $config ` -elementName "DocumentationFile" ` -elementValue $valueName } } # The array of default rulesets when setting the <CodeAnalysisRulesSet> # property so I don't try to do relative paths when setting it. $script:BuiltInRulesets = "AllRules.ruleset", "BasicCorrectnessRules.ruleset", "BasicDesignGuidelineRules.ruleset", "ExtendedCorrectnessRules.ruleset", "ExtendedDesignGuidelineRules.ruleset", "GlobalizationRules.ruleset", "ManagedMinimumRules.ruleset", "MinimumRecommendedRules.ruleset", "MixedMinimumRules.ruleset", "MixedRecommendedRules.ruleset", "NativeMinimumRules.ruleset", "NativeRecommendedRules.ruleset", "SecurityRules.ruleset" ############################################################################### # Public Cmdlets ############################################################################### function Set-ProjectProperties { <# .SYNOPSIS A script to make Visual Studio 2013 and higher project management easier for .NET Standard/Full projects. .DESCRIPTION When you need to make a simple change to a number of Visual Studio projects, it can be a large pain to manually go through and do those changes, especially since it's so easy to forget a project or mess up. This script's job is to automate the process so it's repeatable and consistent. If you do not specify any custom options, the script will automatically update projects with the following settings. [Note that at this time only C# projects are supported.] C# Debug and Release configurations --------------- - Treat warnings as errors - Check for arithmetic overflow and underflow - Enable code analysis with the default Code Analysis settings file. - Turn on creation of XML doc comment files. This script is flexible and you can control down to setting/changing an individual property if necessary. There are many examples in the Examples section. .PARAMETER Path This script can take pipeline input so you can easily handle deeply nested project trees. .PARAMETER OverrideDefaultProperties If set, will not apply the default settings built into the script and only take the properties to change with the CustomGeneralProperties and CustomConfigurationProperties parameters. .PARAMETER Configurations The array of configurations you want to change in the project file these are matching strings so if you specify something like 'Debug|AnyCPU' you are narrowing down the configuration to search. The default is 'Debug' and 'Release'. .PARAMETER CustomGeneralProperties The hash table for the general properties such as TargetFrameworkVersion, FileAlignment and other properties on the Application or Signing tab when looking at the project properties. The key is the property name and the value is either the string, or a script block that will be called to do custom processing. The script block will be passed the XML for all the global project properties so it can do additional processing. .PARAMETER CustomConfigurationProperties The hash table for the properties such as TreatWarningsAsErrors and RunCodeAnalysis which are per build configuration(s). Like the CustomGeneralProperties, the hash table key is the property to set and the value is the string to set or a script block for advanced processing. The script block will be passed the current configuration. See the examples for how this can be used. .EXAMPLE dir -recurse *.csproj | Set-ProjectProperties Recursively updates all the C# project files in the current directory with all the default settings. .EXAMPLE dir A.csproj | ` Set-ProjectProperties ` -CustomGeneralProperties @{"AssemblyOriginatorKeyFile" = "c:\dev\ConsoleApplication1.snk"} Updates A.CSPROJ to the default settings and adds the strong name key to the general properties. When specifying the AssemblyOriginatorKeyFile this script will treat file correctly and make it a relative path from the .CSPROJ folder location. When specifying a file, use the full path to the file so everything works correctly. .EXAMPLE dir B.csproj | ` Set-ProjectProperties ` -CustomConfigurationProperties @{ "CodeAnalysisRuleSet" = "c:\dev\WintellectRuleSet.ruleset"} Updates B.CSPROJ to the default settings and sets all configurations to enable Code Analysis with the custom rules file specified. Always specify the full path to the custom ruleset file as the script will handle making all references to it relative references in the configurations. If you specify one of the default Code Analysis rules files that shipped with Visual Studio, the script properly handles those as well. You can find all the default ruleset files by looking in the "<VS Install Dir>\Team Tools\Static Analysis Tools\Rule Sets" folder. .EXAMPLE dir C.csproj | Set-ProjectProperties ` -OverrideDefaultProperties ` -Configurations "Release" ` -CustomConfigurationProperties @{ "DefineConstants" = { param($config) $defines = $config.GetElementsByTagName("DefineConstants") $defines[0].InnerText = $defines[0].InnerText + ";FOOBAR" } } Updates C.CSPROJ by only adding a new define to only the Release configuration, keeping any existing define and not using the default changes. .INPUTS The Visual Studio project files to change. .NOTES Obviously, to maximize your usage you should be familiar with all the properties in Visual Studio project files and the properties in them. See http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx for more information. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] [CmdletBinding(SupportsShouldProcess=$true)] param ( [parameter(ValueFromPipeline, Mandatory=$true)] [System.IO.FileInfo[]] $Path, [switch] $OverrideDefaultProperties, [string[]] $Configurations = @("Debug", "Release"), [HashTable] $CustomGeneralProperties = @{}, [HashTable] $CustomConfigurationProperties = @{} ) begin { function ReplaceNode( $document=$null, $topElement=$null, [string] $elementName="", [string] $elementValue="") { Write-Debug -Message "Replacing $elementName=$elementValue" $origNode = $topElement[$elementName] if ($null -eq $origNode) { $node = $document.CreateElement($elementName,$script:BuildNamespace) $node.InnerText = $elementValue [void]$topElement.AppendChild($node) } else { $origNode.InnerText = $elementValue } } function ReplaceRelativePathNode([string] $fileLocation="", $document=$null, $topElement=$null, [string] $elementName="", [String] $fullUseFilePath="") { try { Push-Location -Path (Split-Path -Path $fileLocation) $relLocation = Resolve-Path -Path $fullUseFilePath -Relative Write-Debug -Message "Setting relative path $elementName=$relLocation" ReplaceNode -document $document ` -topElement $topElement ` -elementName $elementName ` -elementValue $relLocation } finally { Pop-Location } } function HandleCSharpMainProperties([string] $file, [xml] $fileXML=$null, [hashtable] $newMainProps=@{}) { # Go find the main property group which is the one with the ProjectGuid in it. $mainProps = $fileXML.Project.PropertyGroup | Where-Object { $null -ne $_["ProjectGuid"] } if (($null -eq $mainProps) -or ($mainProps -is [Array])) { throw "$file does not have the correct property group with the ProjectGuid or has multiple" } # Enumerate through the property keys. foreach ($item in $newMainProps.GetEnumerator()) { if ($item.Key -eq "AssemblyOriginatorKeyFile") { # Get the full path to the .SNK file specified. $snkFile = Resolve-Path -Path $item.Value -ErrorAction SilentlyContinue if ($null -eq $snkFile) { [string]$inputFile = $item.Value throw "Unable to find $inputFile, Please specify the full path to the file." } ReplaceRelativePathNode -fileLocation $file ` -document $fileXML ` -topElement $mainProps ` -elementName "AssemblyOriginatorKeyFile" ` -fullUseFilePath $snkFile # In case the user forgot, set the option to use the SNK file also. ReplaceNode -document $fileXML ` -topElement $mainProps ` -elementName "SignAssembly" ` -elementValue "true" } elseif ($item.Value -is [scriptblock]) { & $item.Value $mainProps } else { ReplaceNode -document $fileXML ` -topElement $mainProps ` -elementName $item.Key ` -elementValue $item.Value } } } function HandleCSharpConfigProperties([string] $file, [xml] $allFileXML=$null, [string] $configString="", [HashTable] $newProps=@{}) { # Get the configuration propery group. $configGroup = $allFileXML.GetElementsByTagName("PropertyGroup") | Where-Object { ($_.GetAttribute("Condition") -ne "") -and ($_.Condition -match $configString) } if (($null -eq $configGroup) -or ($configGroup -is [Array])) { throw "$file does not have the $configString property group or has multiple." } foreach($item in $newProps.GetEnumerator()) { # Have to treat the CodeAnalysisRuleSet property special so we get the # relative path set. if ($item.Key -eq "CodeAnalysisRuleSet") { # Is the ruleset file one of the default files? if ($script:BuiltInRulesets -contains $item.Value) { # Simple enough, plop in the default name and go on. ReplaceNode -document $allFileXML ` -topElement $configGroup ` -elementName $item.Key ` -elementValue $item.Value } else { # Get the full path to the .RuleSet file specified. $ruleFile = Resolve-Path -Path $item.Value -ErrorAction SilentlyContinue if ($null -eq $ruleFile) { [string]$inputFile = $item.Value throw "Unable to find $inputFile, Please specify the full path to the file." } ReplaceRelativePathNode -fileLocation $file ` -document $allFileXML ` -topElement $configGroup ` -elementName $item.Key ` -fullUseFilePath $ruleFile } # In case the user forgot, set the option to turn on using the code analysis file. ReplaceNode -document $allFileXML ` -topElement $configGroup ` -elementName "RunCodeAnalysis" ` -elementValue "true" } elseif ($item.Value -is [scriptblock]) { & $item.Value $configGroup } else { ReplaceNode -document $allFileXML ` -topElement $configGroup ` -elementName $item.Key ` -elementValue $item.Value } } } function ProcessCSharpProjectFile([string] $file) { # Try and read the file as XML. Let the errors go if it's not. [xml]$fileXML = Get-Content -Path $file # Check to see if this is a .NET Core project. if ($null -ne $fileXML.Project.Attributes["Sdk"]) { Write-Verbose ".NET Core project types not supported by this cmdlet!" return } # Build up the property hash values. [HashTable]$mainPropertiesHash = @{} [HashTable]$configPropertiesHash = @{} # Does the user just want to apply their properties? if ($OverrideDefaultProperties) { $mainPropertiesHash = $CustomGeneralProperties $configPropertiesHash = $CustomConfigurationProperties } else { $mainPropertiesHash = $script:DefaultDotNetGeneralProperties.Clone() if ($CustomGeneralProperties.Count -gt 0) { $mainPropertiesHash = Merge-HashTables -htold $mainPropertiesHash -htnew $CustomGeneralProperties } $configPropertiesHash = $script:DefaultDotNetConfigProperties.Clone() if ($CustomConfigurationProperties.Count -gt 0) { $configPropertiesHash = Merge-HashTables -htold $configPropertiesHash -htnew $CustomConfigurationProperties } } # Are there any main properties to change? if ($mainPropertiesHash.Count -gt 0) { HandleCSharpMainProperties -file $file -fileXML $fileXML -newMainProps $mainPropertiesHash } # Any configuration properties to change? if ($configPropertiesHash.Count -gt 0) { # Loop through the configuration array. foreach($config in $Configurations) { HandleCSharpConfigProperties -file $file -allFileXML $fileXML -configString $config -newProps $configPropertiesHash } } $fileXML.Save($file) } function ProcessProjectFile([string] $file) { # Is the file read only? if ((Get-ChildItem -Path $file).IsReadOnly) { throw "$file is readonly so it cannot be changed" } $ext = [System.IO.Path]::GetExtension($file) switch -Wildcard ($ext) { "*.csproj" { ProcessCSharpProjectFile -file $file } default { throw "Sorry, $file is an unsupported project type at this time." } } } } process { if ($PSCmdlet.ShouldProcess($path, "Updating settings")) { Write-Verbose "Processing : $path" ProcessProjectFile $path } } end { } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUrpc1cZmX+lWfXhfh//uoWS4M # AbOggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE # BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKjAoBgNVBAMT # IUNPTU9ETyBTSEEt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w7hI8nefmC1VgeMuOipq5Xzl7C0CFUh9amgQjxVecPqJkLciusP3S # +8Q03F4QVc8Z+ZxY99QXWk4ClH3IVY1eAnBzul3B7ucam7ax5nnQX7/xNGlJ3yRt # ABxHtUurN6QFOeCoglnLJw88DDsGjYXZZDFQXM0YmrgY+SDNBzk6XkY0P6CDkwQ= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Remove-IntelliTraceFile.ps1
Remove-IntelliTraceFile.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Remove-IntelliTraceFiles { <# .SYNOPSIS Removes extra IntelliTrace files that may have been left over from your debugging sessions. .DESCRIPTION Best practice with day to day debugging with IntelliTrace is to have the debugger store the IntelliTrace files. This is important because you will gain the ability to open the files after debugging. This option is not on by default, but can be turned on by going to the VS Options dialog, IntelliTrace, Advanced property page and checking "Store IntelliTrace recordings in this directory." Once you have your IntelliTrace files being saved you have a small issue that VS does not always properly clean up the files after shutting down. This cmdlet checks to see if you are storing the files and if you are, deletes any files found in the storage directory. Since IntelliTrace files can take up a lot of disk space, it's good to clean out that directory every once in a while. By default, this script works with Visual Studio 2013, 2015 and 2017 with the default being VS 2017. .PARAMETER VSVersion Removes the stored IntelliTrace files for VS 2017 by default, specify VS 2013 or VS 2015 for those versions. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> [CmdLetBinding(SupportsShouldProcess=$true)] # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] param ( [ValidateSet("VS2013", "VS2015", "VS2017", "Latest")] [string] $VSVersion = "Latest" ) # First check if VS is running. If so, we can't continue as it may be using # the .iTrace files. $proc = Get-Process -Name devenv -ErrorAction SilentlyContinue if ($null -ne $proc) { throw "Visual Studio is running. Please close all instances." } # Default to VS 2017. $regVer = "15.0" switch ($VSVersion) { "VS2013" { $regVer = "12.0" } "VS2015" { $regVer = "14.0" } "VS2017" { $regVer = "15.0" } "Latest" { $regVer = LatestVSRegistryKeyVersion } } [string]$storageDir = "" # Am I supposed to look for VS 2017 or higher? If so, we have work to do because VS 2017 completely changed the # way version detection and the registry are handled. These changes are excellent for performance, but cause # more work on my side. Oh well. :) if ($regVer -lt "15.0") { # Handle older versions of Visual Studio. $regKey = "HKCU:\SOFTWARE\Microsoft\VisualStudio\$regVer\ApplicationPrivateSettings\Microsoft\VisualStudio\TraceLogPackage\ToolsOptionAdvanced" if ($regVer -lt "14.0") { $regKey = "HKCU:\Software\Microsoft\VisualStudio\" + $regVer + "\DialogPage\Microsoft.VisualStudio.TraceLogPackage.ToolsOptionAdvanced" } # Check to see if the user has set the options to save files. If not bail out. if (((Test-PathReg -Path $regKey -Property "SaveRecordings") -eq $false) -or ((Get-ItemProperty -Path $regKey).SaveRecordings -match "False")) { throw "You have not configured IntelliTrace to save recordings. " + "In the Options dialog, IntelliTtrace Advanced page, check the " + "Store IntelliTrace recordings in this directory check box." } if ((Test-PathReg -Path $regKey -Property "RecordingPath") -ne $false) { # Get the storage directory for those files. $storageDir = (Get-ItemProperty -Path $regKey).RecordingPath } # If this is version 14.0 or greater it will have some gunk on the beginning. if ($storageDir.StartsWith("1*System.String*")) { $storageDir = $storageDir.Substring("1*System.String*".Length) } } else { # OK, I'm supposed to do the spiffy new versions. # 1. See if any VS 2017 versions are installed and if any are Enterprise versions # Load my helper that wraps the VS 2017+ setup configuration component. $loadResult = Get-ChildItem -Path $PSScriptRoot -File "WintellectPowerShellHelper.DLL" -ErrorAction Stop | ForEach-Object {[Reflection.Assembly]::LoadFile($_.FullName)} if ($null -eq $loadResult) { throw "Unable to find the required WintellectPowerShellHelper.DLL in the WintellectPowerShell module directory" } $vsInstalls = [WintellectPowerShellHelper.VisualStudioSetup]::GetInstalledInstances() if ($vsInstalls.Count -eq 0) { throw "No Visual Studio 2017+ instances installed on this computer" } # 2. Get the instance ID for the Enterprise version that matches the one the user want to clean up. $vsToProcess = $null for ($i = 0; $i -lt $vsInstalls.Count; $i++) { if (($vsInstalls[$i].ProductName.Contains("Enterprise")) -and ($vsInstalls[$i].InstalledVersionNumber.Substring(0,2) -eq $regVer.SubString(0,2))) { $vsToProcess = $vsInstalls[$i] break } } if ($null -eq $vsToProcess) { throw "The Visual Studio version you requested is not an Enterprise edition" } # 3. Open the registry file in privateregistry.bin and read the value. $regFilePath = $env:LOCALAPPDATA + "\Microsoft\VisualStudio\" + $regVer + "_" + $vsToProcess.InstanceId + "\privateregistry.bin" if (! (Test-Path $regFilePath)) { throw "The privateregistry.bin file does not exist" } $regKey = "Software\Microsoft\VisualStudio\15.0_" + $vsToProcess.InstanceId + "\ApplicationPrivateSettings\Microsoft\VisualStudio\TraceLogPackage\ToolsOptionAdvanced" $storageDir = [WintellectPowerShellHelper.PrivateRegistry]::ReadValue($regFilePath, $regKey, "RecordingPath") if ($storageDir.StartsWith("1*System.String*")) { $storageDir = $storageDir.Substring("1*System.String*".Length) } } if ($storageDir.Length -eq 0) { throw "The IntelliTrace recording directory is empty. Check the " + "Options dialog, IntelliTrace Advanced page to set the "+ "directory." } if ($PSCmdlet.ShouldProcess($storageDir,"Deleting files in")) { # Clean up those files but only do the ones in the main directory so if the # user may have created paths and put other files there we don't delete those. Get-ChildItem -Path $storageDir -Filter "*.iTrace" | Remove-Item -Force } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUGFtrotEPc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BwGA1UEChMVVGhlIFVT # RVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5j # b20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3QtT2JqZWN0Ag8WiPA5JV5jjmkUOQfm # MwswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI # hvcNAQkFMQ8XDTE3MDExMjIzMDcyMlowIwYJKoZIhvcNAQkEMRYEFLZ0o44SlFOg # cay4JDW9b6LqooFaMA0GCSqGSIb3DQEBAQUABIIBAAVHzb7gvhK2e7NIGQ84xrbi # 7FfGjheBcYU7G2icZRjzSBtnYhHI50RDiqui33s2MOQuxevZueWaLIt0FPOBFXeH # hUQHf1Dlt9jz0dYya6/pbndPpHmBzdLdW2NbieHGy9GF+17/QsvEt/uZDcP7XdB+ # HhrWWSlghgEcazQpe0u/OixbjDjXo88M1UvDpVMKldldAqaw6KObuOpBQWi/+j1H # wKHQJrF2Lh4szccNXqa8AkMLB0AqD+FuS/j5d6ahbLcW46auYLi4iE23luKzbOKf # KuER/fYoUgmWr26fXJ+yVGKLnWGUgv9JtIONi6xq36VrBh/s2Ss2Xv00FjUMtCI= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Get-SysinternalsSuite.ps1
Get-SysinternalsSuite.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Get-SysinternalsSuite { <# .SYNOPSIS Gets all the wonderful Sysinternals tools. .DESCRIPTION Downloads and extracts the Sysinternal tools to the directory you specify. .PARAMETER ExtractTo The directory where you want to extract the Sysinternal tools. .PARAMETER Save The default is to download the SysinternalsSuite.zip file and remove it after extracting the contents. If you want to keep the file, specify the save directory with this parameter. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> param ( [Parameter(Mandatory=$true, HelpMessage="Please specify the extract directory")] [Alias("Extract")] [string] $ExtractTo , [Parameter(HelpMessage="Please specify the directory to expand into")] [string] $Save="" ) New-Item -ItemType Directory -Path $ExtractTo -ErrorAction SilentlyContinue > $null [Boolean]$deleteZipFile = $TRUE [String]$downloadFile = "" if ( $Save.Length -gt 0 ) { New-Item -ItemType Directory -Path $Save -ErrorAction SilentlyContinue > $null $downloadFile = $Save $deleteZipFile = $FALSE } else { # Use the %TEMP% path for the user. $downloadFile = $env:temp } # Build up the full location and filename. $downloadFile = $(Get-item -Path $downloadFile).FullName $downloadFile = Join-Path -path $downloadFile -childpath "SysinternalsSuite.zip" # Let the download begin! Invoke-WebRequest -Uri "http://download.sysinternals.com/files/SysinternalsSuite.zip" -OutFile $downloadFile # Because the SysinternalsSuite.zip is quite large, I've seen very random instances where # the Expand-Archive fails because some anti-virus lock the file in exclusive mode. # I hate doing this but don't see any other way around the issue. Start-Sleep -Seconds 1 # Now expand away. Expand-Archive -Path $downloadFile -DestinationPath $ExtractTo -Force # Strip off the NTFS stream marking the files as downloaded. We trust Mark. :) Unblock-File -Path $ExtractTo if ($deleteZipFile -eq $true) { Remove-Item -Path $downloadFile } } # SIG # Begin signature block # MIIaQwYJKoZIhvcNAQcCoIIaNDCCGjACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUfuFoz1Q88y4dtvuUFICi9ZDo # 1M6gghUyMIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR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rrRA6 # P/YHxD20SHoa8rTwymcSNNOEsg0LIt7ye+uaNQMc7QTjSgElvxSrrs0nxniIGpN9 # 7YpAtZ8IJEnKkdcwqiWT3YVSSAeu2KMS56CujvLQ4ibMuPvQnRi1hvOxy3aTq8zj # bHGU5eUw3UJhRvpiKU1viDveqdEdVJuEAHaAIE/5MJZuqGM+m9tqOQER2tDdHiJu # +Mqy7oBOu99CidVnaZLLvBsPT9qLNv3wuSR6qCSjNgeUZkDLPGBOYQV3jFZae3Ej # UgwHNoCQdw== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Internal.ps1
Internal.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest # The location format for the CurrentSettings.vssettings files. $script:settingsFileFormat = "{0}\Visual Studio {1}\Settings\CurrentSettings.vssettings" # The XPath format for getting at individual Debugger properties. $script:dbgPropertyXPath = "//UserSettings/Category[@name='Debugger']/PropertyValue[@name='{0}']" # Takes care of opening the settings file for a specific VS version. # Returns $null if the file does not exist. function OpenSettingsFile($vsVersion) { [xml]$result = $null # Get the documents directory for the user. $documentDir = [System.Environment]::GetFolderPath("MyDocuments") # Build up the filename to open. $currFilename = $script:settingsFileFormat -f $documentDir, $vsVersion # Does the file exist? if (Test-Path -Path $currFilename) { $result = Get-Content -Path $currFilename } return $result } # Writes out the settings file for the VS version. function WriteSettingsFile($vsVersion,[xml]$xmlData) { $documentDir = [System.Environment]::GetFolderPath("MyDocuments") $filename = $script:settingsFileFormat -f $documentDir, $vsVersion $xmlData.Save($filename) } function Get-RegistryKeyPropertiesAndValues { <# .Synopsis This function accepts a registry path and returns all reg key properties and values .Description This function returns registry key properies and values. .Example Get-RegistryKeyPropertiesAndValues -path 'HKCU:\Volatile Environment' Returns all of the registry property values under the \volatile environment key .Parameter path The path to the registry key .Notes NAME: Get-RegistryKeyPropertiesAndValues AUTHOR: ed wilson, msft LASTEDIT: 05/09/2012 15:18:41 KEYWORDS: Operating System, Registry, Scripting Techniques, Getting Started HSG: 5-11-12 .Link Http://www.ScriptingGuys.com/blog #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] Param( [Parameter(Mandatory=$true)] [string]$path) Push-Location Set-Location -Path $path Get-Item -Path . | Select-Object -ExpandProperty property | ForEach-Object { New-Object -TypeName psobject -Property @{"property"=$_; "Value" = (Get-ItemProperty -Path . -Name $_).$_}} Pop-Location } function LatestVSRegistryKeyVersion { $versionSearchKey = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" if ([IntPtr]::size -ne 8) { $versionSearchKey = "HKLM:\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" } $biggest = 0.0 Get-RegistryKeyPropertiesAndValues $versionSearchKey | ForEach-Object { if ([System.Convert]::ToDecimal($_.Property) -gt [System.Convert]::ToDecimal($biggest)) { $biggest = $_.Property } } $biggest } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUpGSO1dHpkfSgkYMFMy9e+BUz # Uzeggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwH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YxwC+MA0GCSqGSIb3DQEBAQUABIIBAJ2D+8m5Rvit6XvvG6c9zqti # 1uLgWCS3y5hjJMgg1Gm0REuTzB4+bGQCNzWfj7xQf/UHIoOLOhlae6m6d38Z7ied # hV5G2i/sJVrbGiaMCB6Kn0vyIilcBqocfTBveRxVC0z4qqfEbmCAq1F/O0q7H2VU # +WnZhfK7z3OkJnBPC2QTVotxppKdM1xEV16GBc791FY7KAbKeDKLN71SFamY4Kbz # 2vu92PXH45HAJ2MkBmnn8lEis1VNJ5K7yBF4MdNFVksGkNW2ZGSzaQ6+jcGM8gQk # IVOxUHq5l0Ln3Fhn1VbCzZLlzySr3aDJvl2WcTx1DsLUQujx3jdUtUJeg7jo5bY= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Compare-Directories.ps1
Compare-Directories.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Compare-Directories { <# .SYNOPSIS Compare two directories to see if they are identical .DESCRIPTION This cmdlet will compare two directories and report if the files are identical by name, and optionally on content. Symbol explanation: => - The file is in the -NewDir directory, not the -OriginalDir. <= - The file is in the -OriginalDir directory and not the -NewDir. != - The file is in both directories, but the content is not identical. If the directories are identical an empty hash table is returned. Since sometimes filenames are long, you can pipe this output of this cmdlet into Format-Table -AutoSize to avoid truncating the filenames. .PARAMETER OriginalDir The original directory to use for the comparison. .PARAMETER NewDir The new directory to compare to. .PARAMETER Excludes The array of exclusions, including wildcards, so you can filter out some of the extraneous files. .PARAMETER Recurse Recurse the directory tree. The default is to just look at the directory. .PARAMETER Force Allows the cmdlet to get items that cannot otherwise not be accessed by the user, such as hidden or system files. .PARAMETER Content Check the content of matching filenames in both directories to see if they are equal. This is done through the Get-FileHash cmdlet from PowerShell 4.0. .OUTPUTS HashTable The name is the file, and the value is the difference indicator. If the directories are identical, an empty hash table is returned. .EXAMPLE C:\PS>Compare-Directories .\Original .\Copied -Content Compares the original directory against a copied directory for both filenames and content. This shows that both file a.pptx, and c.pptx are in both directories but the content is different. Files f.pptx and i.pptx are only in the .\Copied directory. Name Value ---- ----- a.pptx != c.pptx != f.pptx => i.pptx => #> # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] param ( [Parameter(Mandatory=$true)] [string] $OriginalDir, [Parameter(Mandatory=$true)] [string] $NewDir, [string[]] $Excludes="", [switch] $Recurse, [switch] $Force, [switch] $Content ) if ((Test-Path -Path $OriginalDir) -eq $false) { throw "$OriginalDir does not exist" } if ((Test-Path -Path $NewDir) -eq $false) { throw "$NewDir does not exist" } # I need the real paths for the two input directories. $OriginalDir = (Resolve-Path -Path $OriginalDir).ToString().Trim("\") $NewDir = (Resolve-Path -Path $NewDir).ToString().Trim("\") # When you do a Resolve-Path on a network share you get the # Microsoft.PowerShell.Core\FileSystem:: added to the name so # yank it off if there. $OriginalDir = StripFileSystem -directory $OriginalDir $NewDir = StripFileSystem -directory $NewDir # Do the work to find all the files. $origFiles = Get-ChildItem -Path $OriginalDir -Recurse:$Recurse -Force:$Force -Exclude $Excludes $newFiles = Get-ChildItem -Path $NewDir -Recurse:$Recurse -Force:$Force -Exclude $Excludes # Here I'm going to strip off the initial directories and leave the names. Thus if # the OriginalDir was C:\FOO and one of the files is C:\FOO\BAR.TXT, the result would # be BAR.TXT (C:\FOO\BAZ\Z.TXT -> BAZ\Z.TXT. This will make it easier for content checking. # The issue is that by doing the content checking on the default return type from # Compare-Object, I'd lose the relativeness of the filenames. By forcing the data # to be the relative filenames from input I can do the content comparisons much easier. $origFiles = $origFiles | ForEach-Object { $_.FullName.Remove(0,$OriginalDir.Length+1) } $newFiles = $newFiles | ForEach-Object { $_.FullName.Remove(0,$NewDir.Length+1) } # If either return is empty, create an empty array so I can return correct data. if ($null -eq $origFiles) { $origFiles = @() } if ($null -eq $newFiles) { $newFiles = @() } # Now do the comparisons on the names only. $nameComp = Compare-Object -ReferenceObject $origFiles -DifferenceObject $newFiles # The hash we are going to return. $resultHash = @{} # If there's no differences, $nameComp is null. if ($null -ne $nameComp) { # Push the PSCustomObject type into a resultHash table so content checking can put it's custom # results into the table. $nameComp | ForEach-Object { $resultHash[$_.InputObject] = $_.SideIndicator} } # if comparing the content if ($Content) { # Get just the matching values by calling Compare-Object -ExcludeDifferent -IncludeEqual. # Note that I'm using -PassThru here because I want result to be the identical filenames, not the # normal custom object returned by Compare-Object. $sameFiles = Compare-Object -ReferenceObject $origFiles -DifferenceObject $newFiles -IncludeEqual -ExcludeDifferent -PassThru foreach($file in $sameFiles) { # Build up the paths to the original file and the new file. $orig = $OriginalDir $orig += "\" + $file # Am I about to check a directory that's in both places? If so, skip it because the # hash will be different because the strings are different. if ((Get-Item -Path $orig) -is [System.IO.DirectoryInfo]) { continue } $new = $NewDir $new += "\" + $file $origHash = Get-FileHash -Path $orig $newHash = Get-FileHash -Path $new if ($origHash.Hash -ne $newHash.Hash) { $resultHash[$file] = "!=" } } } # Nice trick to get the hash sorted by Name so it's easier to read. $resultHash.GetEnumerator() | Sort-Object -Property Name } function StripFileSystem([string]$directory="") { $fsText = "Microsoft.PowerShell.Core\FileSystem::" if ($directory.StartsWith($fsText)) { $fsLen = $fsText.Length $dirLen = $directory.Length $directory = $directory.Substring($fsLen,$dirLen - $fsLen) } return $directory } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUKQ2N+ER8FrZTCQrNCY1te+o8 # eQqgg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T # RVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5j # b20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3QtT2JqZWN0Ag8WiPA5JV5jjmkUOQfm # MwswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI # hvcNAQkFMQ8XDTE3MDExMjIzMDY1NVowIwYJKoZIhvcNAQkEMRYEFDcCcZgmPpj6 # Nwxe931PsI0bCqU7MA0GCSqGSIb3DQEBAQUABIIBAGtPGCxpIpEo6YNbW2dak4m+ # rAlA9XtzRPiN5RtiHJjiM5Ys6dKvmSJd7LkSOmlZ2F6hbL8QKXmnmvkhonWGhrBU # 5a+cstVwAkpmmw6kwHwgzcQn42eN9YvW+hDrairBolljjHfGOfm+QqOQa6I0+Fvb # 50SQ5King64xGv2+YQMAY+8hTdJWJX/yDf4beq+/iBEuV2A4IfIxg7+AkLIrImjm # rE829XxvsnmTMISqQZ7OT8Gv6vURndiONDd7y+iilyknY8CAkTRPN+WQXXCfs/MG # UkHPQ+RoVYBMHjgsdypBlljEsmFITMz4I0Y9sczgvSP3oeoC747O2peJUaxWFT0= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Expand-ZipFile.ps1
Expand-ZipFile.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Expand-ZipFile { <# .SYNOPSIS DEPRECATED! PowerShell 5.0+ offers Expand-Archive. This cmdlet now just wraps it. .DESCRIPTION Using no external ZIP utilities, expands a .ZIP file to a specified directory. .PARAMETER ZipFile The .ZIP file to expand. .PARAMETER Destination The output directory for the ZipFile. If this directory does not exist, it will be created. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> param ( [Parameter(Mandatory=$true, HelpMessage="Please specify the zip file to expand")] [string] $ZipFile , [Parameter(Mandatory=$true, HelpMessage="Please specify the directory to expand into")] [string] $Destination ) Expand-Archive -Path $ZipFile -DestinationPath $Destination } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUckLXkPru+MW9XZxLpDgKDaCX # vkuggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE # BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKjAoBgNVBAMT # IUNPTU9ETyBTSEEtMSBUaW1lIFN0YW1waW5nIFNpZ25lcjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBAOnpPd/XNwjJHjiyUlNCbSLxscQGBGue/YJ0UEN9 # xqC7H075AnEmse9D2IOMSPznD5d6muuc3qajDjscRBh1jnilF2n+SRik4rtcTv6O # KlR6UPDV9syR55l51955lNeWM/4Og74iv2MWLKPdKBuvPavql9LxvwQQ5z1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jZt9p9Z4d5CJpfx3wYlZjNoVisnHMtbaDdogaVmIeET1pj1d # h/ueMIaRc5bbB5Puoq43wCBNhqzjK3nuLwj5smg6rdaeL//bpt5s1zORQbI3btWP # ooNCWX5dWApHFryOeWZ/8SB0dEXzniUkpcxkvGCuxhfUY8fNqOOXcZOQHPTWitFj # aAjSM/NJhXRIBIrWt0/CtHXg9TMiECRpns7Ho9l9y5iYi6Bpio6I/aGCAkMwggI/ # BgkqhkiG9w0BCQYxggIwMIICLAIBADCBqTCBlTELMAkGA1UEBhMCVVMxCzAJBgNV # BAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVT # RVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5j # b20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3QtT2JqZWN0Ag8WiPA5JV5jjmkUOQfm # MwswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI # hvcNAQkFMQ8XDTE3MDExMjIzMDY1OFowIwYJKoZIhvcNAQkEMRYEFOi1fcyFvaKf # JDwdmword5hfwtRsMA0GCSqGSIb3DQEBAQUABIIBACVsDxRBjAoUkGwKcifeoALb # CHhtXkH7RbXjrECfy09n2/t2gO0OwHByiDhfLEhsg/b1gDF4hQussXBS1hoeJVsN # TF0N4KP6GWZ+7SIJWBj01MB6NIcoFoBVqN9u4eKaQNkQMJlAsYJictQS2JmVEWZG # Qy4ASYYou73GJO6gvcV8C2o3JnITlBwV1RdyzpkfUtAJUQ/iM+ULVtEttL8esc+9 # bDAbPFWjKA5MjY5MtQXhKZDFVAplRplNkaouG/Rijw7003SvAm4nLJOi943/Gn5x # cj6uU3k8GmoisQpZVRJ9chwUjmcuxzxpR/04IStJvmfKOgBLR+7/sF8LwLmt1so= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Add-NgenPdbs.ps1
Add-NgenPdbs.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2013-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Add-NgenPdbs { <# .SYNOPSIS Create PDB files for NGEN'd images on a machine. .DESCRIPTION When running the Visual Studio profiler on Windows 8+ or Windows Server 2012+, you need the PDB files for any binaries that have been NGEN'd and put in the GAC so you can see the calls into those binaries. Fortunately NGEN.EXE can generate the PDB files after the fact and this script automates the process for so you don't have to run NGEN on each binary. Because each machine has it's own unique NGEN'd files, you will have to run this script on the machine you are collecting the performance runs. After creating the PDB files, you'll have to copy them into your symbol server on the machine where you are analyzing the performance runs. Also note that not all files in the GAC can be NGEN'd so you might see some errors about unable to create the PDB. .PARAMETER CacheDirectory The cache directory to place the resulting PDB files. If not specified, looks at the Visual Studio 2013-2017 symbol settings and uses that as the cache directory. On a machine without Visual Studio where you are using the command line profiling tools, alway specify this parameter. .PARAMETER DoAllGACFiles By default, this command only does the NGEN'd binaries that are in the .NET framework directories for both x86 and x64. If you need other NGEN'd binaries from 3rd pary tools, specify this switch. Some NGEN'd binaries, but not from the .NET framework, will report errors when attempting to build their PDB files. .NOTES To read more about using NGEN to produce PDB files after a binary has been precompiled see this article: http://blogs.msdn.com/b/visualstudioalm/archive/2012/12/10/creating-ngen-pdbs-for-profiling-reports.aspx For an alternative implementation to this one, see http://knagis.miga.lv/blog/post/2013/01/22/VS2012-Windows-8-profilesana-ar-NGEN-bibliotekam.aspx .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] [CmdletBinding()] param ( [string]$CacheDirectory = "", [switch]$DoAllGACFiles ) # If the CacheDirectory is empty, use the symbol path directory. if ($CacheDirectory.Length -eq 0) { # I have to look for the cache directory. First I'll start with the easy checks # by using Get-SymbolServer to pull out the VS versions. As a last resort, I have # to try and grab it from the _NT_SYMBOL_PATH environment variable. $symServs = Get-SymbolServer if ($symServs.Count -eq 0) { throw "You don't have a symbol server set" } $vsVersion = $null $symPath = $symServs["VS 2017"] if ($null -eq $symPath) { $symPath = $symServs["VS 2015"] if ($null -eq $symPath) { $symPath = $symServs["VS 2013"] if ($null -eq $symPath) { # Pull it out of _NT_SYMBOL_PATH. Yes this is only looking at the # first cache directory specified. $symPath = $symServs["_NT_SYMBOL_PATH"] if ($null -eq $symPath) { throw "No symbol server configured" } else { if ($symPath -match "SRV\*(?<SymCache>[^*]*)\*(?:.*)\;?") { $symPath = $Matches["SymCache"] } else { throw "_NT_SYMBOL_PATH environment variable does not specify a symbol cache" } } } else { $vsVersion = "2013" } } else { $vsVersion = "2015" } } else { $vsVersion = "2017" } if ($null -ne $vsVersion) { [xml]$settings = OpenSettingsFile $vsVersion $xPathLookup = $script:dbgPropertyXPath -f "SymbolUseMSSymbolServers" $useMSFTSymbolServersNode = $settings | Select-Xml -XPath $xPathLookup # If using the public symbol servers I have to put PublicSymbols on the path. if ($useMSFTSymbolServersNode.Node.InnerText -eq "1") { $SymPath = Join-Path -Path $symPath -ChildPath "PublicSymbols" } } if ($symPath.Length -eq 0) { throw "The symbol path is empty" } $CacheDirectory = $symPath } else { if (-not (Test-Path -Path $CacheDirectory)) { New-Item -Path $CacheDirectory -Type Directory | Out-Null } } # Get all the *.ni.dll files out of the 4.* GAC locations $gacSearchPath = $env:windir + "\assembly\NativeImages_v4*" $files = Get-ChildItem -Recurse -Path $gacSearchPath -Filter "*.ni.dll" -Exclude "*.resources.ni.dll" # I'll need this later to strip off the .ni.dll $niLength = ".ni.dll".Length foreach ($f in $files) { # Build up the command line to call NGEN.EXE on this binary. # Get the name of the DLL. $baseName = (Split-Path -Path $f -Leaf) $baseName = $baseName.SubString(0, $baseName.Length - $niLength) # Extract out the bit version of this compiled binary so I know if I'm supposed # to run the 32 or 64 bit version of NGEN.EXE and where to check if the file exists. # The replace looks weird but that's how you get \\ into the path. :) $pattern = $env:windir -replace '\\' , '\\' $pattern += "\\assembly\\NativeImages_(?<version>v4\.\d\.\d\d\d\d\d)_(?<bits>\d\d)" $f.FullName -match $pattern | Out-Null $bits = '64' if ($Matches.bits -eq '32') { $bits = '' } $fwVersion = $Matches.version # if doing the default of only framework files, check to see if this # file is in the appropriate directory. if ($DoAllGACFiles.IsPresent -eq $false) { # Build up the framework path. $fwPath = Join-Path -Path $env:windir -ChildPath "Microsoft.NET" $fwPath = Join-Path -Path $fwPath -ChildPath ("Framework" + $bits) $fwPath = Join-Path -Path $fwPath -ChildPath $fwVersion $fwFile = Get-ChildItem -Recurse -Path $fwPath -Filter ($baseName + ".dll") if ($null -eq $fwFile) { continue } } $msgBitness = '(x86)' if ($bits -eq "64") { $msgBitness = "(x64)" } Write-Verbose -Message "Generating PDB file for $msgBitness $baseName.dll" $ngenCmd = $env:windir + "\Microsoft.NET\Framework" + $bits + "\" + $fwVersion + "\NGEN.EXE" $ngenArgs = ' createPDB ' + '"' + $f.FullName + '"' + ' "' + $CacheDirectory +'"' # Start-Process can't capture output. $pinfo = New-Object System.Diagnostics.ProcessStartInfo $pinfo.FileName = $ngenCmd $pinfo.Arguments = $ngenArgs $pinfo.RedirectStandardError = $true $pinfo.RedirectStandardOutput = $true $pinfo.UseShellExecute = $false $p = New-Object System.Diagnostics.Process $p.StartInfo = $pinfo $p.Start() | Out-Null $p.WaitForExit() $outputData = $p.StandardOutput.ReadToEnd() $outputData += $p.StandardError.ReadToEnd() if ($p.ExitCode -ne 0) { # This may look odd, but it's because Write-Warning is too dumb to write arrays. Write-Warning -Message ([String]::Join("`n", $outputData)) } } } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgU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I0M4PJmkKGCAkMwggI/ # BgkqhkiG9w0BCQYxggIwMIICLAIBADCBqTCBlTELMAkGA1UEBhMCVVMxCzAJBgNV # BAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVT # RVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5j # b20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3QtT2JqZWN0Ag8WiPA5JV5jjmkUOQfm # MwswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZI # hvcNAQkFMQ8XDTE3MDExMjIzMDY1MlowIwYJKoZIhvcNAQkEMRYEFMaZTfrwmy+N # Oh9eL6d8+nT/f4jXMA0GCSqGSIb3DQEBAQUABIIBABjOuYir8Qz87TjB0TEZ6LrK # L0J/glNk4FtEGV9OXb8UVoTkWFe86qXqB11+RqyQ9pan2gTxoaSX3zbPmJ8K1WY9 # iiNf6rI1S1aVX7BUKb8wLYUXlLAtf4lJgUS8gAyToLpw3/vSVQa4smN2GzaRoyjM # nN86F4pf8/3xAzIq8LhONpaKWJlkV8rxEqibtCmzHc9mortnAJheAkbVqrXaRL4d # vgvzUASl7Lrf4c8QVCjPnU6JUp7jLLKkbXiKgQuaGyunzoL5/ho5/KWgHGXG7kcs # lrvYPiUhCr6KaIQZOAvhwjmQtfbT+GT2Dlnw143hEKgP9HjT9mU03NMepu6gc64= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Get-Uptime.ps1
Get-Uptime.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Get-Uptime { <# .SYNOPSIS Returns how long a computer has been running. .DESCRIPTION Returns the TimeSpan for how long a computer is running. If you'd like it formatted you can use: (Get-Uptime) -f {0} .OUTPUTS A TimeSpan type. .LINK http://www.wintellect.com/devcenter/author/jrobbins https://github.com/Wintellect/WintellectPowerShell #> $cmi = Get-CimInstance -ClassName Win32_OperatingSystem New-TimeSpan -Start $cmi.LastBootUpTime -End $(get-date) } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUh4ZW4rtlwxT6i5u381y3WqHD # mU6ggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE # BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKjAoBgNVBAMT # IUNPTU9ETyBTSEEtMSBUaW1lIFN0YW1waW5nIFNpZ25lcjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBAOnpPd/XNwjJHjiyUlNCbSLxscQGBGue/YJ0UEN9 # xqC7H075AnEmse9D2IOMSPznD5d6muuc3qajDjscRBh1jnilF2n+SRik4rtcTv6O # KlR6UPDV9syR55l51955lNeWM/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ature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Merge-HashTables.ps1
Merge-HashTables.ps1
function Merge-HashTables { # I hate suppressing this warning, but I created this cmdlet long before the # script analyzer came out. If someone has this in a script, changing the # cmdlet name will break them. [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Scope="Function")] param ($htold=$null, $htnew=$null) <# .SYNOPSIS Merges two has tables based on their keys. .DESCRIPTION Thanks jon Z! .LINK http://stackoverflow.com/questions/8800375/merging-hashtables-in-powershell-how #> $keys = $htold.getenumerator() | foreach-object {$_.key} $keys | foreach-object { $key = $_ if ($htnew.containskey($key)) { $htold.remove($key) } } $htnew = $htold + $htnew return $htnew } # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUNKpjaNlLT2JycTY1N7VsZF4f # hM+ggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE # BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKjAoBgNVBAMT # IUNPTU9ETyBT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Ev7apP7kRUHhxd7LCjRoFJQ2x8ir2DFRRWM7zCI0oWgVeZ1HKvH61kI1j33w9jL # W71vky2RfQe9tsM0l616/cORh2lziygJLrWohsJgj5gr4qtMCfe00mGOWF6MRRDv # BAYiXrBezZdLCh36LCiOWidSYEKziUenGW90GwoiKiBf68ae4j5YqVSWKWsGv+w= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Test-PathReg.ps1
Test-PathReg.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest ############################################################################### # Public Cmdlets ############################################################################### function Test-PathReg { <# .SYNOPSIS Validates the existence of a registry key .DESCRIPTION This function searches for the registry value (Property attribute) under the given registry key (Path attribute) and returns $true if it exists. Author: Can Dedeoglu (Thanks Can!) .PARAMETER Path Specifies the Registry path. .PARAMETER Property Specifies the name of the registry property that will be searched for under the given Registry path. .EXAMPLE C:\PS> Test-PathReg -Path HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters -Property Hostname Checks to see if the Hostname property exists in the HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters registry key .LINK http://blogs.msdn.com/candede #> param ( [Parameter(mandatory=$true,position=0)] [string]$Path, [Parameter(mandatory=$true,position=1)] [string]$Property ) $gipReturn = Get-ItemProperty -LiteralPath $Path -ErrorAction SilentlyContinue if ($null -eq $gipReturn) { return $false } $compare = $gipReturn.psbase.members | ` ForEach-Object {$_.name} | ` Compare-Object $Property -IncludeEqual -ExcludeDifferent if($null -eq $compare) { return $false } if($compare.SideIndicator -like "==") { return $true } else { return $false } } # SIG # Begin signature block # MIIaQwYJKoZIhvcNAQcCoIIaNDCCGjACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgW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GgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEH # ATAcBgkqhkiG9w0BCQUxDxcNMTcwMjE4MTk0OTEyWjAjBgkqhkiG9w0BCQQxFgQU # c6tqSefRr9NMDnhiKubYxlD8ovYwDQYJKoZIhvcNAQEBBQAEggEAzYUElfMW2j9J # p80rrDcQCLtbjnq66PgUKhaJ/S6VG1N6Y0jkcBqB9b8ZVSpgGynUErkRfSgJ9BKB # IMHXvaWLPKgghqJFdPkQ1OBOBac21nU/yE46I7A/XK8zIM76A9W8FHmcqtKSyBbo # ZJg/2fOOYdPbNPv3VjB13RIIM5ZI22EIA4ksjcN2Dwhl7oG+qQ2FKK2nzRRwb5Au # oda24DHyvmlnDMUNTJnQdi6KPGI1N7ommCaUI53zCTJmkMlH3A4D4Zr6NIFgB7LL # P9412zHXRJFO2RWQWFidY1nX9KphIy0XKli7u5nTyuxGAWOTWU60n3NhucQk8YEz # c8rqr/ihCw== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Code/Set-Environment.ps1
Set-Environment.ps1
#requires -version 5.0 ############################################################################### # WintellectPowerShell Module # Copyright (c) 2010-2017 - John Robbins/Wintellect # # Do whatever you want with this module, but please do give credit. ############################################################################### # Always make sure all variables are defined and all best practices are # followed. Set-StrictMode -version Latest function Set-Environment { <# .SYNOPSIS Brings the CMD SET command back to PowerShell. .DESCRIPTION PowerShell has a powerfull way to set environment variables, but many of us have the DOS SET command burned into our fingers. This function keeps us productive. :) Full credit to Wes Haggard at http://weblogs.asp.net/whaggard for this gem. To replace the default set alias with the one provided by WintellectPowerShell, execute the following command before importing the this module. Remove-Item alias:set -Force -ErrorAction SilentlyContinue .PARAMETER Var The environment variable in SET format, "var=value". If you want to clear an environment variable, use "var=". If no parameter is specified, this will dump all environment variables currently defined. .LINK http://weblogs.asp.net/whaggard/archive/2007/02/08/powershell-version-of-cmd-set.aspx https://github.com/Wintellect/WintellectPowerShell #> [CmdletBinding(SupportsShouldProcess=$true)] param ( [string]$var ) if ($var -eq "") { get-childitem -Path env: | sort-object -Property name } else { if ($var -match "^(\S*?)\s*=\s*(.*)$") { if ($PSCmdlet.ShouldProcess($matches[1], "Setting environment variable")) { set-item -force -path "env:$($matches[1])" -value $matches[2]; } } else { write-error -Message "ERROR Usage: VAR=VALUE" } } } Set-Alias -Name set -Value Set-Environment -Description "WintellectPowerShell alias" -Force -Scope Global -Option AllScope # SIG # Begin signature block # MIIUywYJKoZIhvcNAQcCoIIUvDCCFLgCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUA2f29Aba+dOiaEVc0fJ0WY6M # Mq2ggg+6MIIEmTCCA4GgAwIBAgIPFojwOSVeY45pFDkH5jMLMA0GCSqGSIb3DQEB # BQUAMIGVMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQg # TGFrZSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNV # BAsTGGh0dHA6Ly93d3cudXNlcnRydXN0LmNvbTEdMBsGA1UEAxMUVVROLVVTRVJG # aXJzdC1PYmplY3QwHhcNMTUxMjMxMDAwMDAwWhcNMTkwNzA5MTg0MDM2WjCBhDEL # MAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE # BxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKjAoBgNVBAMT # IUNPTU9ETyBTSEEtMSBUaW1lIFN0YW1waW5nIFNpZ25lcjCCASIwDQYJKoZIhvcN # AQEBBQADggEPADCCAQoCggEBAOnpPd/XNwjJHjiyUlNCbSLxscQGBGue/YJ0UEN9 # xqC7H075AnEmse9D2IOMSPznD5d6muuc3qajDj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77s+VJh+8wuEfM+xBduEP5CSD/sf63cMaPP94ablVw= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Support/UpdateSignatures.ps1
UpdateSignatures.ps1
Get-ChildItem -Recurse ..\*.ps* -Exclude *Support* | Get-AuthenticodeSignature | Where-Object { $_.Status -eq "HashMismatch"} | Select-Object Path | ForEach-Object { $_.Path } | Set-Signatures
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Support/UploadWintellectPowerShell.ps1
UploadWintellectPowerShell.ps1
param ( [Parameter(Mandatory=$true, HelpMessage="Please specify the api key")] [string] $apiKey ) Publish-Module -NuGetApiKey $apiKey -Path ..\ -Verbose
PowerShellCorpus/PowerShellGallery/WintellectPowerShell/4.0.0.3/Support/SignWintellectPowerShell.ps1
SignWintellectPowerShell.ps1
Set-StrictMode -version Latest $cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] $timeServer = "http://timestamp.comodoca.com/authenticode" # Build my list of files to sign. $files = Get-ChildItem -Path ..\Code\*.* -Include *.ps*,*.dll $files += Get-ChildItem -Path ..\* -Include *.ps* Set-AuthenticodeSignature -FilePath $files -Certificate $cert -TimestampServer $timeServer
PowerShellCorpus/PowerShellGallery/NameIT/1.8.3/customData/customData.ps1
customData.ps1
@{ Region=echo North East South West Food=echo Pizza Pancakes Chinese Fruit=echo lemon lime peach apple banana Response=echo Yes No Maybe "'Not Sure'" Ingredients=echo Flour Sugar Salt Milk Eggs Butter USCapital=echo Montgomery Juneau Phoenix Little Rock Sacramento Denver Hartford Dover Washington Tallahassee Atlanta Honolulu Boise Springfield Indianapolis Des Moines Topeka Frankfort Baton Rouge Augusta Annapolis Boston Lansing Saint Paul Jackson Jefferson City Helena Lincoln Carson City Concord Trenton Santa Fe Albany Raleigh Bismarck Columbus Oklahoma City Salem Harrisburg Providence Columbia Pierre Nashville Austin Salt Lake City Montpelier Richmond Olympia Charleston Madison Cheyenne President=echo "'George Washington'","'John Adams'","'Thomas Jefferson'","'James Madison'","'James Monroe'","'John Quincy AdamsAndrew Jackson'","'Martin Van Buren'","'William Henry Harrison'","'John Tyler'","'James K. Polk'","'Zachary Taylor'","'Millard Fillmore'","'Franklin Pierce'","'James Buchanan'","'Abraham Lincoln'","'Andrew Johnson'","'Ulysses S. Grant'","'Rutherford B. Hayes'","'James A. Garfield'","'Chester Arthur'","'Grover Cleveland'","'Benjamin Harrison'","'Grover Cleveland'","'William McKinley'","'Theodore Roosevelt'","'William Howard Taft'","'Woodrow Wilson'","'Warren G. Harding'","'Calvin Coolidge'","'Herbert Hoover'","'Franklin D. Roosevelt'","'Harry S. Truman'","'Dwight D. Eisenhower'","'John F. Kennedy'","'Lyndon B. Johnson'","'Richard Nixon'","'Gerald Ford'","'Jimmy Carter'","'Ronald Reagan'","'George Bush'","'Bill Clinton'","'George W. Bush'","'Barack Obama'" }
PowerShellCorpus/PowerShellGallery/PoShSQLLocalDB/1.0.2.6/bin/AutoVersion.ps1
AutoVersion.ps1
## Get psd1 file $RawPSD = Get-Content -Path "$($PSScriptRoot)\..\PoShSQLLocalDB.psd1" $ModuleVersion=($RawPSD | Where-Object { $_ -match "^ModuleVersion.*$" }) -replace "^.*=\s|'" [Int[]] $VerArr = $ModuleVersion -split '\.' $NewModuleVersion = '' $CarryValue = 1 $EntryPoint = $($VerArr.Count -1) for($i=$EntryPoint; $i -ge 0; $i--){ $VersionPart = $VerArr[$i] $VersionPart += $CarryValue if($i -eq 0) { $NewModuleVersion = "$VersionPart"+$NewModuleVersion break } else { if($VersionPart -eq 10) { $VersionPart = 0 } else { $CarryValue = 0 } $NewModuleVersion = ".$VersionPart"+$NewModuleVersion } } Write-Verbose -Message "New Version: $NewModuleVersion" $RawPSD | ForEach-Object { $_ -replace "(?<=^ModuleVersion = ')\d+\.\d\.\d\.\d(?=')",$NewModuleVersion } | Out-File -FilePath "$($PSScriptRoot)\..\PoShSQLLocalDB.psd1" -Force
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/Install.ps1
Install.ps1
# Run this in an administrative PowerShell prompt to install the PSObjectInspector PowerShell module: # # iex (New-Object Net.WebClient).DownloadString("https://github.com/TheDollarDes/PSObjectInspector/raw/master/Install.ps1") # Some general variables $ModuleName = 'PSObjectInspector' $DownloadURL = 'https://github.com/TheDollarDes/PSObjectInspector/raw/master/release/PSObjectInspector-current.zip' # Download and install the module $webclient = New-Object System.Net.WebClient $file = "$($env:TEMP)\$($ModuleName).zip" Write-Host "Downloading latest version of $ModuleName from $DownloadURL" -ForegroundColor Cyan $webclient.DownloadFile($DownloadURL,$file) Write-Host "File saved to $file" -ForegroundColor Green $targetondisk = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules\$($ModuleName)" $null = New-Item -ItemType Directory -Force -Path $targetondisk $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($file) Write-Host "Uncompressing the Zip file to $($targetondisk)" -ForegroundColor Cyan $destination = $shell_app.namespace($targetondisk) $destination.Copyhere($zip_file.items(), 0x10) Write-Host "Module has been installed!" -ForegroundColor Green Write-Host "You can now import the module with: Import-Module -Name $ModuleName"
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/Build.ps1
Build.ps1
#Requires -Version 5 [CmdletBinding(DefaultParameterSetName='Build')] param ( [parameter(Position=0, ParameterSetName='Build')] [switch]$BuildModule, [parameter(Position=1, ParameterSetName='Build')] [switch]$CreatePSGalleryProfile, [parameter(Position=2, ParameterSetName='Build')] [switch]$UpdateRelease, [parameter(Position=3, ParameterSetName='Build')] [switch]$UploadPSGallery, [parameter(Position=4, ParameterSetName='Build')] [switch]$GitCheckin, [parameter(Position=5, ParameterSetName='Build')] [switch]$GitPush, [parameter(Position=6, ParameterSetName='Build')] [switch]$InstallAndTestModule, [parameter(Position=7, ParameterSetName='Build')] [version]$NewVersion, [parameter(Position=8, ParameterSetName='Build')] [string]$ReleaseNotes, [parameter(Position=0, ParameterSetName='CBH')] [switch]$InsertCBH, [parameter(Position=0, ParameterSetName='Help')] [switch]$Help ) $HelpContents = @' This is a wrapper script for invoke-build and a set of build tasks in the included .build.ps1 file. As this is a wrapper script almost all parameters are simple switches. This help output will cover what each of these switches will accomplish. Help - This help output. InsertCBH - So far there is the only helper task that doesn't really do anything as part of a build process. When you run with this switch all the function scripts in .\src\public will be inspected for comment based help (CBH) within its function scriptblock. If one is not readily found then a template CBH will be added in a copy of the script which will be saved in the scratch directory (usually located in .\temp\src\public). This switch is stand-alone and will not work with other switches in this script. Use one or more of the following switches with this script to kick off some of the most common build tasks for your module project. All of the following switches can be stringed together. They are listed in the order they would be processed in were they all to be used at once. CreatePSGalleryProfile - Create an initial PSGallery profile for your project. This will only be useful if you have an API key for the site stored in "$(split-path $PROFILE)\psgalleryapi.txt" and plan on releasing the module to the powershell gallery. UpdateRelease - If you have manually updated the version.txt file then this will trigger the build scripts to begin building and releasing the new version. It updates the module manifest file as well. You can use this in conjunction with the -NewVersion parameter to update the version.txt file as well. NewVersion - Can be used with the -UpdateRelease parameter to start a new version of the module for release. BuildModule - This is the default action if no parameters are passed to this script. This kicks off the build process as defined by the .\build\.buildenvironment.ps1 configuration script. If all goes well a completed and fully packaged build of your project will be created in the following locations: .\release\<version> - Every new version you release will be kept in its own directory .\release\<modulename>-<version>.zip - Every version will have an assoicated zip created .\release\<modulename> - The current release will always be in a folder with the module name .\release\<modulename>.zip - The current release in zip format for easy automated installation InstallAndTestModule - Attempt to install a finished build of the module from .\release\<modulename>. After installing the module we then attempt to load it to ensure it works. UploadPSGallery - Upload a release to the PSGallery for others to install with install-module (PowerShell 5+ only). Every uploaded release requires release notes which can be passed via the -ReleaseNotes parameter. This will also fail outright if you don't have appropriate LicenseURI and IconURI entries uncommented and set in your <modulename>.psd1 manifest file. ReleaseNotes - Used in conjunction with the -UploadPSGallery parameter. GitCheckin - Not finished with this yet, sorry. GitPush - Not finished with this yet, sorry. '@ function PrerequisitesLoaded { # Install InvokeBuild module if it doesn't already exist try { if ((get-module InvokeBuild -ListAvailable) -eq $null) { Write-Host "Attempting to install the InvokeBuild module..." $null = Install-Module InvokeBuild } if (get-module InvokeBuild -ListAvailable) { Write-Host -NoNewLine "Importing InvokeBuild module" Import-Module InvokeBuild -Force Write-Host -ForegroundColor Green '...Loaded!' return $true } else { return $false } } catch { return $false } } function CleanUp { try { Write-Output '' Write-Output 'Attempting to clean up the session (loaded modules and such)...' Invoke-Build BuildSessionCleanup Remove-Module InvokeBuild } catch {} } switch ($psCmdlet.ParameterSetName) { 'Help' { Write-Output $HelpContents } 'CBH' { if (-not (PrerequisitesLoaded)) { throw 'Unable to load InvokeBuild!' } if ($InsertCBH) { try { Invoke-Build InsertMissingCBH } catch { throw } } CleanUp } 'Build' { if (-not (PrerequisitesLoaded)) { throw 'Unable to load InvokeBuild!' } # Create a gallery profile? if ($CreatePSGalleryProfile) { try { Invoke-Build NewPSGalleryProfile } catch { throw 'Unable to create the .psgallery profile file!' } } # Update your release version? if ($UpdateRelease) { if ($NewVersion -ne $null) { $NewVersion.ToString() | Out-File -FilePath .\version.txt -Force } try { Invoke-Build UpdateVersion } catch { throw } } # If no parameters were specified or the build action was manually specified then kick off a standard build if (($psboundparameters.count -eq 0) -or ($BuildModule)) { try { Invoke-Build } catch { Write-Output 'Build Failed with the following error:' Write-Output $_ } } # Install and test the module? if ($InstallAndTestModule) { try { Invoke-Build InstallAndTestModule } catch { Write-Output 'Install and test of module failed:' Write-Output $_ } } # Upload to gallery? if ($UploadPSGallery) { if ([string]::IsNullOrEmpty($ReleaseNotes)) { throw '$ReleaseNotes needs to be specified to run this operation!' } try { Invoke-Build PublishPSGallery -ReleaseNotes $ReleaseNotes } catch { throw 'Unable to upload projec to the PowerShell Gallery!' } } # Not implemented yet if ($GitCheckin) { # Finish me } # Not implemented yet if ($GitPush) { # Finish me } CleanUp } }
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/src/other/PostLoad.ps1
PostLoad.ps1
# Use this variable for any path-sepecific actions (like loading dlls and such) to ensure it will work in testing and after being built $MyModulePath = $( Function Get-ScriptPath { $Invocation = (Get-Variable MyInvocation -Scope 1).Value if($Invocation.PSScriptRoot) { $Invocation.PSScriptRoot } Elseif($Invocation.MyCommand.Path) { Split-Path $Invocation.MyCommand.Path } elseif ($Invocation.InvocationName.Length -eq 0) { (Get-Location).Path } else { $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\")); } } Get-ScriptPath ) if ($host.Name -ne "Windows PowerShell ISE Host") { Write-Warning "Runtime Inspector is a PowerShell ISE Addon" } else { Add-Type -Path $MyModulePath\RuntimeInspector.dll -PassThru $typeRuntimeInspector = [IseAddons.VariableExplorer] $psISE.CurrentPowerShellTab.VerticalAddOnTools.Add("RuntimeInspector", $typeRuntimeInspector, $true) } #region Module Cleanup $ExecutionContext.SessionState.Module.OnRemove = { # Action to take if the module is removed $RITab = $psISE.CurrentPowerShellTab.VerticalAddOnTools | Where-Object { $_.Name -eq "RuntimeInspector" } $OITab = $psISE.CurrentPowerShellTab.HorizontalAddOnTools | Where-Object { $_.Name -eq "OutputInspector" } if ($RITab) { $null = $psISE.CurrentPowerShellTab.VerticalAddOnTools.Remove($RITab) } if ($OITab) { $null = $psISE.CurrentPowerShellTab.HorizontalAddOnTools.Remove($OITab) } } $null = Register-EngineEvent -SourceIdentifier ( [System.Management.Automation.PsEngineEvent]::Exiting ) -Action { # Action to take if the whole pssession is killed } #endregion Module Cleanup # Exported members #Export-ModuleMember -Variable SomeVariable -Function *
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/src/public/ObjectModule.ps1
ObjectModule.ps1
Function Show-Object-Flat { <# .SYNOPSIS Flatten an object to simplify discovery of data .DESCRIPTION Flatten an object. This function will take an object, and flatten the properties using their full path into a single object with one layer of properties. You can use this to flatten XML, JSON, and other arbitrary objects. This can simplify initial exploration and discovery of data returned by APIs, interfaces, and other technologies. NOTE: Use tools like Get-Member, Select-Object, and Show-Object to further explore objects. This function does not handle certain data types well. It was original designed to expand XML and JSON. .PARAMETER InputObject Object to flatten .PARAMETER Exclude Exclude any nodes in this list. Accepts wildcards. Example: -Exclude price, title .PARAMETER ExcludeDefault Exclude default properties for sub objects. True by default. This simplifies views of many objects (e.g. XML) but may exclude data for others (e.g. if flattening a process, ProcessThread properties will be excluded) .PARAMETER Include Include only leaves in this list. Accepts wildcards. Example: -Include Author, Title .PARAMETER Value Include only leaves with values like these arguments. Accepts wildcards. .PARAMETER MaxDepth Stop recursion at this depth. .INPUTS Any object .OUTPUTS System.Management.Automation.PSCustomObject .EXAMPLE #Pull unanswered PowerShell questions from StackExchange, Flatten the data to date a feel for the schema Invoke-RestMethod "https://api.stackexchange.com/2.0/questions/unanswered?order=desc&sort=activity&tagged=powershell&pagesize=10&site=stackoverflow" | ConvertTo-FlatObject -Include Title, Link, View_Count $object.items[0].owner.link : http://stackoverflow.com/users/1946412/julealgon $object.items[0].view_count : 7 $object.items[0].link : http://stackoverflow.com/questions/26910789/is-it-possible-to-reuse-a-param-block-across-multiple-functions $object.items[0].title : Is it possible to reuse a &#39;param&#39; block across multiple functions? $object.items[1].owner.link : http://stackoverflow.com/users/4248278/nitin-tyagi $object.items[1].view_count : 8 $object.items[1].link : http://stackoverflow.com/questions/26909879/use-powershell-to-retreive-activated-features-for-sharepoint-2010 $object.items[1].title : Use powershell to retreive Activated features for sharepoint 2010 ... .EXAMPLE #Set up some XML to work with $object = [xml]' <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developers Guide</title> <genre>Computer</genre> <price>44.95</price> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> </book> </catalog>' #Call the flatten command against this XML ConvertTo-FlatObject $object -Include Author, Title, Price #Result is a flattened object with the full path to the node, using $object as the root. #Only leaf properties we specified are included (author,title,price) $object.catalog.book[0].author : Gambardella, Matthew $object.catalog.book[0].title : XML Developers Guide $object.catalog.book[0].price : 44.95 $object.catalog.book[1].author : Ralls, Kim $object.catalog.book[1].title : Midnight Rain $object.catalog.book[1].price : 5.95 #Invoking the property names should return their data if the orginal object is in $object: $object.catalog.book[1].price 5.95 $object.catalog.book[0].title XML Developers Guide .EXAMPLE #Set up some XML to work with [xml]'<catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developers Guide</title> <genre>Computer</genre> <price>44.95</price> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> </book> </catalog>' | ConvertTo-FlatObject -exclude price, title, id Result is a flattened object with the full path to the node, using XML as the root. Price and title are excluded. $Object.catalog : catalog $Object.catalog.book : {book, book} $object.catalog.book[0].author : Gambardella, Matthew $object.catalog.book[0].genre : Computer $object.catalog.book[1].author : Ralls, Kim $object.catalog.book[1].genre : Fantasy .EXAMPLE #Set up some XML to work with [xml]'<catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developers Guide</title> <genre>Computer</genre> <price>44.95</price> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> </book> </catalog>' | ConvertTo-FlatObject -Value XML*, Fantasy Result is a flattened object filtered by leaves that matched XML* or Fantasy $Object.catalog.book[0].title : XML Developers Guide $Object.catalog.book[1].genre : Fantasy .EXAMPLE #Get a single process with all props, flatten this object. Don't exclude default properties Get-Process | select -first 1 -skip 10 -Property * | ConvertTo-FlatObject -ExcludeDefault $false #NOTE - There will likely be bugs for certain complex objects like this. For example, $Object.StartInfo.Verbs.SyncRoot.SyncRoot... will loop until we hit MaxDepth. (Note: SyncRoot is now addressed individually) .NOTES I have trouble with algorithms. If you have a better way to handle this, please let me know! .FUNCTIONALITY General Command #> [cmdletbinding()] param( [parameter( Mandatory = $True, ValueFromPipeline = $True)] [PSObject[]]$InputObject, [string[]]$Exclude = "", [bool]$ExcludeDefault = $True, [string[]]$Include = $null, [string[]]$Value = $null, [int]$MaxDepth = 10 ) Begin { #region FUNCTIONS #Before adding a property, verify that it matches a Like comparison to strings in $Include... Function IsIn-Include { param($prop) if(-not $Include) {$True} else { foreach($Inc in $Include) { if($Prop -like $Inc) { $True } } } } #Before adding a value, verify that it matches a Like comparison to strings in $Value... Function IsIn-Value { param($val) if(-not $Value) {$True} else { foreach($string in $Value) { if($val -like $string) { $True } } } } Function Get-Exclude { [cmdletbinding()] param($obj) #Exclude default props if specified, and anything the user specified. Thanks to Jaykul for the hint on [type]! if($ExcludeDefault) { Try { $DefaultTypeProps = @( $obj.gettype().GetProperties() | Select -ExpandProperty Name -ErrorAction Stop ) if($DefaultTypeProps.count -gt 0) { Write-Verbose "Excluding default properties for $($obj.gettype().Fullname):`n$($DefaultTypeProps | Out-String)" } } Catch { Write-Verbose "Failed to extract properties from $($obj.gettype().Fullname): $_" $DefaultTypeProps = @() } } @( $Exclude + $DefaultTypeProps ) | Select -Unique } #Function to recurse the Object, add properties to object Function Recurse-Object { [cmdletbinding()] param( $Object, [string[]]$path = '$Object', [psobject]$Output, $depth = 0 ) # Handle initial call Write-Verbose "Working in path $Path at depth $depth" Write-Debug "Recurse Object called with PSBoundParameters:`n$($PSBoundParameters | Out-String)" $Depth++ #Exclude default props if specified, and anything the user specified. $ExcludeProps = @( Get-Exclude $object ) #Get the children we care about, and their names $Children = $object.psobject.properties | Where {$ExcludeProps -notcontains $_.Name } Write-Debug "Working on properties:`n$($Children | select -ExpandProperty Name | Out-String)" #Loop through the children properties. foreach($Child in @($Children)) { $ChildName = $Child.Name $ChildValue = $Child.Value Write-Debug "Working on property $ChildName with value $($ChildValue | Out-String)" # Handle special characters... if($ChildName -match '[^a-zA-Z0-9_]') { $FriendlyChildName = "'$ChildName'" } else { $FriendlyChildName = $ChildName } #Add the property. if((IsIn-Include $ChildName) -and (IsIn-Value $ChildValue) -and $Depth -le $MaxDepth) { $ThisPath = @( $Path + $FriendlyChildName ) -join "." $Output | Add-Member -MemberType NoteProperty -Name $ThisPath -Value $ChildValue Write-Verbose "Adding member '$ThisPath'" } #Handle null... if($ChildValue -eq $null) { Write-Verbose "Skipping NULL $ChildName" continue } #Handle evil looping. Will likely need to expand this. Any thoughts on a better approach? if( ( $ChildValue.GetType() -eq $Object.GetType() -and $ChildValue -is [datetime] ) -or ( $ChildName -eq "SyncRoot" -and -not $ChildValue ) ) { Write-Verbose "Skipping $ChildName with type $($ChildValue.GetType().fullname)" continue } #Check for arrays $IsArray = @($ChildValue).count -gt 1 $count = 0 #Set up the path to this node and the data... $CurrentPath = @( $Path + $FriendlyChildName ) -join "." #Exclude default props if specified, and anything the user specified. $ExcludeProps = @( Get-Exclude $ChildValue ) #Get the children's children we care about, and their names. Also look for signs of a hashtable like type $ChildrensChildren = $ChildValue.psobject.properties | Where {$ExcludeProps -notcontains $_.Name } $HashKeys = if($ChildValue.Keys -notlike $null -and $ChildValue.Values) { $ChildValue.Keys } else { $null } Write-Debug "Found children's children $($ChildrensChildren | select -ExpandProperty Name | Out-String)" #If we aren't at max depth or a leaf... if( (@($ChildrensChildren).count -ne 0 -or $HashKeys) -and $Depth -lt $MaxDepth ) { #This handles hashtables. But it won't recurse... if($HashKeys) { Write-Verbose "Working on hashtable $CurrentPath" foreach($key in $HashKeys) { Write-Verbose "Adding value from hashtable $CurrentPath['$key']" $Output | Add-Member -MemberType NoteProperty -name "$CurrentPath['$key']" -value $ChildValue["$key"] $Output = Recurse-Object -Object $ChildValue["$key"] -Path "$CurrentPath['$key']" -Output $Output -depth $depth } } #Sub children? Recurse! else { if($IsArray) { foreach($item in @($ChildValue)) { Write-Verbose "Recursing through array node '$CurrentPath'" $Output = Recurse-Object -Object $item -Path "$CurrentPath[$count]" -Output $Output -depth $depth $Count++ } } else { Write-Verbose "Recursing through node '$CurrentPath'" $Output = Recurse-Object -Object $ChildValue -Path $CurrentPath -Output $Output -depth $depth } } } } $Output } #endregion FUNCTIONS } Process { Foreach($Object in $InputObject) { #Flatten the XML and write it to the pipeline Recurse-Object -Object $Object -Output $( New-Object -TypeName PSObject ) } } } function Show-Object-Detail { <# .SYNOPSIS Decorate an object with - A TypeName - New properties - Default parameters .DESCRIPTION Helper function to decorate an object with - A TypeName - New properties - Default parameters .PARAMETER InputObject Object to decorate. Accepts pipeline input. .PARAMETER TypeName Typename to insert. This will show up when you use Get-Member against the resulting object. .PARAMETER PropertyToAdd Add these noteproperties. Format is a hashtable with Key (Property Name) = Value (Property Value). Example to add a One and Date property: -PropertyToAdd @{ One = 1 Date = (Get-Date) } .PARAMETER DefaultProperties Change the default properties that show up .PARAMETER Passthru Whether to pass the resulting object on. Defaults to true .EXAMPLE # # Create an object to work with $Object = [PSCustomObject]@{ First = 'Cookie' Last = 'Monster' Account = 'CMonster' } #Add a type name and a random property Add-ObjectDetail -InputObject $Object -TypeName 'ApplicationX.Account' -PropertyToAdd @{ AnotherProperty = 5 } # First Last Account AnotherProperty # ----- ---- ------- --------------- # Cookie Monster CMonster 5 #Verify that get-member shows us the right type $Object | Get-Member # TypeName: ApplicationX.Account ... .EXAMPLE # # Create an object to work with $Object = [PSCustomObject]@{ First = 'Cookie' Last = 'Monster' Account = 'CMonster' } #Add a random property, set a default property set so we only see two props by default Add-ObjectDetail -InputObject $Object -PropertyToAdd @{ AnotherProperty = 5 } -DefaultProperties Account, AnotherProperty # Account AnotherProperty # ------- --------------- # CMonster 5 #Verify that the other properties are around $Object | Select -Property * # First Last Account AnotherProperty # ----- ---- ------- --------------- # Cookie Monster CMonster 5 .NOTES This breaks the 'do one thing' rule from certain perspectives... The goal is to decorate an object all in one shot This abstraction simplifies decorating an object, with a slight trade-off in performance. For example: 10,000 objects, add a property and typename: Add-ObjectDetail: ~4.6 seconds Add-Member + PSObject.TypeNames.Insert: ~3 seconds Initial code borrowed from Shay Levy: http://blogs.microsoft.co.il/scriptfanatic/2012/04/13/custom-objects-default-display-in-powershell-30/ .LINK http://ramblingcookiemonster.github.io/Decorating-Objects/ .FUNCTIONALITY PowerShell Language #> [CmdletBinding()] param( [Parameter( Mandatory = $true, Position=0, ValueFromPipeline=$true )] [ValidateNotNullOrEmpty()] [psobject[]]$InputObject, [Parameter( Mandatory = $false, Position=1)] [string]$TypeName, [Parameter( Mandatory = $false, Position=2)] [System.Collections.Hashtable]$PropertyToAdd, [Parameter( Mandatory = $false, Position=3)] [ValidateNotNullOrEmpty()] [Alias('dp')] [System.String[]]$DefaultProperties, [boolean]$Passthru = $True ) Begin { if($PSBoundParameters.ContainsKey('DefaultProperties')) { # define a subset of properties $ddps = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet,$DefaultProperties $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]$ddps } } Process { foreach($Object in $InputObject) { switch ($PSBoundParameters.Keys) { 'PropertyToAdd' { foreach($Key in $PropertyToAdd.Keys) { #Add some noteproperties. Slightly faster than Add-Member. $Object.PSObject.Properties.Add( ( New-Object System.Management.Automation.PSNoteProperty($Key, $PropertyToAdd[$Key]) ) ) } } 'TypeName' { #Add specified type [void]$Object.PSObject.TypeNames.Insert(0,$TypeName) } 'DefaultProperties' { # Attach default display property set Add-Member -InputObject $Object -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers } } if($Passthru) { $Object } } } } function Show-Object-List { ############################################################################# ## ## Show-Object ## ## From Windows PowerShell Cookbook (O'Reilly) ## by Lee Holmes (http://www.leeholmes.com/guide) ## ############################################################################## <# .SYNOPSIS Spelunking with Show-Object .DESCRIPTION Spelunk [spi-luhngk], verb. To explore caves, especially as a hobby. We must first recall that PowerShell pipelines are very different from, say, Linux pipelines. Rather than consisting of text, PowerShell objects are "three-dimensional" data structures that consist of properties (descriptive attributes), methods (actions the object can undertake), and events (actions that can be undertaken on the object). Collectively, these data elements are called object members. For instance, take Get-Service. Unless you perform filtering, you receive an object collection as output. You probably know that Get-Member shows us the object's .NET Framework type name and its properties, methods, and events. Here's partial output from my Windows 8.1 administrative workstation running Windows Management Framework 5.0 Production Preview: PS C:\> Get-Service | Get-Member TypeName: System.ServiceProcess.ServiceController Name MemberType Definition —- ———- ———- Name AliasProperty Name = ServiceName RequiredServices AliasProperty RequiredServices… Disposed Event System.EventHandler… Close Method void Close() Continue Method void Continue() PowerShell objects are instances of underlying .NET classes, and by default those classes are self-discovering through a process known as reflection. If you want to see everything about the previous ServiceController objects, pipe the Get-Member output to Format-List like so: Get-Service | Get-Member | Format-List * What I've told you means that, practically speaking, we do an awful lot of get-membering and format-listing when we need to look up specific property, method, or event values. Is there (banish the thought!) an easier-on-the-eyes graphical solution? .EXAMPLE First we can locate the appropriate module: Find-Module -Name *cookbook* Cool. So Lee's module is named PowerShellCookbook, and it is stored on the PowerShell Gallery repository. Let's install it! Install-Module -Name PowerShellCookbook -Force As it happens, Show-Object is only one function among many that are contained in the PowerShellCookbook module. Run the following command to see them all: Get-Command -Module PowerShellCookbook Using the Show-Object Function To use Show-Object, simply pipe your desired PowerShell object into the function like so: Get-Service -Name Spooler | Show-Object Take a look at the following Show-Object output, and I'll walk you through it. The bottom pane (sadly unresizable) shows your ordinary Get-Member output. The upper pane allows you to quickly parse the object properties. For instance, we can expand each RequiredServices node to learn that the Print Spooler service in Windows 8.1 depends on a Remote Procedure Call (RPC) and HTTP services. If you're of the mind to do so, you can inspect the Show-Object source code by visiting the book's website (see Program: Interactively View and Explore Objects) or by using PowerShell directly in your console: (Get-Command -name Show-Object).Definition | Out-File 'C:\show-object-source.txt' | Notepad 'C:\show-object-source.txt' Going further One of the many things I love about the Windows PowerShell community is how friendly and helpful most people are. I don't want to draw comparisons to, say, the *NIX open-source community, but…well, let's just leave that alone. That's all there is to it! .FUNCTIONALITY General Command #> param( ## The object to examine [Parameter(ValueFromPipeline = $true)] $InputObject ) Set-StrictMode -Version 3 Add-Type -Assembly System.Windows.Forms ## Figure out the variable name to use when displaying the ## object navigation syntax. To do this, we look through all ## of the variables for the one with the same object identifier. $rootVariableName = dir variable:\* -Exclude InputObject,Args | Where-Object { $_.Value -and ($_.Value.GetType() -eq $InputObject.GetType()) -and ($_.Value.GetHashCode() -eq $InputObject.GetHashCode()) } ## If we got multiple, pick the first $rootVariableName = $rootVariableName| % Name | Select -First 1 ## If we didn't find one, use a default name if(-not $rootVariableName) { $rootVariableName = "InputObject" } ## A function to add an object to the display tree function PopulateNode($node, $object) { ## If we've been asked to add a NULL object, just return if(-not $object) { return } ## If the object is a collection, then we need to add multiple ## children to the node if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object)) { ## Some very rare collections don't support indexing (i.e.: $foo[0]). ## In this situation, PowerShell returns the parent object back when you ## try to access the [0] property. $isOnlyEnumerable = $object.GetHashCode() -eq $object[0].GetHashCode() ## Go through all the items $count = 0 foreach($childObjectValue in $object) { ## Create the new node to add, with the node text of the item and ## value, along with its type $newChildNode = New-Object Windows.Forms.TreeNode $newChildNode.Text = "$($node.Name)[$count] = $childObjectValue" $newChildNode.ToolTipText = $childObjectValue.GetType() ## Use the node name to keep track of the actual property name ## and syntax to access that property. ## If we can't use the index operator to access children, add ## a special tag that we'll handle specially when displaying ## the node names. if($isOnlyEnumerable) { $newChildNode.Name = "@" } $newChildNode.Name += "[$count]" $null = $node.Nodes.Add($newChildNode) ## If this node has children or properties, add a placeholder ## node underneath so that the node shows a '+' sign to be ## expanded. AddPlaceholderIfRequired $newChildNode $childObjectValue $count++ } } else { ## If the item was not a collection, then go through its ## properties foreach($child in $object.PSObject.Properties) { ## Figure out the value of the property, along with ## its type. $childObject = $child.Value $childObjectType = $null if($childObject) { $childObjectType = $childObject.GetType() } ## Create the new node to add, with the node text of the item and ## value, along with its type $childNode = New-Object Windows.Forms.TreeNode $childNode.Text = $child.Name + " = $childObject" $childNode.ToolTipText = $childObjectType if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($childObject)) { $childNode.ToolTipText += "[]" } $childNode.Name = $child.Name $null = $node.Nodes.Add($childNode) ## If this node has children or properties, add a placeholder ## node underneath so that the node shows a '+' sign to be ## expanded. AddPlaceholderIfRequired $childNode $childObject } } } ## A function to add a placeholder if required to a node. ## If there are any properties or children for this object, make a temporary ## node with the text "..." so that the node shows a '+' sign to be ## expanded. function AddPlaceholderIfRequired($node, $object) { if(-not $object) { return } if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object) -or @($object.PSObject.Properties)) { $null = $node.Nodes.Add( (New-Object Windows.Forms.TreeNode "...") ) } } ## A function invoked when a node is selected. function OnAfterSelect { param($Sender, $TreeViewEventArgs) ## Determine the selected node $nodeSelected = $Sender.SelectedNode ## Walk through its parents, creating the virtual ## PowerShell syntax to access this property. $nodePath = GetPathForNode $nodeSelected ## Now, invoke that PowerShell syntax to retrieve ## the value of the property. $resultObject = Invoke-Expression $nodePath $outputPane.Text = $nodePath ## If we got some output, put the object's member ## information in the text box. if($resultObject) { $members = Get-Member -InputObject $resultObject | Out-String $outputPane.Text += "`n" + $members } } ## A function invoked when the user is about to expand a node function OnBeforeExpand { param($Sender, $TreeViewCancelEventArgs) ## Determine the selected node $selectedNode = $TreeViewCancelEventArgs.Node ## If it has a child node that is the placeholder, clear ## the placehoder node. if($selectedNode.FirstNode -and ($selectedNode.FirstNode.Text -eq "...")) { $selectedNode.Nodes.Clear() } else { return } ## Walk through its parents, creating the virtual ## PowerShell syntax to access this property. $nodePath = GetPathForNode $selectedNode ## Now, invoke that PowerShell syntax to retrieve ## the value of the property. Invoke-Expression "`$resultObject = $nodePath" ## And populate the node with the result object. PopulateNode $selectedNode $resultObject } ## A function to handle key presses on the tree view. ## In this case, we capture ^C to copy the path of ## the object property that we're currently viewing. function OnTreeViewKeyPress { param($Sender, $KeyPressEventArgs) ## [Char] 3 = Control-C if($KeyPressEventArgs.KeyChar -eq 3) { $KeyPressEventArgs.Handled = $true ## Get the object path, and set it on the clipboard $node = $Sender.SelectedNode $nodePath = GetPathForNode $node [System.Windows.Forms.Clipboard]::SetText($nodePath) $form.Close() } elseif([System.Windows.Forms.Control]::ModifierKeys -eq "Control") { if($KeyPressEventArgs.KeyChar -eq '+') { $SCRIPT:currentFontSize++ UpdateFonts $SCRIPT:currentFontSize $KeyPressEventArgs.Handled = $true } elseif($KeyPressEventArgs.KeyChar -eq '-') { $SCRIPT:currentFontSize-- if($SCRIPT:currentFontSize -lt 1) { $SCRIPT:currentFontSize = 1 } UpdateFonts $SCRIPT:currentFontSize $KeyPressEventArgs.Handled = $true } } } ## A function to handle key presses on the form. ## In this case, we handle Ctrl-Plus and Ctrl-Minus ## to adjust font size. function OnKeyUp { param($Sender, $KeyUpEventArgs) if([System.Windows.Forms.Control]::ModifierKeys -eq "Control") { if($KeyUpEventArgs.KeyCode -in 'Add','OemPlus') { $SCRIPT:currentFontSize++ UpdateFonts $SCRIPT:currentFontSize $KeyUpEventArgs.Handled = $true } elseif($KeyUpEventArgs.KeyCode -in 'Subtract','OemMinus') { $SCRIPT:currentFontSize-- if($SCRIPT:currentFontSize -lt 1) { $SCRIPT:currentFontSize = 1 } UpdateFonts $SCRIPT:currentFontSize $KeyUpEventArgs.Handled = $true } elseif($KeyUpEventArgs.KeyCode -eq 'D0') { $SCRIPT:currentFontSize = 12 UpdateFonts $SCRIPT:currentFontSize $KeyUpEventArgs.Handled = $true } } } ## A function to handle mouse wheel scrolling. ## In this case, we translate Ctrl-Wheel to zoom. function OnMouseWheel { param($Sender, $MouseEventArgs) if( ([System.Windows.Forms.Control]::ModifierKeys -eq "Control") -and ($MouseEventArgs.Delta -ne 0)) { $SCRIPT:currentFontSize += ($MouseEventArgs.Delta / 120) if($SCRIPT:currentFontSize -lt 1) { $SCRIPT:currentFontSize = 1 } UpdateFonts $SCRIPT:currentFontSize $MouseEventArgs.Handled = $true } } ## A function to walk through the parents of a node, ## creating virtual PowerShell syntax to access this property. function GetPathForNode { param($Node) $nodeElements = @() ## Go through all the parents, adding them so that ## $nodeElements is in order. while($Node) { $nodeElements = ,$Node + $nodeElements $Node = $Node.Parent } ## Now go through the node elements $nodePath = "" foreach($Node in $nodeElements) { $nodeName = $Node.Name ## If it was a node that PowerShell is able to enumerate ## (but not index), wrap it in the array cast operator. if($nodeName.StartsWith('@')) { $nodeName = $nodeName.Substring(1) $nodePath = "@(" + $nodePath + ")" } elseif($nodeName.StartsWith('[')) { ## If it's a child index, we don't need to ## add the dot for property access } elseif($nodePath) { ## Otherwise, we're accessing a property. Add a dot. $nodePath += "." } ## Append the node name to the path $tempNodePath = $nodePath + $nodeName if($nodeName -notmatch '^[$\[\]a-zA-Z0-9]+$') { $nodePath += "'" + $nodeName + "'" } else { $nodePath = $tempNodePath } } ## And return the result $nodePath } function UpdateFonts { param($fontSize) $treeView.Font = New-Object System.Drawing.Font "Consolas",$fontSize $outputPane.Font = New-Object System.Drawing.Font "Consolas",$fontSize } $SCRIPT:currentFontSize = 12 ## Create the TreeView, which will hold our object navigation ## area. $treeView = New-Object Windows.Forms.TreeView $treeView.Dock = "Top" $treeView.Height = 500 $treeView.PathSeparator = "." $treeView.ShowNodeToolTips = $true $treeView.Add_AfterSelect( { OnAfterSelect @args } ) $treeView.Add_BeforeExpand( { OnBeforeExpand @args } ) $treeView.Add_KeyPress( { OnTreeViewKeyPress @args } ) ## Create the output pane, which will hold our object ## member information. $outputPane = New-Object System.Windows.Forms.TextBox $outputPane.Multiline = $true $outputPane.WordWrap = $false $outputPane.ScrollBars = "Both" $outputPane.Dock = "Fill" ## Create the root node, which represents the object ## we are trying to show. $root = New-Object Windows.Forms.TreeNode $root.ToolTipText = $InputObject.GetType() $root.Text = $InputObject $root.Name = '$' + $rootVariableName $root.Expand() $null = $treeView.Nodes.Add($root) UpdateFonts $currentFontSize ## And populate the initial information into the tree ## view. PopulateNode $root $InputObject ## Finally, create the main form and show it. $form = New-Object Windows.Forms.Form $form.Text = "Browsing " + $root.Text $form.Width = 1000 $form.Height = 800 $form.Controls.Add($outputPane) $form.Controls.Add($treeView) $form.Add_MouseWheel( { OnMouseWheel @args } ) $treeView.Add_KeyUp( { OnKeyUp @args } ) $treeView.Select() $null = $form.ShowDialog() $form.Dispose() } function Show-Object-Tree{ <# .SYNOPSIS Spelunking with Show-Object .DESCRIPTION Spelunk [spi-luhngk], verb. To explore caves, especially as a hobby. We must first recall that PowerShell pipelines are very different from, say, Linux pipelines. Rather than consisting of text, PowerShell objects are "three-dimensional" data structures that consist of properties (descriptive attributes), methods (actions the object can undertake), and events (actions that can be undertaken on the object). Collectively, these data elements are called object members. For instance, take Get-Service. Unless you perform filtering, you receive an object collection as output. You probably know that Get-Member shows us the object's .NET Framework type name and its properties, methods, and events. Here's partial output from my Windows 8.1 administrative workstation running Windows Management Framework 5.0 Production Preview: PS C:\> Get-Service | Get-Member TypeName: System.ServiceProcess.ServiceController Name MemberType Definition —- ———- ———- Name AliasProperty Name = ServiceName RequiredServices AliasProperty RequiredServices… Disposed Event System.EventHandler… Close Method void Close() Continue Method void Continue() PowerShell objects are instances of underlying .NET classes, and by default those classes are self-discovering through a process known as reflection. If you want to see everything about the previous ServiceController objects, pipe the Get-Member output to Format-List like so: Get-Service | Get-Member | Format-List * What I've told you means that, practically speaking, we do an awful lot of get-membering and format-listing when we need to look up specific property, method, or event values. Is there (banish the thought!) an easier-on-the-eyes graphical solution? .EXAMPLE First we can locate the appropriate module: Find-Module -Name *cookbook* Cool. So Lee's module is named PowerShellCookbook, and it is stored on the PowerShell Gallery repository. Let's install it! Install-Module -Name PowerShellCookbook -Force As it happens, Show-Object is only one function among many that are contained in the PowerShellCookbook module. Run the following command to see them all: Get-Command -Module PowerShellCookbook Using the Show-Object Function To use Show-Object, simply pipe your desired PowerShell object into the function like so: Get-Service -Name Spooler | Show-Object Take a look at the following Show-Object output, and I'll walk you through it. The bottom pane (sadly unresizable) shows your ordinary Get-Member output. The upper pane allows you to quickly parse the object properties. For instance, we can expand each RequiredServices node to learn that the Print Spooler service in Windows 8.1 depends on a Remote Procedure Call (RPC) and HTTP services. If you're of the mind to do so, you can inspect the Show-Object source code by visiting the book's website (see Program: Interactively View and Explore Objects) or by using PowerShell directly in your console: (Get-Command -name Show-Object).Definition | Out-File 'C:\show-object-source.txt' | Notepad 'C:\show-object-source.txt' Going further One of the many things I love about the Windows PowerShell community is how friendly and helpful most people are. I don't want to draw comparisons to, say, the *NIX open-source community, but…well, let's just leave that alone. That's all there is to it! .FUNCTIONALITY General Command #> param( ## The object to examine [Parameter(ValueFromPipeline = $true)] $InputObject ) #custom controls for treeview... found it on MSDN a while ago, lost link :-/ [void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework') add-type @" using System; using System.Windows.Controls; using System.Windows; using System.Windows.Data; using System.Globalization; namespace _treeListView { public class TreeListView : TreeView { protected override DependencyObject GetContainerForItemOverride() { return new TreeListViewItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return item is TreeListViewItem; } } public class TreeListViewItem : TreeViewItem { private int _level = -1; public int Level { get { if (_level != -1) return _level; var parent = ItemsControl.ItemsControlFromItemContainer(this) as TreeListViewItem; _level = (parent != null) ? parent.Level + 1 : 0; return _level; } } public TreeListViewItem(object header) { Header = header; } public TreeListViewItem(){} protected override DependencyObject GetContainerForItemOverride() { return new TreeListViewItem(); } protected override bool IsItemItsOwnContainerOverride(object item) { return item is TreeListViewItem; } } public class LevelToIndentConverter : IValueConverter { private const double c_IndentSize = 19.0; public object Convert(object o, Type type, object parameter,CultureInfo culture) { return new Thickness((int)o * c_IndentSize, 0, 0, 0); } public object ConvertBack(object o, Type type, object parameter,CultureInfo culture) { throw new NotSupportedException(); } } } "@ -ReferencedAssemblies presentationFramework,PresentationCore,WindowsBase,System.Xaml -ErrorAction SilentlyContinue ## form layout [xml]$xaml = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s='clr-namespace:System;assembly=mscorlib' xmlns:l='clr-namespace:_treeListView;assembly=$([_treeListView.LevelToIndentConverter].Assembly)' Title="TreeListView" Width="640" Height="480"> <Window.Resources> <Style x:Key="ExpandCollapseToggleStyle" TargetType="{x:Type ToggleButton}"> <Setter Property="Focusable" Value="False"/> <Setter Property="Width" Value="19"/> <Setter Property="Height" Value="13"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ToggleButton}"> <Border Width="19" Height="13" Background="Transparent"> <Border Width="9" Height="9" BorderThickness="1" BorderBrush="#FF7898B5" CornerRadius="1" SnapsToDevicePixels="true"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="1,1"> <LinearGradientBrush.GradientStops> <GradientStop Color="White" Offset=".2"/> <GradientStop Color="#FFC0B7A6" Offset="1"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.Background> <Path x:Name="ExpandPath" Margin="1,1,1,1" Fill="Black" Data="M 0 2 L 0 3 L 2 3 L 2 5 L 3 5 L 3 3 L 5 3 L 5 2 L 3 2 L 3 0 L 2 0 L 2 2 Z"/> </Border> </Border> <ControlTemplate.Triggers> <Trigger Property="IsChecked" Value="True"> <Setter Property="Data" TargetName="ExpandPath" Value="M 0 2 L 0 3 L 5 3 L 5 2 Z"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <l:LevelToIndentConverter x:Key="LevelToIndentConverter"/> <DataTemplate x:Key="CellTemplate_Name"> <DockPanel> <ToggleButton x:Name="Expander" Style="{StaticResource ExpandCollapseToggleStyle}" Margin="{Binding Level, Converter={StaticResource LevelToIndentConverter}, RelativeSource={RelativeSource AncestorType={x:Type l:TreeListViewItem}}}" IsChecked="{Binding Path=IsExpanded, RelativeSource= {RelativeSource AncestorType={x:Type l:TreeListViewItem}}}" ClickMode="Press"/> <TextBlock Text="{Binding Name}"/> </DockPanel> <DataTemplate.Triggers> <DataTrigger Binding="{Binding Path=HasItems,RelativeSource={RelativeSource AncestorType={x:Type l:TreeListViewItem}}}" Value="False"> <Setter TargetName="Expander" Property="Visibility" Value="Hidden"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> <GridViewColumnCollection x:Key="gvcc"> <GridViewColumn Header="Name" CellTemplate="{StaticResource CellTemplate_Name}" /> <GridViewColumn Header="MemberType" DisplayMemberBinding="{Binding MemberType}" /> <GridViewColumn Header="Definition" DisplayMemberBinding="{Binding Definition}" /> <GridViewColumn Header="Value" DisplayMemberBinding="{Binding Value}" /> </GridViewColumnCollection> <Style TargetType="{x:Type l:TreeListViewItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type l:TreeListViewItem}"> <StackPanel> <Border Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"> <GridViewRowPresenter x:Name="PART_Header" Content="{TemplateBinding Header}" Columns="{StaticResource gvcc}" /> </Border> <ItemsPresenter x:Name="ItemsHost" /> </StackPanel> <ControlTemplate.Triggers> <Trigger Property="IsExpanded" Value="false"> <Setter TargetName="ItemsHost" Property="Visibility" Value="Collapsed"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="HasHeader" Value="false"/> <Condition Property="Width" Value="Auto"/> </MultiTrigger.Conditions> <Setter TargetName="PART_Header" Property="MinWidth" Value="75"/> </MultiTrigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="HasHeader" Value="false"/> <Condition Property="Height" Value="Auto"/> </MultiTrigger.Conditions> <Setter TargetName="PART_Header" Property="MinHeight" Value="19"/> </MultiTrigger> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="true"/> <Condition Property="IsSelectionActive" Value="false"/> </MultiTrigger.Conditions> <Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/> </MultiTrigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="{x:Type l:TreeListView}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type l:TreeListView}"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <DockPanel> <GridViewHeaderRowPresenter Columns="{StaticResource gvcc}" DockPanel.Dock="Top"/> <ScrollViewer CanContentScroll="True"> <Grid> <ItemsPresenter/> </Grid> </ScrollViewer> </DockPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <l:TreeListView x:Name="Tlv"/> </Window> "@ $rootVariableName = dir variable:\* -Exclude InputObject,Args | Where-Object { $_.Value -and ($_.Value.GetType() -eq $InputObject.GetType()) -and ($_.Value.GetHashCode() -eq $InputObject.GetHashCode()) } ## If we got multiple, pick the first $rootVariableName = $rootVariableName| % Name | Select -First 1 ## If we didn't find one, use a default name if(-not $rootVariableName) { $rootVariableName = "InputObject" } ## A function to add an object to the display tree function PopulateNode($node, $object) { ## If we've been asked to add a NULL object, just return if(-not $object) { return } ## If the object is a collection, then we need to add multiple ## children to the node if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object)) { ## Some very rare collections don't support indexing (i.e.: $foo[0]). ## In this situation, PowerShell returns the parent object back when you ## try to access the [0] property. $isOnlyEnumerable = $object.GetHashCode() -eq $object[0].GetHashCode() ## Go through all the items $count = 0 foreach($childObjectValue in $object) { ## Create the new node to add, with the node text of the item and ## value, along with its type $newChildNode = New-Object _treeListView.TreeListViewItem #make sure the string version of it isnt more than a single line. $showValue = if(($arr="$childObjectValue" -split "\n" | ?{$_}).count -gt 1) { "$($arr[0].trim()) ..." } else { "$childObjectValue" } $newChildNode.ToolTip = "$childObjectValue" $newChildNode.Header = [pscustomobject] @{ Name=$childObjectValue.GetType().name Value="$showValue" Definition=$childObjectValue.gettype() MemberType="Collection" } ## Use the node name to keep track of the actual property name ## and syntax to access that property. ## If we can't use the index operator to access children, add ## a special tag that we'll handle specially when displaying ## the node names. if($isOnlyEnumerable) { $newChildNode.Tag = "@" } $newChildNode.Tag += "[$count]" $null = $node.Items.Add($newChildNode) ## If this node has children or properties, add a placeholder ## node underneath so that the node shows a '+' sign to be ## expanded. AddPlaceholderIfRequired $newChildNode $childObjectValue $count++ } } else { ## If the item was not a collection, then go through its ## properties $members = Get-Member -InputObject $object foreach($member in $members) { $childNode = New-Object _treeListView.TreeListViewItem $memberValue = if($member.MemberType -like "*Propert*") { $prop = $object.($member.Name) if($prop) { $prop $childnode.ToolTip = $prop if($prop.gettype().fullname | ?{($_ -split '\.').count -gt 2}) { AddPlaceholderIfRequired $childNode $prop } } else { '$null' } } elseif($member.MemberType -eq "Method") { $childNode.ToolTip = ($object.($member.name) | Out-String).trim() } $showValue = if(($arr="$memberValue" -split "\n"|?{$_}).count -gt 1) { "$($arr[0].trim()) ..." } else { "$memberValue" } $childNode.Header = [pscustomobject] @{ Name=$member.name Value=$showValue Definition=$member.Definition MemberType=$member.MemberType } $childNode.Tag = $member.Name $null = $node.Items.Add($childNode) } } } ## A function to add a placeholder if required to a node. ## If there are any properties or children for this object, make a temporary ## node with the text "..." so that the node shows a '+' sign to be ## expanded. function AddPlaceholderIfRequired($node, $object) { if(-not $object) { return } if([System.Management.Automation.LanguagePrimitives]::GetEnumerator($object) -or @($object.PSObject.Properties)) { $null = $node.Items.Add( (New-Object _treeListView.TreeListViewItem ([pscustomobject]@{Name="..."}) ) ) } } ## A function invoked when a node is selected. function OnSelect { param($Sender, $TreeViewEventArgs) ## Determine the selected node $nodeSelected = $TreeViewEventArgs.source ## Walk through its parents, creating the virtual ## PowerShell syntax to access this property. $nodePath = GetPathForNode $nodeSelected ## Now, invoke that PowerShell syntax to retrieve ## the value of the property. $resultObject = Invoke-Expression $nodePath #$outputPane.Text = $nodePath ## If we got some output, put the object's member ## information in the text box. if($resultObject) { $members = Get-Member -InputObject $resultObject | Out-String #$outputPane.Text += "`n" + $members } } ## A function invoked when the user is about to expand a node function OnExpand { param($Sender, $TreeViewCancelEventArgs) ## Determine the selected node $selectedNode = $TreeViewCancelEventArgs.Source ## If it has a child node that is the placeholder, clear ## the placeholder node. if($selectedNode.items.Count -eq 1 -and ($selectedNode.Items[0].Header.Name-eq "...")) { $selectedNode.items.Clear() } else { return } ## Walk through its parents, creating the virtual ## PowerShell syntax to access this property. $nodePath = GetPathForNode $selectedNode $global:nodepath= $nodePath ## Now, invoke that PowerShell syntax to retrieve ## the value of the property. Invoke-Expression "`$resultObject = $nodePath" ## And populate the node with the result object. PopulateNode $selectedNode $resultObject } ## A function to handle keypresses on the form. ## In this case, we capture ^C to copy the path of ## the object property that we're currently viewing. function OnKeyPress { param($Sender, $KeyPressEventArgs) ## [Char] 3 = Control-C if($KeyPressEventArgs.KeyChar -eq 3) { $KeyPressEventArgs.Handled = $true ## Get the object path, and set it on the clipboard $node = $Sender.SelectedNode $nodePath = GetPathForNode $node [System.Windows.Forms.Clipboard]::SetText($nodePath) $form.Close() } } ## A function to walk through the parents of a node, ## creating virtual PowerShell syntax to access this property. function GetPathForNode { param($Node) $nodeElements = @() ## Go through all the parents, adding them so that ## $nodeElements is in order. while($Node.Tag) { $nodeElements = ,$Node + $nodeElements $Node = $Node.Parent } ## Now go through the node elements $nodePath = "" foreach($Node in $nodeElements) { $nodeName = $Node.Tag ## If it was a node that PowerShell is able to enumerate ## (but not index), wrap it in the array cast operator. if($nodeName.StartsWith('@')) { $nodeName = $nodeName.Substring(1) $nodePath = "@(" + $nodePath + ")" } elseif($nodeName.StartsWith('[')) { ## If it's a child index, we don't need to ## add the dot for property access } elseif($nodePath) { ## Otherwise, we're accessing a property. Add a dot. $nodePath += "." } ## Append the node name to the path $nodePath += $nodeName } ## And return the result $nodePath } ## Create the TreeView, which will hold our object navigation ## area. $reader=(New-Object System.Xml.XmlNodeReader $xaml) $Form=[Windows.Markup.XamlReader]::Load( $reader ) $tlv = $Form.FindName('Tlv') [System.Windows.RoutedEventHandler]$Script:Select = { OnSelect @args } [System.Windows.RoutedEventHandler]$Script:Expand = { OnExpand @args } [System.Windows.RoutedEventHandler]$Script:KeyPress = { OnKeyPress @args } $tlv.AddHandler([_treeListView.TreeListViewItem]::SelectedEvent, $Script:Select) $tlv.AddHandler([_treeListView.TreeListViewItem]::ExpandedEvent, $Script:Expand) $tlv.AddHandler([_treeListView.TreeListViewItem]::KeyUpEvent, $Script:KeyPress) ## Create the root node, which represents the object ## we are trying to show. $root = New-Object _treeListView.TreeListViewItem ([pscustomobject]@{ Name=$InputObject.gettype().name Value="$InputObject" Definition=$InputObject.gettype().fullname}) #root.Header = "$InputObject : " + $InputObject.GetType() $root.Tag = '$' + $rootVariableName $root.ToolTip = "$InputObject" $root.IsExpanded = $true ## And populate the initial information into the tree ## view. PopulateNode $root $InputObject $null = $tlv.Items.Add($root) $null = $Form.ShowDialog() }
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/src/public/Out-Default-Capture.ps1
Out-Default-Capture.ps1
function Out-Default { <# .SYNOPSIS Spelunking with Show-Object .DESCRIPTION Spelunk [spi-luhngk], verb. To explore caves, especially as a hobby. We must first recall that PowerShell pipelines are very different from, say, Linux pipelines. Rather than consisting of text, PowerShell objects are "three-dimensional" data structures that consist of properties (descriptive attributes), methods (actions the object can undertake), and events (actions that can be undertaken on the object). Collectively, these data elements are called object members. For instance, take Get-Service. Unless you perform filtering, you receive an object collection as output. You probably know that Get-Member shows us the object's .NET Framework type name and its properties, methods, and events. Here's partial output from my Windows 8.1 administrative workstation running Windows Management Framework 5.0 Production Preview: PS C:\> Get-Service | Get-Member TypeName: System.ServiceProcess.ServiceController Name MemberType Definition —- ———- ———- Name AliasProperty Name = ServiceName RequiredServices AliasProperty RequiredServices… Disposed Event System.EventHandler… Close Method void Close() Continue Method void Continue() PowerShell objects are instances of underlying .NET classes, and by default those classes are self-discovering through a process known as reflection. If you want to see everything about the previous ServiceController objects, pipe the Get-Member output to Format-List like so: Get-Service | Get-Member | Format-List * What I've told you means that, practically speaking, we do an awful lot of get-membering and format-listing when we need to look up specific property, method, or event values. Is there (banish the thought!) an easier-on-the-eyes graphical solution? .EXAMPLE First we can locate the appropriate module: Find-Module -Name *cookbook* Cool. So Lee's module is named PowerShellCookbook, and it is stored on the PowerShell Gallery repository. Let's install it! Install-Module -Name PowerShellCookbook -Force As it happens, Show-Object is only one function among many that are contained in the PowerShellCookbook module. Run the following command to see them all: Get-Command -Module PowerShellCookbook Using the Show-Object Function To use Show-Object, simply pipe your desired PowerShell object into the function like so: Get-Service -Name Spooler | Show-Object Take a look at the following Show-Object output, and I'll walk you through it. The bottom pane (sadly unresizable) shows your ordinary Get-Member output. The upper pane allows you to quickly parse the object properties. For instance, we can expand each RequiredServices node to learn that the Print Spooler service in Windows 8.1 depends on a Remote Procedure Call (RPC) and HTTP services. If you're of the mind to do so, you can inspect the Show-Object source code by visiting the book's website (see Program: Interactively View and Explore Objects) or by using PowerShell directly in your console: (Get-Command -name Show-Object).Definition | Out-File 'C:\show-object-source.txt' | Notepad 'C:\show-object-source.txt' Going further One of the many things I love about the Windows PowerShell community is how friendly and helpful most people are. I don't want to draw comparisons to, say, the *NIX open-source community, but…well, let's just leave that alone. That's all there is to it! .FUNCTIONALITY General Command #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [psobject] $InputObject ) begin { $global:lastOutputCollection = New-Object Collections.ArrayList try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Out-Default', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($true) } catch { throw } $invocation = Get-PSCallStack } process { try { $willProcess = $true if ($_ -is [Management.Automation.ErrorRecord]) { $e = $_ $i = $invocation <# $cs = Get-PSCallStack $lastAction = Get-History -Count 1 if ($lastAction.CommandLine -like "*http*") { if ($lastAction.CommandLine -like "`$*=*http*") { $maybeUrl = $lastAction.CommandLine.Substring($lastAction.CommandLine.IndexOf("=") + 1).Trim() $variableName = $lastAction.CommandLine.Substring(0, $lastAction.CommandLine.IndexOf("=") - 1).TrimStart('$') if ($maybeUrl -like "http*") { Set-Variable -Name $variableName -Value ( Get-Web -UseWebRequest $maybeUrl ) -Option AllScope } } else { Start-Process -FilePath $lastAction.CommandLine } } $null = $null #> } $steppablePipeline.Process($_) $null = $global:lastOutputCollection.Add($_) $global:lastOutputItem = $_ } catch { throw } } end { if ($global:lastOutputCollection.Count) { $global:LastOutput = $global:lastOutputCollection } try { $steppablePipeline.End() } catch { throw } } }
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/templates/Install.ps1
Install.ps1
# Run this in an administrative PowerShell prompt to install the {{ModuleName}} PowerShell module: # # iex (New-Object Net.WebClient).DownloadString("{{ModuleWebsite}}/raw/master/Install.ps1") # Some general variables $ModuleName = '{{ModuleName}}' $DownloadURL = '{{ModuleWebsite}}/raw/master/release/{{ModuleName}}-current.zip' # Download and install the module $webclient = New-Object System.Net.WebClient $file = "$($env:TEMP)\$($ModuleName).zip" Write-Host "Downloading latest version of $ModuleName from $DownloadURL" -ForegroundColor Cyan $webclient.DownloadFile($DownloadURL,$file) Write-Host "File saved to $file" -ForegroundColor Green $targetondisk = "$($env:USERPROFILE)\Documents\WindowsPowerShell\Modules\$($ModuleName)" $null = New-Item -ItemType Directory -Force -Path $targetondisk $shell_app=new-object -com shell.application $zip_file = $shell_app.namespace($file) Write-Host "Uncompressing the Zip file to $($targetondisk)" -ForegroundColor Cyan $destination = $shell_app.namespace($targetondisk) $destination.Copyhere($zip_file.items(), 0x10) Write-Host "Module has been installed!" -ForegroundColor Green Write-Host "You can now import the module with: Import-Module -Name $ModuleName"
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/templates/Build.ps1
Build.ps1
#Requires -Version 5 [CmdletBinding(DefaultParameterSetName='Build')] param ( [parameter(Position=0, ParameterSetName='Build')] [switch]$BuildModule, [parameter(Position=1, ParameterSetName='Build')] [switch]$CreatePSGalleryProfile, [parameter(Position=2, ParameterSetName='Build')] [switch]$UpdateRelease, [parameter(Position=3, ParameterSetName='Build')] [switch]$UploadPSGallery, [parameter(Position=4, ParameterSetName='Build')] [switch]$GitCheckin, [parameter(Position=5, ParameterSetName='Build')] [switch]$GitPush, [parameter(Position=6, ParameterSetName='Build')] [switch]$InstallAndTestModule, [parameter(Position=7, ParameterSetName='Build')] [version]$NewVersion, [parameter(Position=8, ParameterSetName='Build')] [string]$ReleaseNotes, [parameter(Position=0, ParameterSetName='CBH')] [switch]$InsertCBH, [parameter(Position=0, ParameterSetName='Help')] [switch]$Help ) $HelpContents = @' This is a wrapper script for invoke-build and a set of build tasks in the included .build.ps1 file. As this is a wrapper script almost all parameters are simple switches. This help output will cover what each of these switches will accomplish. Help - This help output. InsertCBH - So far there is the only helper task that doesn't really do anything as part of a build process. When you run with this switch all the function scripts in .\src\public will be inspected for comment based help (CBH) within its function scriptblock. If one is not readily found then a template CBH will be added in a copy of the script which will be saved in the scratch directory (usually located in .\temp\src\public). This switch is stand-alone and will not work with other switches in this script. Use one or more of the following switches with this script to kick off some of the most common build tasks for your module project. All of the following switches can be stringed together. They are listed in the order they would be processed in were they all to be used at once. CreatePSGalleryProfile - Create an initial PSGallery profile for your project. This will only be useful if you have an API key for the site stored in "$(split-path $PROFILE)\psgalleryapi.txt" and plan on releasing the module to the powershell gallery. UpdateRelease - If you have manually updated the version.txt file then this will trigger the build scripts to begin building and releasing the new version. It updates the module manifest file as well. You can use this in conjunction with the -NewVersion parameter to update the version.txt file as well. NewVersion - Can be used with the -UpdateRelease parameter to start a new version of the module for release. BuildModule - This is the default action if no parameters are passed to this script. This kicks off the build process as defined by the .\build\.buildenvironment.ps1 configuration script. If all goes well a completed and fully packaged build of your project will be created in the following locations: .\release\<version> - Every new version you release will be kept in its own directory .\release\<modulename>-<version>.zip - Every version will have an assoicated zip created .\release\<modulename> - The current release will always be in a folder with the module name .\release\<modulename>.zip - The current release in zip format for easy automated installation InstallAndTestModule - Attempt to install a finished build of the module from .\release\<modulename>. After installing the module we then attempt to load it to ensure it works. UploadPSGallery - Upload a release to the PSGallery for others to install with install-module (PowerShell 5+ only). Every uploaded release requires release notes which can be passed via the -ReleaseNotes parameter. This will also fail outright if you don't have appropriate LicenseURI and IconURI entries uncommented and set in your <modulename>.psd1 manifest file. ReleaseNotes - Used in conjunction with the -UploadPSGallery parameter. GitCheckin - Not finished with this yet, sorry. GitPush - Not finished with this yet, sorry. '@ function PrerequisitesLoaded { # Install InvokeBuild module if it doesn't already exist try { if ((get-module InvokeBuild -ListAvailable) -eq $null) { Write-Host "Attempting to install the InvokeBuild module..." $null = Install-Module InvokeBuild } if (get-module InvokeBuild -ListAvailable) { Write-Host -NoNewLine "Importing InvokeBuild module" Import-Module InvokeBuild -Force Write-Host -ForegroundColor Green '...Loaded!' return $true } else { return $false } } catch { return $false } } function CleanUp { try { Write-Output '' Write-Output 'Attempting to clean up the session (loaded modules and such)...' Invoke-Build BuildSessionCleanup Remove-Module InvokeBuild } catch {} } switch ($psCmdlet.ParameterSetName) { 'Help' { Write-Output $HelpContents } 'CBH' { if (-not (PrerequisitesLoaded)) { throw 'Unable to load InvokeBuild!' } if ($InsertCBH) { try { Invoke-Build InsertMissingCBH } catch { throw } } CleanUp } 'Build' { if (-not (PrerequisitesLoaded)) { throw 'Unable to load InvokeBuild!' } # Create a gallery profile? if ($CreatePSGalleryProfile) { try { Invoke-Build NewPSGalleryProfile } catch { throw 'Unable to create the .psgallery profile file!' } } # Update your release version? if ($UpdateRelease) { if ($NewVersion -ne $null) { $NewVersion.ToString() | Out-File -FilePath .\version.txt -Force } try { Invoke-Build UpdateVersion } catch { throw } } # If no parameters were specified or the build action was manually specified then kick off a standard build if (($psboundparameters.count -eq 0) -or ($BuildModule)) { try { Invoke-Build } catch { Write-Output 'Build Failed with the following error:' Write-Output $_ } } # Install and test the module? if ($InstallAndTestModule) { try { Invoke-Build InstallAndTestModule } catch { Write-Output 'Install and test of module failed:' Write-Output $_ } } # Upload to gallery? if ($UploadPSGallery) { if ([string]::IsNullOrEmpty($ReleaseNotes)) { throw '$ReleaseNotes needs to be specified to run this operation!' } try { Invoke-Build PublishPSGallery -ReleaseNotes $ReleaseNotes } catch { throw 'Unable to upload projec to the PowerShell Gallery!' } } # Not implemented yet if ($GitCheckin) { # Finish me } # Not implemented yet if ($GitPush) { # Finish me } CleanUp } }
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/New-PSGalleryProjectProfile.ps1
New-PSGalleryProjectProfile.ps1
#Requires -version 5 function Script:New-PSGalleryProjectProfile { <# .SYNOPSIS Create a powershell Gallery module upload profile .DESCRIPTION Create a powershell Gallery module upload profile. Some items (like Name) are inferred from the module manifest and are left out. .PARAMETER Path Path of module project files to upload. .PARAMETER ProjectUri Module project website. .PARAMETER Tags Tags used to search for the module (separated by commas) .PARAMETER Repository Destination gallery (default is PSGallery) .PARAMETER ReleaseNotes Release notes. .PARAMETER LicenseUri License website. .PARAMETER IconUri Icon web path. .PARAMETER NuGetApiKey API key for the powershellgallery.com site. .PARAMETER OutputFile OutputFile (default is .psgallery) .EXAMPLE .NOTES Author: Zachary Loeber Site: http://www.the-little-things.net/ Version History 1.0.0 - Initial release #> [CmdletBinding()] param( [parameter(Position=0, Mandatory=$true, HelpMessage='Path of module project files to upload.')] [string]$Path, [parameter(Position=1, HelpMessage='Module project website.')] [string]$ProjectUri = '', [parameter(Position=2, HelpMessage='Tags used to search for the module (separated by commas)')] [string]$Tags = '', [parameter(Position=3, HelpMessage='Destination gallery (default is PSGallery)')] [string]$Repository = 'PSGallery', [parameter(Position=4, HelpMessage='Release notes.')] [string]$ReleaseNotes = '', [parameter(Position=5, HelpMessage=' License website.')] [string]$LicenseUri = '', [parameter(Position=6, HelpMessage='Icon web path.')] [string]$IconUri = '', [parameter(Position=7, HelpMessage='NugetAPI key for the powershellgallery.com site.')] [string]$NuGetApiKey = '', [parameter(Position=8, HelpMessage='OutputFile (default is .psgallery)')] [string]$OutputFile = '.psgallery' ) $PublishParams = @{ Path = $Path NuGetApiKey = $NuGetApiKey ProjectUri = $ProjectUri Tags = $Tags Repository = $Repository ReleaseNotes = $ReleaseNotes LicenseUri = $LicenseUri IconUri = $IconUri } if (Test-Path $OutputFile) { $PublishParams | Export-Clixml -Path $OutputFile -confirm } else { $PublishParams | Export-Clixml -Path $OutputFile } }
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Out-Zip.ps1
Out-Zip.ps1
function Script:Out-Zip { param ( [Parameter(Position=0, Mandatory=$true)] [string] $Directory, [Parameter(Position=1, Mandatory=$true)] [string] $FileName, [Parameter(Position=2)] [switch] $overwrite ) Add-Type -Assembly System.IO.Compression.FileSystem $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal if (-not $FileName.EndsWith('.zip')) {$FileName += '.zip'} if ($overwrite) { if (Test-Path $FileName) { Remove-Item $FileName } } [System.IO.Compression.ZipFile]::CreateFromDirectory($Directory, $FileName, $compressionLevel, $false) }
PowerShellCorpus/PowerShellGallery/PSObjectInspector/0.0.1/build/dotSource/Upload-ProjectToPSGallery.ps1
Upload-ProjectToPSGallery.ps1
#Requires -version 5 function Script:Upload-ProjectToPSGallery { <# .SYNOPSIS Upload module project to Powershell Gallery .DESCRIPTION Upload module project to Powershell Gallery .PARAMETER ModulePath Path to module to upload. .PARAMETER APIKey API key for the powershellgallery.com site. .PARAMETER Tags Tags for your module .PARAMETER ProjectURI Project site (like github). .EXAMPLE .\Upload-ProjectToPSGallery.ps1 .NOTES Author: Zachary Loeber Site: http://www.the-little-things.net/ Requires: Powershell 5.0 Version History 1.0.0 - Initial release #> [CmdletBinding(DefaultParameterSetName='PSGalleryProfile')] param( [parameter(Mandatory=$true, HelpMessage='Module short name.', ParameterSetName='ManualInput')] [string]$Name, [parameter(Mandatory=$true, HelpMessage='Path of module project files to upload.', ParameterSetName='ManualInput')] [string]$Path, [parameter(HelpMessage='Module project website.', ParameterSetName='ManualInput')] [string]$ProjectUri, [parameter(HelpMessage='Tags used to search for the module (separated by spaces)', ParameterSetName='ManualInput')] [string]$Tags, [parameter(HelpMessage='Required powershell version (default is 2)', ParameterSetName='ManualInput')] [string]$RequiredVersion, [parameter(HelpMessage='Destination gallery (default is PSGallery)', ParameterSetName='ManualInput')] [string]$Repository = 'PSGallery', [parameter(HelpMessage='Release notes.', ParameterSetName='ManualInput')] [string]$ReleaseNotes, [parameter(HelpMessage=' License website.', ParameterSetName='ManualInput')] [string]$LicenseUri, [parameter(HelpMessage='Icon web path.', ParameterSetName='ManualInput')] [string]$IconUri, [parameter(Mandatory = $true, HelpMessage='API key for the powershellgallery.com site.', ParameterSetName='ManualInput')] [parameter(HelpMessage='API key for the powershellgallery.com site.', ParameterSetName='PSGalleryProfile')] [string]$NuGetApiKey, [parameter(HelpMessage='Path to CliXML file containing your psgallery project information.', ParameterSetName='PSGalleryProfile')] [string]$PSGalleryProfilePath = '.psgallery' ) Write-Verbose "Using parameterset $($PSCmdlet.ParameterSetName)" if ($PSCmdlet.ParameterSetName -eq 'PSGalleryProfile') { if (Test-Path $PSGalleryProfilePath) { Write-Verbose "Loading PSGallery profile information from $PSGalleryProfilePath" $PublishParams = Import-Clixml $PSGalleryProfilePath } else { Write-Error "$PSGalleryProfilePath not found" return } } else { $MyParams = $PSCmdlet.MyInvocation.BoundParameters $MyParams.Keys | ForEach { Write-Verbose "Adding manually defined parameter $($_)" $PublishParams.$_ = $MyParams[$_] } } # if no API key is defined then look for psgalleryapi.txt in the local profile directory and try to use it instead. if ([string]::IsNullOrEmpty($PublishParams.NuGetApiKey)) { $psgalleryapipath = "$(Split-Path $Profile)\psgalleryapi.txt" Write-Verbose "No PSGallery API key specified. Attempting to load one from the following location: $($psgalleryapipath)" if (-not (test-path $psgalleryapipath)) { Write-Error "$psgalleryapipath wasn't found and there was no defined API key, please rerun script with a defined APIKey parameter." return } else { $PublishParams.NuGetApiKey = get-content -raw $psgalleryapipath } } $PublishParams.Tags = $PublishParams.Tags -split ',' # If we made it this far then try to publish the module wth our loaded parameters Publish-Module @PublishParams }