full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/PoshRegistry/0.0.2/Public/Remove-RegValue.ps1
Remove-RegValue.ps1
function Remove-RegValue { <# .SYNOPSIS Deletes the specified registry value from local or remote computers. .DESCRIPTION Use Remove-RegValue to delete the specified registry value from local or remote computers. .PARAMETER ComputerName An array of computer names. The default is the local computer. .PARAMETER Hive The HKEY to open, from the RegistryHive enumeration. The default is 'LocalMachine'. Possible values: - ClassesRoot - CurrentUser - LocalMachine - Users - PerformanceData - CurrentConfig - DynData .PARAMETER Key The path of the registry key to open. .PARAMETER Value The name of the registry value to delete. .PARAMETER Force Overrides any confirmations made by the command. Even using the Force parameter, the function cannot override security restrictions. .PARAMETER Ping Use ping to test if the machine is available before connecting to it. If the machine is not responding to the test a warning message is output. .EXAMPLE $Key = "SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer" Test-RegValue -Key $Key -Value NoDriveTypeAutorun -ComputerName SERVER1,SERVER2 -PassThru | Remove-RegValue -Force Description ----------- The command checks if the NoDriveTypeAutorun key value on SERVER1 and SERVER2. When using the PassThru parameter, each value, if found, it emitted to the pipeline. Each value found that is piped into Remove-RegValue is deleted without any confirmations. .NOTES Author: Shay Levy Blog : http://blogs.microsoft.co.il/blogs/ScriptFanatic/ .LINK http://code.msdn.microsoft.com/PSRemoteRegistry .LINK Get-RegValue Test-RegValue #> [CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='High',DefaultParameterSetName="__AllParameterSets")] param( [Parameter( Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="An array of computer names. The default is the local computer." )] [Alias("CN","__SERVER","IPAddress")] [string[]]$ComputerName="", [Parameter( Position=1, ValueFromPipelineByPropertyName=$true, HelpMessage="The HKEY to open, from the RegistryHive enumeration. The default is 'LocalMachine'." )] [ValidateSet("ClassesRoot","CurrentUser","LocalMachine","Users","PerformanceData","CurrentConfig","DynData")] [string]$Hive="LocalMachine", [Parameter( Mandatory=$true, Position=2, ValueFromPipelineByPropertyName=$true, HelpMessage="The path of the subkey to open." )] [string]$Key, [Parameter( Mandatory=$true, Position=3, ValueFromPipelineByPropertyName=$true, HelpMessage="The name of the value to remove." )] [string]$Value, [switch]$Force, [switch]$Ping ) process { Write-Verbose "Enter process block..." foreach($c in $ComputerName) { try { if($c -eq "") { $c=$env:COMPUTERNAME Write-Verbose "Parameter [ComputerName] is not presnet, setting its value to local computer name: [$c]." } if($Ping) { Write-Verbose "Parameter [Ping] is presnet, initiating Ping test" if( !(Test-Connection -ComputerName $c -Count 1 -Quiet)) { Write-Warning "[$c] doesn't respond to ping." return } } Write-Verbose "Starting remote registry connection against: [$c]." Write-Verbose "Registry Hive is: [$Hive]." $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]$Hive,$c) Write-Verbose "Open remote subkey: [$Key] with write access." $subKey = $reg.OpenSubKey($Key,$true) if(!$subKey) { Throw "Key '$Key' doesn't exist." } if($Force -or $PSCmdlet.ShouldProcess($c,"Remove Registry Value '$Hive\$Key\$Value'")) { Write-Verbose "Parameter [Force] or [Confirm:`$False] is presnet, suppressing confirmations." Write-Verbose "Setting value name: [$Value]" $subKey.DeleteValue($Value,$true) } Write-Verbose "Closing remote registry connection on: [$c]." $reg.close() } catch { Write-Error $_ } } Write-Verbose "Exit process block..." } }
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/_Context.ps1
_Context.ps1
$Script:SourceRoot = Join-Path $PSScriptRoot Templates
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/New-ForgeModuleFunction.ps1
New-ForgeModuleFunction.ps1
<# Copyright 2016 Dominique Broeglin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> function New-ForgeModuleFunction { <# .SYNOPSIS Creates a new function in a module. .DESCRIPTION Creates a new skeleton module function based on the arguments passed to the function. .EXAMPLE New-ForgeModuleFunction -Name MyFunction .PARAMETER Name The name of the new function. .PARAMETER Path The path where the function should be generated. .PARAMETER ModuleName The name of the module in which the function is generated if it is not the same as the parent directory name. .PARAMETER Parameter An array of parameter names to generate for the new function. .PARAMETER Export If $True the function will be added to the list of exported functions in the PSD1 file. Default: $True #> [CmdletBinding(ConfirmImpact='Low')] Param( [Parameter(Mandatory = $true)] [String]$Name, [String]$Path = "./", [String]$ModuleName, [String[]]$Parameter = @(), [switch]$NoExport ) Begin { Initialize-ForgeContext -SourceRoot $Script:SourceRoot ` -DestinationPath $Path if (-not $ModuleName) { $ModuleName = Split-Path -Leaf (Get-Location) } } Process { if (Test-Path -PathType Container src) { $SourceDir = "src" } elseif (Test-Path -PathType Container $ModuleName) { $SourceDir = $ModuleName } else { throw "Could'nt find either 'src' or '$ModuleName' directory" } if (-not (Test-Path -PathType Container 'Tests')) { throw "Test directory 'Tests' does not exist" } $PsdPath = Join-Path (Get-ForgeContext).DestinationPath (Join-Path $SourceDir "$ModuleName.psd1") if (!$NoExport -and -not (Test-Path -PathType Leaf $PsdPath)) { throw "PSD file '$PsdPath' does not exist" } Set-ForgeBinding @{ Name = $Name ModuleName = $ModuleName Parameters = $Parameter } $FunctionFilename = "$Name.ps1" $TestsFilename = "$Name.Tests.ps1" Copy-ForgeFile -Source "Function.ps1" -Dest (Join-Path $SourceDir $FunctionFilename) Copy-ForgeFile -Source "Function.Tests.ps1" -Dest (Join-Path Tests $TestsFilename) if (!$NoExport) { Update-ModuleManifest -Path $PsdPath -FunctionsToExport $( $FunctionsToExport = (Import-PowerShellDataFile $PsdPath)["FunctionsToExport"] if (($Null -eq $FunctionsToExport) -or ("*" -eq $FunctionsToExport)) { $FunctionsToExport = @() } elseif ($FunctionsToExport -is [String]) { $FunctionsToExport = @($FunctionsToExport) } $FunctionsToExport + $Name ) } } }
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/New-ForgeModule.ps1
New-ForgeModule.ps1
<# Copyright 2016 Dominique Broeglin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> function New-ForgeModule { <# .SYNOPSIS Generates a new module. .DESCRIPTION Generates a new skeleton module based on the arguments passed to the function. .EXAMPLE New-ForgeModule -Name MyModule .PARAMETER Name The name of the new module. .PARAMETER Path The path where the new module is created. .PARAMETER Description Description of the generated module. .PARAMETER License License to add to the generated module. Allowed values are: - Apache : Apache License - MIT : MIT License .PARAMETER Author Name to use as module author. .PARAMETER Email Email to use for the generated module. .PARAMETER Git Optional, if set add a default .gitignore file to the generated module. .PARAMETER Editor Optional, editor configuration to setup inside the generated module. Allowed values are: - VSCode : Visual Studio Code .PARAMETER Build Optional, if set add build support to the module. Allowed values are: - PSake : Add PSake build support to the module. - TODO: InvokeBuild : Add InvokeBuild support to the module. #> [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact='Low')] Param( [Parameter(Mandatory = $true)] [String]$Name, [String]$Path = $Name, [String]$Description = "$Name module", [ValidateSet('', 'Apache', 'MIT')] [String]$License, [String]$Author, [String]$Email, [Switch]$Git, [ValidateSet('', 'VSCode')] [String]$Editor, [ValidateSet('', 'PSake', 'InvokeBuild')] [String]$Build, [ValidateSet('Src', 'ModuleName')] [String]$Layout = 'Src' ) Begin { Initialize-ForgeContext -SourceRoot $Script:SourceRoot ` -DestinationPath $Path } Process { if (!$PSCmdlet.ShouldProcess($Name, "Create module")) { return } $Author = Get-ValueOrGitOrDefault $Author "user.user" "John Doe" $Email = Get-ValueOrGitOrDefault $Email "user.email" "JohnDoe@example.com" $CopyrightYear = Get-Date -UFormat %Y switch ($Layout) { "Src" { $ModuleDir = "src"} "ModuleName" { $ModuleDir = $Name} } Set-ForgeBinding @{ Name = $Name Description = $Description Author = $Author Email = $Email CopyrightYear = $CopyrightYear } New-ForgeDirectory Copy-ForgeFile -Source "README.md" New-ForgeDirectory -Dest $ModuleDir Copy-ForgeFile -Source "Module.psm1" -Dest "$ModuleDir\$Name.psm1" New-ModuleManifest -Path "$Path\$ModuleDir\$Name.psd1" -RootModule "$Name.psm1" ` -ModuleVersion "0.1.0" -Description $Description -Author $Author ` -Copyright "(c) $CopyrightYear $Author. All rights reserved." New-ForgeDirectory -Dest "Tests" Copy-ForgeFile -Source "Manifest.Tests.ps1" -Dest "Tests" New-ForgeDirectory -Dest "$ModuleDir/en-US" Copy-ForgeFile -Source "docs/en-US/about_Module_help.txt" -Dest "$ModuleDir/en-US/about_$($Name).help.txt" if ($License) { Copy-ForgeFile -Source "LICENSE.txt.$License" -Dest "LICENSE.txt" } if ($Git) { Copy-ForgeFile -Source "DotGitIgnore" -Dest ".gitignore" } switch ($Build) { "PSake" { Copy-ForgeFile -Source "Build.PSake\build.ps1" -Dest "build.ps1" Copy-ForgeFile -Source "Build.PSake\build.psake.ps1" -Dest "build.psake.ps1" Copy-ForgeFile -Source "Build.PSake\build.settings.ps1" -Dest "build.settings.ps1" Copy-ForgeFile -Source "ScriptAnalyzerSettings.psd1" } "InvokeBuild" { Copy-ForgeFile -Source "Build.InvokeBuild\build.ps1" -Dest "build.ps1" Copy-ForgeFile -Source "Build.InvokeBuild\.build.ps1" -Dest ".build.ps1" Copy-ForgeFile -Source "Build.InvokeBuild\build.settings.ps1" -Dest "build.settings.ps1" Copy-ForgeFile -Source "ScriptAnalyzerSettings.psd1" } } switch ($Editor) { "VSCode" { New-ForgeDirectory -Dest .vscode Copy-ForgeFile -Source "VSCode.settings.json" -Dest ".vscode\settings.json" Copy-ForgeFile -Source "VSCode.tasks.json" -Dest ".vscode\tasks.json" Copy-ForgeFile -Source "ScriptAnalyzerSettings.psd1" } } } }
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/Templates/Build.InvokeBuild/build.settings.ps1
build.settings.ps1
############################################################################### # Customize these properties and tasks for your module. ############################################################################### # ----------------------- Basic properties -------------------------------- # The name of your module should match the basename of the PSD1 file. $ModuleName = "<%= $Name %>" # The root directories for the module's docs, src and test. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $DocsRootDir = "$PSScriptRoot/docs" $SrcRootDir = "$PSScriptRoot/$ModuleName" [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $TestRootDir = "$PSScriptRoot/Tests" # The $OutDir must match the ModuleName in order to support publishing the module. $ReleaseDir = "$PSScriptRoot/Release" [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $OutDir = "$ReleaseDir/$ModuleName" # Default Locale used for documentation generatioon, defaults to en-US. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $DefaultLocale = $null # Items in the $Exclude array will not be copied to the $OutDir e.g. $Exclude = @('.gitattributes') # Typically you wouldn't put any file under the src dir unless the file was going to ship with # the module. However, if there are such files, add their $SrcRootDir relative paths to the exclude list. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $Exclude = @() # -------------------- Script analysis properties ------------------------------ # To control the failure of the build with specific script analyzer rule severities, # the CodeAnalysisStop variable can be used. The supported values for this variable are # 'Warning', 'Error', 'All', 'None' or 'ReportOnly'. Invalid input will stop on all rules. # 'None' will skip over the code analysis step all together. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ScriptAnalysisAction = 'None' # Path to PowerShell Script Analyzer settings file. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ScriptAnalysisSettingsPath = "$PSScriptRoot\ScriptAnalyzerSettings.psd1" # The script analysis task step will run, unless your host is in the array defined below. # This allows you to control whether code analysis is executed, for hosts where script # analysis is included in the product. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $SkipScriptAnalysisHost = @( 'Visual Studio Code Host', 'My Custom Host with scriptanalyzer support' ) # ------------------- Testing properties ---------------------------------- # To control the build with code coverage, the $CodeCoverageStop variable can be used. # The supported values for this variable are $true, $false and $null. $true enables # code coverage, with the $CodeCoveragePercentage variable to reach (info below). # $false disables code coverage entirely, while $null enables code coverage, but will # only report on coverage status and not stop the build. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CodeCoverageStop = $false # You can specify a minimum code coverage percentage that must be reached in order # for the test task to pass. The code coverage test is not performed if # $CodeCoveragePercentage is 0. If $CodeCoveragePercentage is non-zero, but is not # reached, the build script will fail. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CodeCoveragePercentage = 60 # CodeCoverageFiles specifies the files to perform code coverage analysis on. This property # acts as a direct input to the Pester -CodeCoverage parameter, so will support constructions # like the ones found here: https://github.com/pester/Pester/wiki/Code-Coverage. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CodeCoverageSelection = "$SrcRootDir\*.ps1", "$SrcRootDir\*.psm1" # ------------------- Script signing properties --------------------------- # Set to $true if you want to sign your scripts. You will need to have a code-signing certificate. # You can specify the certificate's subject name below. If not specified, you will be prompted to # provide either a subject name or path to a PFX file. After this one time prompt, the value will # saved for future use and you will no longer be prompted. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $SignScripts = $false # Specify the Subject Name of the certificate used to sign your scripts. Leave it as $null and the # first time you build, you will be prompted to enter your code-signing certificate's Subject Name. # This variable is used only if $SignScripts is set to $true. # # This does require the code-signing certificate to be installed to your certificate store. If you # have a code-signing certificate in a PFX file, install the certificate to your certificate store # with the command below. You may be prompted for the certificate's password. # # Import-PfxCertificate -FilePath .\myCodeSigingCert.pfx -CertStoreLocation Cert:\CurrentUser\My # [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CertSubjectName = $null # Certificate store path. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CertPath = "Cert:\" # -------------------- Publishing properties ------------------------------ # Your NuGet API key for the PSGallery. Leave it as $null and the first time you publish, # you will be prompted to enter your API key. The build will store the key encrypted in the # settings file, so that on subsequent publishes you will no longer be prompted for the API key. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $NuGetApiKey = $null # Name of the repository you wish to publish to. If $null is specified the default repo (PowerShellGallery) is used. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $PublishRepository = $null # Path to the release notes file. Set to $null if the release notes reside in the manifest file. # The contents of this file are used during publishing for the ReleaseNotes parameter. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ReleaseNotesPath = "$PSScriptRoot\ReleaseNotes.md" # ----------------------- Misc properties --------------------------------- # In addition, PFX certificates are supported in an interactive scenario only, # as a way to import a certificate into the user personal store for later use. # This can be provided using the CertPfxPath parameter. PFX passwords will not be stored. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $SettingsPath = "$env:LOCALAPPDATA\Plaster\NewModuleTemplate\SecuredBuildSettings.clixml" # The local installation directory for the install task. Defaults to your user PSModulePath. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $InstallPath = $null # Specifies an output file path to send to Invoke-Pester's -OutputFile parameter. # This is typically used to write out test results so that they can be sent to a CI # system like AppVeyor. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $TestOutputFile = $null # Specifies the test output format to use when the TestOutputFile property is given # a path. This parameter is passed through to Invoke-Pester's -OutputFormat parameter. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $TestOutputFormat = "NUnitXml" <############################################################################## Add tasks for performing operations before and/or after Plaster tasks. Plaster tasks: Clean, Build, Sign, BuildHelp, Install, Test, Publish. Examples of added tasks: # Synopsis: The task invoked after Build. Task PostBuild -After Build { ... } # Synopsis: The task invoked before Install. Task PreInstall -Before Install { ... } ##############################################################################>
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/Templates/Build.InvokeBuild/build.ps1
build.ps1
#Requires -Modules InvokeBuild Import-Module InvokeBuild # Builds the module by invoking Invoke-Build on the .build.ps1 script. Invoke-Build -File $PSScriptRoot\.build.ps1 -Task Build
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/Templates/Build.PSake/build.settings.ps1
build.settings.ps1
############################################################################### # Customize these properties and tasks for your module. ############################################################################### Properties { # ----------------------- Basic properties -------------------------------- # The name of your module should match the basename of the PSD1 file. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ModuleName = "<%= $Name %>" # The root directories for the module's docs, src and test. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $DocsRootDir = "$PSScriptRoot\docs" $SrcRootDir = "$PSScriptRoot\$ModuleName" [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $TestRootDir = "$PSScriptRoot\Tests" # The $OutDir is where module files and updatable help files are staged for signing, install and publishing. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $OutDir = "$PSScriptRoot\Release" # The local installation directory for the install task. Defaults to your home Modules location. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $InstallPath = Join-Path (Split-Path $profile.CurrentUserAllHosts -Parent) ` "Modules\$ModuleName\$((Test-ModuleManifest -Path $SrcRootDir\$ModuleName.psd1).Version.ToString())" # Default Locale used for help generation, defaults to en-US. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $DefaultLocale = 'en-US' # Items in the $Exclude array will not be copied to the $OutDir e.g. $Exclude = @('.gitattributes') # Typically you wouldn't put any file under the src dir unless the file was going to ship with # the module. However, if there are such files, add their $SrcRootDir relative paths to the exclude list. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $Exclude = @() # ------------------ Script analysis properties --------------------------- # Enable/disable use of PSScriptAnalyzer to perform script analysis. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ScriptAnalysisEnabled = $True # When PSScriptAnalyzer is enabled, control which severity level will generate a build failure. # Valid values are Error, Warning, Information and None. "None" will report errors but will not # cause a build failure. "Error" will fail the build only on diagnostic records that are of # severity error. "Warning" will fail the build on Warning and Error diagnostic records. # "Any" will fail the build on any diagnostic record, regardless of severity. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] [ValidateSet('Error', 'Warning', 'Any', 'None')] $ScriptAnalysisFailBuildOnSeverityLevel = 'Error' # Path to the PSScriptAnalyzer settings file. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ScriptAnalyzerSettingsPath = "$PSScriptRoot\ScriptAnalyzerSettings.psd1" # ------------------- Script signing properties --------------------------- # Set to $true if you want to sign your scripts. You will need to have a code-signing certificate. # You can specify the certificate's subject name below. If not specified, you will be prompted to # provide either a subject name or path to a PFX file. After this one time prompt, the value will # saved for future use and you will no longer be prompted. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ScriptSigningEnabled = $false # Specify the Subject Name of the certificate used to sign your scripts. Leave it as $null and the # first time you build, you will be prompted to enter your code-signing certificate's Subject Name. # This variable is used only if $SignScripts is set to $true. # # This does require the code-signing certificate to be installed to your certificate store. If you # have a code-signing certificate in a PFX file, install the certificate to your certificate store # with the command below. You may be prompted for the certificate's password. # # Import-PfxCertificate -FilePath .\myCodeSigingCert.pfx -CertStoreLocation Cert:\CurrentUser\My # [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CertSubjectName = $null # Certificate store path. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CertPath = "Cert:\" # -------------------- File catalog properties ---------------------------- # Enable/disable generation of a catalog (.cat) file for the module. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CatalogGenerationEnabled = $true # Select the hash version to use for the catalog file: 1 for SHA1 (compat with Windows 7 and # Windows Server 2008 R2), 2 for SHA2 to support only newer Windows versions. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CatalogVersion = 2 # ---------------------- Testing properties ------------------------------- # Enable/disable Pester code coverage reporting. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CodeCoverageEnabled = $true # CodeCoverageFiles specifies the files to perform code coverage analysis on. This property # acts as a direct input to the Pester -CodeCoverage parameter, so will support constructions # like the ones found here: https://github.com/pester/Pester/wiki/Code-Coverage. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $CodeCoverageFiles = "$SrcRootDir\*.ps1", "$SrcRootDir\*.psm1" # -------------------- Publishing properties ------------------------------ # Your NuGet API key for the PSGallery. Leave it as $null and the first time you publish, # you will be prompted to enter your API key. The build will store the key encrypted in the # settings file, so that on subsequent publishes you will no longer be prompted for the API key. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $NuGetApiKey = $null # Name of the repository you wish to publish to. If $null is specified the default repo (PowerShellGallery) is used. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $PublishRepository = $null # Path to the release notes file. Set to $null if the release notes reside in the manifest file. # The contents of this file are used during publishing for the ReleaseNotes parameter. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ReleaseNotesPath = "$PSScriptRoot\ReleaseNotes.md" # ----------------------- Misc properties --------------------------------- # In addition, PFX certificates are supported in an interactive scenario only, # as a way to import a certificate into the user personal store for later use. # This can be provided using the CertPfxPath parameter. PFX passwords will not be stored. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $SettingsPath = "$env:LOCALAPPDATA\Plaster\NewModuleTemplate\SecuredBuildSettings.clixml" # Specifies an output file path to send to Invoke-Pester's -OutputFile parameter. # This is typically used to write out test results so that they can be sent to a CI # system like AppVeyor. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $TestOutputFile = $null # Specifies the test output format to use when the TestOutputFile property is given # a path. This parameter is passed through to Invoke-Pester's -OutputFormat parameter. [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $TestOutputFormat = "NUnitXml" } ############################################################################### # Customize these tasks for performing operations before and/or after file staging. ############################################################################### # Executes before the StageFiles task. Task BeforeStageFiles { } # Executes after the StageFiles task. Task AfterStageFiles { } ############################################################################### # Customize these tasks for performing operations before and/or after Build. ############################################################################### # Executes before the BeforeStageFiles phase of the Build task. Task BeforeBuild { } # Executes after the Build task. Task AfterBuild { } ############################################################################### # Customize these tasks for performing operations before and/or after BuildHelp. ############################################################################### # Executes before the BuildHelp task. Task BeforeBuildHelp { } # Executes after the BuildHelp task. Task AfterBuildHelp { } ############################################################################### # Customize these tasks for performing operations before and/or after BuildUpdatableHelp. ############################################################################### # Executes before the BuildUpdatableHelp task. Task BeforeBuildUpdatableHelp { } # Executes after the BuildUpdatableHelp task. Task AfterBuildUpdatableHelp { } ############################################################################### # Customize these tasks for performing operations before and/or after GenerateFileCatalog. ############################################################################### # Executes before the GenerateFileCatalog task. Task BeforeGenerateFileCatalog { } # Executes after the GenerateFileCatalog task. Task AfterGenerateFileCatalog { } ############################################################################### # Customize these tasks for performing operations before and/or after Install. ############################################################################### # Executes before the Install task. Task BeforeInstall { } # Executes after the Install task. Task AfterInstall { } ############################################################################### # Customize these tasks for performing operations before and/or after Publish. ############################################################################### # Executes before the Publish task. Task BeforePublish { } # Executes after the Publish task. Task AfterPublish { }
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/Templates/Build.PSake/build.psake.ps1
build.psake.ps1
#Requires -Modules psake ############################################################################## # DO NOT MODIFY THIS FILE! Modify build.settings.ps1 instead. ############################################################################## ############################################################################## # This is the PowerShell Module psake build script. It defines the following tasks: # # Clean, Build, Sign, BuildHelp, Install, Test and Publish. # # The default task is Build. This task copies the appropriate files from the # $SrcRootDir under the $OutDir. Later, other tasks such as Sign and BuildHelp # will further modify the contents of $OutDir and add new files. # # The Sign task will only sign scripts if the $SignScripts variable is set to # $true. A code-signing certificate is required for this task to complete. # # The BuildHelp task invokes platyPS to generate markdown files from # comment-based help for your exported commands. platyPS then generates # a help file for your module from the markdown files. # # The Install task simplies copies the module folder under $OutDir to your # profile's Modules folder. # # The Test task invokes Pester on the $TestRootDir. # # The Publish task uses the Publish-Module command to publish # to either the PowerShell Gallery (the default) or you can change # the $PublishRepository property to the name of an alternate repository. # Note: the Publish task requires that the Test task execute without failures. # # You can exeute a specific task, such as the Test task by running the # following command: # # PS C:\> invoke-psake build.psake.ps1 -taskList Test # # You can execute the Publish task with the following command. # The first time you execute the Publish task, you will be prompted to enter # your PowerShell Gallery NuGetApiKey. After entering the key, it is encrypted # and stored so you will not have to enter it again. # # PS C:\> invoke-psake build.psake.ps1 -taskList Publish # # You can verify the stored and encrypted NuGetApiKey by running the following # command which will display a portion of your NuGetApiKey in plain text. # # PS C:\> invoke-psake build.psake.ps1 -taskList ShowApiKey # # You can store a new NuGetApiKey with this command. You can leave off # the -properties parameter and you'll be prompted for the key. # # PS C:\> invoke-psake build.psake.ps1 -taskList StoreApiKey -properties @{NuGetApiKey='test123'} # ############################################################################### # Dot source the user's customized properties and extension tasks. ############################################################################### . $PSScriptRoot\build.settings.ps1 ############################################################################### # Private properties. ############################################################################### Properties { [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $ModuleOutDir = "$OutDir\$ModuleName" [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $UpdatableHelpOutDir = "$OutDir\UpdatableHelp" [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $SharedProperties = @{} [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '')] $LineSep = "-" * 78 } ############################################################################### # Core task implementations. Avoid modifying these tasks. ############################################################################### Task default -depends Build Task Init -requiredVariables OutDir { if (!(Test-Path -LiteralPath $OutDir)) { New-Item $OutDir -ItemType Directory -Verbose:$VerbosePreference > $null } else { Write-Verbose "$($psake.context.currentTaskName) - directory already exists '$OutDir'." } } Task Clean -depends Init -requiredVariables OutDir { # Maybe a bit paranoid but this task nuked \ on my laptop. Good thing I was not running as admin. if ($OutDir.Length -gt 3) { Get-ChildItem $OutDir | Remove-Item -Recurse -Force -Verbose:$VerbosePreference } else { Write-Verbose "$($psake.context.currentTaskName) - `$OutDir '$OutDir' must be longer than 3 characters." } } Task StageFiles -depends Init, Clean, BeforeStageFiles, CoreStageFiles, AfterStageFiles { } Task CoreStageFiles -requiredVariables ModuleOutDir, SrcRootDir { if (!(Test-Path -LiteralPath $ModuleOutDir)) { New-Item $ModuleOutDir -ItemType Directory -Verbose:$VerbosePreference > $null } else { Write-Verbose "$($psake.context.currentTaskName) - directory already exists '$ModuleOutDir'." } Copy-Item -Path $SrcRootDir\* -Destination $ModuleOutDir -Recurse -Exclude $Exclude -Verbose:$VerbosePreference } Task Build -depends Init, Clean, BeforeBuild, StageFiles, Analyze, Sign, AfterBuild { } Task Analyze -depends StageFiles ` -requiredVariables ModuleOutDir, ScriptAnalysisEnabled, ScriptAnalysisFailBuildOnSeverityLevel, ScriptAnalyzerSettingsPath { if (!$ScriptAnalysisEnabled) { "Script analysis is not enabled. Skipping $($psake.context.currentTaskName) task." return } if (!(Get-Module PSScriptAnalyzer -ListAvailable)) { "PSScriptAnalyzer module is not installed. Skipping $($psake.context.currentTaskName) task." return } "ScriptAnalysisFailBuildOnSeverityLevel set to: $ScriptAnalysisFailBuildOnSeverityLevel" $analysisResult = Invoke-ScriptAnalyzer -Path $ModuleOutDir -Settings $ScriptAnalyzerSettingsPath -Recurse -Verbose:$VerbosePreference $analysisResult | Format-Table switch ($ScriptAnalysisFailBuildOnSeverityLevel) { 'None' { return } 'Error' { Assert -conditionToCheck ( ($analysisResult | Where-Object Severity -eq 'Error').Count -eq 0 ) -failureMessage 'One or more ScriptAnalyzer errors were found. Build cannot continue!' } 'Warning' { Assert -conditionToCheck ( ($analysisResult | Where-Object { $_.Severity -eq 'Warning' -or $_.Severity -eq 'Error' }).Count -eq 0) -failureMessage 'One or more ScriptAnalyzer warnings were found. Build cannot continue!' } default { Assert -conditionToCheck ( $analysisResult.Count -eq 0 ) -failureMessage 'One or more ScriptAnalyzer issues were found. Build cannot continue!' } } } Task Sign -depends StageFiles -requiredVariables CertPath, SettingsPath, ScriptSigningEnabled { if (!$ScriptSigningEnabled) { "Script signing is not enabled. Skipping $($psake.context.currentTaskName) task." return } $validCodeSigningCerts = Get-ChildItem -Path $CertPath -CodeSigningCert -Recurse | Where-Object NotAfter -ge (Get-Date) if (!$validCodeSigningCerts) { throw "There are no non-expired code-signing certificates in $CertPath. You can either install " + "a code-signing certificate into the certificate store or disable script analysis in build.settings.ps1." } $certSubjectNameKey = "CertSubjectName" $storeCertSubjectName = $true # Get the subject name of the code-signing certificate to be used for script signing. if (!$CertSubjectName -and ($CertSubjectName = GetSetting -Key $certSubjectNameKey -Path $SettingsPath)) { $storeCertSubjectName = $false } elseif (!$CertSubjectName) { "A code-signing certificate has not been specified." "The following non-expired, code-signing certificates are available in your certificate store:" $validCodeSigningCerts | Format-List Subject,Issuer,Thumbprint,NotBefore,NotAfter $CertSubjectName = Read-Host -Prompt 'Enter the subject name (case-sensitive) of the certificate to use for script signing' } # Find a code-signing certificate that matches the specified subject name. $certificate = $validCodeSigningCerts | Where-Object { $_.SubjectName.Name -cmatch [regex]::Escape($CertSubjectName) } | Sort-Object NotAfter -Descending | Select-Object -First 1 if ($certificate) { $SharedProperties.CodeSigningCertificate = $certificate if ($storeCertSubjectName) { SetSetting -Key $certSubjectNameKey -Value $certificate.SubjectName.Name -Path $SettingsPath "The new certificate subject name has been stored in ${SettingsPath}." } else { "Using stored certificate subject name $CertSubjectName from ${SettingsPath}." } $LineSep "Using code-signing certificate: $certificate" $LineSep $files = @(Get-ChildItem -Path $ModuleOutDir\* -Recurse -Include *.ps1,*.psm1) foreach ($file in $files) { $setAuthSigParams = @{ FilePath = $file.FullName Certificate = $certificate Verbose = $VerbosePreference } $result = Microsoft.PowerShell.Security\Set-AuthenticodeSignature @setAuthSigParams if ($result.Status -ne 'Valid') { throw "Failed to sign script: $($file.FullName)." } "Successfully signed script: $($file.Name)" } } else { $expiredCert = Get-ChildItem -Path $CertPath -CodeSigningCert -Recurse | Where-Object { ($_.SubjectName.Name -cmatch [regex]::Escape($CertSubjectName)) -and ($_.NotAfter -lt (Get-Date)) } Sort-Object NotAfter -Descending | Select-Object -First 1 if ($expiredCert) { throw "The code-signing certificate `"$($expiredCert.SubjectName.Name)`" EXPIRED on $($expiredCert.NotAfter)." } throw 'No valid certificate subject name supplied or stored.' } } Task BuildHelp -depends Build, BeforeBuildHelp, GenerateMarkdown, GenerateHelpFiles, AfterBuildHelp { } Task GenerateMarkdown -requiredVariables DefaultLocale, DocsRootDir, ModuleName, ModuleOutDir { if (!(Get-Module platyPS -ListAvailable)) { "platyPS module is not installed. Skipping $($psake.context.currentTaskName) task." return } $moduleInfo = Import-Module $ModuleOutDir\$ModuleName.psd1 -Global -Force -PassThru try { if ($moduleInfo.ExportedCommands.Count -eq 0) { "No commands have been exported. Skipping $($psake.context.currentTaskName) task." return } if (!(Test-Path -LiteralPath $DocsRootDir)) { New-Item $DocsRootDir -ItemType Directory > $null } if (Get-ChildItem -LiteralPath $DocsRootDir -Filter *.md -Recurse) { Get-ChildItem -LiteralPath $DocsRootDir -Directory | ForEach-Object { Update-MarkdownHelp -Path $_.FullName -Verbose:$VerbosePreference > $null } } # ErrorAction set to SilentlyContinue so this command will not overwrite an existing MD file. New-MarkdownHelp -Module $ModuleName -Locale $DefaultLocale -OutputFolder $DocsRootDir\$DefaultLocale ` -WithModulePage -ErrorAction SilentlyContinue -Verbose:$VerbosePreference > $null } finally { Remove-Module $ModuleName } } Task GenerateHelpFiles -requiredVariables DocsRootDir, ModuleName, ModuleOutDir, OutDir { if (!(Get-Module platyPS -ListAvailable)) { "platyPS module is not installed. Skipping $($psake.context.currentTaskName) task." return } if (!(Get-ChildItem -LiteralPath $DocsRootDir -Filter *.md -Recurse -ErrorAction SilentlyContinue)) { "No markdown help files to process. Skipping $($psake.context.currentTaskName) task." return } $helpLocales = (Get-ChildItem -Path $DocsRootDir -Directory).Name # Generate the module's primary MAML help file. foreach ($locale in $helpLocales) { New-ExternalHelp -Path $DocsRootDir\$locale -OutputPath $ModuleOutDir\$locale -Force ` -ErrorAction SilentlyContinue -Verbose:$VerbosePreference > $null } } Task BuildUpdatableHelp -depends BuildHelp, BeforeBuildUpdatableHelp, CoreBuildUpdatableHelp, AfterBuildUpdatableHelp { } Task CoreBuildUpdatableHelp -requiredVariables DocsRootDir, ModuleName, UpdatableHelpOutDir { if (!(Get-Module platyPS -ListAvailable)) { "platyPS module is not installed. Skipping $($psake.context.currentTaskName) task." return } $helpLocales = (Get-ChildItem -Path $DocsRootDir -Directory).Name # Create updatable help output directory. if (!(Test-Path -LiteralPath $UpdatableHelpOutDir)) { New-Item $UpdatableHelpOutDir -ItemType Directory -Verbose:$VerbosePreference > $null } else { Write-Verbose "$($psake.context.currentTaskName) - directory already exists '$UpdatableHelpOutDir'." Get-ChildItem $UpdatableHelpOutDir | Remove-Item -Recurse -Force -Verbose:$VerbosePreference } # Generate updatable help files. Note: this will currently update the version number in the module's MD # file in the metadata. foreach ($locale in $helpLocales) { New-ExternalHelpCab -CabFilesFolder $ModuleOutDir\$locale -LandingPagePath $DocsRootDir\$locale\$ModuleName.md ` -OutputFolder $UpdatableHelpOutDir -Verbose:$VerbosePreference > $null } } Task GenerateFileCatalog -depends Build, BuildHelp, BeforeGenerateFileCatalog, CoreGenerateFileCatalog, AfterGenerateFileCatalog { } Task CoreGenerateFileCatalog -requiredVariables CatalogGenerationEnabled, CatalogVersion, ModuleName, ModuleOutDir, OutDir { if (!$CatalogGenerationEnabled) { "FileCatalog generation is not enabled. Skipping $($psake.context.currentTaskName) task." return } if (!(Get-Command Microsoft.PowerShell.Security\New-FileCatalog -ErrorAction SilentlyContinue)) { "FileCatalog commands not available on this version of PowerShell. Skipping $($psake.context.currentTaskName) task." return } $catalogFilePath = "$OutDir\$ModuleName.cat" $newFileCatalogParams = @{ Path = $ModuleOutDir CatalogFilePath = $catalogFilePath CatalogVersion = $CatalogVersion Verbose = $VerbosePreference } Microsoft.PowerShell.Security\New-FileCatalog @newFileCatalogParams > $null if ($ScriptSigningEnabled) { if ($SharedProperties.CodeSigningCertificate) { $setAuthSigParams = @{ FilePath = $catalogFilePath Certificate = $SharedProperties.CodeSigningCertificate Verbose = $VerbosePreference } $result = Microsoft.PowerShell.Security\Set-AuthenticodeSignature @setAuthSigParams if ($result.Status -ne 'Valid') { throw "Failed to sign file catalog: $($catalogFilePath)." } "Successfully signed file catalog: $($catalogFilePath)" } else { "No code-signing certificate was found to sign the file catalog." } } else { "Script signing is not enabled. Skipping signing of file catalog." } Move-Item -LiteralPath $newFileCatalogParams.CatalogFilePath -Destination $ModuleOutDir } Task Install -depends Build, BuildHelp, GenerateFileCatalog, BeforeInstall, CoreInstall, AfterInstall { } Task CoreInstall -requiredVariables ModuleOutDir { if (!(Test-Path -LiteralPath $InstallPath)) { Write-Verbose 'Creating install directory' New-Item -Path $InstallPath -ItemType Directory -Verbose:$VerbosePreference > $null } Copy-Item -Path $ModuleOutDir\* -Destination $InstallPath -Verbose:$VerbosePreference -Recurse -Force "Module installed into $InstallPath" } Task Test -depends Build -requiredVariables TestRootDir, ModuleName, CodeCoverageEnabled, CodeCoverageFiles { if (!(Get-Module Pester -ListAvailable)) { "Pester module is not installed. Skipping $($psake.context.currentTaskName) task." return } Import-Module Pester try { Microsoft.PowerShell.Management\Push-Location -LiteralPath $TestRootDir if ($TestOutputFile) { $testing = @{ OutputFile = $TestOutputFile OutputFormat = $TestOutputFormat PassThru = $true Verbose = $VerbosePreference } } else { $testing = @{ PassThru = $true Verbose = $VerbosePreference } } # To control the Pester code coverage, a boolean $CodeCoverageEnabled is used. if ($CodeCoverageEnabled) { $testing.CodeCoverage = $CodeCoverageFiles } $testResult = Invoke-Pester @testing Assert -conditionToCheck ( $testResult.FailedCount -eq 0 ) -failureMessage "One or more Pester tests failed, build cannot continue." if ($CodeCoverageEnabled) { $testCoverage = [int]($testResult.CodeCoverage.NumberOfCommandsExecuted / $testResult.CodeCoverage.NumberOfCommandsAnalyzed * 100) "Pester code coverage on specified files: ${testCoverage}%" } } finally { Microsoft.PowerShell.Management\Pop-Location Remove-Module $ModuleName -ErrorAction SilentlyContinue } } Task Publish -depends Build, Test, BuildHelp, GenerateFileCatalog, BeforePublish, CorePublish, AfterPublish { } Task CorePublish -requiredVariables SettingsPath, ModuleOutDir { $publishParams = @{ Path = $ModuleOutDir NuGetApiKey = $NuGetApiKey } # Publishing to the PSGallery requires an API key, so get it. if ($NuGetApiKey) { "Using script embedded NuGetApiKey" } elseif ($NuGetApiKey = GetSetting -Path $SettingsPath -Key NuGetApiKey) { "Using stored NuGetApiKey" } else { $promptForKeyCredParams = @{ DestinationPath = $SettingsPath Message = 'Enter your NuGet API key in the password field' Key = 'NuGetApiKey' } $cred = PromptUserForCredentialAndStorePassword @promptForKeyCredParams $NuGetApiKey = $cred.GetNetworkCredential().Password "The NuGetApiKey has been stored in $SettingsPath" } $publishParams = @{ Path = $ModuleOutDir NuGetApiKey = $NuGetApiKey } # If an alternate repository is specified, set the appropriate parameter. if ($PublishRepository) { $publishParams['Repository'] = $PublishRepository } # Consider not using -ReleaseNotes parameter when Update-ModuleManifest has been fixed. if ($ReleaseNotesPath) { $publishParams['ReleaseNotes'] = @(Get-Content $ReleaseNotesPath) } "Calling Publish-Module..." Publish-Module @publishParams } ############################################################################### # Secondary/utility tasks - typically used to manage stored build settings. ############################################################################### Task ? -description 'Lists the available tasks' { "Available tasks:" $psake.context.Peek().Tasks.Keys | Sort-Object } Task RemoveApiKey -requiredVariables SettingsPath { if (GetSetting -Path $SettingsPath -Key NuGetApiKey) { RemoveSetting -Path $SettingsPath -Key NuGetApiKey } } Task StoreApiKey -requiredVariables SettingsPath { $promptForKeyCredParams = @{ DestinationPath = $SettingsPath Message = 'Enter your NuGet API key in the password field' Key = 'NuGetApiKey' } PromptUserForCredentialAndStorePassword @promptForKeyCredParams "The NuGetApiKey has been stored in $SettingsPath" } Task ShowApiKey -requiredVariables SettingsPath { $OFS = "" if ($NuGetApiKey) { "The embedded (partial) NuGetApiKey is: $($NuGetApiKey[0..7])" } elseif ($NuGetApiKey = GetSetting -Path $SettingsPath -Key NuGetApiKey) { "The stored (partial) NuGetApiKey is: $($NuGetApiKey[0..7])" } else { "The NuGetApiKey has not been provided or stored." return } "To see the full key, use the task 'ShowFullApiKey'" } Task ShowFullApiKey -requiredVariables SettingsPath { if ($NuGetApiKey) { "The embedded NuGetApiKey is: $NuGetApiKey" } elseif ($NuGetApiKey = GetSetting -Path $SettingsPath -Key NuGetApiKey) { "The stored NuGetApiKey is: $NuGetApiKey" } else { "The NuGetApiKey has not been provided or stored." } } Task RemoveCertSubjectName -requiredVariables SettingsPath { if (GetSetting -Path $SettingsPath -Key CertSubjectName) { RemoveSetting -Path $SettingsPath -Key CertSubjectName } } Task StoreCertSubjectName -requiredVariables SettingsPath { $certSubjectName = 'CN=' $certSubjectName += Read-Host -Prompt 'Enter the certificate subject name for script signing. Use exact casing, CN= prefix will be added' SetSetting -Key CertSubjectName -Value $certSubjectName -Path $SettingsPath "The new certificate subject name '$certSubjectName' has been stored in ${SettingsPath}." } Task ShowCertSubjectName -requiredVariables SettingsPath { $CertSubjectName = GetSetting -Path $SettingsPath -Key CertSubjectName "The stored certificate is: $CertSubjectName" $cert = Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert | Where-Object { $_.Subject -eq $CertSubjectName -and $_.NotAfter -gt (Get-Date) } | Sort-Object -Property NotAfter -Descending | Select-Object -First 1 if ($cert) { "A valid certificate for the subject $CertSubjectName has been found" } else { 'A valid certificate has not been found' } } ############################################################################### # Helper functions ############################################################################### function PromptUserForCredentialAndStorePassword { [Diagnostics.CodeAnalysis.SuppressMessage("PSProvideDefaultParameterValue", '')] param( [Parameter()] [ValidateNotNullOrEmpty()] [string] $DestinationPath, [Parameter(Mandatory)] [string] $Message, [Parameter(Mandatory, ParameterSetName = 'SaveSetting')] [string] $Key ) $cred = Get-Credential -Message $Message -UserName "ignored" if ($DestinationPath) { SetSetting -Key $Key -Value $cred.Password -Path $DestinationPath } $cred } function AddSetting { [System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope='Function')] param( [Parameter(Mandatory)] [string]$Key, [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [ValidateNotNull()] [object]$Value ) switch ($type = $Value.GetType().Name) { 'securestring' { $setting = $Value | ConvertFrom-SecureString } default { $setting = $Value } } if (Test-Path -LiteralPath $Path) { $storedSettings = Import-Clixml -Path $Path $storedSettings.Add($Key, @($type, $setting)) $storedSettings | Export-Clixml -Path $Path } else { $parentDir = Split-Path -Path $Path -Parent if (!(Test-Path -LiteralPath $parentDir)) { New-Item $parentDir -ItemType Directory > $null } @{$Key = @($type, $setting)} | Export-Clixml -Path $Path } } function GetSetting { param( [Parameter(Mandatory)] [string]$Key, [Parameter(Mandatory)] [string]$Path ) if (Test-Path -LiteralPath $Path) { $securedSettings = Import-Clixml -Path $Path if ($securedSettings.$Key) { switch ($securedSettings.$Key[0]) { 'securestring' { $value = $securedSettings.$Key[1] | ConvertTo-SecureString $cred = New-Object -TypeName PSCredential -ArgumentList 'jpgr', $value $cred.GetNetworkCredential().Password } default { $securedSettings.$Key[1] } } } } } function SetSetting { param( [Parameter(Mandatory)] [string]$Key, [Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [ValidateNotNull()] [object]$Value ) if (GetSetting -Key $Key -Path $Path) { RemoveSetting -Key $Key -Path $Path } AddSetting -Key $Key -Value $Value -Path $Path } function RemoveSetting { param( [Parameter(Mandatory)] [string]$Key, [Parameter(Mandatory)] [string]$Path ) if (Test-Path -LiteralPath $Path) { $storedSettings = Import-Clixml -Path $Path $storedSettings.Remove($Key) if ($storedSettings.Count -eq 0) { Remove-Item -Path $Path } else { $storedSettings | Export-Clixml -Path $Path } } else { Write-Warning "The build setting file '$Path' has not been created yet." } }
PowerShellCorpus/PowerShellGallery/Forge.Module/0.4.1/Templates/Build.PSake/build.ps1
build.ps1
#Requires -Modules psake # Builds the module by invoking psake on the build.psake.ps1 script. Invoke-PSake $PSScriptRoot\build.psake.ps1 -taskList Build
PowerShellCorpus/PowerShellGallery/cMsmq/1.0.3/SourceFiles/GenerateCMsmqDll.ps1
GenerateCMsmqDll.ps1
<# Compiles the cMsmq.cs source file into the cMsmq.dll library. It implements the MQGetQueueSecurity function to retrieve information from the access control security descriptors of MSMQ queues. #> $TypeDefinition = Get-Content -Path "$PSScriptRoot\cMsmq.cs" | Out-String Add-Type -TypeDefinition $TypeDefinition -Language CSharpVersion3 -OutputAssembly "$PSScriptRoot\cMsmq.dll" -OutputType Library
PowerShellCorpus/PowerShellGallery/cMsmq/1.0.3/Examples/Sample_cMsmq.ps1
Sample_cMsmq.ps1
configuration Sample_cMsmq { Import-DscResource -ModuleName PSDesiredStateConfiguration Import-DscResource -ModuleName cMsmq # Ensure the Message Queueing is installed. WindowsFeature MSMQ { Ensure = 'Present' Name = 'MSMQ' } # Ensure the MSMQ service is running. Service MsmqService { Name = 'MSMQ' State = 'Running' DependsOn = '[WindowsFeature]MSMQ' } # Ensure the specified private queue exists. # All the parameters will be either left unchanged or, if the queue is to be created, set to their default values. cMsmqQueue Queue1 { Ensure = 'Present' Name = 'Queue-1' DependsOn = '[Service]MsmqService' } # Ensure the specified transactional private queue exists. # If there is already a private queue with the same name but of different type, an error will be thrown. cMsmqQueue Queue2 { Ensure = 'Present' Name = 'Queue-2' Transactional = $true Authenticate = $true Journaling = $true JournalQuota = 65536 Label = 'Created by the cMsmqQueue DSC resource' PrivacyLevel = 'Body' QueueQuota = 262144 DependsOn = '[Service]MsmqService' } # Ensure the specified private queue does not exist. # If provided, all the other non-mandatory properties will be ignored. cMsmqQueue Queue3 { Ensure = 'Absent' Name = 'Queue-3' DependsOn = '[Service]MsmqService' } # Grant Full Control permission level for the specified principal. cMsmqQueuePermissionEntry QueuePermission1 { Ensure = 'Present' Name = 'Queue-1' Principal = $Env:UserDomain, $Env:UserName -join '\' AccessRights = 'FullControl' DependsOn = '[cMsmqQueue]Queue1' } # Grant multiple access rights for the specified principal. cMsmqQueuePermissionEntry QueuePermission2 { Ensure = 'Present' Name = 'Queue-2' Principal = 'BUILTIN\Administrators' AccessRights = 'ChangeQueuePermissions', 'DeleteQueue' DependsOn = '[cMsmqQueue]Queue2' } # Revoke all permissions for the specified principal. cMsmqQueuePermissionEntry QueuePermission3 { Ensure = 'Absent' Name = 'Queue-2' Principal = 'BUILTIN\Users' DependsOn = '[cMsmqQueue]Queue2' } } Sample_cMsmq -OutputPath "$Env:SystemDrive\Sample_cMsmq" Start-DscConfiguration -Path "$Env:SystemDrive\Sample_cMsmq" -Force -Verbose -Wait Get-DscConfiguration
PowerShellCorpus/PowerShellGallery/cMsmq/1.0.3/ResourceDesignerScripts/GenerateCMsmqQueueSchema.ps1
GenerateCMsmqQueueSchema.ps1
#requires -Version 4.0 -Modules xDSCResourceDesigner $ModuleName = 'cMsmq' $ResourceName = 'cMsmqQueue' $DscResourceProperties = @( (New-xDscResourceProperty -Type String -Attribute Write -Name Ensure -ValidateSet 'Absent', 'Present' -Description "Indicates whether the queue exists.") (New-xDscResourceProperty -Type String -Attribute Key -Name Name -Description 'Indicates the name of the queue.') (New-xDscResourceProperty -Type Boolean -Attribute Write -Name Transactional -Description 'Indicates whether the queue is transactional.') (New-xDscResourceProperty -Type Boolean -Attribute Write -Name Authenticate -Description 'Indicates whether the queue accepts only authenticated messages.') (New-xDscResourceProperty -Type Boolean -Attribute Write -Name Journaling -Description 'Indicates whether received messages are copied to the journal queue.') (New-xDscResourceProperty -Type UInt32 -Attribute Write -Name JournalQuota -Description 'Indicates the maximum size of the journal queue in KB.') (New-xDscResourceProperty -Type String -Attribute Write -Name Label -Description 'Indicates the description of the queue.') (New-xDscResourceProperty -Type String -Attribute Write -Name PrivacyLevel -ValidateSet 'None', 'Optional', 'Body' -Description 'Indicates the privacy level associated with the queue.') (New-xDscResourceProperty -Type UInt32 -Attribute Write -Name QueueQuota -Description 'Indicates the maximum size of the queue in KB.') ) New-xDscResource -Name $ResourceName -ModuleName $ModuleName -Property $DscResourceProperties -Verbose
PowerShellCorpus/PowerShellGallery/cMsmq/1.0.3/ResourceDesignerScripts/GenerateCMsmqQueuePermissionEntrySchema.ps1
GenerateCMsmqQueuePermissionEntrySchema.ps1
#requires -Version 4.0 -Modules xDSCResourceDesigner $ModuleName = 'cMsmq' $ResourceName = 'cMsmqQueuePermissionEntry' $DscResourceProperties = @( (New-xDscResourceProperty -Type String -Attribute Write -Name Ensure -ValidateSet 'Absent', 'Present' -Description "Indicates whether the permission entry exists. The default value is Present. Set this property to Absent to ensure that any access rights the principal has are revoked.") (New-xDscResourceProperty -Type String -Attribute Key -Name Name -Description 'Indicates the name of the queue.'), (New-xDscResourceProperty -Type String -Attribute Key -Name Principal -Description 'Indicates the identity of the principal. Valid name formats: Down-Level Logon Name; User Principal Name; sAMAccountName; Security Identifier.'), (New-xDscResourceProperty -Type String[] -Attribute Write -Name AccessRights -Description 'Indicates the access rights to be granted to the principal. Specify one or more values from the System.Messaging.MessageQueueAccessRights enumeration type. Multiple values can be specified by using a comma-separated string.') ) New-xDscResource -Name $ResourceName -ModuleName $ModuleName -Property $DscResourceProperties -Verbose
PowerShellCorpus/PowerShellGallery/cMsmq/1.0.3/Tests/ResourceDesignerTests.ps1
ResourceDesignerTests.ps1
#requires -Version 4.0 -Modules xDSCResourceDesigner Split-Path -Path $PSScriptRoot -Parent | Join-Path -ChildPath 'DSCResources' | Get-ChildItem -Directory | Test-xDscResource -Name {$_.FullName} -Verbose
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Private/Get-DDKey.ps1
Get-DDKey.ps1
function Get-DDKey { <# .SYNOPSIS Search for API or App keys in different places .DESCRIPTION Get-DDKey will search for keys in different places: - in a standard JSON file within the user directory by default - in environment variables - in a specific JSON file when used with the -ConfigFilePath parameter. .PARAMETER ApplicationKey Retrieves the Application Key instead of the default API Key. .EXAMPLE # Retrieves the API Key Get-DDKey -ErrorAction Stop .EXAMPLE # Retrieves the API Key from a file Get-DDKey -ErrorAction Stop -ConfigFilePath 'c:\file.json' .EXAMPLE # Retrieves the Application Key Get-DDKey -ApplicationKey -ErrorAction Stop .LINK .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter ( Position = 0, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [switch]$ApplicationKey, [Parameter( Mandatory=$false, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [string]$ConfigFilePath ) process { if ($ApplicationKey) { $KeyType = "dd_app_key" } else { $KeyType = "dd_api_key" } Try { if (-not $ConfigFilePath) { Write-Verbose 'Looking for the configuration file at default location of %APPDATA%\PoshDog\keys.json' $ConfigFilePath = (Get-Item Env:APPDATA).value $ConfigFilePath += '\PoshDog\keys.json' } else { Write-Verbose "Path specified with value $ConfigFilePath, searching there" } Get-item $ConfigFilePath -ErrorAction Stop | Out-Null Write-Verbose "Found the file $ConfigFilePath" Try { Write-Verbose "Looking for the $KeyType key in the configuration file" $key= (Get-Content $ConfigFilePath | ConvertFrom-Json).$KeyType if ($key) { Write-Verbose "Key found!" return $key } else { Throw } } Catch { Write-Verbose "Could not find the $KeyType key in the file, continuing the search process" } } Catch { Write-Verbose "Unable to find the file, got this instead: $_" Continue } Try { Write-Verbose "Looking for an environment variable" $key = (Get-item Env:$KeyType -ErrorAction stop).value if ($key) { Write-Verbose "$KeyType found!" return $key } else { Throw } } Catch { Write-Verbose "Could not find the $KeyType key in Env, got this instead: $_" } Write-Error "Could not find the required key, try running Set-DDConfiguration" } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Private/New-DDQuery.ps1
New-DDQuery.ps1
function New-DDQuery { <# .SYNOPSIS Make a request to the API with the parameters entered by the user .DESCRIPTION .PARAMETER APIVersion Version of the API, defaults to v1 .PARAMETER EndPoint The API endpoint, as defined on http://docs.datadoghq.com/api/?lang=console, e.g /monitor .PARAMETER Method The HTTP method used, should be one of GET, PUT, PUSH, DELETE .PARAMETER Body An object used as body for the HTTP request. If the request is a GET call, the body must be a Powershell hashtable, it will get added to the query parameters. If the request is NOT a GET, the body must be a JSON string. .PARAMETER RequiresApplicationKey The API call requires an application key to be set .EXAMPLE # A GET request with no Body: New-DDQuery -EndPoint $Endpoint -Method 'Get' -RequiresApplicationKey -ErrorAction Stop .EXAMPLE # A GET request with an array as -Body parameter $Body = @{'option1','value1'} New-DDQuery -EndPoint $Endpoint -Method 'Get' -Body $Body -RequiresApplicationKey -ErrorAction Stop .EXAMPLE # A POST request New-DDQuery -EndPoint "/monitor" -Method 'Post' -Body $($MonitorObject | ConvertTo-Json) -RequiresApplicationKey -ErrorAction Stop .LINK .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [string]$APIVersion = "v1", [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [string]$Endpoint, [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateSet("Get","Post","Put","Push","Delete")] [ValidateNotNullOrEmpty()] [string]$Method, [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [AllowNull()] [object]$Body, [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [switch]$RequiresApplicationKey ) process { $key_string = "?api_key=" $key_string += (Get-DDKey -ErrorAction Stop) if ($RequiresApplicationKey) { Write-Verbose "" write-verbose "This API call also requires an APP KEY, adding it." $key_string += "&application_key=" $key_string += (Get-DDKey -ApplicationKey -ErrorAction Stop) } $dd_url = "https://app.datadoghq.com/api/" + $APIVersion + $Endpoint + $key_string Try { $result = Invoke-RestMethod -Method $Method -Uri $dd_url -ContentType "application/json" -Body $Body } Catch { Throw "Request to Datadog API backend was NOT successful; It returned this: $_" } return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Private/Compare-HashTable.ps1
Compare-HashTable.ps1
# Inspired from https://github.com/stuartleeks/PesterMatchHashtable function Compare-Hashtable { [CmdletBinding()] param ( [Parameter( Position=0, Mandatory=$True )] [hashtable]$value, [Parameter( Position=1, Mandatory=$True )] [hashtable]$expectedMatch ) process { if($value.Count -ne $expectedMatch.Count){ Write-Verbose 'Count is different' return $false; } foreach($expectedKey in $expectedMatch.Keys) { if (-not($value.Keys -contains $expectedKey)){ write-verbose "key $expectedKey from ExpectedMatch is not in Value" return $false; } if (-not ($value[$expectedKey] -eq $expectedMatch[$expectedKey])){ write-verbose "different values for $expectedKey" return $false; } } return $true; } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Suspend-DDMonitor.ps1
Suspend-DDMonitor.ps1
function Suspend-DDMonitor { <# .SYNOPSIS Mutes Datadog monitors. Either all of them with -All or a specific one with -MonitorID .DESCRIPTION .EXAMPLE # Mute all monitors Suspend-DDMonitor -All .EXAMPLE # Mute a single monitor Suspend-DDMonitor -MonitorID 123456 .EXAMPLE # Mute a single monitor and specify and end date in 2 days. Suspend-DDMonitor -MonitorID 123456 -EndDate (Get-Date).AddDays(2) .EXAMPLE # Mute a single monitor and specify and end timestamp, also mute only for scope role:frontend Suspend-DDMonitor -MonitorID 123456 -EndTimestamp -Scope 'role:frontend' .LINK http://docs.datadoghq.com/api/?lang=console#monitor-mute http://docs.datadoghq.com/api/?lang=console#monitor-mute-all .FUNCTIONALITY #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High',DefaultParameterSetName="Default")] param ( [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, ParameterSetName="Suspend-DDMonitor:All" )] [switch]$All, # Can be part of 3 parameter sets [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID", ParameterSetName="Default" )] [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID", ParameterSetName="Suspend-DDMonitor:IDAndDate" )] [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID", ParameterSetName="Suspend-DDMonitor:IDAndTimestamp" )] [Alias('Id')] [uint32]$MonitorId, # Can be part of 3 parameter sets! [Parameter( Position=1, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, Mandatory=$False, HelpMessage="The scope to apply the mute to, e.g. role:db", ParameterSetName="Default" )] [Parameter( Position=1, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, Mandatory=$False, HelpMessage="The scope to apply the mute to, e.g. role:db", ParameterSetName="Suspend-DDMonitor:IDAndDate" )] [Parameter( Position=1, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, Mandatory=$False, HelpMessage="The scope to apply the mute to, e.g. role:db", ParameterSetName="Suspend-DDMonitor:IDAndTimestamp" )] [string[]]$Scope, [Parameter( Position=2, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, Mandatory=$False, HelpMessage="A POSIX timestamp for when the mute should end", ParameterSetName="Suspend-DDMonitor:IDAndTimestamp" )] [Double]$EndTimestamp, [Parameter( Position=2, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, Mandatory=$False, HelpMessage="A Datetime object representing when the mute should end", ParameterSetName="Suspend-DDMonitor:IDAndDate" )] [DateTime]$EndDate ) process { if ($PSCmdlet.ParameterSetName -eq "Suspend-DDMonitor:All") { $Endpoint = '/monitor/mute_all' $ConfirmationMessage = 'Muting all monitors' $defaultDisplaySet = 'id', 'active', 'disabled', 'start', 'end', 'scope' } else { $Endpoint = "/monitor/$MonitorId/mute" $ConfirmationMessage = "Muting monitor $MonitorId" $Body = @{} $defaultDisplaySet = 'id', 'name', 'type', 'query', 'overall_state', 'message', 'options', 'creator', 'created', 'modified' if ($PSCmdlet.ParameterSetName -eq "Suspend-DDMonitor:IDAndDate") { $unixEpochStart = new-object DateTime 1970,1,1,0,0,0,([DateTimeKind]::Utc) $EndTimestamp = [int]($EndDate - $unixEpochStart).TotalSeconds $Body.Add('end',$EndTimestamp) } elseif ($PSCmdlet.ParameterSetName -eq "Suspend-DDMonitor:IDAndTimestamp") { $Body.Add('end',$EndTimestamp) } if ($Scope) { $Body.Add('scope',$Scope) } $Body = $Body | ConvertTo-Json } if ($pscmdlet.ShouldProcess($ConfirmationMessage)) { $result = New-DDQuery -EndPoint $Endpoint -Method 'Post' -Body $Body -RequiresApplicationKey -ErrorAction Stop } else { Write-Verbose "Task aborted by user" return } $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Get-DDTag.ps1
Get-DDTag.ps1
function Get-DDTag { <# .SYNOPSIS Retrieves a mapping of tags to hosts for your whole infrastructure when called with -All, or the list of tags that apply to a given host when called with -Hostname. .DESCRIPTION .PARAMETER All Returns a mapping of tags to hosts for your whole infrastructure. Incompatible with -Hostname. .PARAMETER Hostname A hostname as shown on Datadog's Infrastructure List. Incompatible with -All. .PARAMETER Source Only shows tags from a particular source. Valid sources are: nagios, hudson, jenkins, users, feed, chef, puppet, git, bitbucket, fabric, capistrano. .Parameter BySource Returns tags grouped by source. Incompatible with -All. .EXAMPLE # Get a list of all tags Get-DDTag -All .EXAMPLE # Get a list of all tags coming from nagios Get-DDTag -All -Source nagios .EXAMPLE # Get a list of all tags for host myhost, grouped by source Get-DDTag -Hostname myhost -BySource .LINK http://docs.datadoghq.com/api/?lang=console#tags-get http://docs.datadoghq.com/api/?lang=console#tags-get-host .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( Mandatory=$True, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, ParameterSetName="Get-DDTag:All" )] [switch]$All, [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Get-DDTag:ByHostname" )] [Alias('Computername')] [ValidateNotNullOrEmpty()] [string]$Hostname, # Can be part of both Parameter Sets [Parameter( Position=1, ValueFromPipeline=$False, ValueFromRemainingArguments=$True, ParameterSetName="Get-DDTag:All" )] [Parameter( Position=1, ValueFromPipeline=$False, ValueFromRemainingArguments=$True, ParameterSetName="Get-DDTag:ByHostname" )] [ValidateNotNullOrEmpty()] [ValidateSet('nagios', 'hudson', 'jenkins', 'users', 'feed', 'chef', 'puppet', 'git', 'bitbucket', 'fabric', 'capistrano' )] [string]$Source, [Parameter( Position=2, ValueFromPipeline=$False, ParameterSetName="Get-DDTag:ByHostname" )] [switch]$BySource ) process { if ($Source -or $BySource) { $Body = @{} } if ($Source) { $Body.Add('source',$Source) } if ($BySource) { $Body.Add('by_source','True') } if ($PSCmdlet.ParameterSetName -eq "Get-DDTag:All") { $Endpoint = '/tags/hosts' } else { # Parameter Set is Get-DDTag:ByHostname $Endpoint = "/tags/hosts/$Hostname" $defaultDisplaySet = 'tags' } $result = New-DDQuery -EndPoint $Endpoint -Method 'Get' -Body $Body -RequiresApplicationKey -ErrorAction SilentlyContinue -ErrorVariable err if ($result -eq $null) { Write-Verbose "Get-DDTag: The query returned nothing. The server returned $err" } $defaultDisplaySet = 'tags' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Suspend-DDHost.ps1
Suspend-DDHost.ps1
function Suspend-DDHost { <# .SYNOPSIS Mutes Datadog hosts. .PARAMETER Hostname A hostname as shown on Datadog's Infrastructure List .PARAMETER Message A message to associate with the muting of this host .PARAMETER EndDate A Datetime object representing when the mute should end. If omitted, the host will remain muted until explicitly unmuted. .PARAMETER EndTimestamp POSIX timestamp when the host will be unmuted. If omitted, the host will remain muted until explicitly unmuted. .PARAMETER override If true and the host is already muted, will replace existing host mute settings. .DESCRIPTION .EXAMPLE # Mute a host called myhost, undefinitely Suspend-DDHost -Hostname myhost .EXAMPLE # Mute a host for 1h using a Datetime object Suspend-DDMonitor -Hostname myhost -EndDate (get-date).AddHours(1) .EXAMPLE # Mute a host for 1h using a Unix timestamp Suspend-DDMonitor -Hostname myhost -EndTimestamp 1473358000 .EXAMPLE # Mute a host, provide an informationnal message and override an existing muting Suspend-DDMonitor -Hostname myhost -Message 'Shutting down this server' -Override .LINK http://docs.datadoghq.com/api/?lang=console#hosts-mute .FUNCTIONALITY #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High',DefaultParameterSetName="Default")] param ( # Can be part of 3 parameter sets [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Default" )] [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Suspend-DDHost:ByDate" )] [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Suspend-DDHost:ByTimestamp" )] [Alias('Computername')] [ValidateNotNullOrEmpty()] [string]$Hostname, # Can be part of 3 parameter sets [Parameter( Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Default" )] [Parameter( Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Suspend-DDHost:ByDate" )] [Parameter( Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Suspend-DDHost:ByTimestamp" )] [ValidateNotNullOrEmpty()] [string]$Message, [Parameter( Position=2, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, HelpMessage="A POSIX timestamp for when the mute should end", ParameterSetName="Suspend-DDHost:ByTimestamp" )] [ValidateNotNullOrEmpty()] [Double]$EndTimestamp, [Parameter( Position=2, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, HelpMessage="A Datetime object representing when the mute should end", ParameterSetName="Suspend-DDHost:ByDate" )] [DateTime]$EndDate, # Can be part of 3 parameter sets [Parameter( Position=3, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Default" )] [Parameter( Position=3, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Suspend-DDHost:ByDate" )] [Parameter( Position=3, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Suspend-DDHost:ByTimestamp" )] [switch]$Override ) process { $Body = @{} if ($Message) { $Body.Add('message',$Message) } if ($Override) { $Body.Add('override','true') } if ($PSCmdlet.ParameterSetName -eq "Suspend-DDHost:ByDate") { $unixEpochStart = new-object DateTime 1970,1,1,0,0,0,([DateTimeKind]::Utc) $EndTimestamp = [int]($EndDate - $unixEpochStart).TotalSeconds $Body.Add('end',$EndTimestamp) } elseif ($PSCmdlet.ParameterSetName -eq "Suspend-DDHost:ByTimestamp") { $Body.Add('end',$EndTimestamp) } if ($pscmdlet.ShouldProcess($ConfirmationMessage)) { $result = New-DDQuery -EndPoint "/host/$Hostname/mute" -Method 'Post' -Body ($Body | ConvertTo-Json) -RequiresApplicationKey -ErrorAction Stop } else { Write-Verbose 'Task aborted by user' return } $defaultDisplaySet = 'hostname', 'action', 'message' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/New-DDSearch.ps1
New-DDSearch.ps1
function New-DDSearch { <# .SYNOPSIS Search for entities from the last 24 hours in Datadog. .DESCRIPTION .PARAMETER Query The query string. .PARAMETER Facet Limits results to an object type, chosen from: hosts, metrics. .EXAMPLE # Search for metric or host object that match 'windows' New-DDSearch -Query 'windows' .EXAMPLE # Search for hosts that match 'db01' New-DDSearch -Query 'db01' -Facet hosts .EXAMPLE # Search for metrics that match 'replication' New-DDSearch -Query 'replication' -Facet metrics .LINK http://docs.datadoghq.com/api/?lang=console#search .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] [ValidateNotNullOrEmpty()] [string]$Query, [Parameter( Position=1, Mandatory=$False, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False)] [ValidateSet("hosts", "metrics")] [ValidateNotNullOrEmpty()] [string]$Facet ) process { $Body = @{} if ($Facet) { $Query = "${Facet}:${Query}" } $Body.Add('q',$Query) $result = New-DDQuery -EndPoint '/search' -Method 'Get' -Body $Body -RequiresApplicationKey -ErrorAction Stop # Build the default property set $defaultDisplaySet = 'results' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Get-DDMonitor.ps1
Get-DDMonitor.ps1
function Get-DDMonitor { <# .SYNOPSIS Retrieves a list of all existing Datadog monitors with -All or a specific one with -MonitorID. .DESCRIPTION .PARAMETER All Retrieves all monitors. Incompatible with -MonitorID. .PARAMETER MonitorId A Datadog Monitor ID. Incompatible with -All. .PARAMETER GroupStates A string or array of strings indicating what, if any, group states to include. Choose from one or more from 'all', 'alert', 'warn', or 'no data'. The argument `group_states` will in fact not render all the monitors that have an alert / warning state. Rather, they give more details on different groups within a monitor that has the multi-alert feature activated. .Parameter Tags A string or array of strings indicating what tags, if any, should be used to filter the list of monitors by scope. Incompatible with -MonitorID .EXAMPLE # Get a list of all monitors Get-DDMonitor -All .EXAMPLE # Get a list of all monitors and filter with a tags Get-DDMonitor -All -Tags host:myhostname .EXAMPLE # Get a list of all monitors and request the alert and warn group states Get-DDMonitor -All -GroupStates @('alert', 'warn') .EXAMPLE # Get a specific monitor Get-DDMonitor -MonitorID 123456 .LINK .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, ParameterSetName="Get-DDMonitor:All" )] [switch]$All, [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID", ParameterSetName="Get-DDMonitor:ByID" )] # [int]$null is 0, so we can't use [ValidateNullOrEmpty] [ValidateScript( {if ($_ -eq 0) {throw 'Cannot bind argument to parameter <<MonitorID>> because it is null or 0.'} else {return $True} } )] [Alias('Id')] [uint32]$MonitorId, # Can be part of both Parameter Sets [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="A string or array of strings indicating what, if any, group states to include. Choose from one or more from 'all', 'alert', 'warn', or 'no data'. Example: 'alert,warn'", ParameterSetName="Get-DDMonitor:All" )] [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="A string or array of strings indicating what, if any, group states to include. Choose from one or more from 'all', 'alert', 'warn', or 'no data'. Example: 'alert,warn'", ParameterSetName="Get-DDMonitor:ByID" )] [ValidateSet("all","alert","warn","no data")] [string[]]$GroupStates, [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="A string or array of strings indicating what tags, if any, should be used to filter the list of monitors by scope", ParameterSetName="Get-DDMonitor:All" )] [string[]]$Tags ) process { if ($GroupStates -or $Tags) { $Body = @{} } # GroupStates can be a member of both parameter sets if ($GroupStates){ $Body.Add("group_states",($GroupStates -join ',')) } if ($PSCmdlet.ParameterSetName -eq "Get-DDMonitor:All") { $Endpoint = '/monitor' if ($Tags) { $Body.Add("tags",($Tags -join ',')) } # Build the default property set $defaultDisplaySet = 'name','id','query' } else { # otherwise ($PSCmdlet.ParameterSetName -eq "Get-DDMonitor:ByID") { $Endpoint = "/monitor/$MonitorId" # Build the default property set $defaultDisplaySet = 'id', 'name', 'type', 'query', 'overall_state', 'message', 'options', 'created', 'creator' } $result = New-DDQuery -EndPoint $Endpoint -Method 'Get' -Body $Body -RequiresApplicationKey -ErrorAction Stop $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Remove-DDMonitor.ps1
Remove-DDMonitor.ps1
function Remove-DDMonitor { <# .SYNOPSIS Remove a Datadog monitor. .DESCRIPTION .PARAMETER MonitorObject A Datadog Monitor object. Can be created from scratch or passed from the pipeline .EXAMPLE # Enter confirmation when asked Remove-DDMonitor -MonitorID 123456 .EXAMPLE # Pass the value by pipeline and bypass confirmation $m.id | Remove-DDMonitor -Confirm:$False .LINK http://docs.datadoghq.com/api/?lang=console#monitor-delete .FUNCTIONALITY #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')] param ( [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID" )] # [int]$null is 0, so we can't use [ValidateNullOrEmpty] [ValidateScript( {if ($_ -eq 0) {throw 'Cannot bind argument to parameter <<MonitorID>> because it is null or 0.'} else {return $True} } )] [Alias('Id')] [uint32]$MonitorId ) process { if ($pscmdlet.ShouldProcess($MonitorId, "Removing monitor '$MonitorId'")) { $result = New-DDQuery -EndPoint "/monitor/$MonitorId" -Method 'Delete' -Body $Body -RequiresApplicationKey -ErrorAction Stop } else { Write-Verbose "Task aborted by user" return } return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Resume-DDHost.ps1
Resume-DDHost.ps1
function Resume-DDHost { <# .SYNOPSIS Unmutes Datadog hosts. .DESCRIPTION .PARAMETER Hostname A hostname as shown on Datadog's Infrastructure List .EXAMPLE # Unmute a host called myhost Resume-DDHost -Hostname myhost .LINK http://docs.datadoghq.com/api/?lang=console#hosts-unmute .FUNCTIONALITY #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High',DefaultParameterSetName="Default")] param ( # Can be part of 3 parameter sets [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True, ParameterSetName="Default" )] [Alias('Computername')] [ValidateNotNullOrEmpty()] [string]$Hostname ) process { if ($pscmdlet.ShouldProcess($ConfirmationMessage)) { $result = New-DDQuery -EndPoint "/host/$Hostname/unmute" -Method 'Post' -RequiresApplicationKey -ErrorAction Stop } else { Write-Verbose 'Task aborted by user' return } $defaultDisplaySet = 'hostname', 'action' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Resume-DDMonitor.ps1
Resume-DDMonitor.ps1
function Resume-DDMonitor { <# .SYNOPSIS Unmutes Datadog monitors. Either all of them with -All or a specific one with -MonitorID .DESCRIPTION .PARAMETER All A switch to resume all monitors. Incompatible with all other parameters. .PARAMETER MonitorID A Datadog monitor ID. .PARAMETER Scope A string or array of strings representing the scope to apply the unmuting to. .PARAMETER AllScopes A switch to clear muting for a monitor across all scopes. .EXAMPLE # Unmute all monitors Resume-DDMonitor -All .EXAMPLE # Mute a single monitor Resume-DDMonitor -MonitorID 123456 .EXAMPLE # Unmute a single monitor for scope role:frontend Resume-DDMonitor -MonitorID 123456 -Scope role:frontend .EXAMPLE # Unmute a single monitor across all scopes Resume-DDMonitor -MonitorID 123456 -AllScopes .LINK http://docs.datadoghq.com/api/?lang=console#monitor-mute http://docs.datadoghq.com/api/?lang=console#monitor-mute-all .FUNCTIONALITY #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High',DefaultParameterSetName="Default")] param ( [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, HelpMessage="Unmute all monitors", ParameterSetName="Resume-DDMonitor:All" )] [switch]$All, [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID", ParameterSetName="Resume-DDMonitor:ByID" )] [Alias('Id')] [uint32]$MonitorId, [Parameter( Position=1, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$False, Mandatory=$False, HelpMessage="The scope to apply the unmute to, e.g. role:db", ParameterSetName="Resume-DDMonitor:ByID" )] [string[]]$Scope, [Parameter( ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false, HelpMessage="Unmute the monitor across all scopes", ParameterSetName="Resume-DDMonitor:ByID" )] [switch]$AllScopes ) process { if ($PSCmdlet.ParameterSetName -eq "Resume-DDMonitor:All") { $Endpoint = '/monitor/unmute_all' $ConfirmationMessage = 'Unmuting all monitors' } else { $Endpoint = "/monitor/$MonitorId/unmute" $ConfirmationMessage = "Unmuting monitor $MonitorId" $Body = @{} $defaultDisplaySet = 'id', 'name', 'type', 'query', 'overall_state', 'message', 'options', 'creator', 'created', 'modified' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) -ErrorAction SilentlyContinue $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) if ($Scope) { $Body.Add('scope',$Scope) } if ($AllScopes) { $Body.Add('all_scopes','True') } $Body = $Body | ConvertTo-Json } if ($pscmdlet.ShouldProcess($ConfirmationMessage)) { $result = New-DDQuery -EndPoint $Endpoint -Method 'Post' -Body $Body -RequiresApplicationKey -ErrorAction Stop } else { Write-Verbose "Task aborted by user" return } $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers -ErrorAction SilentlyContinue return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Set-DDConfiguration.ps1
Set-DDConfiguration.ps1
function Set-DDConfiguration { <# .SYNOPSIS Creates a configuration file with Datadog keys to be used in subsequent requests .DESCRIPTION .EXAMPLE # Write keys in the standard Env:APPDATA\PoshDog\keys.json file Set-DDConfiguration -DDAPIKey somekey -DDAppKey somekey .EXAMPLE # Write keys in an alternate file Set-DDConfiguration -DDAPIKey somekey -DDAppKey somekey -ConfigFilePath 'c:\file.json' .LINK .FUNCTIONALITY #> [CmdletBinding()] Param ( [Parameter( Mandatory=$true, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [string]$DDAPIKey, [Parameter( Mandatory=$true, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [string]$DDAppKey, [Parameter( Mandatory=$false, ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [string]$ConfigFilePath ) Process { $content = @{dd_api_key=$DDAPIKey;dd_app_key=$DDAppKey}| ConvertTo-Json -ErrorAction stop Try { if ($ConfigFilePath) { Write-Verbose "The path $ConfigFilePath was specified, writting there" Set-Content -Path $ConfigFilePath -value $content -ErrorAction Stop | Out-Null } else { Write-Verbose "Trying to create the configuration file at default location" $ConfigFilePath = (Get-Item Env:APPDATA).value $ConfigFilePath += "\PoshDog\keys.json" New-Item -ItemType Directory -Path (Split-Path $ConfigFilePath) -Force -ErrorAction Stop | Out-Null Set-Content -Path $ConfigFilePath -Value $Content -ErrorAction Stop | Out-Null } Write-Verbose "File $ConfigFilePath was successfully written to disk" Write-Output "Configuration file successfully written at $ConfigFilePath" } Catch { Throw "Could not write to file, got this instead: $_" } } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/New-DDMonitor.ps1
New-DDMonitor.ps1
function New-DDMonitor { <# .SYNOPSIS Create a new Datadog monitor by using parameters or by providing a custom object. .DESCRIPTION .PARAMETER MonitorObject A Datadog Monitor object. Can be created from scratch or retrieved with Get-DDMonitor, edited and fed to New-DDMonitor. If it's the later, the commandlet will make sure that only supported properties are supplied by removing others. Incompatible with all other parameters. .PARAMETER Type The type of the monitor, chosen from: metric alert, service check, event alert. .PARAMETER Query The monitor query to notify on with syntax varying depending on what type of monitor you are creating. The syntax varies depending on the -Type parameter. .PARAMETER Name The name of the alert. Default value is dynamic and based on the query. .PARAMETER Message A message to include with notifications for this monitor. Email notifications can be sent to specific users by using the same '@username' notation as events. .PARAMETER Message A message to include with notifications for this monitor. Email notifications can be sent to specific users by using the same '@username' notation as events. .PARAMETER Tags A list of tags to associate with your monitor, as string or array of strings .PARAMETER Options A hashtable of options for the monitor. There are options that are common to all types as well as options that are specific to certain monitor types. .EXAMPLE # Use a simple custom object $obj=[PSCustomObject]@{type='metric alert'; query='avg(last_5m):sum:system.net.bytes_rcvd{*} > 10000'} .EXAMPLE # Create a more comple custom object $query='avg(last_5m):sum:system.net.bytes_rcvd{*} > 10000' $name='Created from scratch' $type='metric alert' $message = @" This is a long message You better read it all! "@ $tags=@('frontend','webapp') $options=@{'timeout_h'='12';'locked'='True'} $obj=[PSCustomObject]@{type=$type;query=$query;name=$name;message=$message;options=$options} New-DDMonitor -MonitorObject $obj .EXAMPLE # Use parameters to create a monitor New-DDMonitor -Type 'metric alert' -Query 'avg(last_5m):sum:system.net.bytes_rcvd{*} > 100' .LINK http://docs.datadoghq.com/api/?lang=console#monitor-create .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID", ParameterSetName="New-DDMonitor:ByPipeline" )] [ValidateNotNullOrEmpty()] [PSCustomObject]$MonitorObject, [Parameter( Position=0, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="The type of the monitor, chosen from: metric alert, service check, event alert", ParameterSetName="New-DDMonitor:ByCommandLine" )] [ValidateSet("metric alert", "service check", "event alert")] [ValidateNotNullOrEmpty()] [String]$Type, [Parameter( Position=1, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="The monitor query to notify on with syntax varying depending on what type of monitor you are creating.", ParameterSetName="New-DDMonitor:ByCommandLine" )] [ValidateNotNullOrEmpty()] [string]$Query, [Parameter( Position=2, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="The name of the alert. Default value is dynamic and based on the query", ParameterSetName="New-DDMonitor:ByCommandLine" )] [ValidateNotNullOrEmpty()] [string]$Name, [Parameter( Position=3, ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="A message to include with notifications for this monitor", ParameterSetName="New-DDMonitor:ByCommandLine" )] [ValidateNotNullOrEmpty()] [string]$Message, [Parameter( ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="A list of tags to associate with your monitor, as string or array of strings", ParameterSetName="New-DDMonitor:ByCommandLine" )] [ValidateNotNullOrEmpty()] [string[]]$Tags, [Parameter( ValueFromPipeline=$False, ValueFromPipelineByPropertyName=$False, ValueFromRemainingArguments=$false, Mandatory=$False, HelpMessage="A dictionary of options for the monitor.", ParameterSetName="New-DDMonitor:ByCommandLine" )] [ValidateNotNullOrEmpty()] [Hashtable]$Options ) process { if ($PSCmdlet.ParameterSetName -eq "New-DDMonitor:ByCommandLine") { $Body = @{} # From http://stackoverflow.com/questions/21559724/getting-all-named-parameters-from-powershell-including-empty-and-set-ones $ParameterList = (Get-Command -Name $MyInvocation.InvocationName).Parameters; foreach ($key in $ParameterList.keys) { $var = Get-Variable -Name $key -ErrorAction SilentlyContinue; if($var.value) { Write-Verbose "New-DDMonitor: Parameter $($var.name) was detected, adding it to the request body" $Body.Add($($var.name).ToLower(),$($var.value)) } } $result = New-DDQuery -EndPoint "/monitor" -Method 'Post' -Body $($Body | ConvertTo-Json) -RequiresApplicationKey -ErrorAction Stop } else { Write-Verbose "New-DDMonitor: An object was passed by pipeline" $result = New-DDQuery -EndPoint "/monitor" -Method 'Post' -Body $($MonitorObject | ConvertTo-Json) -RequiresApplicationKey -ErrorAction Stop } # Build the default property set $defaultDisplaySet = 'id', 'name', 'type', 'query', 'message', 'options', 'tags', 'created' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Add-DDTag.ps1
Add-DDTag.ps1
function Add-DDTag { <# .SYNOPSIS Add tags to a host. .DESCRIPTION .PARAMETER Hostname A hostname as shown on Datadog's Infrastructure List page. .Parameter Tags String or array of strings representing the tags to apply to the host. .PARAMETER Source Specify a source for the tags. Valid sources are: nagios, hudson, jenkins, users, feed, chef, puppet, git, bitbucket, fabric, capistrano. .EXAMPLE # Add a tag 'role:frontend' coming from Nagios to host 'myhost' Add-DDTag -Hostname 'myhost' -Tags 'role:frontend' -Source 'nagios' .LINK http://docs.datadoghq.com/api/?lang=console#tags-add .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( Position=0, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True )] [Alias('Computername')] [ValidateNotNullOrEmpty()] [string]$Hostname, [Parameter( Position=1, Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$True )] [ValidateNotNullOrEmpty()] [string[]]$Tags, [Parameter( Position=2, Mandatory=$False, ValueFromPipeline=$False, ValueFromRemainingArguments=$True )] [ValidateNotNullOrEmpty()] [ValidateSet('nagios', 'hudson', 'jenkins', 'users', 'feed', 'chef', 'puppet', 'git', 'bitbucket', 'fabric', 'capistrano' )] [string]$Source ) process { $Body = @{} $Body.Add('tags',$Tags) if ($Source) { $Body.Add('source',$Source) } $result = New-DDQuery -EndPoint "/tags/hosts/$Hostname" -Method 'Post' -Body ($Body | ConvertTo-Json) -RequiresApplicationKey -ErrorAction Stop $defaultDisplaySet = 'tags' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/poshdog/0.0.5/Public/Edit-DDMonitor.ps1
Edit-DDMonitor.ps1
function Edit-DDMonitor { <# .SYNOPSIS Edit a Datadog monitor .DESCRIPTION .PARAMETER MonitorObject # A Datadog Monitor object. Can be created from scratch or retrieved with Get-DDMonitor, edited and fed to Edit-DDMonitor. If it's the later, the commandlet will make sure that only supported properties are supplied by removing others. The only required property is query. .EXAMPLE # Edit an existing object $m = Get-DDMonitor -All | Select -First 1 $m += ' - EDITED' Edit-DDMonitor -MonitorObject $m .EXAMPLE # Edit an existing object and pass it by the pipeline $m = Get-DDMonitor -All | Select -First 1 $m += ' - EDITED' $m | Edit-DDMonitor .EXAMPLE # Create a custom object and pass it to the commandlet $o=[PSCustomObject]@{id = '869861'; query = 'avg(last_5m):sum:system.net.bytes_rcvd{*} > 10000'; name = 'CREATED FROM SCRATCH' } $o | Edit-DDMonitor .LINK http://docs.datadoghq.com/api/?lang=console#monitor-edit .FUNCTIONALITY #> [CmdletBinding()] param ( [Parameter( Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ValueFromRemainingArguments=$false, Mandatory=$True, HelpMessage="A Datadog Monitor ID" )] [PSCustomObject]$MonitorObject ) process { $MonitorId = $MonitorObject.id if (!$MonitorId) { Throw "The object does not contain an id property" } $EditedMonitorObject = @{} $ValidProperties = @("name", "options", "message", "query", "tags") foreach ($property in $MonitorObject.PSObject.Properties) { Write-Verbose "Edit-DDMonitor: Looking at property $($property.name)" if ($ValidProperties -contains $property.name) { Write-Verbose "Edit-DDMonitor: Adding property $($property.name) to the EditedMonitorObject" $EditedMonitorObject.add($($property.name),$($property.value)) } else { Write-Verbose "Edit-DDMonitor: Property $($property.name) is NOT valid, removing it" } } $result = New-DDQuery -EndPoint "/monitor/$MonitorId" -Method 'Put' -Body $($EditedMonitorObject | ConvertTo-Json) -RequiresApplicationKey -ErrorAction Stop #Build the default property set $defaultDisplaySet = 'id', 'name', 'type', 'query', 'message', 'options', 'modified' $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet) $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet) $result | Add-Member MemberSet PSStandardMembers $PSStandardMembers return $result } }
PowerShellCorpus/PowerShellGallery/DebugPx/1.0.3.14/functions/Disable-EnterDebuggerCommand.ps1
Disable-EnterDebuggerCommand.ps1
<############################################################################# The DebugPx module provides a set of commands that make it easier to debug PowerShell scripts, functions and modules. These commands leverage the native debugging capabilities in PowerShell (the callstack, breakpoints, error output and the -Debug common parameter) and provide additional functionality that these features do not provide, enabling a richer debugging experience. Copyright 2016 Kirk Munro Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #############################################################################> <# .SYNOPSIS Disables the breakpoint command. .DESCRIPTION The Disable-EnterDebuggerCommand command disables the breakpoint command in your PowerShell environment. .PARAMETER WhatIf Shows what would happen if the command was run unrestricted. The command is run, but any changes it would make are prevented, and text descriptions of those changes are written to the console instead. .PARAMETER Confirm Prompts you for confirmation before any system changes are made using the command. .INPUTS None .OUTPUTS None .NOTES When the breakpoint command is enabled, invoking breakpoint, bp, or Enter-Debugger may result in a script that is running stopping on a breakpoint on that line. For more information, invoke Get-Help breakpoint. .EXAMPLE PS C:\> Disable-EnterDebuggerCommand PS C:\> Get-Service w* | breakpoint {$_.Name -eq 'wuauserv'} | Select-Object -ExpandProperty Name The first command disables the breakpoint command. When the next command is invoked, the services are output in the console and the breakpoint is skipped entirely. .EXAMPLE PS C:\> Disable-EnterDebuggerCommand PS C:\> & {'Before breakpoint'; breakpoint; 'After breakpoint'} The first command disables the breakpoint command. When the next command is invoked, the string "Before breakpoint" will be output to the console, and then the string "After breakpoint" will be output to the console. The breakpoint command does nothing in this scenario. .LINK Enable-EnterDebuggerCommand .LINK breakpoint #> function Disable-EnterDebuggerCommand { [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([System.Void])] [System.Diagnostics.DebuggerHidden()] param() try { #region Disable the breakpoint command breakpoint. Disable-PSBreakpoint -Breakpoint $script:EnterDebuggerCommandBreakpointMetadata['Breakpoint'] #endregion } catch { $PSCmdlet.ThrowTerminatingError($_) } } Export-ModuleMember -Function Disable-EnterDebuggerCommand if (-not (Get-Alias -Name Disable-BreakpointCommand -ErrorAction Ignore)) { New-Alias -Name Disable-BreakpointCommand -Value Disable-EnterDebuggerCommand Export-ModuleMember -Alias Disable-BreakpointCommand } if (-not (Get-Alias -Name dbpc -ErrorAction Ignore)) { New-Alias -Name dbpc -Value Disable-EnterDebuggerCommand Export-ModuleMember -Alias dbpc } # SIG # Begin signature block # MIIXyQYJKoZIhvcNAQcCoIIXujCCF7YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUlqVSfRHf7gK9SJtHaK7OfBnD # OoegghL8MIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV # UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu # dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQ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HYZd62NodeLa2qfNfnLFTHNhtOadI0cvdcWyUIYybsScW # IhuiGW8HcsKrB/RLLD4LsTRMAXldbB7uspsXueKrUVMgpJh8Cevz3a+NSxq9A+rx # 5N6gWFgooGYQxo1wNbSH8iStkEOvuU2/kRqDfu0k10xkdDKcXh8lupxS8UWB9zK0 # qyGx54zM8e4xFpuBMVAnW0POwoywSneMX5LAA36nU6BYjf24u+GvKtE6jngz # SIG # End signature block
PowerShellCorpus/PowerShellGallery/DebugPx/1.0.3.14/functions/Enable-EnterDebuggerCommand.ps1
Enable-EnterDebuggerCommand.ps1
<############################################################################# The DebugPx module provides a set of commands that make it easier to debug PowerShell scripts, functions and modules. These commands leverage the native debugging capabilities in PowerShell (the callstack, breakpoints, error output and the -Debug common parameter) and provide additional functionality that these features do not provide, enabling a richer debugging experience. Copyright 2016 Kirk Munro Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #############################################################################> <# .SYNOPSIS Enables the breakpoint command. .DESCRIPTION The Enable-EnterDebuggerCommand command enables the breakpoint command in your PowerShell environment. .PARAMETER WhatIf Shows what would happen if the command was run unrestricted. The command is run, but any changes it would make are prevented, and text descriptions of those changes are written to the console instead. .PARAMETER Confirm Prompts you for confirmation before any system changes are made using the command. .INPUTS None .OUTPUTS None .NOTES When the breakpoint command is enabled, invoking breakpoint, bp, or Enter-Debugger may result in a script that is running stopping on a breakpoint on that line. For more information, invoke Get-Help breakpoint. .EXAMPLE PS C:\> Enable-EnterDebuggerCommand PS C:\> Get-Service w* | breakpoint {$_.Name -eq 'wuauserv'} | Select-Object -ExpandProperty Name The first command enables the breakpoint command. When the next command is invoked, a breakpoint will be hit when the Windows Update service is passed down the pipeline. .EXAMPLE PS C:\> Enable-EnterDebuggerCommand PS C:\> & {'Before breakpoint'; breakpoint; 'After breakpoint'} The first command enables the breakpoint command. When the next command is invoked, the string "Before breakpoint" will be output to the console, and then the debugger will stop on the breakpoint command. "After breakpoint" will only be output to the console when the debugger is told to step or continue execution. .LINK Disable-EnterDebuggerCommand .LINK breakpoint #> function Enable-EnterDebuggerCommand { [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([System.Void])] [System.Diagnostics.DebuggerHidden()] param() try { #region Enable the breakpoint command breakpoint. Enable-PSBreakpoint -Breakpoint $script:EnterDebuggerCommandBreakpointMetadata['Breakpoint'] #endregion } catch { $PSCmdlet.ThrowTerminatingError($_) } } Export-ModuleMember -Function Enable-EnterDebuggerCommand if (-not (Get-Alias -Name Enable-BreakpointCommand -ErrorAction Ignore)) { New-Alias -Name Enable-BreakpointCommand -Value Enable-EnterDebuggerCommand Export-ModuleMember -Alias Enable-BreakpointCommand } if (-not (Get-Alias -Name ebpc -ErrorAction Ignore)) { New-Alias -Name ebpc -Value Enable-EnterDebuggerCommand Export-ModuleMember -Alias ebpc } # SIG # Begin signature block # MIIXyQYJKoZIhvcNAQcCoIIXujCCF7YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUgMKh3s3+piTNqvKcno4QBA0s # YpCgghL8MIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAw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v7t9e1/ # 00QCVCQm7Oi22jANBgkqhkiG9w0BAQEFAASCAQAAXiVRVP2yfmpYzMPGrehkVfA+ # gspltvmLjXo87OCKIqGU6bF9HEmIlb9fEaLxvQnUO9+DBmWyui3d99OItP92NDAl # AZKEaWcIPEVoywuLjXBuhwDeKIBxhcEHyrAyaIzoZ8nQaWnV1yD1qkfmbWinzkaY # OMctBQTXZpnvBuQP7YuwWh+HO6gOP1TlnJ7+TuZ746k1wHHX+JSzwGxHdNCumbUq # +kTchhFpjhbMLy5bR89eam338yDdClH0xgPZIfgjWy06S1MZDADW2kBIhjjllWbV # bEOS/I7ef/BXwIQFizm7uEpFQpjhv5BHPR7CSCQg1TMCbpRdpglzEcQ041Xo # SIG # End signature block
PowerShellCorpus/PowerShellGallery/DebugPx/1.0.3.14/functions/Get-CommandDebugMode.ps1
Get-CommandDebugMode.ps1
<############################################################################# The DebugPx module provides a set of commands that make it easier to debug PowerShell scripts, functions and modules. These commands leverage the native debugging capabilities in PowerShell (the callstack, breakpoints, error output and the -Debug common parameter) and provide additional functionality that these features do not provide, enabling a richer debugging experience. Copyright 2016 Kirk Munro Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #############################################################################> <# .SYNOPSIS Gets the current debug mode for a command. .DESCRIPTION The Get-CommandDebugMode command gets the current debug mode for a command. Debug modes include DebuggerHidden and DebuggerStepThrough. .INPUTS String .OUTPUTS DebugPx.CommandDebugMode .NOTES The Get-/Set-CommandDebugMode commands are used to manage the debug mode settings on Windows PowerShell functions and filters. They have no effect on other types of commands. When a command is in DebuggerHidden mode, the debugger will not step into that command. When a command is in DebuggerStepThrough mode, the debugger will step through that command into other commands that it invoked that are not hidden from the debugger, without stepping into the lines within that command. To enable DebuggerHidden or DebuggerStepThrough on a function or script block, set the System.Diagnostics.DebuggerHidden or System.Diagnostics.DebuggerStepThrough attributes for that function or script block, respectively. .EXAMPLE PS C:\> Get-CommandDebugMode This command returns the current debug mode for all functions and filters that are available in PowerShell. .EXAMPLE PS C:\> Get-CommandDebugMode -Module DebugPx This command returns the current debug mode for all functions and filters that are exported by the DebugPx module. .LINK Set-CommandDebugMode .LINK Get-Command #> function Get-CommandDebugMode { [CmdletBinding()] [OutputType('DebugPx.CommandDebugMode')] [System.Diagnostics.DebuggerHidden()] param( # Gets the debug mode for commands with the specified name. Enter a name or name pattern. Wildcards are permitted. [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [System.String[]] $Name = '*', # Gets the debug mode for commands that came from the specified modules. Enter the names of modules, or pass in module objects. [Parameter(Position=1, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias('ModuleName')] [System.String[]] $Module ) begin { try { #region Find the DebuggerHidden and DebuggerStepThrough properties, whether they are public or not. $debuggerHiddenProperty = [System.Management.Automation.ScriptBlock].GetProperty('DebuggerHidden',[System.Reflection.BindingFlags]'Public,NonPublic,Instance') $debuggerStepThroughProperty = [System.Management.Automation.ScriptBlock].GetProperty('DebuggerStepThrough',[System.Reflection.BindingFlags]'Public,NonPublic,Instance') #endregion #region Define a hashtable to store exported module functions. $exportedModuleFunctions = @{} #endregion } catch { $PSCmdlet.ThrowTerminatingError($_) } } process { try { #region If the Module parameter is used, look up the list of exported functions in the module and prepare to splat the parameter later. $moduleParameter = @{} if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Module')) { $moduleParameter['Module'] = $Module if (-not $exportedModuleFunctions.ContainsKey($Module)) { foreach ($item in Get-Module -Name $Module -ListAvailable) { $exportedModuleFunctions[$item.Name] = $item.ExportedFunctions.Keys } } } #endregion #region Process any functions or filters that match our search criteria. foreach ($command in Get-Command -CommandType Function,Filter -Name $Name -ErrorAction Ignore @moduleParameter) { #region Skip any non-exported functions when processing modules. if (-not [System.String]::IsNullOrEmpty($command.ModuleName) -and $exportedModuleFunctions.ContainsKey($command.ModuleName) -and ($exportedModuleFunctions[$command.ModuleName] -notcontains $command.Name)) { continue } #endregion #region Now return custom objects that contain the debug mode information that was requested. # You must "prime the pump" by walking through the Attributes collection before you check # the values of DebuggerHidden or DebuggerStepThrough properties. Otherwise, the value of # the boolean properties may report incorrectly (bug in PowerShell?). foreach ($attribute in $command.ScriptBlock.Attributes) {} # Once the pump is primed, we can return objects containing command debug mode information. [pscustomobject]@{ PSTypeName = 'DebugPx.CommandDebugMode' Name = $command.Name DebuggerHidden = $debuggerHiddenProperty.GetValue($command.ScriptBlock) DebuggerStepThrough = $debuggerStepThroughProperty.GetValue($command.ScriptBlock) } #endregion } #endregion } catch { $PSCmdlet.ThrowTerminatingError($_) } } } Export-ModuleMember -Function Get-CommandDebugMode if (-not (Get-Alias -Name gcmdm -ErrorAction Ignore)) { New-Alias -Name gcmdm -Value Get-CommandDebugMode Export-ModuleMember -Alias gcmdm } # SIG # Begin signature block # MIIXyQYJKoZIhvcNAQcCoIIXujCCF7YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUKAPzwm+WtN9Cu7hJxQ8GGjyN # DLegghL8MIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMj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b3DQEJBDEWBBQWO1AsWZZJirmi # Qw2nk8bOBb5PmjANBgkqhkiG9w0BAQEFAASCAQAZya7SDc2FghF9tT8rEnTS9yhU # LvWS7yAKfLOir3NWhOohWGfgButZtvfY5EVvjyFY9A6dgxuc+NJFq+IqsnQbN/Ai # nlZvUvjnJ8e4boIpv6iMCNrCP0TCMf2xeXEEOPE6BRE4ZlwuJ/NeXCfqEequhujC # 2hmoJRzjm/vNxbD5y4jbFMvS0Eyws8VO/a/DlfoOicPJ2fuKZF31qh5yIukJTlNB # QbNQg54cPo3TuaWRhA8EPQDZjnRhwEJCZwaREXvP4LTjiiGdNqicJT3h9iWJI3Z6 # VhNr0Z6tLiEOiJH6E84suvuxelUuM46/haWsq+ngl6WPyX5hFI2EfWqVFO1r # SIG # End signature block
PowerShellCorpus/PowerShellGallery/DebugPx/1.0.3.14/functions/Set-CommandDebugMode.ps1
Set-CommandDebugMode.ps1
<############################################################################# The DebugPx module provides a set of commands that make it easier to debug PowerShell scripts, functions and modules. These commands leverage the native debugging capabilities in PowerShell (the callstack, breakpoints, error output and the -Debug common parameter) and provide additional functionality that these features do not provide, enabling a richer debugging experience. Copyright 2016 Kirk Munro Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #############################################################################> <# .SYNOPSIS Sets the current debug mode for a command. .DESCRIPTION The Set-CommandDebugMode command sets the current debug mode for a command. Debug modes include DebuggerHidden and DebuggerStepThrough. .PARAMETER WhatIf Shows what would happen if the command was run unrestricted. The command is run, but any changes it would make are prevented, and text descriptions of those changes are written to the console instead. .PARAMETER Confirm Prompts you for confirmation before any system changes are made using the command. .INPUTS String .OUTPUTS None .NOTES The Get-/Set-CommandDebugMode commands are used to manage the debug mode settings on Windows PowerShell functions and filters. They have no effect on other types of commands. When a command is in DebuggerHidden mode, the debugger will not step into that command. When a command is in DebuggerStepThrough mode, the debugger will step through that command into other commands that it invoked that are not hidden from the debugger, without stepping into the lines within that command. To enable DebuggerHidden or DebuggerStepThrough on a function or script block, set the System.Diagnostics.DebuggerHidden or System.Diagnostics.DebuggerStepThrough attributes for that function or script block, respectively. .EXAMPLE PS C:\> Set-CommandDebugMode -Module FormatPx -DebuggerHidden This command sets the debug mode for all functions in the FormatPx module to DebuggerHidden. By invoking this command, you're instructing the PowerShell debugger to keep these command internals hidden from the debugger, such that the debugger will not step into them. .EXAMPLE PS C:\> function Invoke-ScriptBlock {param([ScriptBlock]$ScriptBlock) breakpoint; $ScriptBlock.Invoke()} PS C:\> Invoke-ScriptBlock {'When you run this, the debugger will stop inside the Invoke-ScriptBlock function on the breakpoint. Press c to let it finish executing.'} PS C:\> Set-CommandDebugMode -Name Invoke-ScriptBlock -DebuggerHidden PS C:\> Invoke-ScriptBlock {'This time the debugger will skip over any breakpoints in the Invoke-ScriptBlock function because the internals are hidden from the debugger, but it will still stop on breakpoints in the script block passed into the function because that script block is not hidden from the debugger. Press c to let it finish executing.'; breakpoint} The first command creates a function that invokes a script block that is passed into it. This function has a breakpoint set on the first line. The second command invokes that function, which stops on a breakpoint, as expected. After pressing c to continue, you can invoke the third command. The third command configures that function so that its internals are hidden from the debugger. The last command invokes the function again, but this time the breakpoint inside the function is ignored because it is hidden from the debugger. Note however that breakpoints in the script block that it invokes are not ignored unless those script blocks themselves have the debugger hidden attribute set on them. .EXAMPLE PS C:\> function Test-Function {'Command 1'; 'Command 2'} PS C:\> function Test-DebuggerStepThrough {'Press s twice to step into the next command and note how you can only step into Test-Function when the DebuggerStepThrough attribute is not present or when that attribute is present and there is a breakpoint in that function. Press c to let it finish executing.'; breakpoint; Test-Function} PS C:\> Test-DebuggerStepThrough PS C:\> Set-CommandDebugMode -Name Test-Function -DebuggerStepThrough PS C:\> Test-DebuggerStepThrough PS C:\> function Test-Function {'Command 1'; breakpoint; 'Command 2'} PS C:\> Set-CommandDebugMode -Name Test-Function -DebuggerStepThrough PS C:\> Test-DebuggerStepThrough The first command creates a test function with two commands. The second command creates a test function to see how the DebuggerStepThrough attribute works. The third command invokes that function, and you can step into the first function using the debugger. The fourth command configures Test-Function such that the debugger will not step into it unless a breakpoint is set. The fifth command invokes the Test-DebuggerStepThrough function again, and this time stepping results in the debugger stepping over Test-Function. The sixth command redefines the test function with a breakpoint. The seventh command sets DebuggerStepThrough mode on that redefined function. When the last command is invoked, and you step through using the debugger, the debugger will step over the Test-Function however since there is a breakpoint, the debugger stops on the breakpoint in that function. From this point, stepping through the rest of the function works as normal. .EXAMPLE PS C:\> Set-CommandDebugMode -Module DebugPx -DebuggerHidden:$false -DebuggerStepThrough:$false This command removes all debug mode options from all functions and filters that are exported by the DebugPx module. With these options removed, the debugger can then step into these functions if necessary. .EXAMPLE PS C:\> Set-CommandDebugMode -Module DebugPx This command removes all debug mode options from all functions and filters that are exported by the DebugPx module. With these options removed, the debugger can then step into these functions if necessary. .LINK Get-CommandDebugMode .LINK Get-Command #> function Set-CommandDebugMode { [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([System.Void])] [System.Diagnostics.DebuggerHidden()] param( # Sets the debug mode for commands with the specified name. Enter a name or name pattern. Wildcards are permitted. [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [System.String[]] $Name = '*', # Sets the debug mode for commands that came from the specified modules. Enter the names of modules, or pass in module objects. [Parameter(Position=1, ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias('ModuleName')] [System.String[]] $Module, [Parameter()] [System.Management.Automation.SwitchParameter] $DebuggerHidden = $false, [Parameter()] [System.Management.Automation.SwitchParameter] $DebuggerStepThrough = $false ) begin { try { #region Find the DebuggerHidden and DebuggerStepThrough properties, whether they are public or not. $debuggerHiddenProperty = [System.Management.Automation.ScriptBlock].GetProperty('DebuggerHidden',[System.Reflection.BindingFlags]'Public,NonPublic,Instance') $debuggerStepThroughProperty = [System.Management.Automation.ScriptBlock].GetProperty('DebuggerStepThrough',[System.Reflection.BindingFlags]'Public,NonPublic,Instance') #endregion #region Define a hashtable to store exported module functions. $exportedModuleFunctions = @{} #endregion } catch { $PSCmdlet.ThrowTerminatingError($_) } } process { try { #region If the Module parameter is used, look up the list of exported functions in the module and prepare to splat the parameter later. $moduleParameter = @{} if ($PSCmdlet.MyInvocation.BoundParameters.ContainsKey('Module')) { $moduleParameter['Module'] = $Module if (-not $exportedModuleFunctions.ContainsKey($Module)) { foreach ($item in Get-Module -Name $Module -ListAvailable) { $exportedModuleFunctions[$item.Name] = $item.ExportedFunctions.Keys } } } #endregion #region Process any functions or filters that match our search criteria. foreach ($command in Get-Command -CommandType Function,Filter -Name $Name -ErrorAction Ignore @moduleParameter) { #region Skip any non-exported functions when processing modules. if (-not [System.String]::IsNullOrEmpty($command.ModuleName) -and $exportedModuleFunctions.ContainsKey($command.ModuleName) -and ($exportedModuleFunctions[$command.ModuleName] -notcontains $command.Name)) { continue } #endregion #region Now update the debug mode for commands acccording to whether or not ShouldProcess allows it. if ($PSCmdlet.ShouldProcess($command)) { # You must "prime the pump" by walking through the Attributes collection before you check # the values of DebuggerHidden or DebuggerStepThrough properties. Otherwise, the value of # the boolean properties may report incorrectly (bug in PowerShell?). foreach ($attribute in $command.ScriptBlock.Attributes) {} # Once the pump is primed, you can set the values and they will stick. $debuggerHiddenProperty.SetValue($command.ScriptBlock,$DebuggerHidden.IsPresent) $debuggerStepThroughProperty.SetValue($command.ScriptBlock,$DebuggerStepThrough.IsPresent) } #endregion } #endregion } catch { $PSCmdlet.ThrowTerminatingError($_) } } } Export-ModuleMember -Function Set-CommandDebugMode if (-not (Get-Alias -Name scmdm -ErrorAction Ignore)) { New-Alias -Name scmdm -Value Set-CommandDebugMode Export-ModuleMember -Alias scmdm } # SIG # Begin signature block # MIIXyQYJKoZIhvcNAQcCoI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nn93JpMpBTTi9aQchk6DlNmB9CF2Ime0O4nU0w9vuroU5jOK+p171OM8hD # LfaFXiIgN7/9EttVnjFc8yAScqbIcm83HT9Lf26s6vuTbLjGLnac7LKEDf5hHKGC # AgswggIHBgkqhkiG9w0BCQYxggH4MIIB9AIBATByMF4xCzAJBgNVBAYTAlVTMR0w # GwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEwMC4GA1UEAxMnU3ltYW50ZWMg # VGltZSBTdGFtcGluZyBTZXJ2aWNlcyBDQSAtIEcyAhAOz/Q4yP6/NW4E2GqYGxpQ # MAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3 # DQEJBTEPFw0xNjA0MDIxNDA1MTRaMCMGCSqGSIb3DQEJBDEWBBTNXENcQNvYn1iI # lQD0n5aPRlVrXjANBgkqhkiG9w0BAQEFAASCAQA1uePEBGjbDwU6Ai/s/mnOqddm # /vIdI5oteOAbpb7gsPx/DXUGFpXPinNfe6xml6p1j9NDv0cYdcogDX9c2owCWnkS # SJefZDux6v+1tNKQ0X47wjqRn4yJIwEG8xxK9mkDJh3ilse4FCSX9ccsdJGkm1o3 # gl50ielJ2nyzfoVmoAxsA3b7WeajFWToyuZutuYWQLuE1YGvfo9MRD0cCyAXYXYO # eIjXg+yavjtDrMI44Yv9UxNfalAPm3hGsjaRokh88286bcJaCoHxrwCpYexHECle # McX7avpTfLirlCL9idM5NfY6jerDNt9eJlIl77dDr+MBFDfl9TTfaEMzd/BW # SIG # End signature block
PowerShellCorpus/PowerShellGallery/DebugPx/1.0.3.14/scripts/Export-BinaryModule.ps1
Export-BinaryModule.ps1
<############################################################################# The DebugPx module provides a set of commands that make it easier to debug PowerShell scripts, functions and modules. These commands leverage the native debugging capabilities in PowerShell (the callstack, breakpoints, error output and the -Debug common parameter) and provide additional functionality that these features do not provide, enabling a richer debugging experience. Copyright 2016 Kirk Munro Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #############################################################################> # Export the cmdlets that are defined in the nested module Export-ModuleMember -Cmdlet Debug-Module,Enter-Debugger,Invoke-IfDebug # Define a dgmo alias so that debugging modules is more natural. if (-not (Get-Alias -Name dgmo -ErrorAction Ignore)) { New-Alias -Name dgmo -Value Debug-Module Export-ModuleMember -Alias dgmo } # Define a breakpoint alias so that setting breakpoints is more natural. Set-Alias -Force -Name breakpoint -Value Enter-Debugger Export-ModuleMember -Alias breakpoint # Define a bp alias so that setting breakpoints is even easier. if (-not (Get-Alias -Name bp -ErrorAction Ignore)) { New-Alias -Name bp -Value breakpoint Export-ModuleMember -Alias bp } # Define an ifdebug alias so that using conditional debug blocks is more natural. Set-Alias -Force -Name ifdebug -Value Invoke-IfDebug Export-ModuleMember -Alias ifdebug # SIG # Begin signature block # MIIXyQYJKoZIhvcNAQcCoIIXujCCF7YCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU4pRyngLo1q3wihpio9a+dw/3 # p0OgghL8MIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B # AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG # A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh # d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg # Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMj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ihrnFet+DANBgkqhkiG9w0BAQEFAASCAQCc4ewtWI+JvLImVT3qWrQq7ciK # 0wI17rEPraW7iu+zx/eP9EfZ/K/oBVdyx/7Wh00+D68xpc2xiI00y+3mqHJ3JNbY # 66sV9UDHO0LvnVtzXiE5h3ensRc8NVLEmA4h8uGhJnhzJ43KMjNsPRYvZtZSl+ez # su6jtai6iMYMhOLCsW36pgD9fKBH8oTEI8AGXZkGaydXtuco8sg20FR+zPEeiW0A # mMsjqosq+pLcMKFBw9PS95Coze7aGB5z+AEx7kJD8uhiOe45MLBKxC+sfk+5uNA0 # +hH0CiobQtGiNKrdtCUCAS+/NBv2jsOiQS7PM+F/AAeHRwC0VkSqY/g5QLiD # SIG # End signature block
PowerShellCorpus/PowerShellGallery/RyanAirPS/1.0/Get-RyanAirSchedules.ps1
Get-RyanAirSchedules.ps1
<# .SYNOPSIS This commandlet queries ryan air api for rountrip available flights .DESCRIPTION This commandlet queries ryan air api for available flights during specific dates .PARAMETER Origin The IATA code of origin airport .PARAMETER Destination The IATA code of destination airport .EXAMPLE Get-RyanAirSchedules -Origin BRU .EXAMPLE Get-RyanAirSchedules -Origin BRU -Destination SXF .EXAMPLE @("BRU","CLR") | Get-RyanAirSchedules .EXAMPLE Get-RyanAirSchedules -Origin BRU -Destination SXF .EXAMPLE @("BRU","ATH") | Get-RyanAirSchedules -Destination SXF .EXAMPLE Get-RyanAirSchedules -Origin BRU .INPUTS The IATA code of origin airport .OUTPUTS The available flights #> function Get-RyanAirSchedules{ [CmdletBinding()] [OutputType([PSObject[]])] param( [Parameter(Mandatory=$true,ValueFromPipeline = $true)] [string] $Origin, [Parameter(Mandatory=$false)] [string] $Destination=$null ) Begin { } Process { try { if($Destination) { $ryanAirApi="https://api.ryanair.com/timetable/3/schedules/$Origin/$Destination/period" } else { $ryanAirApi="https://api.ryanair.com/timetable/3/schedules/$origin/periods" } Write-Debug $ryanAirApi $json=Invoke-RestMethod -Uri "$ryanAirApi" -Method Get Write-Debug $json $schedules=@() $hash=@{} if($Destination) { $hash["Origin"]=$Origin $hash["Destination"]=$Destination $hash["Months"]=$json.months $hash["MonthsFromToday"]=$json.monthsFromToday $hash["FirstFlightDate"]=Get-Date $json.firstFlightDate $hash["LastFlightDate"]=Get-Date $json.lastFlightDate New-Object PSObject –Prop $hash } else { $destinations=@() $json|Get-Member |Where-Object {$_.MemberType -eq "NoteProperty"} |ForEach-Object { $scheduleJson=$json| Select -ExpandProperty $_.Name $hash["Origin"]=$Origin $hash["Destination"]=$_.Name $hash["Months"]=$scheduleJson.months $hash["MonthsFromToday"]=$scheduleJson.monthsFromToday $hash["FirstFlightDate"]=Get-Date $scheduleJson.firstFlightDate $hash["LastFlightDate"]=Get-Date $scheduleJson.lastFlightDate New-Object PSObject –Prop $hash } } } catch { Write-Error $_ } } End { } }
PowerShellCorpus/PowerShellGallery/RyanAirPS/1.0/Get-RyanAirCommon.ps1
Get-RyanAirCommon.ps1
<# .SYNOPSIS This commandlet queries ryan air api for countries, cities and airports .DESCRIPTION This commandlet queries ryan air api for countries, cities and airports .PARAMETER Type One of the Countries, Cities or Airports .EXAMPLE Get-RyanAirCommon -Type Countries .EXAMPLE Get-RyanAirCommon -Type Cities .EXAMPLE Get-RyanAirCommon -Type Airports .OUTPUTS An array of Countries or Cities or Airports #> function Get-RyanAirCommon{ [OutputType([PSObject[]])] Param ( [Parameter( Mandatory = $true, Position = 0 )] [ValidateSet("Countries","Cities","Airports")] [string]$Type ) Begin { } Process { switch ($Type) { "Countries" { $embedded+="countries" } "Cities" { $embedded+="cities" } "Airports" { $embedded+="airports" } } $ryanAirApi="https://api.ryanair.com/aggregate/3/common?embedded=$embedded&market=en-gb" Write-Verbose "ryanAirApi=$ryanAirApi" $json=Invoke-RestMethod -Uri "$ryanAirApi" -Method Get switch ($Type) { "Countries" { foreach($countryJson in $json.countries) { $countryHash=@{} $countryHash["Code"]=$countryJson.code $countryHash["Name"]=$countryJson.name $countryHash["Currency"]=$countryJson.currency New-Object PSObject –Prop $countryHash } } "Cities" { foreach($cityJson in $json.cities) { $cityHash=@{} $cityHash["Code"]=$cityJson.code $cityHash["Name"]=$cityJson.name $cityHash["CountryCode"]=$cityJson.countryCode New-Object PSObject –Prop $cityHash } } "Airports" { foreach($airportJson in $json.airports) { $airportHash=@{} $airportHash["IataCode"]=$airportJson.iataCode $airportHash["Name"]=$airportJson.name $airportHash["Base"]=[boolean]$airportJson.base $airportHash["CountryCode"]=$airportJson.countryCode $airportHash["CityCode"]=$airportJson.cityCode New-Object PSObject –Prop $airportHash } } } } End { } }
PowerShellCorpus/PowerShellGallery/RyanAirPS/1.0/Get-RyanAirFlights.ps1
Get-RyanAirFlights.ps1
<# .SYNOPSIS This commandlet queries ryan air api for rountrip available flights .DESCRIPTION This commandlet queries ryan air api for available flights during specific dates .PARAMETER Origin The IATA code of origin airport .PARAMETER Destination The IATA code of destination airport .PARAMETER DateOut The date of departure .PARAMETER DateIN The date of return .PARAMETER FlexDaysOut The number of extra days to include with DateOut .PARAMETER FlexDaysIn The number of extra days to include with DateIn .EXAMPLE $date=Get-Date Get-RyanAirFlights -Origin BRU -Destination SXF -DateOut $date .EXAMPLE $date=Get-RyanAirFlights Get-RyanAirAvailability -Origin BRU -Destination SXF -DateOut $date -FlexDaysOut 1 .EXAMPLE $date=Get-Date Get-RyanAirFlights -Origin BRU -Destination SXF -DateOut $date -DateIn ($date.AddDays(2)) .EXAMPLE $date=Get-Date Get-RyanAirFlights -Origin BRU -Destination SXF -DateOut $date -FlexDaysOut 1 -DateIn ($date.AddDays(2)) -FlexDaysIn 1 .INPUTS The IATA code of origin airport .OUTPUTS The available flights #> function Get-RyanAirFlights{ [CmdletBinding()] [OutputType([PSObject[]])] param( [Parameter(Mandatory=$true,ValueFromPipeline = $true,ParameterSetName = "Default Param Set")] [Parameter(Mandatory=$true,ValueFromPipeline = $true,ParameterSetName="RoundTrip")] [string] $Origin, [Parameter(Mandatory=$true,ParameterSetName = "Default Param Set")] [Parameter(Mandatory=$true,ParameterSetName="RoundTrip")] [string] $Destination, [Parameter(Mandatory=$true,ParameterSetName = "Default Param Set")] [Parameter(Mandatory=$true,ParameterSetName="RoundTrip")] [DateTime] $DateOut, [Parameter(Mandatory=$false,ParameterSetName = "Default Param Set")] [Parameter(Mandatory=$false,ParameterSetName="RoundTrip")] [int] $FlexDaysOut, [Parameter(Mandatory=$true,ParameterSetName="RoundTrip")] [DateTime] $DateIn, [Parameter(Mandatory=$false,ParameterSetName="RoundTrip")] [int] $FlexDaysIn ) Begin { $ryanAirApi="https://desktopapps.ryanair.com/en-gb/availability" Write-Debug $ryanAirApi $queryParameters=@{ "DateOut"=$DateOut.ToString("yyyy-MM-dd") } if($Destination) { $queryParameters["Destination"]=$Destination } if($DateIn) { $queryParameters["DateIn"]=$DateIn.ToString("yyyy-MM-dd") $queryParameters["RoundTrip"]=$true } if($FlexDaysOut) { $queryParameters["FlexDaysOut"]=$FlexDaysOut } if($FlexDaysIn) { $queryParameters["FlexDaysIn"]=$FlexDaysIn } } Process { try { $queryParameters["Origin"]=$Origin Write-Debug $queryParameters $json=Invoke-RestMethod -Uri "$ryanAirApi" -Body $queryParameters -Method Get Write-Debug $json $flights=@() foreach($tripJson in $json.trips) { foreach($dateJson in $tripJson.dates) { foreach($flightJson in $dateJson.flights) { $flightHash=@{} $flightHash["Origin"]=$tripJson.origin $flightHash["Destination"]=$tripJson.destination $flightHash["Date"]=$dateJson.dateOut $flightHash["FlightNumber"]=$flightJson.flightNumber $flightHash["From"]=Get-Date $flightJson.time[0] $flightHash["To"]=Get-Date $flightJson.time[1] $flightHash["FromUTC"]=Get-Date $flightJson.timeUTC[0] $flightHash["ToUTC"]=Get-Date $flightJson.timeUTC[1] $flightHash["Duration"]=$flightJson.duration $flightHash["FaresLeft"]=$flightJson.faresLeft $flightHash["InfantsLeft"]=$flightJson.infantsLeft $flightHash["RegularFare"]=$flightJson.regularFare.fares |Where-Object {$_.Type -eq "ADT"}|Select-Object -ExpandProperty amount $flightHash["BusinessFare"]=$flightJson.businessFare.fares |Where-Object {$_.Type -eq "ADT"}|Select-Object -ExpandProperty amount New-Object PSObject –Prop $flightHash } } } } catch { Write-Error $_ } } End { } }
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_New-OneDriveFolder.ps1
Func_New-OneDriveFolder.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function New-OneDriveFolder { <# .SYNOPSIS Create a new folder in the specified location. .EXAMPLE New-OneDriveFolder -Path 'path/to/folder' .EXAMPLE New-OneDriveFolder -Name 'NewFolder' -ParentId '1234ABC!123' .EXAMPLE 'path/to/folder1', 'path/to/folder2' | odmkdir .NOTES The API will create all folders in the path, even if they don't exist. This command does not fail if the folder already exists. #> [CmdletBinding(DefaultParameterSetName='Folder Path')] [Alias('odnf','odmkdir')] [OutputType([PsObject])] Param ( # API path of the new folder. [Parameter(Mandatory=$False, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Folder Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # Name of the folder [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Parent ID')] [string]$Name, # Id of the parent [Parameter(Mandatory=$True, Position=2, ValueFromPipelineByPropertyName=$True, ParameterSetName='Parent ID')] [Alias('id')] [string]$ParentId, # By default, if folder exists is fails. Set to overwrite. [Parameter(Mandatory=$False)] [switch]$Force ) Process { if ($ParentId) { $parent = joinPath $PSOD.drive.itemRoot $ParentId $parent = joinPath $parent 'children' } else { $parent = joinPath $PSOD.drive.pathRoot (Split-Path $Path) $parent = joinPath $parent 'children' ':/' $Name = Split-Path $Path -Leaf } Write-Verbose "Folder name: $Name" Write-Verbose "Parent path: $parent" $body = [ordered]@{ name = $Name folder = @{} } | ConvertTo-Json Write-Verbose "Request body:`n$body" if ($Force) { $parent += '?@name.conflictBehavior=replace' } else { $parent += '?@name.conflictBehavior=fail' } $rsp = Invoke-OneDriveApiCall -Path $parent ` -Method POST ` -Body $body if ($rsp) { Write-Output $rsp | newOneDriveItem } } } Export-ModuleMember -Function 'New-OneDriveFolder' -Alias 'odnf', 'odmkdir'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Get-OneDriveChildItem.ps1
Func_Get-OneDriveChildItem.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Get-OneDriveChildItem { <# .SYNOPSIS Gets the items in the specified path, or that are children of the specified Item ID from the OneDrive API. By default gets the items in the default drive's root. Can be used with either a relative path, or an item id. .EXAMPLE Get-OneDriveChildItem # Gets all the items in the default drive's root. .EXAMPLE "Documents" | Get-OneDriveChildItem .EXAMPLE Get-OneDriveChildItem -ItemId "1234ABC!123" #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odgci','odls')] [OutputType([PsObject])] Param ( # API resource path. [Parameter(Mandatory=$False, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId, # Gets the items in the specified path, and all child items. [Parameter(Mandatory=$False)] [switch]$Recurse ) Process { if ($ItemId) { $rsp = Get-OneDriveItem -ItemId (joinPath $ItemId 'children') } else { $rsp = Get-OneDriveItem -Path (joinPath $Path 'children' ':/') } Write-Output $rsp if ($Recurse) { $rsp | ? { [int]$_.folder.childCount -gt 0 } | % { Get-OneDriveChildItem -ItemId $_.id -Recurse } } } } Export-ModuleMember -Function 'Get-OneDriveChildItem' -Alias 'odgci', 'odls'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/PSOD.helpers.ps1
PSOD.helpers.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ ################################### Helpers #################################### Function joinPath($Path1, $Path2, $Delimiter = '/') { if (!$Path1) { $Path1 = "" } if (!$Path2) { $Path2 = "" } return $Path1.Replace('\','/').TrimEnd('/'), $Path2.Replace('\','/').TrimStart('/') ` -join $Delimiter } ################################################################################ Function newOneDriveItem { <# .SYNOPSIS Creates a new PSOD.OneDriveItem object from an API response. .EXAMPLE New-OneDriveItem $response .EXAMPLE $response | New-OneDriveItem #> [CmdletBinding()] [OutputType([PsObject])] Param ( # [Parameter(Mandatory=$True, ValueFromPipeline=$True, Position=1)] [PsObject]$ApiResponse ) Process { if ($ApiResponse.PsObject.Properties['value']) { $val = $ApiResponse.value } else { $val = $ApiResponse } $val | % { $_.PsObject.TypeNames.Insert(0, "PSOD.OneDriveItem") Write-Output $_ } } } ################################################################################
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Invoke-OneDriveApiCall.ps1
Func_Invoke-OneDriveApiCall.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Invoke-OneDriveApiCall { <# .SYNOPSIS Wrapper for Invoke-RestMethod to send commands to the OneDrive API. .EXAMPLE Invoke-OneDriveApiCall -Path $path .EXAMPLE 'drive/root:/Documents:/children' | Invoke-OneDriveApiCall #> [CmdletBinding()] [OutputType([PsObject])] Param ( # API resource path. [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)] [Alias("ApiUrl", "Resource")] [string]$Path, # The method used for the API request. [Parameter(Mandatory=$False, ValueFromPipelineByPropertyName=$True)] [Microsoft.PowerShell.Commands.WebRequestMethod]$Method, # Data to be sent as part of the API request. [Parameter(Mandatory=$False, ValueFromPipelineByPropertyName=$True)] $Body, # Gets the content of the request from the specified file. [Parameter(Mandatory=$False, ValueFromPipelineByPropertyName=$True)] [string]$InFile, # Saves the response to the specified path. [Parameter(Mandatory=$False, ValueFromPipelineByPropertyName=$True)] [string]$OutFile, # Additional headers for the request. [Parameter(Mandatory=$False, ValueFromPipelineByPropertyName=$True)] [hashtable]$AdditionalRequestHeaders ) Begin { if ((Get-Date) -ge $PSOD.token.ExpiryDate) { Write-Verbose "Requesting new token." $token = Get-OneDriveAuthToken if ($token) { $PSOD.token = $token } else { Write-Error "Unable to authenticate with OneDrive. Please check the configuration file." break } } } Process { $requestUri = joinPath $PSOD.api.url $Path Write-Verbose "Request URI:`n$requestUri" $requestHeaders = @{ Authorization = "bearer $($PSOD.token)" Accept = 'application/json' } if ($AdditionalRequestHeaders) { $requestHeaders += $AdditionalRequestHeaders } $irmParams = @{ Uri = $requestUri Headers = $requestHeaders ContentType = 'application/json' } if ($Method) { $irmParams['Method'] = $Method } if ($Body) { $irmParams['Body'] = $Body } if ($InFile) { $irmParams['InFile'] = $InFile } if ($OutFile) { $irmParams['OutFile'] = $OutFile } try { $rsp = Invoke-RestMethod @irmParams } catch [System.Net.WebException] { $errorMessage = $_.ErrorDetails.Message | ConvertFrom-Json Write-Error "'$Path' - $($errorMessage.error.message). (Error code: $($errorMessage.error.code))" $httpResponse = $_.Exception.Response Write-Verbose "HTTP status code : $($httpResponse.StatusCode.value__)" Write-Verbose "HTTP status description : $($httpResponse.StatusDescription)" } catch { Write-Error $_.Exception.Message } Write-Output $rsp } } Export-ModuleMember -Function 'Invoke-OneDriveApiCall'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Get-OneDriveItem.ps1
Func_Get-OneDriveItem.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Get-OneDriveItem { <# .SYNOPSIS Gets item (folder/file) details from the OneDrive API. By default gets the default drive's root. Can be used with either a relative path, or an item id. .EXAMPLE Get-OneDriveItem # return the root .EXAMPLE "Documents" | Get-OneDriveItem .EXAMPLE Get-OneDriveItem -ItemId "1234ABC!123" #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odgi')] [OutputType([PsObject])] Param ( # API resource path. [Parameter(Mandatory=$False, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId ) Process { if ($ItemId) { $p = joinPath $PSOD.drive.itemRoot $ItemId } else { $p = joinPath $PSOD.drive.pathRoot $Path } Write-Verbose "Sending request to '$p'" $rsp = Invoke-OneDriveApiCall -Path $p if ($rsp) { Write-Output $rsp | newOneDriveItem } } } Export-ModuleMember -Function 'Get-OneDriveItem' -Alias 'odgi'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Remove-OneDriveItem.ps1
Func_Remove-OneDriveItem.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Remove-OneDriveItem { <# .SYNOPSIS Deletes the specified item. .EXAMPLE Remove-OneDriveItem "Documents/doc-to-remove.pdf" .EXAMPLE "Documents/Office Lens/0000001.docx" | Remove-OneDriveItem .EXAMPLE Remove-OneDriveItem -ItemId "1234ABC!123" #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odrm', 'oddel')] [OutputType([boolean])] Param ( # API resource path. [Parameter(Mandatory=$False, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId ) Process { if ($ItemId) { $p = joinPath $PSOD.drive.itemRoot $ItemId } else { $p = joinPath $PSOD.drive.pathRoot $Path } Write-Verbose "Sending request to '$p'" $rsp = Invoke-OneDriveApiCall -Path $p -Method DELETE if ($rsp -is [string]) { Write-Output $True } else { Write-Output $False } } } Export-ModuleMember -Function 'Remove-OneDriveItem' -Alias 'odrm', 'oddel'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Get-OneDriveContent.ps1
Func_Get-OneDriveContent.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Get-OneDriveContent { <# .SYNOPSIS Downloads the contents of a file and saves it to the specified destination. If no destination is specified, the current directory is used. .EXAMPLE Get-OneDriveContent -Path "Documents\onedrive file.txt" .EXAMPLE Get-OneDriveContent -ItemId "1234ABC!123" #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odgc')] [OutputType()] Param ( # API resource path. [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId, # The path to the destination directory / file. [Parameter(Mandatory=$False, Position=2)] [string]$Destination ) Begin { if ($Destination) { if (!(Test-Path $Destination)) { Write-Error "The destination directory '$Destination' does not exist." break } } else { $Destination = Get-Location } } Process { if ($ItemId) { $item = Get-OneDriveItem -ItemId $ItemId } else { $item = Get-OneDriveItem -Path $Path } if ($item.Type -eq 'folder') { $newDestination = Join-Path $Destination $item.Name if (Test-Path $newDestination) { Write-Error "Destination directory '$newDestination' already exists." } else { New-Item -ItemType Directory -Path $newDestination | Out-Null if (Test-Path $newDestination) { Get-OneDriveChildItem -id $item.id | % { Get-OneDriveContent -ItemId $_.id -Destination $newDestination } } else { Write-Warning "Unable to create new directory '$newDestination'." } } } else { $outFile = Join-Path $Destination $item.Name $dloadPath = joinPath $PSOD.drive.itemRoot $item.Id $dloadPath = joinPath $dloadPath 'content' Invoke-OneDriveApiCall -Path $dloadPath -OutFile $outFile } } } Export-ModuleMember -Function 'Get-OneDriveContent' -Alias 'odgc'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Move-OneDriveItem.ps1
Func_Move-OneDriveItem.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Move-OneDriveItem { <# .SYNOPSIS Move a OneDrive item from one parent to another. .EXAMPLE "Documents/file.pdf" | Move-OneDriveItem "destination/directory" .EXAMPLE Move-OneDriveItem -ItemID "85B75A4CE0397EE!1492" -destination "destination/directory" .EXAMPLE Move-OneDriveItem "Documents/DirToMove" "new/parent" #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odmv', 'odmove')] [OutputType([PsObject])] Param ( # API resource path. [Parameter(Mandatory=$False, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId, # The path to the destination directory / file. [Parameter(Mandatory=$True, Position=2)] [string]$Destination ) Process { if ($ItemId) { $p = joinPath $PSOD.drive.itemRoot $ItemId } else { $p = joinPath $PSOD.drive.pathRoot $Path } Write-Verbose "Sending request to '$p'" $body = [ordered]@{ parentReference = @{ path = "/" + (joinPath $PSOD.drive.pathRoot $Destination) } } | ConvertTo-Json Write-Verbose "Request body:`n$body" $rsp = Invoke-OneDriveApiCall -Path $p ` -Method PATCH ` -Body $body ` -AdditionalRequestHeaders @{ Prefer = "respond-async" } if ($rsp) { Write-Output $rsp | newOneDriveItem } } } Export-ModuleMember -Function 'Move-OneDriveItem' -Alias 'odmv', 'odmove'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Get-OneDriveAuthToken.ps1
Func_Get-OneDriveAuthToken.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Get-OneDriveAuthToken { <# .SYNOPSIS Gets an authorization token for the application defined in the PSOD.config.json or onedrive.opt file. By default, the onedrive.readwrite permissions are requested. .EXAMPLE Get-OneDriveAuthToken .EXAMPLE Get-OneDriveAuthToken -AuthenticationScopes 'onedrive.readwrite', 'offline_access' #> [CmdletBinding()] [OutputType("PSOD.OneDriveToken")] Param ( # The scope(s) to request authentication for. Default is 'onedrive.readwrite'. [Parameter(Mandatory=$False)] [string[]]$AuthenticationScopes = @('onedrive.readwrite'), # The response type to request from the authentication server. Either token or code. Default is token. [Parameter(Mandatory=$False)] [string]$ResponseType = 'token' ) Begin { $DEFAULT_FORM_WIDTH = 420 $DEFAULT_FORM_HEIGHT = 680 $DEFAULT_BROWSER_WIDTH = 400 $DEFAULT_BROWSER_HEIGHT = 660 } End { $requestUri = $PSOD.auth.signInUrl $requestUri += "?client_id=$($PSOD.auth.applicationId)" $requestUri += "&scope=$($AuthenticationScopes -join ' ')" $requestUri += "&response_type=$ResponseType" $requestUri += "&redirect_url=$($PSOD.auth.callbackUrl)" Write-Verbose "$requestUri" $form = New-Object -TypeName System.Windows.Forms.Form -Property @{ Width = $DEFAULT_FORM_WIDTH Height = $DEFAULT_FORM_HEIGHT } $browser = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{ Width = $DEFAULT_BROWSER_WIDTH Height = $DEFAULT_BROWSER_HEIGHT Url = $requestUri } $tempVar = [guid]::NewGuid().Guid New-Variable -Name $tempVar -Scope Global $browser.Add_DocumentCompleted({ ${Global:$tempVar} = [System.Web.HttpUtility]::UrlDecode($browser.Url.AbsoluteUri) Write-Verbose "Response URI: ${Global:$tempVar}" switch (${Global:$tempVar}) { {$_ -match 'error=|access_token=[^&]'} { $form.Close() } {$browser.DocumentTitle -eq 'Navigation Canceled'} { $form.Close() } } }) $form.Controls.Add($browser) $form.ShowDialog() | Out-Null $form.Activate() if (${Global:$tempVar} -match 'error=') { $errId = [regex]::Match(${Global:$tempVar}, "error=(.+?)&").Groups[1].Value $errMsg = [regex]::Match(${Global:$tempVar}, "error_description=(.+?)(&|$)").Groups[1].Value Write-Error "$errMsg ($errId)" } elseif (${Global:$tempVar} -eq $requestUri) { Write-Error "An error occured when navigating to the login page." } else { $token = New-OneDriveToken -ResponseUrl ${Global:$tempVar} } Remove-Variable -Name $tempVar -Scope Global Write-Output $token } } Export-ModuleMember -Function 'Get-OneDriveAuthToken'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_New-OneDriveToken.ps1
Func_New-OneDriveToken.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function New-OneDriveToken { <# .SYNOPSIS Creates a new OneDrive Authentication token from an API response. .EXAMPLE New-OneDriveToken -ResponseUrl $ApiResponse #> [CmdletBinding(DefaultParameterSetName='API Response')] [Alias('odnt')] [OutputType([PsObject])] Param ( # The API response URL from an authentication request. [Parameter(Mandatory=$True, ValueFromPipeline=$True, Position=1, ParameterSetName='API Response')] [string]$ResponseUrl, # The access token. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Token Details')] [string]$AccessToken, # Type of token requested. Either bearer or code. [Parameter(Mandatory=$True, Position=2, ValueFromPipelineByPropertyName=$True, ParameterSetName='Token Details')] [Alias("TokenType")] [string]$Type, # Number of seconds that the token is valid for. [Parameter(Mandatory=$True, Position=3, ValueFromPipelineByPropertyName=$True, ParameterSetName='Token Details')] [int]$ExpiresIn, # The requested authentication scope(s). [Parameter(Mandatory=$True, Position=4, ValueFromPipelineByPropertyName=$True, ParameterSetName='Token Details')] [string[]]$Scope, # The user ID of the requestor. [Parameter(Mandatory=$True, Position=5, ValueFromPipelineByPropertyName=$True, ParameterSetName='Token Details')] [string]$UserId ) Process { if ($ResponseUrl) { $AccessToken = [regex]::Match($ResponseUrl, "access_token=(.+?)&").Groups[1].Value $Type = [regex]::Match($ResponseUrl, "token_type=(.+?)&").Groups[1].Value $ExpiresIn = [regex]::Match($ResponseUrl, "expires_in=(.+?)&").Groups[1].Value $Scope = [regex]::Match($ResponseUrl, "scope=(.+?)&").Groups[1].Value -split " " $UserId = [regex]::Match($ResponseUrl, "user_id=(.+?)(&|$)").Groups[1].Value } $nt = [pscustomobject]@{ AccessToken = $AccessToken Type = $Type ExpiresIn = $ExpiresIn Created = Get-Date Scope = $Scope UserId = $UserId } $nt.PsObject.TypeNames.Insert(0, "PSOD.OneDriveToken") Write-Output $nt } } Export-ModuleMember -Function 'New-OneDriveToken' -Alias 'odnt'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Set-OneDriveContent.ps1
Func_Set-OneDriveContent.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Set-OneDriveContent { <# .SYNOPSIS Uploads a new file, or update the contents of an existing OneDrive file. .EXAMPLE Set-OneDriveContent -Path "Documents" -Source 'C:\Temp\test.pdf' -Force .EXAMPLE Set-OneDriveContent -Path "Documents/aNewDirectory/" -Source 'C:\Temp\test.pdf' .EXAMPLE Set-OneDriveContent -Path "Documents/another-name.pdf" -Source 'C:\Temp\test.pdf' .EXAMPLE Set-OneDriveContent -ItemId "85B75A4CE0397EE!1450" -Source 'C:\Temp\test.pdf' .NOTES Add a '/' to the end of the path if you're uploading to a directory that does not exist; otherwise, the path leaf is considered the remote file name. #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odsc')] [OutputType([PsObject])] Param ( # API resource destination path. [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API destination item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId, # The local path of the source file or directory. [Parameter(Mandatory=$True, Position=2)] [string]$Source, # By default, remote items are not overwritten. Set this to overwrite. [Parameter(Mandatory=$False)] [switch]$Force ) Process { $upload = Get-Item -Path $Source if (!$upload) { return } Write-Verbose "Source path: $($upload.FullName)" if ($ItemId) { $remote = Get-OneDriveItem -ItemId $ItemId if (!$remote) { return } } else { $remote = Get-OneDriveItem -Path $Path -ErrorAction SilentlyContinue } if (!$remote -and !$Path.EndsWith('/')) { # Assume path leaf is the file name even if no extension $uploadPath = joinPath $PSOD.drive.pathRoot $Path $uploadPath = joinPath $uploadPath 'content' ':/' } elseif ($remote.Type -eq 'folder' -or $Path.EndsWith('/')) { if ($ItemId) { $uploadPath = joinPath $PSOD.drive.itemRoot $ItemId $uploadPath = joinPath $uploadPath 'children' $uploadPath = joinPath $uploadPath $upload.Name $uploadPath = joinPath $uploadPath 'content' } else { $uploadPath = joinPath $PSOD.drive.pathRoot $Path $uploadPath = joinPath $uploadPath $upload.Name $uploadPath = joinPath $uploadPath 'content' ':/' } } else { if ($ItemId) { $uploadPath = joinPath $PSOD.drive.itemRoot $remote.ParentId $uploadPath = joinPath $uploadPath $remote.Name ':/' $uploadPath = joinPath $uploadPath 'content' ':/' } else { $uploadPath = joinPath $PSOD.drive.pathRoot $Path $uploadPath = joinPath $uploadPath 'content' ':/' } } Write-Verbose "Destination path: $uploadPath" if ($Force) { $uploadPath += '?@name.conflictBehavior=replace' } else { $uploadPath += '?@name.conflictBehavior=fail' } $rsp = Invoke-OneDriveApiCall -Path $uploadPath ` -Method PUT ` -InFile $upload.FullName if ($rsp) { Write-Output $rsp | newOneDriveItem } } } Export-ModuleMember -Function 'Set-OneDriveContent' -Alias 'odsc'
PowerShellCorpus/PowerShellGallery/PSOD/1.0/Func_Copy-OneDriveItem.ps1
Func_Copy-OneDriveItem.ps1
################################################################################ # Author : Antony Onipko # Copyright : (c) 2016 Antony Onipko. All rights reserved. ################################################################################ # This work is licensed under the # Creative Commons Attribution-ShareAlike 4.0 International License. # To view a copy of this license, visit # https://creativecommons.org/licenses/by-sa/4.0/ ################################################################################ Function Copy-OneDriveItem { <# .SYNOPSIS Copies a one drive item from one path to another. .EXAMPLE "Documents/file.pdf" | Copy-OneDriveItem "destination/directory" .EXAMPLE Copy-OneDriveItem -ItemID "85B75A4CE0397EE!1492" -destination "destination/directory" .EXAMPLE Copy-OneDriveItem "Documents/DirToCopy" "destination/directory" #> [CmdletBinding(DefaultParameterSetName='Item Path')] [Alias('odcp', 'odcopy')] [OutputType([PsObject])] Param ( # API resource path. [Parameter(Mandatory=$False, Position=1, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item Path')] [Alias('ApiUrl', 'Resource')] [string]$Path, # API item ID. [Parameter(Mandatory=$True, Position=1, ValueFromPipelineByPropertyName=$True, ParameterSetName='Item ID')] [Alias('id')] [string]$ItemId, # The path to the destination directory / file. [Parameter(Mandatory=$True, Position=2)] [string]$Destination ) Process { if ($ItemId) { $p = joinPath $PSOD.drive.itemRoot $ItemId $p = joinPath $p 'action.copy' } else { $p = joinPath $PSOD.drive.pathRoot $Path $p = joinPath $p 'action.copy' ':/' } Write-Verbose "Sending request to '$p'" $body = [ordered]@{ parentReference = @{ path = "/" + (joinPath $PSOD.drive.pathRoot $Destination) } } | ConvertTo-Json Write-Verbose "Request body:`n$body" $rsp = Invoke-OneDriveApiCall -Path $p ` -Method POST ` -Body $body ` -AdditionalRequestHeaders @{ Prefer = "respond-async" } # TODO: Implement a way to check when a copy is finished. if ($rsp) { Write-Output $rsp } } } Export-ModuleMember -Function 'Copy-OneDriveItem' -Alias 'odcp', 'odcopy'
PowerShellCorpus/PowerShellGallery/gpowmi/1.0.6.0/build.ps1
build.ps1
#build module script [cmdletbinding()] Param( [string]$ModuleFileName = "GPOWMI.psm1" , [string]$ProjectUrl = "https://bitbucket.org/torgro/gpowmi/overview" , [switch]$Major , [switch]$Minor , [switch]$LoadModule ) cd C:\Users\Tore\Dropbox\SourceTreeRepros\gpowmi -ErrorAction SilentlyContinue $F = $MyInvocation.InvocationName Write-Verbose -Message "$F - Starting build, getting files" if(Get-Module -Name GPOWMI) { Write-Verbose "$F - Removing FIMautomation snapIn and Powerfim module" Remove-FIMsnapin -Verbose Remove-Module PowerFIM -Verbose:$false } $fileList = Get-ChildItem -Filter .\functions\*.ps1 | where name -NotLike "*Tests*" $ModuleName = (Get-ChildItem -Path $ModuleFileName -ErrorAction SilentlyContinue).BaseName if(-not $ModuleName) { $ModuleName = $ModuleFileName.Replace(".psm1","") } Write-Verbose -Message "$f - Modulename is $ModuleName" $ExportedFunctions = New-Object System.Collections.ArrayList $fileList | foreach { Write-Verbose -Message "$F - Function = $($_.BaseName) added" [void]$ExportedFunctions.Add($_.BaseName) } $ModuleLevelFunctions = $null foreach($function in $ModuleLevelFunctions) { Write-Verbose -Message "$f - Checking function $function" if($ExportedFunctions -contains $function) { write-verbose -Message "$f - Removing function $function from exportlist" $ExportedFunctions.Remove($function) } else { Write-Verbose -Message "$f - Exported functions does not contain $function" } } Write-Verbose -Message "$f - Constructing content of module file" [string]$ModuleFile = "" foreach($file in $fileList) { $filecontent = Get-Content -Path $file.FullName -raw $filecontent = "$filecontent`n`n" $ModuleFile += $filecontent } [System.Version]$ver = $null if((Test-Path -Path $moduleFileName -ErrorAction SilentlyContinue) -eq $true) { Write-Verbose -Message "$f - Getting version info" Import-Module -Name ".\$ModuleName.psd1" -Verbose:$false $ver = (Get-Module $Modulename).Version Remove-Module $ModuleName -Verbose:$false #Remove-PSSnapin -Name FIMautomation -ErrorAction SilentlyContinue Write-Verbose -Message "$f - Removing previous version of $ModuleFileName" Remove-Item -Path $ModuleFileName } function Get-NextVersion { [cmdletbinding()] [outputtype([System.Version])] Param( [System.Version]$CurrentVersion , [switch]$Major , [switch]$Minor ) [System.Version]$newVersion = $null $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" if($Major) { Write-Verbose -Message "$F - Bumping Major version" $build = $CurrentVersion.Build $ma = $CurrentVersion.Major + 1 $mi = $CurrentVersion.Minor $newVersion = New-Object System.Version("$Ma.$Mi.$build.0") } if($Minor) { Write-Verbose -Message "$f - Bumping Minor version" $build = $CurrentVersion.Build $ma = $CurrentVersion.Major $mi = $CurrentVersion.Minor + 1 $newVersion = New-Object System.Version("$Ma.$Mi.$build.0") } if($Minor -and $Major) { Write-Verbose -Message "$f - Bumping Major and Minor version" $build = $CurrentVersion.Build $ma = $CurrentVersion.Major + 1 $mi = $CurrentVersion.Minor + 1 $newVersion = New-Object System.Version("$Ma.$Mi.$build.0") } if(-not $Minor -and -not $Major) { Write-Verbose -Message "$f - Bumping build version" $build = $CurrentVersion.Build + 1 $ma = $CurrentVersion.Major $mi = $CurrentVersion.Minor $newVersion = New-Object System.Version("$Ma.$Mi.$build.0") } return $newVersion } if(-not $ver) { Write-Verbose -Message "$f - No previous version found, creating new version" $ver = New-Object System.Version("1.0.0.0") } if($Major) { $ver = Get-NextVersion -CurrentVersion $ver -Major } if($Minor) { $ver = Get-NextVersion -CurrentVersion $ver -Minor } if($Minor -and $Major) { $ver = Get-NextVersion -CurrentVersion $ver -Minor -Major } if(-not $Minor -and -not $Major) { Write-Verbose -Message "$f - Defaults to bump build version" $ver = Get-NextVersion -CurrentVersion $ver } Write-Verbose -Message "$f - New version is $($ver.ToString())" Write-Verbose -Message "$f - Writing contents to modulefile" Set-Content -Path $ModuleFileName -Value $ModuleFile -Encoding UTF8 $ManifestName = "$((Get-ChildItem -Path $ModuleFileName -ErrorAction SilentlyContinue).BaseName).psd1" Write-Verbose -Message "$f - ManifestfileName is $ManifestName" if((Test-Path -Path $ManifestName -ErrorAction SilentlyContinue) -eq $true) { Write-Verbose -Message "$f - Removing previous version of $ManifestName" Remove-Item -Path $ManifestName } Write-Verbose -Message "$f - Creating manifestfile" $privateData = @{ PSdata = @{ Tags = @("Group Policy","ActiveDirectory","WMI","WMIFilter") LicenseUri = "" ProjectUri = "https://bitbucket.org/torgro/gpowmi/overview" IconUri = "" ReleaseNotes = "" } } $New_moduleManifest = @{ Path = $ManifestName Author = "Tore Groneng @toregroneng tore@firstpoint.no" CompanyName = "Firstpoint Bergen AS" Description = "Manage Group Policy WMIfilters with Powershell" ModuleVersion = $ver.ToString() FunctionsToExport = $ExportedFunctions RootModule = $ModuleFileName ProjectUri = $ProjectUrl Tags = @("Group Policy","ActiveDirectory","WMI","WMIFilter") Copyright = '(c) 2015 Tore Groneng @toregroneng tore@firstpoint.no. All rights reserved.' PowerShellVersion = '4.0' } #New-ModuleManifest -Path $ManifestName -Author "Tore Grøneng @toregroneng tore@firstpoint.no" -CompanyName "Sparebanken Vest AS" -ModuleVersion $ver.ToString() -FunctionsToExport $ExportedFunctions -RootModule $ModuleFileName New-ModuleManifest @New_moduleManifest Write-Verbose -Message "$f - Reading back content to contert to UTF8 (content management tracking)" Set-Content -Path $ManifestName -Value (Get-Content -Path $ManifestName -Raw) -Encoding UTF8 $Answer = "n" if(-not $LoadModule) { $Answer = Read-Host -Prompt "Load module $ModuleName? (Yes/No)" } if($Answer -eq "y" -or $Answer -eq "yes" -or $LoadModule) { Write-Verbose -Message "$f - Loading module" if(Test-Path -Path $ManifestName) { Import-Module $PSScriptRoot\$ManifestName } else { Write-Warning -Message "Modulefile $ManifestName not found, module not imported" } } else { Write-Verbose -Message "$f - Module not loaded" } Write-Verbose -Message "$f - END"
PowerShellCorpus/PowerShellGallery/gpowmi/1.0.6.0/Functions/Get-GPOWmiFilter.ps1
Get-GPOWmiFilter.ps1
function Get-GPOWmiFilter { <# .Synopsis Gets all Group Policy Filters or by name .DESCRIPTION This cmdlet depends on the GroupPolicy module .EXAMPLE Get-GPOWmiFilter Lists all (if any) WMIFilter configured in Group Policy Management .EXAMPLE Get-GPOWmiFilter -Name HR Get a WMIFilter named HR .EXAMPLE "HR" | Get-GPOWmiFilter Get a WMIFilter named HR using the pipeline .EXAMPLE "HR","AllClients" | Get-GPOWmiFilter Gets WMIFilters named HR and Allclients using the pipeline .INPUTS String (Name of WMIFilter) .OUTPUTS Microsoft.GroupPolicy.WmiFilter .NOTES Created by Tore.Groneng@firstpoint.no @ToreGroneng 2016 .ROLE Active Directory scripting .FUNCTIONALITY Linking GPOs with WMIFilters #> [cmdletbinding()] Param( [Parameter(ValueFromPipeline)] [string[]]$Name = "*" ) BEGIN { $f = $MyInvocation.InvocationName if(-not (Get-Module -Name GroupPolicy)) { Import-Module -Name GroupPolicy -ErrorAction Stop -Verbose:$false } Write-Verbose -Message "$f - START" $GPdomain = New-Object Microsoft.GroupPolicy.GPDomain $SearchFilter = New-Object Microsoft.GroupPolicy.GPSearchCriteria Write-Verbose -Message "$f - Searching for WmiFilters" $allWmiFilters = $GPdomain.SearchWmiFilters($SearchFilter) Write-Verbose -Message "$f - Found $($allWmiFilters.Count) filters" } PROCESS { foreach($FilterName in $Name) { Write-Verbose -Message "$f - Looking for $FilterName" $allWmiFilters | Where-Object Name -like $FilterName } } END { Write-Verbose -Message "$f - END" } }
PowerShellCorpus/PowerShellGallery/gpowmi/1.0.6.0/Functions/Set-GPOWmiFilter.ps1
Set-GPOWmiFilter.ps1
function Set-GPOWmiFilter { <# .Synopsis Links a Group Policy to a WMIFilter .DESCRIPTION This cmdlet depends on the GroupPolicy module. Apply a WMI filter to any Group Policy configured in Active Directory .EXAMPLE Set-GPOWmiFilter -WMIFilterName HR -GroupPolicyName MyGPO Links the WMIfilter named HR to the Group Policy MyGPO .EXAMPLE Set-GPOWmiFilter -WMIFilterName HR -GroupPolicyGUID ed3119f9-4038-464e-abdc-9202bfd24917 Links the WMIfilter named HR to the Group Policy with the specified GUID .EXAMPLE Get-GPOWmiFilter -Name HR | Set-GPOWmiFilter -GroupPolicyName MyGPO Get a WMIFilter named HR and applies it using the pipeline to the Group Policy MyGPO .OUTPUTS $null .NOTES Created by Tore.Groneng@firstpoint.no @ToreGroneng 2016 .ROLE Active Directory scripting .FUNCTIONALITY Linking GPOs with WMIFilters #> [cmdletbinding()] Param( [Parameter( ValueFromPipeline, ParameterSetName='ByWMIFilterObject')] [Microsoft.GroupPolicy.WmiFilter]$WMIfilter , [Parameter(ParameterSetName='ByWMIFilterName')] [Parameter(ParameterSetName='FilterByPolicyName')] [Parameter(ParameterSetName='FilterByPolicyGUID')] [string]$WMIFilterName , [Parameter(ParameterSetName='FilterByPolicyName')] [Parameter(ParameterSetName='ByWMIFilterObject')] [string]$GroupPolicyName , [Parameter(ParameterSetName='FilterByPolicyGUID')] [Parameter(ParameterSetName='ByWMIFilterObject')] [guid]$GroupPolicyGUID ) BEGIN { $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" Write-Verbose -Message "$f - Loading required module GroupPolicy" if(-not (Get-Module -Name GroupPolicy)) { Import-Module -Name GroupPolicy -ErrorAction Stop -Verbose:$false } $GPdomain = New-Object Microsoft.GroupPolicy.GPDomain $SearchFilter = New-Object Microsoft.GroupPolicy.GPSearchCriteria Write-Verbose -Message "$f - Searching for WmiFilters" $allWmiFilters = $GPdomain.SearchWmiFilters($SearchFilter) } PROCESS { if($WMIFilterName) { Write-Verbose -Message "$f - Finding WMI-filter with name $WMIFilterName" $WMIfilter = $allWmiFilters | Where-Object Name -eq $WMIFilterName if(-not $WMIfilter) { $msg = "Did not find a WMIfilter with name '$WMIFilterName'" Write-Verbose -Message "$f - ERROR - $msg" Write-Error -Message $msg -ErrorAction Stop } } $GroupPolicyObject = $null if($GroupPolicyName) { Write-Verbose -Message "$f - Finding Group Policy with name '$GroupPolicyName'" $GroupPolicyObject = Get-GPO -Name $GroupPolicyName if(-not $GroupPolicyObject) { $msg = "Unable to find GPO with Name '$GroupPolicyName'" Write-Verbose -Message "$f - ERROR - $msg" Write-Error -Message $msg -ErrorAction Stop } } if($GroupPolicyGUID) { Write-Verbose -Message "$f - Finding Group Policy with GUID '$GroupPolicyGUID'" $GroupPolicyObject = Get-GPO -Guid $GroupPolicyGUID if(-not $GroupPolicyObject) { $msg = "Unable to find GPO with GUID '$GroupPolicyGUID'" Write-Verbose -Message "$f - ERROR - $msg" Write-Error -Message $msg -ErrorAction Stop } } Write-Verbose -Message "$f - Applying filter with name '$($WMIfilter.Name)' to GPO '$($GroupPolicyObject.DisplayName)'" try { $GroupPolicyObject.WmiFilter = $WMIfilter } catch { $ex = $_.Exception Write-Verbose -Message "$f - EXCEPTION - $($ex.Message)" throw $ex } } END { Write-Verbose -Message "$f - END" } }
PowerShellCorpus/PowerShellGallery/DSCR_AutoLogon/2.0.1/Example/DSCR_AutoLogon_Example.ps1
DSCR_AutoLogon_Example.ps1
$output = 'C:\MOF' $ConfigurationData = @{ AllNodes = @( @{ NodeName = 'localhost' PsDscAllowPlainTextPassword = $true } ) } Configuration DSCR_AutoLogon_Example { param ( [Parameter(Mandatory)] [PSCredential] $AutoLogonCredential ) Import-DscResource -ModuleName DSCR_AutoLogon Node localhost { cAutoLogon AutoLogon_Example { Ensure = "Present" AutoLogonCredential = $AutoLogonCredential Encrypt = $true } } } DSCR_AutoLogon_Example -OutputPath $output -ConfigurationData $ConfigurationData -AutoLogonCredential (Get-Credential) #Test-DscConfiguration -Path $output -Verbose Start-DscConfiguration -Path $output -Verbose -Wait -Force
PowerShellCorpus/PowerShellGallery/DSCR_AutoLogon/2.0.1/Utils/LSAUtil.ps1
LSAUtil.ps1
# C# Code to P-invoke LSA functions. # This code is copied from PInvoke.net # http://www.pinvoke.net/default.aspx/advapi32.lsaretrieveprivatedata Add-Type @" using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace PInvoke.LSAUtil { public class LSAutil { [StructLayout (LayoutKind.Sequential)] private struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; public IntPtr Buffer; } [StructLayout (LayoutKind.Sequential)] private struct LSA_OBJECT_ATTRIBUTES { public int Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public uint Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } private enum LSA_AccessPolicy : long { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, POLICY_TRUST_ADMIN = 0x00000008L, POLICY_CREATE_ACCOUNT = 0x00000010L, POLICY_CREATE_SECRET = 0x00000020L, POLICY_CREATE_PRIVILEGE = 0x00000040L, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, POLICY_AUDIT_LOG_ADMIN = 0x00000200L, POLICY_SERVER_ADMIN = 0x00000400L, POLICY_LOOKUP_NAMES = 0x00000800L, POLICY_NOTIFICATION = 0x00001000L } [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaRetrievePrivateData ( IntPtr PolicyHandle, ref LSA_UNICODE_STRING KeyName, out IntPtr PrivateData ); [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaStorePrivateData ( IntPtr policyHandle, ref LSA_UNICODE_STRING KeyName, ref LSA_UNICODE_STRING PrivateData ); [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy ( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle ); [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaNtStatusToWinError ( uint status ); [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaClose ( IntPtr policyHandle ); [DllImport ("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaFreeMemory ( IntPtr buffer ); private LSA_OBJECT_ATTRIBUTES objectAttributes; private LSA_UNICODE_STRING localsystem; private LSA_UNICODE_STRING secretName; public LSAutil (string key) { if (key.Length == 0) { throw new Exception ("Key lenght zero"); } objectAttributes = new LSA_OBJECT_ATTRIBUTES (); objectAttributes.Length = 0; objectAttributes.RootDirectory = IntPtr.Zero; objectAttributes.Attributes = 0; objectAttributes.SecurityDescriptor = IntPtr.Zero; objectAttributes.SecurityQualityOfService = IntPtr.Zero; localsystem = new LSA_UNICODE_STRING (); localsystem.Buffer = IntPtr.Zero; localsystem.Length = 0; localsystem.MaximumLength = 0; secretName = new LSA_UNICODE_STRING (); secretName.Buffer = Marshal.StringToHGlobalUni (key); secretName.Length = (UInt16) (key.Length * UnicodeEncoding.CharSize); secretName.MaximumLength = (UInt16) ((key.Length + 1) * UnicodeEncoding.CharSize); } private IntPtr GetLsaPolicy (LSA_AccessPolicy access) { IntPtr LsaPolicyHandle; uint ntsResult = LsaOpenPolicy (ref this.localsystem, ref this.objectAttributes, (uint) access, out LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError (ntsResult); if (winErrorCode != 0) { throw new Exception ("LsaOpenPolicy failed: " + winErrorCode); } return LsaPolicyHandle; } private static void ReleaseLsaPolicy (IntPtr LsaPolicyHandle) { uint ntsResult = LsaClose (LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError (ntsResult); if (winErrorCode != 0) { throw new Exception ("LsaClose failed: " + winErrorCode); } } private static void FreeMemory (IntPtr Buffer) { uint ntsResult = LsaFreeMemory (Buffer); uint winErrorCode = LsaNtStatusToWinError (ntsResult); if (winErrorCode != 0) { throw new Exception ("LsaFreeMemory failed: " + winErrorCode); } } public void SetSecret (string value) { LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING (); if (value.Length > 0) { //Create data and key lusSecretData.Buffer = Marshal.StringToHGlobalUni (value); lusSecretData.Length = (UInt16) (value.Length * UnicodeEncoding.CharSize); lusSecretData.MaximumLength = (UInt16) ((value.Length + 1) * UnicodeEncoding.CharSize); } else { //Delete data and key lusSecretData.Buffer = IntPtr.Zero; lusSecretData.Length = 0; lusSecretData.MaximumLength = 0; } IntPtr LsaPolicyHandle = GetLsaPolicy (LSA_AccessPolicy.POLICY_CREATE_SECRET); uint result = LsaStorePrivateData (LsaPolicyHandle, ref secretName, ref lusSecretData); ReleaseLsaPolicy (LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError (result); if (winErrorCode != 0) { throw new Exception ("StorePrivateData failed: " + winErrorCode); } } public string GetSecret () { IntPtr PrivateData = IntPtr.Zero; IntPtr LsaPolicyHandle = GetLsaPolicy (LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION); uint ntsResult = LsaRetrievePrivateData (LsaPolicyHandle, ref secretName, out PrivateData); ReleaseLsaPolicy (LsaPolicyHandle); uint winErrorCode = LsaNtStatusToWinError (ntsResult); if (winErrorCode != 0) { throw new Exception ("RetreivePrivateData failed: " + winErrorCode); } LSA_UNICODE_STRING lusSecretData = (LSA_UNICODE_STRING) Marshal.PtrToStructure (PrivateData, typeof (LSA_UNICODE_STRING)); string value = Marshal.PtrToStringAuto (lusSecretData.Buffer).Substring (0, lusSecretData.Length / 2); FreeMemory (PrivateData); return value; } } } "@
PowerShellCorpus/PowerShellGallery/CommonUtilities/1.0/CommonUtilities.prepare.ps1
CommonUtilities.prepare.ps1
<# MIT License Copyright © 2016 by Gee Law Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Website: http://psguy.me/modules/CommonUtilities Preparation script. #> <# Native Win32 APIs for Switch-User. #> Add-Type -Name 'SwitchUser' -MemberDefinition '[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll", SetLastError=true)] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", SetLastError=true)] public static extern bool BringWindowToTop(IntPtr hWnd);' -Namespace '__3b043047842e4cfa94dbcb39a5ccf3e5';
PowerShellCorpus/PowerShellGallery/EzPath/0.2/EzPath/Remove-EzPath.ps1
Remove-EzPath.ps1
function Remove-EzPath () { [CmdletBinding()] Param () DynamicParam { $ParameterName = "Name" $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $true $ParameterAttribute.Position = 1 # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) # Generate and set the ValidateSet $usings = $Script:Data.UsedPaths $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($usings) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } BEGIN { $Name = $PsBoundParameters[$ParameterName] } PROCESS { $NewPath = $Script:Data.Unuse($Name) if ([String]::IsNullOrWhiteSpace($NewPath)) { Write-Output "Could not find using with key $Name!" return } if ($ENV:Path -eq $NewPath) { Write-Output "PATH has not changed" return } $ENV:Path = $NewPath Write-Output "PATH changed" } }
PowerShellCorpus/PowerShellGallery/EzPath/0.2/EzPath/Add-EzPath.ps1
Add-EzPath.ps1
function Add-EzPath () { [CmdletBinding()] Param () DynamicParam { $ParameterName = "Name" $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $true $ParameterAttribute.Position = 1 # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) # Generate and set the ValidateSet $usings = $Script:Data.AvailablePaths.Keys $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($usings) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } BEGIN { $Name = $PsBoundParameters[$ParameterName] } PROCESS { $NewPath = $Script:Data.Use($Name) if ([String]::IsNullOrWhiteSpace($NewPath)) { Write-Output "Could not find using with key $Name!" return } if ($ENV:Path -eq $NewPath) { Write-Output "PATH has not changed" return } $ENV:Path = $NewPath Write-Output "PATH changed" } }
PowerShellCorpus/PowerShellGallery/EzPath/0.2/EzPath/Import-EzPaths.ps1
Import-EzPaths.ps1
function Import-EzPaths () { [CmdletBinding()] Param ( # JSON File to import [Parameter(Mandatory = $False)] [String] $JsonFile = (Join-Path "$HOME" ".ezpaths.json"), # Clear before importing [Parameter(Mandatory = $False)] [Switch] $Clear ) PROCESS { if (-not (Test-Path $JsonFile)) { Write-Error "$JsonFile does not exist!" Return } $File = Get-Item -Path $JsonFile Write-Verbose "Reading paths from $File" $Config = (Get-Content $File | ConvertFrom-Json) $Keys = ($Config | Get-Member -MemberType *Property).Name | Sort-Object Write-Verbose "Found $($Keys.Count) keys: `n $([String]::Join(', ', $Keys))" if ($Clear) { $Script:Data.Clear() } foreach ($Key in $Keys) { $Script:Data.Add($Key, $Config.$Key) } } }
PowerShellCorpus/PowerShellGallery/EzPath/0.2/EzPath/EzPathData.ps1
EzPathData.ps1
class EzPathData { EzPathData() { $this.OriginalPath = $ENV:Path $this.AvailablePaths = @{} $this.UsedPaths = New-Object System.Collections.ArrayList } [HashTable] $AvailablePaths [System.Collections.ArrayList] $UsedPaths [String] $OriginalPath [String] BuildPath () { $Path = $this.OriginalPath foreach ($Key in $this.UsedPaths) { $Paths = $this.AvailablePaths.$Key [Array]::Reverse($Paths) foreach ($Entry in $Paths) { $Path = $Entry + ";" + $Path } } Return $Path } [Void] Add ([String] $Name, [String[]] $Paths) { if ($this.AvailablePaths.ContainsKey($Name)) { Write-Warning "Key $Name already exists!" Return } if ($Paths.Count -ne 0) { $this.AvailablePaths.Add($Name, $Paths) } } [String] Use ($Name) { if (-not $this.AvailablePaths.ContainsKey($Name)) { Return $null } if (-not $this.UsedPaths.Contains($Name)) { $this.UsedPaths.Add($Name) } Return $this.BuildPath() } [String] Unuse ($Name) { if (-not $this.AvailablePaths.ContainsKey($Name)) { Return $null } if ($this.UsedPaths.Contains($Name)) { $this.UsedPaths.Remove($Name) } Return $this.BuildPath() } [String] Reset () { $this.UsedPaths.Clear() Return $this.BuildPath() } [Void] Clear () { $this.AvailablePaths.Clear() $this.UsedPaths.Clear() } }
PowerShellCorpus/PowerShellGallery/EzPath/0.2/EzPath/Commands.ps1
Commands.ps1
. "$PSScriptRoot\Import-EzPaths.ps1" . "$PSScriptRoot\Add-EzPath.ps1" . "$PSScriptRoot\Remove-EzPath.ps1" function Reset-EzPaths () { $env:Path = $Script:Data.Reset() Write-Output "PATH reset" } function Get-EzPaths () { $Keys = $Script:Data.AvailablePaths.Keys | Sort-Object foreach ($Key in $Keys) { $Template = "[ ] $Key" $Color = (Get-Host).UI.RawUI.ForegroundColor # When used, star it and make it green if ($Script:Data.UsedPaths.Contains($Key)) { $Template = "[*] $Key" $Color = "Green" } Write-Host $Template -ForegroundColor $Color } }
PowerShellCorpus/PowerShellGallery/PowerForensics/1.1.1/BinShredDemo/Import-HelloWorldBitmap.ps1
Import-HelloWorldBitmap.ps1
$r = forensicbinshred .\hello_world.bmp .\bitmap.bst $rows = $r.dibHeader.bitmapHeight $r.pixelData.rows[($rows - 1)..0] | % { -join ($_.Pixels | % { if( $_.Pixel[0] ) { ' ' } else { '*' } }) }
PowerShellCorpus/PowerShellGallery/PowerForensics/1.1.1/Tests/PowerForensics.Tests.ps1
PowerForensics.Tests.ps1
# TODO: # Add tests for pipeline input Import-Module -Force $PSScriptRoot\..\PowerForensics.psd1 Describe 'Copy-ForensicFile' { Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Copy-ForensicFile -Path C:\Windows\System32\config\SOFTWARE -Destination C:\Windows\Temp\SOFTWAREcopy } | Should Not Throw } It 'should work with positional parameters' { { Copy-ForensicFile C:\Windows\System32\config\SAM C:\Windows\Temp\SAMcopy } | Should Not Throw } It 'should fail if file does not exist' { } It 'should fail if destination file already exists' { } } Context 'ByIndex ParameterSet' { It 'should work with explicit parameters' { { Copy-ForensicFile -VolumeName \\.\C: -Index 7 -Destination C:\Windows\Temp\BOOT } | Should Not Throw } It 'should work without nonmandatory parameters' { { Copy-ForensicFile -Index 4 -Destination C:\Windows\Temp\ATTRDEF } | Should Not Throw } It 'should work with positional parameters' { { Copy-ForensicFile 0 C:\Windows\Temp\MFT } | Should Not Throw } It 'should fail if index is not valid' { } It 'should fail if destination file already exists' { } } } # Took forever on AppVeyor Describe 'Get-ForensicAlternateDataStream' { <#Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicAlternateDataStream -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicAlternateDataStream -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicAlternateDataStream \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicAlternateDataStream } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicAlternateDataStream -VolumeName \\.\L: } | Should Throw } }#> Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicAlternateDataStream -Path 'C:\$Extend\$UsnJrnl' } | Should Not Throw } It 'should return two ADS named $J and $Max' { $ads = Get-ForensicAlternateDataStream -Path 'C:\$Extend\$UsnJrnl' $ads.Length | Should Be 2 $ads[0].StreamName | Should Be '$J' $ads[1].StreamName | Should Be '$Max' } It 'should return nothing if file has no ADS' { $foo = Get-ForensicAlternateDataStream -Path C:\Windows\notepad.exe $foo | Should Be $null } It 'should fail when the file does not exist' { { Get-ForensicAlternateDataStream -Path C:\This\file\should\not\exist.txt } | Should Throw } } } # Tests Commented Out Describe 'Get-ForensicAmcache' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicAmcache -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicAmcache -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicAmcache \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicAmcache } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicAmcache -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicAmcache -HivePath C:\Windows\appcompat\Programs\Amcache.hve } | Should Not Throw } It 'should fail when the file is not an Amcache.hve' { { Get-ForensicAmcache -HivePath C:\Windows\System32\config\SAM } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicAmcache -HivePath C:\crazydirectory\thisshouldnotexist.hve } | Should Throw } } } Describe 'Get-ForensicAttrDef' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicAttrDef -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicAttrDef -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicAttrDef \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicAttrDef } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicAttrDef -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicAttrDef -Path 'C:\$AttrDef' } | Should Not Throw } It 'should fail if the file is not an AttrDef file' { # Need to figure out how to determine if a file is an AttrDef file } It 'should fail if the file does not exist' { { Get-ForensicAttrDef -Path C:\this\file\should\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicBitmap' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { (Get-ForensicBitmap -VolumeName \\.\C: -Cluster 0).InUse | Should Be $true } It 'should work with volume letter only' { (Get-ForensicBitmap -VolumeName C -Cluster 0).Cluster | Should Be 0 } It 'should work with positional parameters' { (Get-ForensicBitmap \\.\C: -Cluster 0).InUse | Should Be $true } It 'should work without nonmandatory parameters' { { Get-ForensicBitmap -Cluster 0 } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicBitmap -VolumeName \\.\L: -Cluster 0 } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicBitmap -Path 'C:\$Bitmap' -Cluster 0 } | Should Not Throw } # I dont think there is a way to ensure that the file is truly a Bitmap file It 'should fail if the file does not exist' { { Get-ForensicBitmap -Path C:\this\file\should\not\exist.txt -Cluster 0 } | Should Throw } } } # Not Done Describe 'Get-ForensicBootSector' { It 'should work with explicit parameters' { { Get-ForensicBootSector -Path \\.\PHYSICALDRIVE0 } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicBootSector \\.\PHYSICALDRIVE0 } | Should Not Throw } It 'should work with the -AsBytes parameter' { (Get-ForensicBootSector \\.\PHYSICALDRIVE0 -AsBytes).GetType().Name | Should Be 'Byte[]' } It 'should parse a Master Boot Record formatted drive' { } It 'should parse a Guid Partition Table formatted drive' { } } Describe 'Get-ForensicChildItem' { It 'should work with explicit parameters' { { Get-ForensicChildItem -Path C:\ } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicChildItem C:\ } | Should Not Throw } It 'should work without nonmandatory parameters' { Set-Location \ { Get-ForensicChildItem } | Should Not Throw } It 'should fail gracefully if the file does not exist' { { Get-ForensicChildItem -Path C:\windoxs } | Should Not Throw } It 'should work with listing system files' { (Get-ForensicChildItem -Path 'C:\$Volume').FullName | Should Be '$Volume' } } # Not Done Describe 'Get-ForensicContent' { Context 'ByIndex ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicContent -VolumeName \\.\C: -Index 0 } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicContent -VolumeName C -Index 0 } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicContent -Index 0 } | Should Not Throw } It 'should work with the Encoding parameter' { } It 'should work with the TotalCount parameter' { (Get-ForensicContent -VolumeName \\.\C: -Index 0 -TotalCount 10).Length | Should Be 10 } It 'should work with the Tail parameter' { (Get-ForensicContent -VolumeName \\.\C: -Index 0 -Tail 10).Length | Should Be 10 } It 'should fail if the file does not exist' { { Get-ForensicContent -VolumeName \\.\C: -Index 1000000 } | Should Throw } It 'should fail when the volume does not exist' { { Get-ForensicContent -VolumeName \\.\L: -Index 0 } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicContent -Path C:\Windows\System32\config\SAM } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicContent C:\Windows\System32\config\SAM } | Should Not Throw } It 'should work with the Encoding parameter' { } It 'should work with the TotalCount parameter' { (Get-ForensicContent -Path C:\Windows\System32\config\SAM -TotalCount 10).Length | Should Be 10 } It 'should work with the Tail parameter' { (Get-ForensicContent -Path C:\Windows\System32\config\SAM -Tail 10).Length | Should Be 10 } It 'should fail if the file does not exist' { { Get-ForensicContent -Path C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicEventLog' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicEventLog -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicEventLog -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicEventLog \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicEventLog } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicEventLog -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicEventLog -Path C:\Windows\System32\winevt\Logs\Application.evtx } | Should Not Throw } It 'should fail when the file is not an EventLog' { { Get-ForensicEventLog -Path C:\Windows\system32\cmd.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicEventLog -Path C:\this\file\does\not\exist.txt } | Should Throw } } } # MftPath parameter doesnt seem to work Describe 'Get-ForensicFileRecord' { Context 'ByIndex ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicFileRecord -VolumeName \\.\C: -Index 5 } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicFileRecord -VolumeName C -Index 5 } | Should Not Throw } It 'should work with positional "Index" parameter' { { Get-ForensicFileRecord -VolumeName \\.\C: 5 } } It 'should work without nonmandatory parameters' { { Get-ForensicFileRecord -Index 5} | Should Not Throw } It 'should work without nonmandatory and positional parameters' { { Get-ForensicFileRecord 5 } | Should Not Throw } It 'should return 1 File Record' { $r = Get-ForensicFileRecord 5 $r.Length | Should Be 1 } It 'should return all File Records' { { $mft = Get-ForensicFileRecord } | Should Not Throw [GC]::Collect() } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { (Get-ForensicFileRecord -Path 'C:\$Volume').FullName | Should Be 'C:\$Volume' } It 'should work with positional parameters' { (Get-ForensicFileRecord 'C:\$Volume').FullName | Should Be 'C:\$Volume' } It 'should work fail if the file does not exist' { { Get-ForensicFileRecord -Path C:\this\file\does\not\exist.txt } | Should Throw } } Context 'ByMftPath ParameterSet' { It 'should work with explicit parameters' { #{ Get-ForensicFileRecord -MftPath 'C:\$MFT' } | Should Not Throw } It 'should fail if not a $MFT file' { #{ Get-ForensicFileRecord -MftPath C:\Windows\notepad.exe } | Should Throw } It 'should fail if the file does not exist' { #{ Get-ForensicFileRecord -MftPath C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicFileRecordIndex' { It 'should work with explicit parameters' { { Get-ForensicFileRecordIndex -Path C:\Windows\notepad.exe } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicFileRecordIndex C:\Windows\system32\cmd.exe } | Should Not Throw } It 'should work with directories' { (Get-ForensicFileRecordIndex -Path C:\) | Should be 5 } It 'should work with system files' { { Get-ForensicFileRecordIndex -Path 'C:\$Extend\$UsnJrnl' } | Should Not Throw } It 'should fail when the file does not exist' { { Get-ForensicFileRecordIndex -Path C:\this\file\does\not\exist.txt } | Should Throw } } Describe 'Get-ForensicFileSlack' { Context 'ByIndex ParameterSet' { It 'should work with explicit parameters' { #{ Get-ForensicFileSlack -VolumeName \\.\C: } | Should Not Throw } It 'should work with the Index Parameter' { { Get-ForensicFileSlack -VolumeName \\.\C: -Index 0 } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicFileSlack -VolumeName C -Index 0} | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicFileSlack 0 } | Should Not Throw } It 'should work without nonmandatory parameters' { #{ Get-ForensicFileSlack } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicFileSlack -VolumeName \\.\L: -Index 0 } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicFileSlack -Path C:\Windows\notepad.exe } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicFileSlack C:\Windows\notepad.exe } | Should Not Throw } It 'should fail when the file does not exist' { { Get-ForensicFileSlack -Path C:\this\file\does\not\exist.txt } | Should Throw } } } # Not Done Describe 'Get-ForensicGuidPartitionTable' { It 'should work with explicit parameters' { } It 'should work with positional parameters' { } It 'should return a byte array from the -AsBytes parameter' { } It 'should return a MasterBootRecord object if the drive is not Guid Partition Table format' { } } # Not Done Describe 'Get-ForensicMasterBootRecord' { It 'should work with explicit parameters' { { Get-ForensicMasterBootRecord -Path \\.\PHYSICALDRIVE0 } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicMasterBootRecord \\.\PHYSICALDRIVE0 } | Should Not Throw } It 'should return a byte array from the -AsBytes parameter' { $mbr = Get-ForensicMasterBootRecord -Path \\.\PHYSICALDRIVE0 -AsBytes $mbr.Length | Should Be 512 $mbr.GetType().Name | Should Be 'Byte[]' } It 'should return the protective MBR if the drive is Guid Partition Table format' { } } # Not Done Describe 'Get-ForensicMftSlack' { Context 'ByIndex ParameterSet' { It 'should' { } } Context 'ByPath ParameterSet' { It 'should' { } } Context 'ByMftPath ParameterSet' { It 'should' { } } } Describe 'Get-ForensicNetworkList' { It 'should work with explicit parameters' { { Get-ForensicNetworkList -HivePath C:\Windows\System32\config\SOFTWARE } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicNetworkList C:\Windows\System32\config\SOFTWARE } | Should Not Throw } It 'should work with nonmandatory parameters' { { Get-ForensicNetworkList } | Should Not Throw } It 'should fail if the hive is not a SOFTWARE hive' { { Get-ForensicNetworkList -HivePath C:\Windows\notepad.exe } | Should Throw } } # Not Done # Need to figure out how to test GPT Describe 'Get-ForensicPartitionTable' { } Describe 'Get-ForensicPrefetch' { if(Test-Path C:\Windows\Prefetch){ Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicPrefetch -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicPrefetch -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicPrefetch \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicPrefetch } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicPrefetch -VolumeName \\.\L: } | Should Throw } It 'should work with the Fast parameter' { { Get-ForensicPrefetch -Fast } | Should Not Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { Write-Host 'Need to write something to detect the name of a prefetch file' } It 'should fail when the file does not exist' { { Get-ForensicPrefetch -Path C:\this\file\does\not\exist.txt } | Should Throw } } } else{ Write-Host 'Prefetch is not enabled' } } Describe 'Get-ForensicRegistryKey' { Context 'ByKey ParameterSet' { It 'should work with from Hive Root' { { Get-ForensicRegistryKey -HivePath C:\Windows\System32\config\SOFTWARE } | Should Not Throw } It 'should work with the Key parameter specified' { { Get-ForensicRegistryKey -HivePath C:\Windows\System32\config\SYSTEM -Key ControlSet001 } | Should Not Throw } It 'should fail when the file is not a registry hive' { { Get-ForensicRegistryKey -HivePath C:\Windows\notepad.exe } | Should Throw } It 'should fail when the specified Key does not exist' { { Get-ForensicRegistryKey -HivePath C:\Windows\System32\config\SAM -Key keydoesnotexist } | Should Throw } } Context 'Recursive ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicRegistryKey -HivePath C:\Windows\System32\config\SAM -Recurse } | Should Not Throw } It 'should fail when the file is not a registry hive' { { Get-ForensicRegistryKey -HivePath C:\Windows\notepad.exe -Recurse } | Should Throw } } } Describe 'Get-ForensicRegistryValue' { It 'should return one value if the Value parameter is used' { { Get-ForensicRegistryValue -HivePath C:\Windows\System32\config\SAM -Key SAM -Value C } | Should Not Throw } It 'should return all values if the Value parameter is not used' { { Get-ForensicRegistryValue -HivePath C:\Windows\System32\config\SAM -Key SAM } | Should Not Throw } It 'should fail if there are no values' { { Get-ForensicRegistryValue -HivePath C:\Windows\System32\config\SAM } | Should Throw } It 'should fail if the value does not exist' { { Get-ForensicRegistryValue -HivePath C:\Windows\System32\config\SAM -Key SAM -Value Jared } | Should Throw } } # Not Done Describe 'Get-ForensicScheduledJob' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicScheduledJob -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicScheduledJob -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicScheduledJob \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicScheduledJob } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicScheduledJob -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { } It 'should fail when the file is not a ScheduledJob' { { Get-ForensicScheduledJob -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicScheduledJob -Path C:\this\file\does\not\exist.txt } | Should Throw } } } # Not Done Describe 'Get-ForensicShellLink' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicShellLink -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicShellLink -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicShellLink \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicShellLink } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicShellLink -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { # Need to have a path to a ShellLink file here } It 'should fail when the file is not a ShellLink' { { Get-ForensicShellLink -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicShellLink -Path C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicSid' { It 'should work with explicit parameters' { { Get-ForensicSid -HivePath C:\Windows\System32\config\SAM } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicSid C:\Windows\System32\config\SAM } | Should Not Throw } It 'should work with nonmandatory parameters' { { Get-ForensicSid } | Should Not Throw } It 'should fail if the hive is not a SAM hive' { Write-Host 'Need to make the cmdlet check the header of the hive' { Get-ForensicSid -HivePath C:\Windows\System32\config\SOFTWARE } | Should Throw } } Describe 'Get-ForensicTimezone' { It 'should work with explicit parameters' { { Get-ForensicTimezone -HivePath C:\Windows\System32\config\SYSTEM } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicTimezone C:\Windows\System32\config\SYSTEM } | Should Not Throw } It 'should work with nonmandatory parameters' { { Get-ForensicTimezone } | Should Not Throw } It 'should fail if the hive is not a SYSTEM hive' { Write-Host 'Need to make the cmdlet check the header of the hive' { Get-ForensicTimezone -HivePath C:\Windows\System32\config\SAM } | Should Throw } } # Need to dynamically find the current user's name # Need to make it spcifically check the registry header for NTUSER.DAT signature Describe 'Get-ForensicUserAssist' { It 'should work with explicit parameters' { { Get-ForensicUserAssist -HivePath C:\Users\tester\NTUSER.DAT } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicUserAssist C:\Users\tester\NTUSER.DAT } | Should Not Throw } It 'should fail if the hive is not a NTUSER.DAT hive' { Write-Host 'Need to make the cmdlet check the header of the hive' { Get-ForensicUserAssist -HivePath C:\Windows\System32\config\SAM } | Should Throw } } Describe 'Get-ForensicUsnJrnl' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { $usn = Get-ForensicUsnJrnl -VolumeName \\.\C: } | Should Not Throw [GC]::Collect() } It 'should work with volume letter only' { { $usn = Get-ForensicUsnJrnl -VolumeName C } | Should Not Throw [GC]::Collect() } It 'should work with positional parameters' { { $usn = Get-ForensicUsnJrnl \\.\C: } | Should Not Throw [GC]::Collect() } It 'should work without nonmandatory parameters' { { $usn = Get-ForensicUsnJrnl } | Should Not Throw [GC]::Collect() } It 'should work with the Usn parameter' { } It 'should return just one entry with the Usn parameter' { } It 'should fail when the volume does not exist' { { Get-ForensicUsnJrnl -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { $usn = Get-ForensicUsnJrnl -Path 'C:\$Extend\$UsnJrnl' } | Should Not Throw [GC]::Collect() } It 'should work with the Usn parameter' { } It 'should return just one entry with the Usn parameter' { } It 'should fail when the file is not $UsnJrnl' { { Get-ForensicUsnJrnl -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicUsnJrnl -Path C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicUsnJrnlInformation' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicUsnJrnlInformation -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicUsnJrnlInformation -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicUsnJrnlInformation \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicUsnJrnlInformation } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicUsnJrnlInformation -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicUsnJrnlInformation -Path 'C:\$Extend\$UsnJrnl' } | Should Not Throw } It 'should fail when the file is not $UsnJrnl' { { Get-ForensicUsnJrnlInformation -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicUsnJrnlInformation -Path C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicVolumeBootRecord' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicVolumeBootRecord -VolumeName \\.\C: } | Should Not Throw } It 'should work with volume letter only' { { Get-ForensicVolumeBootRecord -VolumeName C } | Should Not Throw } It 'should work with positional parameters' { { Get-ForensicVolumeBootRecord \\.\C: } | Should Not Throw } It 'should work without nonmandatory parameters' { { Get-ForensicVolumeBootRecord } | Should Not Throw } It 'should fail when the volume does not exist' { { Get-ForensicVolumeBootRecord -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { { Get-ForensicVolumeBootRecord -Path 'C:\$Boot' } | Should Not Throw } It 'should fail when the file is not $Boot' { { Get-ForensicVolumeBootRecord -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicVolumeBootRecord -Path C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicVolumeInformation' { Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { (Get-ForensicVolumeInformation -VolumeName \\.\C:).Name | Should Be 'VOLUME_INFORMATION' } It 'should work with volume letter only' { (Get-ForensicVolumeInformation -VolumeName C).Name | Should Be 'VOLUME_INFORMATION' } It 'should work with positional parameters' { (Get-ForensicVolumeInformation \\.\C:).Name | Should Be 'VOLUME_INFORMATION' } It 'should work without nonmandatory parameters' { (Get-ForensicVolumeInformation).Name | Should Be 'VOLUME_INFORMATION' } It 'should fail when the volume does not exist' { { Get-ForensicVolumeInformation -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters' { (Get-ForensicVolumeInformation -Path 'C:\$Volume').Name | Should Be 'VOLUME_INFORMATION' } It 'should fail when the file is not $Volume' { { Get-ForensicVolumeInformation -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicVolumeInformation -Path C:\this\file\does\not\exist.txt } | Should Throw } } } Describe 'Get-ForensicVolumeName' { label.exe C: testdrive Context 'ByVolume ParameterSet' { It 'should work with explicit parameters' { (Get-ForensicVolumeName -VolumeName \\.\C:).VolumeNameString | Should Be 'testdrive' } It 'should work with volume letter only' { (Get-ForensicVolumeName -VolumeName C).VolumeNameString | Should Be 'testdrive' } It 'should work with positional parameters' { (Get-ForensicVolumeName \\.\C:).VolumeNameString | Should Be 'testdrive' } It 'should work without nonmandatory parameters' { (Get-ForensicVolumeName).VolumeNameString | Should Be 'testdrive' } It 'should fail when the volume does not exist' { { Get-ForensicVolumeName -VolumeName \\.\L: } | Should Throw } } Context 'ByPath ParameterSet' { It 'should work with explicit parameters'{ (Get-ForensicVolumeName -Path 'C:\$Volume').VolumeNameString | Should Be 'testdrive' } It 'should fail when the file is not $Volume' { { Get-ForensicVolumeName -Path C:\Windows\notepad.exe } | Should Throw } It 'should fail when the file does not exist' { { Get-ForensicVolumeName -Path C:\this\file\does\not\exist.txt } | Should Throw } } } # Not Done Describe 'Invoke-ForensicDD' { It 'should write to file' { #Invoke-ForensicDD -InFile \\.\PHYSICALDRIVE0 -OutFile C:\temp\mbr -Offset 0 -BlockSize 512 -Count 1 } It 'should write to the Output Stream' { (Invoke-ForensicDD -InFile \\.\PHYSICALDRIVE0 -Offset 0 -BlockSize 1024 -Count 1).Length | Should Be 1024 } It 'should work without nonmandatory parameters' { (Invoke-ForensicDD -InFile \\.\C: -Count 1).Length | Should Be 512 } } Describe 'ConvertTo-ForensicTimeline' { It 'should work with explicit parameters' { { ConvertTo-ForensicTimeline -InputObject (Get-ForensicFileRecord -Index 0) } | Should Not Throw } It 'should work through the pipeline' { { Get-ForensicFileRecord -Index 0 | ConvertTo-ForensicTimeline } | Should Not Throw } <#It 'should work with Prefetch objects' { { Get-ForensicPrefetch -VolumeName \\.\C: | ConvertTo-ForensicTimeline } | Should Not Throw }#> It 'should work with ScheduledJob objects' { { Get-ForensicScheduledJob -VolumeName \\.\C: | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should work with ShellLink objects' { { Get-ForensicShellLink -VolumeName \\.\C: | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should work with UserAssist objects' { { Get-ForensicUserAssist -HivePath C:\Users\tester\NTUSER.DAT | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should work with EventRecord objects' { { Get-ForensicEventLog -Path C:\Windows\System32\winevt\Logs\Application.evtx | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should work with FileRecord objects' { { Get-ForensicFileRecord -Index 0 | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should work with UsnJrnl objects' { { Get-ForensicUsnJrnl -VolumeName \\.\C: | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should work with NamedKey objects' { { Get-ForensicRegistryKey -HivePath C:\Windows\System32\config\SAM | ConvertTo-ForensicTimeline } | Should Not Throw } It 'should fail for unsupported types' { { Get-Process -Name lsass | ConvertTo-ForensicTimeline } | Should Throw } } Describe 'Invoke-ForensicTimeline' { It 'should work with explicit parameters' { { $timeline = Invoke-ForensicTimeline -VolumeName \\.\C: } | Should Not Throw [GC]::Collect() } It 'should work with volume letter only' { { $timeline = Invoke-ForensicTimeline -VolumeName C } | Should Not Throw [GC]::Collect() } It 'should work with positional parameters' { { $timeline = Invoke-ForensicTimeline \\.\C: } | Should Not Throw [GC]::Collect() } It 'should work without nonmandatory parameters' { { $timeline = Invoke-ForensicTimeline } | Should Not Throw [GC]::Collect() } It 'should fail when the file does not exist' { { $timeline = InvokeForensicTimeline -VolumeName \\.\L: } | Should Throw } }
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/End_To_End.ps1
End_To_End.ps1
<# End_to_end.ps1 - Example scripts to illustrate how to end to end rollout the new system via PowerShell. - Manage system, firmware update, configuration, os deployment. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" # Define reference system and target systems, here assume all system is rack server # Reference system should have been managed in LXCA and has been assigned the update policy and config pattern. $referenceSystem = @{ uuid = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" systemType = "RackServer" } $targetSystem = @{ uuid = "89B8E140DF7C11D49AB09F8B8B8B8B8B" systemType = "RackServer" username = "USERID" password = ConvertTo-SecureString "Password" -AsPlainText –Force recovery = ConvertTo-SecureString "Password" -AsPlainText –Force } $deploySet = @{ macAddress = "40:F2:E9:B8:1B:68" imageProfileId = "win2012|win2012-x86_64-install-Datacenter" targetDevice = "localdisk" # localdisk / usbdisk / sandisk (SAN ID is required) IpAssignment = "dhcpv4" # dhcpv4 / staticv4 } # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Manage target system in LXCA server if ($targetSystem.systemType -eq "RackServer") { $ret = Add-LXCAManagedDevice -RackServerUuid $targetSystem.uuid -UserName $targetSystem.username -Password $targetSystem.password } else { $ret = Add-LXCAManagedDevice -ChassisUuid $targetSystem.uuid -UserName $targetSystem.username -Password $targetSystem.password -ChassisRecoveryPassword $targetSystem.recovery } # wait until the inventory state is not "Pending" after management $bWait = $true while ($bWait) { Start-Sleep -Seconds 20 if ($targetSystem.systemType -eq "RackServer") { $server = Get-LXCARackServer -Uuid $targetSystem.uuid if ($server.AccessState -eq "Pending") { continue } } else { $chassis = Get-LXCAChassis -ChassisUuid $targetSystem.uuid if ($chassis.AccessState -eq "Pending") { continue } } $bWait = $false } # Update firmware to the same level with reference system, assume the related update packages have been existed on LXCA repository. # Get the update policy from reference system $policy = Get-LXCAUpdateCompliancePolicy -SystemUuid $referenceSystem.uuid -SystemType $referenceSystem.systemType # Assign the policy to target system $compliance = Join-LXCAUpdateCompliancePolicy -Policy $policy -SystemUuid $targetSystem.uuid -SystemType $targetSystem.systemType # Perform firmware update due to the compliance result $ret = Install-LXCAUpdatePackage -Compliance $compliance -UpdateRule NotCompliantOnly -ActivationMode Delayed -OnErrorMode ContinueOnError -Simulation if ($ret -eq $null) { Write-Host "Install-LXCAUpdatePackage is failed with unexcepted error!" -ForegroundColor Red } else { Write-Host "`nFirmware update result:" $ret | Format-Table -Property Uuid,Type,TotalTasks,TotalSuccess,TotalFailed $ret.Components | Format-Table -Property ComponentName,UpdateStatus,Message } # Wait 60 seconds #Start-Sleep -Seconds 60 # Apply the same config pattern from reference system to target system # Get the same config pattern which is used on reference system. $patternId = "" $profile = Get-LXCAConfigProfile | where {$_.ServerUuid -eq $referenceSystem.uuid} if ($profile -ne $null) { $patternId = $profile[0].PatternId } # Apply the config pattern to target system if ($patternId -eq "") { Write-Error -Message "Pattern Id is empty (cannot retrieve pattern id from reference system)." } else { Write-Host ("`nDeploy pattern {0} to target systems {1}." -f $patternId,([string]::Join(",",$targetSystems))) $ret = Install-LXCAConfigPattern -PatternId $patternId -TargetRackServerId $targetSystems -Restart Defer if ($ret -eq $null) { Write-Host "Install-LXCAConfigPattern is failed with unexcepted error!" -ForegroundColor Red } else { $ret | Format-Table -Property Uuid,Success } } # Wait 60 seconds #Start-Sleep -Seconds 60 # Deploy OS image to target system # Set global deploy setting $globalSet = Get-LXCADeployGlobalSetting $globalSet.IpAssignment = $deploySet.IpAssignment Set-LXCADeployGlobalSetting -DeployGlobalSetting $globalSet # Create a deploy task $deployTask = New-LXCADeployTask -MacAddress $deploySet.macAddress -ServerUuid $targetSystem.uuid -ImageProfileID $deploySet.imageProfileId -TargetDevice $deploySet.targetDevice -Mtu 1500 -PrefixLength 0 # Deploy OS image to target system $ret = Install-LXCAOSImage -DeployTask $deployTask if ($ret -eq $null) { Write-Host "Install-LXCAOSImage is failed with unexcepted error!" -ForegroundColor Red } else { $ret | Format-Table -Property ServerUuid,Percentage,Result,Message -Wrap } # Disconnect from LXCA Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/OS_Deployment.ps1
OS_Deployment.ps1
<# OS_Deployment.ps1 - Example scripts to illustrate how to deploy os image to target systems. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" $targetSystem = @{ uuid = "89B8E140DF7C11D49AB09F8B8B8B8B8B" systemType = "RackServer" } $deploySet = @{ macAddress = "40:F2:E9:B8:1B:68" imageProfileId = "win2012|win2012-x86_64-install-Datacenter" targetDevice = "localdisk" # localdisk / usbdisk / sandisk (SAN ID is required) IpAssignment = "dhcpv4" # dhcpv4 / staticv4 } # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Deploy OS image to target system # Set global deploy setting $globalSet = Get-LXCADeployGlobalSetting $globalSet.IpAssignment = $deploySet.IpAssignment Set-LXCADeployGlobalSetting -DeployGlobalSetting $gloalSet # Create a deploy task $deployTask = New-LXCADeployTask -MacAddress $deploySet.macAddress -ServerUuid $targetSystem.uuid -ImageProfileID $deploySet.imageProfileId -TargetDevice $deploySet.targetDevice -Mtu 1500 -PrefixLength 0 # Deploy OS image to target system $ret = Install-LXCAOSImage -DeployTask $deployTask if ($ret -eq $null) { Write-Host "Install-LXCAOSImage is failed with unexcepted error!" -ForegroundColor Red } else { $ret | Format-Table -Property ServerUuid,Percentage,Result,Message -Wrap } # Disconnect from LXCA server Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/Monitor_Events.ps1
Monitor_Events.ps1
<# Monitor_Events.ps1 - Example scripts to illustrate how to monitor the events on LXCA server. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # # Please run this script in PowerShell console and keep the windows opened. # # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.196.152" # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Create a monitor which will monitor all incoming events with severity CRITIAL,FATAL and WARNING. # It will re-connect to Lenovo XClarity Administrator when the network is not available or the management server is rebooted, and to continue monitoring events. $monitor = Start-LXCAEventMonitor -Severity CRITICAL,FATAL,WARNING Write-Host "`nStart to monitor event..." Write-Host "`nPlease do not close the PowerShell windows" Write-Host "If you want to stop the monitor, run below commands in the console:" Write-Host '$monitor.StopMonitor()' -ForegroundColor Green # Register this monitor, send a mail when there is new event incoming. # You also can record the events to local file or deal with them in other ways. # Here the value of -EventName must be LXCAEvent which is defined in Start-LXCAEventMonitor # View http://technet.microsoft.com/en-us/library/dd347672.aspx for help on cmdlet Register-ObjectEvent $ret = Register-ObjectEvent -InputObject $monitor -EventName LXCAEvent -Action { #Create a Email message $msg = new-object Net.Mail.MailMessage #Create SMTP server object $smtp = new-object Net.Mail.SmtpClient("smtp.gmail.com") $smtp.Credentials = New-Object System.Net.NetworkCredential("yourid@gmail.com", "yourpassword") #Port for TLS (587) or SSL (465) $smtp.Port = 587 $smtp.EnableSsl = $true #Ignore SSL trust validation [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} #Email content $msg.From = "yourid@gmail.com" $msg.To.Add("name@company.com") #Get all incoming events from $EventArgs.Events. #Here the event has the same structure as the event returned by cmdlet Get-LXCAEvent. foreach ($event in $EventArgs.Events) { $msg.subject = "Event -" + $event.EventID + ": " + $event.Message $msg.body = Out-String -InputObject $event #Send email $smtp.Send($msg) #Record event to local file Out-File -InputObject $event -FilePath c:\monitor.txt -Append } }
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/View_Systems.ps1
View_Systems.ps1
<# View_Systems.ps1 - Example scripts to illustrate how to view the managed systems on lxca server. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # First connect to LXCA server $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # View the LXCA version Get-LXCAInformation # List all managed chassis $allChassis = Get-LXCAChassis Write-Host "" Write-Host ("There are {0} chassis managed by this LXCA server." -f $allChassis.Count) $allChassis | Sort-Object Name | Format-Table -Property Name,MachineType,IPAddresses,AccessState,HealthState -Wrap # List all compute nodes on each chassis ForEach ($chassis in $allChassis) { $nodes = Get-LXCAComputeNode -ChassisUuid $chassis.Uuid Write-Host "" Write-Host $chassis.Name ": there are" $nodes.Count "compute nodes in this chassis." $nodes | Sort-Object Name | Format-Table -Property Name,MachineType,IPAddresses,HealthState,PowerState -Wrap } # List all managed rack servers (and record result to c:\lxca.txt) $allServers = Get-LXCARackServer Write-Host ("`nThere are {0} rack server managed by this LXCA server." -f $allServers.Count ) $allServers | Sort-Object Name | Format-Table -Wrap $allServers | Sort-Object Name | Format-Table -Property Name,MachineType,IPAddresses,AccessState,HealthState,PowerState -Wrap >> c:\lxca.txt # Disconnect from LXCA server Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/BulkImport_And_Configuration.ps1
BulkImport_And_Configuration.ps1
<# BulkImport_And_Configuration.ps1 - Example scripts to illustrate how to bulk import multiple systems and configuration. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" # Define the configuration pattern (name) for flex compute node and rack server $configPattern = @{ flex = "Flex_Pattern" rack = "Rack_Pattern" } # Define the bulk import file and username, password. $bulkImportCsv = "c:\bulkimport.csv" $serverUserName = "USERID" $serverPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $chassisUserName = "USERID" $chassisPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $recoveryPassword = ConvertTo-SecureString "Password" -AsPlainText –Force # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Bulk import servers Write-Host "`nTry to manage servers via file:" $bulkImportCsv $ret = Add-LXCAManagedDevice -BulkImportFile $bulkImportCsv -CurrentRackServerUserName $serverUserName -CurrentRackServerPassword $serverPassword -CurrentChassisUserName $chassisUserName -CurrentChassisPassword $chassisPassword -ChassisRecoveryPassword $recoveryPassword Write-Host "`nManaged chassis:" $ret.ChassisManageResult | Format-Table -Wrap Write-Host "`nManaged rack server:" $ret.RackServerManageResult | Format-Table -Wrap # wait until the inventory state is not "Pending" after management $bWait = $true while ($bWait) { Start-Sleep -Seconds 20 Foreach($chassisRet in $ret.ChassisManageResult) { $allNonPending = $true if ($chassisRet.Success -eq $true) { $chassis = Get-LXCAChassis -ChassisUuid $chassisRet.Uuid if ($chassis.AccessState -eq "Pending") { $allNonPending = $allNonPending -and $false break } else { $allNonPending = $allNonPending -and $true } $allNonPending $bWait = -not $allNonPending } } } # Configure them via configuration pattern # Configure compute node Foreach($chassisRet in $ret.ChassisManageResult) { # Check if the chassis is managed succesfully if ($chassisRet.Success -eq $true) { # Get the compute node list in this chassis $computeNodes = Get-LXCAComputeNode -ChassisUuid $chassisRet.Uuid | Select-Object -Property Uuid $nodeUuids = @() foreach ($node in $computeNodes) { # config pattern only accepts uuid in upper case $nodeUuids += $node.Uuid.ToUpper() } # Get pattern due to the pattern name $pattern = Get-LXCAConfigPattern | where { $_.Name -eq $configPattern.flex} if ($pattern -eq $null) { Write-Host ("`nCannot get pattern with name {0}" -f $configPattern.flex) -ForegroundColor Red } else { # Deploy pattern to the compute nodes Write-Host "`nDeploy pattern to compute nodes under chassis" $chassisRet.Uuid $ret = Install-LXCAConfigPattern -PatternId $pattern.Id -TargetComputeNodeId $nodeUuids -Restart Immediate $ret | Format-Table -Property Uuid,Success } } } # wait until the inventory state is not "Pending" after management $bWait = $true while ($bWait) { Start-Sleep -Seconds 20 Foreach($serverRet in $ret.RackServerManageResult) { $allNonPending = $true if ($serverRet.Success -eq $true) { $server = Get-LXCARackServer -Uuid $serverRet.Uuid if ($server.AccessState -eq "PENDING") { $allNonPending = $allNonPending -and $false break } else { $allNonPending = $allNonPending -and $true } $allNonPending $bWait = -not $allNonPending } } } # Configure rack server $serverUuids = @() Foreach($serverRet in $ret.RackServerManageResult) { # Check if the server is managed succesfully if ($serverRet.Success -eq $true) { # config pattern only accepts uuid in upper case $serverUuids += $serverRet.Uuid.ToUpper() } } if ($serverUuids.Count -gt 0) { # Get pattern due to the pattern name $pattern = Get-LXCAConfigPattern | where { $_.Name -eq $configPattern.rack} if ($pattern -eq $null) { Write-Host ("`nCannot get pattern with name {0}" -f $configPattern.rack) -ForegroundColor Red } else { # Deploy pattern to the rack servers Write-Host ("`nDeploy pattern to rack servers {0}" -f [string]::Join(",",$serverUuids)) $ret = Install-LXCAConfigPattern -PatternId $pattern.Id -TargetRackServerId $serverUuids -Restart Immediate $ret | Format-Table -Property Uuid,Success } } # Disconnect LXCA Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/View_Events.ps1
View_Events.ps1
<# View_Events.ps1 - Example scripts to illustrate how to view the events on LXCA server. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Get all events in previous 2 hours $allEvents = Get-LXCAEvent -PreviousHours 2 Write-Host "`nAll events in previous 2 hours:" $allEvents | Sort-Object -Property SequenceNumber | Format-Table -Property SequenceNumber,EventID,Severity,Message,TimeStamp,SourceID,EventClass -Wrap # Get events from target system with specified severity $systemUuid = "BB6EEE4EDF8811D49D17C70202020202" $severity = "MAJOR","CRITICAL","FATAL" Write-Host ("`nEvents on system {0} with severity {1}:" -f $systemUuid,([string]::Join(",",$severity))) $events = Get-LXCAEvent -SourceID $systemUuid -Severity $severity $events | Sort-Object -Property SequenceNumber | Format-Table -Property SequenceNumber,EventID,Severity,Message,TimeStamp,SourceID,EventClass -Wrap # Get all active status with specified severity <# Now active status returns 500 error $severity = "CRITICAL","FATAL" Write-Host ("`nSystems with active status in severity {0}:" -f ([string]::Join(",",$severity)) $status = Get-LXCAActiveStatus -Severity $severity $status | Sort-Object -Property SourceID | Format-Table -Wrap #> #Disconnect from LXCA Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/Manage_Systems.ps1
Manage_Systems.ps1
<# Manage_Systems.ps1 - Example scripts to illustrate how to manage systems on LXCA server. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" $ChassisUserName = "USERID" $ChassisPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $RecoveryPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $ServerUserName = "USERID" $ServerPassword = ConvertTo-SecureString "Password" -AsPlainText –Force # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Manage chassis via S/N, precondition is the target chassis have been discovered by LXCA server $SNlist = "23ENY12","23ENY13","23EVN14","23EVN15" Write-Host "`nTry to manage chassis with S/N:" $SNlist $standaloneChassis = Get-LXCAChassis -Unmanaged | where { $_.SerialNumber -in $SNlist } Write-Host "`nStandalone chassis discovered by LXCA server:" $standaloneChassis | Sort-Object Name | Format-Table -Property Name,UUID,SerialNumber,IPAddresses -AutoSize $Uuids = @() foreach ($Chassis in $standaloneChassis){ $Uuids += ,@($Chassis.Uuid) } $Uuids = [string[]]$Uuids $ret = Add-LXCAManagedDevice -ChassisUuid $Uuids -UserName $ChassisUserName -Password $ChassisPassword -ChassisRecoveryPassword $RecoveryPassword Write-Host "`nManage chassis result:" $ret | Format-Table -AutoSize # Manage servers via IP address or IP range $IpRange = "10.240.195.40-10.240.195.50" Write-Host "`nTry to manage servers in IP range" $IpRange $ret = Add-LXCAManagedDevice -Ipv4Range $IpRange -UserName $ServerUserName -Password $ServerPassword Write-Host "`nManaged chassis:" $ret.ChassisManageResult | Format-Table -Wrap Write-Host "`nManaged rack server:" $ret.RackServerManageResult | Format-Table -Wrap # Manage chassis/rack server via bulk import csv # The bulk import csv template can be downloaded from web ui <# $csvPath = "C:\bulkimport.csv" Write-Host "`nTry to manage servers via file:" $csvPath $ret = Add-LXCAManagedDevice -BulkImportFile $csvPath -CurrentRackServerUserName $ServerUserName -CurrentRackServerPassword $ServerPassword Write-Host "`nManaged chassis:" $ret.ChassisManageResult | Format-Table -Wrap Write-Host "`nManaged rack server:" $ret.RackServerManageResult | Format-Table -Wrap #> <# # Power off all managed rack servers $allServers = Get-LXCARackServer Write-Host "`nAll managed rack servers" $allServers | Sort-Object Name | Format-Table -Property Name,MachineType,IPAddresses,AccessState,HealthState,PowerState -Wrap # Power off each rack server Foreach ($server in $assServers) { Invoke-LXCASystemAction -RackServerUuid $server.Uuid -RackServerAction ShutdownOSandPowerOff } # Wait 10 mins to get the result again Start-Sleep -Seconds (60*10) $allServers = Get-LXCARackServer Write-Host "`nAll managed rack servers after PowerOff:" $allServers | Sort-Object Name | Format-Table -Property Name,MachineType,IPAddresses,AccessState,HealthState,PowerState -Wrap #> # Disconnect from LXCA server Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/Config_Systems.ps1
Config_Systems.ps1
<# Config_Systems.ps1 - Example scripts to illustrate how to deploy config pattern to target systems. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" # The pattern id, you can get it by cmdlet Get-LXCAConfigPattern $patternId = 4 $referenceSystemUuid = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" $targetSystems = "226B3EA4DF7A11D493E6951515157171","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck if ($patternId -eq "") { $profile = Get-LXCAConfigProfile | where {$_.ServerUuid -eq $referenceSystemUuid} if ($profile -ne $null) { $patternId = $profile[0].PatternId } } if ($patternId -eq "") { Write-Error -Message "Pattern Id is empty (cannot retrieve pattern id from reference system)." } else { Write-Host ("`nDeploy pattern {0} to target systems {1}." -f $patternId,([string]::Join(",",$targetSystems))) $ret = Install-LXCAConfigPattern -PatternId $patternId -TargetRackServerId $targetSystems -Restart Defer if ($ret -eq $null) { Write-Host "Install-LXCAConfigPattern is failed with unexcepted error!" -ForegroundColor Red } else { $ret | Format-Table -Property Uuid,Success } } # Disconnect from LXCA server Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/LXCAPSTool/1.1.0/Sample/Firmware_Update.ps1
Firmware_Update.ps1
<# Firmware_Update.ps1 - Example scripts to illustrate how to update firmware. Lenovo Copyright © Copyright Lenovo 2015. LIMITED AND RESTRICTED RIGHTS NOTICE: If data or software is delivered pursuant a General Services Administration “GSA” contract, use, reproduction, or disclosure is subject to restrictions set forth in Contract No. GS-35F-05925. #> # Define the variable value $LxcaUserName = "USERID" $LxcaPassword = ConvertTo-SecureString "Password" -AsPlainText –Force $LxcaIP = "10.240.197.26" # Define reference system and target systems, here assume all system is rack server $referenceSystemUuid = "226B3EA4DF7A11D493E6951515157171" $targetSystems = "226B3EA4DF7A11D493E6951515157171" # First connect to LXCA server $Cred = New-Object System.Management.Automation.PSCredential($LxcaUserName, $LxcaPassword) Connect-LXCA $LxcaIP -Credential $Cred -SkipCertificateCheck # Get the update policy from reference system $policy = Get-LXCAUpdateCompliancePolicy -SystemUuid $referenceSystemUuid -SystemType RackServer | where {$_.SystemUuid -eq $referenceSystemUuid} if ($policy -eq $null) { Write-Host ("Cannot find policy from reference system {0}." -f $referenceSystemUuid) -ForegroundColor Red } else { Write-Host ("`nGet policy {0}." -f $policy.Name) # Perform firmware update on each target system (now it is simulation mode in this sample) foreach ($uuid in $targetSystems) { $compliance = Join-LXCAUpdateCompliancePolicy -Policy $policy -SystemUuid $uuid -SystemType RackServer $ret = Install-LXCAUpdatePackage -Compliance $compliance -UpdateRule NotCompliantOnly -ActivationMode Immediate -OnErrorMode ContinueOnError -Simulation if ($ret -eq $null) { Write-Host ("Install-LXCAUpdatePackage is failed on {0} with unexcepted error!" -f $uuid) -ForegroundColor Red } else { Write-Host ("`nFirmware update result on {0}:" -f $uuid) $ret | Format-Table -Property Uuid,Type,TotalTasks,TotalSuccess,TotalFailed $ret.Components | Format-Table -Property ComponentName,UpdateStatus,Message -Wrap } } } #Disconnect from LXCA Disconnect-LXCA
PowerShellCorpus/PowerShellGallery/PingMe/1.0/Get-Ping.ps1
Get-Ping.ps1
function Get-Ping { <# .Synopsis Gets things to ping .Description Gets things to ping, and resolves the ping if you use -Resolve. .Example Get-Ping .Example Get-Ping -Resolve .Link Add-Ping .Link Remove-Ping .Link Clear-Ping .Link Watch-Ping #> [CmdletBinding(DefaultParameterSetName='All')] param( # The server name, DNS name, or URL to ping [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ParameterSetName='Computer')] [Alias('Server', 'ComputerName', 'Destination')] [uri]$Ping, # The name of the group to add the ping monitor [string]$Group, # If set, performs the actual ping validation [switch]$Resolve ) begin { $outputPingResult = { $result = New-Object PSObject -Property @{ Pinged = $pinged Destination = $pingObject.Ping Result = $pingResult PingType = $pingType } $result.pstypenames.clear() $result.pstypenames.add('PingResult') $result } $ResolvePing = { $pingObject = $_ if (-not $resolve) { if ($pingObject) { $returnObject =New-Object PSObject -Property $pingObject $returnObject.pstypenames.clear() $null = $returnObject.pstypenames.add('PingInfo') return $returnObject } } $pingType = if ($pingObject.Echo) { "Echo" } elseif ($pingObject.WebClient) { "Web" } elseif ($pingObject.Dns) { "Dns" } elseif ($pingObject.Dns) { "PowerShell" } if ($PingObject.Echo) { $pingResult = ping $pingObject.Ping -n 1 $pinged = if ($pingResult | ? {$_ -like "*(100%*" }) { $false } else { $true } . $outputPingResult } if ($PingObject.WebClient) { $wc = New-Object Net.Webclient $pinged = $false $pingResult = try { $wc.DownloadString("$($pingObject.ping)") $pinged = $true } catch { $_ } . $outputPingResult } if ($pingObject.DNS) { Add-Type -AssemblyName System.Net $pinged = $false $pingResult = try { [Net.Dns]::Resolve($pingObject.Ping) $pinged = $true } catch { $_ } . $outputPingResult } if ($PingObject.PowerShellConnection) { $issue = $null $psConn = Invoke-Command -ComputerName $pingObject.Ping -ScriptBlock { Get-Command } -ErrorAction SilentlyContinue -ErrorVariable issue $pinged = $false if ($issue) { $pingResult = $issue } elseif ($psConn) { $pinged = $true $pingResult = $psConn } . $outputPingResult } } } process { if ($PsCmdlet.ParameterSetName -eq 'All') { $script:PingList.Values | ForEach-Object { $_ } | ForEach-Object $ResolvePing } elseif ($psCmdlet.ParameterSetName -eq 'Computer') { $script:PingList.Values | ForEach-Object { $_ } | Where-Object { $_.Ping -eq $ping } | ForEach-Object $ResolvePing } elseif ($psCmdlet.ParameterSetName -eq 'Group') { if ($script:PingList.$Group) { $script:PingList.$Group | Get-Ping -Resolve:$Resolve } } } }
PowerShellCorpus/PowerShellGallery/PingMe/1.0/Clear-Ping.ps1
Clear-Ping.ps1
function Clear-Ping { <# .Synopsis Clears the ping cache .Description Clears the ping cache .Example Clear-Ping #> param() $script:PingList = @{} }
PowerShellCorpus/PowerShellGallery/PingMe/1.0/Add-Ping.ps1
Add-Ping.ps1
function Add-Ping { <# .Synopsis Adds a thing to ping .Description Adds a computer, DNS name, or URL to ping .Example # 'Pings' start-automating.com (really, downloads a webpage) Add-Ping start-automating.com .Link Remove-Ping .Link Clear-Ping .Link Watch-Ping .Link Get-Ping #> [CmdletBinding(DefaultParameterSetName='WebTest')] param( # The server name, DNS name, or URL to ping [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [Alias('Server', 'ComputerName')] [uri]$Ping, # If set, will do an old-fashioned "ping" request [Parameter(Mandatory=$true,ParameterSetName='PingTest')] [Switch]$Echo, # If set, will use the web client to ping the server. This is great for ensuring that pages render [Parameter(ParameterSetName='WebTest')] [Switch]$WebClient, # If set, will ensure that PowerShell can connect to the server. [Parameter(Mandatory=$true,ParameterSetName='PowerShellTest')] [Switch]$PowerShellConnection, # If set, resolves the name in DNS [Parameter(Mandatory=$true,ParameterSetName='DNSTest')] [Switch]$Dns, # The name of the group to add the ping monitor [string]$Group, # If set, outputs the ping object [switch]$PassThru ) begin { #region Declare Ping List if (-not ($script:PingList)) { $script:PingList = @{} } #endregion } process { if (-not $Group) { $group = 'Default' } $pingData = @{} + $psBoundParameters if ($psCmdlet.ParameterSetName -eq 'WebTest' -and -not $WebClient) { $pingData.Webclient = $true } $null = $pingData.Remove('PassThru') if (-not $script:PingList.$Group) { $script:PingList.$group = @() } $pingObject = New-Object PSObject $pingData $script:PingList.$group += $pingObject if ($PassThru) { # region create ping object $returnObject =New-Object PSObject -Property $pingData $returnObject.pstypenames.clear() $null = $returnObject.pstypenames.add('PingInfo') return $returnObject # endregion } } }
PowerShellCorpus/PowerShellGallery/PingMe/1.0/Watch-Ping.ps1
Watch-Ping.ps1
function Watch-Ping { <# .Synopsis Watches the things to ping .Description Watches the things to ping Green is Good Red is Wrong .Example Watch-Heatmap .Link Add-Ping .Link Remove-Ping .Link Get-Ping #> param( # If set, continously watches the heatmap [switch]$Continuous, # If set, waits this period of time between each sample of the heatmap [Timespan]$WaitAfterGet = "0:0:0" ) process { do { #region Get the values Get-Ping -Resolve #endregion Get the values #region Wait if needed if ($Continuous -and $WaitAfterGet.TotalMilliseconds) { Start-Sleep -Milliseconds $WaitAfterGet.TotalMilliseconds } #endregion Wait if needed } while ($continuous) } }
PowerShellCorpus/PowerShellGallery/PingMe/1.0/Remove-Ping.ps1
Remove-Ping.ps1
None
PowerShellCorpus/PowerShellGallery/AzureRM.ContainerRegistry/0.2.0/ResourceManagerStartup.ps1
ResourceManagerStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- # Authorization script commandlet that builds on top of existing Insights comandlets. # This commandlet gets all events for the "Microsoft.Authorization" resource provider by calling the "Get-AzureRmResourceProviderLog" commandlet function Get-AzureRmAuthorizationChangeLog { <# .SYNOPSIS Gets access change history for the selected subscription for the specified time range i.e. role assignments that were added or removed, including classic administrators (co-administrators and service administrators). Maximum duration that can be queried is 15 days (going back up to past 90 days). .DESCRIPTION The Get-AzureRmAuthorizationChangeLog produces a report of who granted (or revoked) what role to whom at what scope within the subscription for the specified time range. The command queries all role assignment events from the Insights resource provider of Azure Resource Manager. Specifying the time range is optional. If both StartTime and EndTime parameters are not specified, the default query interval is the past 1 hour. Maximum duration that can be queried is 15 days (going back up to past 90 days). .PARAMETER StartTime Start time of the query. Optional. .PARAMETER EndTime End time of the query. Optional .EXAMPLE Get-AzureRmAuthorizationChangeLog Gets the access change logs for the past hour. .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime "09/20/2015 15:00" -EndTime "09/24/2015 15:00" Gets all access change logs between the specified dates Timestamp : 2015-09-23 21:52:41Z Caller : admin@rbacCliTest.onmicrosoft.com Action : Revoked PrincipalId : 54401967-8c4e-474a-9fbb-a42073f1783c PrincipalName : testUser PrincipalType : User Scope : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testresource ScopeName : testresource ScopeType : Resource RoleDefinitionId : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c RoleName : Contributor .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime ([DateTime]::Now - [TimeSpan]::FromDays(5)) -EndTime ([DateTime]::Now) | FT Caller, Action, RoleName, PrincipalName, ScopeType Gets access change logs for the past 5 days and format the output Caller Action RoleName PrincipalName ScopeType ------ ------ -------- ------------- --------- admin@contoso.com Revoked Contributor User1 Subscription admin@contoso.com Granted Reader User1 Resource Group admin@contoso.com Revoked Contributor Group1 Resource .LINK New-AzureRmRoleAssignment .LINK Get-AzureRmRoleAssignment .LINK Remove-AzureRmRoleAssignment #> [CmdletBinding()] param( [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The start time. Optional If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $StartTime, [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The end time. Optional. If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $EndTime ) PROCESS { # Get all events for the "Microsoft.Authorization" provider by calling the Insights commandlet $events = Get-AzureRmLog -ResourceProvider "Microsoft.Authorization" -DetailedOutput -StartTime $StartTime -EndTime $EndTime $startEvents = @{} $endEvents = @{} $offlineEvents = @() # StartEvents and EndEvents will contain matching pairs of logs for when role assignments (and definitions) were created or deleted. # i.e. A PUT on roleassignments will have a Start-End event combination and a DELETE on roleassignments will have another Start-End event combination $startEvents = $events | ? { $_.httpRequest -and $_.Status -ieq "Started" } $events | ? { $_.httpRequest -and $_.Status -ne "Started" } | % { $endEvents[$_.OperationId] = $_ } # This filters non-RBAC events like classic administrator write or delete $events | ? { $_.httpRequest -eq $null } | % { $offlineEvents += $_ } $output = @() # Get all role definitions once from the service and cache to use for all 'startevents' $azureRoleDefinitionCache = @{} Get-AzureRmRoleDefinition | % { $azureRoleDefinitionCache[$_.Id] = $_ } $principalDetailsCache = @{} # Process StartEvents # Find matching EndEvents that succeeded and relating to role assignments only $startEvents | ? { $endEvents.ContainsKey($_.OperationId) ` -and $endEvents[$_.OperationId] -ne $null ` -and $endevents[$_.OperationId].OperationName.StartsWith("Microsoft.Authorization/roleAssignments", [System.StringComparison]::OrdinalIgnoreCase) ` -and $endEvents[$_.OperationId].Status -ieq "Succeeded"} | % { $endEvent = $endEvents[$_.OperationId]; # Create the output structure $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $endEvent.EventTimestamp -Format u $out.Caller = $_.Caller if ($_.HttpRequest.Method -ieq "PUT") { $out.Action = "Granted" if ($_.Properties.Content.ContainsKey("requestbody")) { $messageBody = ConvertFrom-Json $_.Properties.Content["requestbody"] } $out.Scope = $_.Authorization.Scope } elseif ($_.HttpRequest.Method -ieq "DELETE") { $out.Action = "Revoked" if ($endEvent.Properties.Content.ContainsKey("responseBody")) { $messageBody = ConvertFrom-Json $endEvent.Properties.Content["responseBody"] } } if ($messageBody) { # Process principal details $out.PrincipalId = $messageBody.properties.principalId if ($out.PrincipalId -ne $null) { # Get principal details by querying Graph. Cache principal details and read from cache if present $principalId = $out.PrincipalId if($principalDetailsCache.ContainsKey($principalId)) { # Found in cache $principalDetails = $principalDetailsCache[$principalId] } else { # not in cache $principalDetails = "" | select Name, Type $user = Get-AzureRmADUser -ObjectId $principalId if ($user) { $principalDetails.Name = $user.DisplayName $principalDetails.Type = "User" } else { $group = Get-AzureRmADGroup -ObjectId $principalId if ($group) { $principalDetails.Name = $group.DisplayName $principalDetails.Type = "Group" } else { $servicePrincipal = Get-AzureRmADServicePrincipal -objectId $principalId if ($servicePrincipal) { $principalDetails.Name = $servicePrincipal.DisplayName $principalDetails.Type = "Service Principal" } } } # add principal details to cache $principalDetailsCache.Add($principalId, $principalDetails); } $out.PrincipalName = $principalDetails.Name $out.PrincipalType = $principalDetails.Type } # Process scope details if ([string]::IsNullOrEmpty($out.Scope)) { $out.Scope = $messageBody.properties.Scope } if ($out.Scope -ne $null) { # Remove the authorization provider details from the scope, if present if ($out.Scope.ToLower().Contains("/providers/microsoft.authorization")) { $index = $out.Scope.ToLower().IndexOf("/providers/microsoft.authorization") $out.Scope = $out.Scope.Substring(0, $index) } $scope = $out.Scope $resourceDetails = "" | select Name, Type $scopeParts = $scope.Split('/', [System.StringSplitOptions]::RemoveEmptyEntries) $len = $scopeParts.Length if ($len -gt 0 -and $len -le 2 -and $scope.ToLower().Contains("subscriptions")) { $resourceDetails.Type = "Subscription" $resourceDetails.Name = $scopeParts[1] } elseif ($len -gt 0 -and $len -le 4 -and $scope.ToLower().Contains("resourcegroups")) { $resourceDetails.Type = "Resource Group" $resourceDetails.Name = $scopeParts[3] } elseif ($len -ge 6 -and $scope.ToLower().Contains("providers")) { $resourceDetails.Type = "Resource" $resourceDetails.Name = $scopeParts[$len -1] } $out.ScopeName = $resourceDetails.Name $out.ScopeType = $resourceDetails.Type } # Process Role definition details $out.RoleDefinitionId = $messageBody.properties.roleDefinitionId if ($out.RoleDefinitionId -ne $null) { if ($azureRoleDefinitionCache[$out.RoleDefinitionId]) { $out.RoleName = $azureRoleDefinitionCache[$out.RoleDefinitionId].Name } else { $out.RoleName = "" } } } $output += $out } # start event processing complete # Filter classic admins events $offlineEvents | % { if($_.Status -ne $null -and $_.Status -ieq "Succeeded" -and $_.OperationName -ne $null -and $_.operationName.StartsWith("Microsoft.Authorization/ClassicAdministrators", [System.StringComparison]::OrdinalIgnoreCase)) { $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $_.EventTimestamp -Format u $out.Caller = "Subscription Admin" if($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/write"){ $out.Action = "Granted" } elseif($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/delete"){ $out.Action = "Revoked" } $out.RoleDefinitionId = $null $out.PrincipalId = $null $out.PrincipalType = "User" $out.Scope = "/subscriptions/" + $_.SubscriptionId $out.ScopeType = "Subscription" $out.ScopeName = $_.SubscriptionId if($_.Properties -ne $null){ $out.PrincipalName = $_.Properties.Content["adminEmail"] $out.RoleName = "Classic " + $_.Properties.Content["adminType"] } $output += $out } } # end offline events $output | Sort Timestamp } } # End commandlet # SIG # Begin signature block # MIIkHQYJKoZIhvcNAQcCoIIkDjCCJAoCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0B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cNAQkQAQQwLwYJKoZIhvcNAQkEMSIEINvuSa/2bYJ1lP5FWlVuggdj8oYGgUHU # Ao44vqpodkqlMIHiBgsqhkiG9w0BCRACDDGB0jCBzzCBzDCBsQQUGA2ss4xoMLP4 # dBmyeM6AKzUvCPowgZgwgYCkfjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2Fz # aGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENv # cnBvcmF0aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EgMjAx # MAITMwAAAJ0gnFZ3VdQomgAAAAAAnTAWBBRoFpuEdEUWojsFxAdQ15qcNRJMOjAN # BgkqhkiG9w0BAQsFAASCAQBOfj4MycWmi7qKlXvdNuKnWddKnX9DjzuKiOdNqPj/ # npcE6EbaUb93KznLa7i3wXvEI1Kwp/qfahYUy54Mgqr+VG7a4NjoNjodxT2p/Lnl # TPnWWusMbyRi9yukt8IdkCL4ektI7VgCa1wdBMJ23xohJaKHUAYvfuOYUebTkaTv # jEkPtSgDRO3IyDETyJphxUOPggl+qv6YtPYNF1YzqSOOCnsM8nB5R9gsNitUYXLf # x1V6foLz2idDCykuwZrtLRittvazocsPThkzqcfLSFGLox4Cg8iE9j6AIA9nWpwt # JlYYtNSLLkqAmkMB6z4AYMT3BHWH9rmu40yMcTVEMtXd # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Parser/1.0.13/Tests/Parser.Test.ps1
Parser.Test.ps1
using module ColoredText using module Parser using module .\Rules.psm1 $text = @' [19/01/16 00:00:00] WARNING : Warning Message [19/01/16 00:00:00] ERROR : Error Message [19/01/16 00:00:00] INFO : Info Message '@ $global:calback = { param ( [Parser.Node]$node, [Object]$writer ) if ($node.fields.message_type -match 'ERROR') { # Send Email or SMS } } $rules = New-Object ParsingRules $coloredText = New-Object ColoredText $parser = [Parser]@{ output = $coloredText; rules = $rules } $parser.parse([Parser]::split($text))
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/Normalize-SSRSFolder.ps1
Normalize-SSRSFolder.ps1
function Normalize-SSRSFolder ( [string]$Folder ) { $script:ErrorActionPreference = 'Stop' if (-not $Folder.StartsWith('/')) { $Folder = '/' + $Folder } if($Folder.EndsWith('/')) { $Folder = $Folder.Substring(0, $Folder.Length -1) } return $Folder }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/Publish-SSRSSolution.ps1
Publish-SSRSSolution.ps1
function Publish-SSRSSolution{ #requires -version 2.0 [CmdletBinding()] # Path is the full path to the solution file, including the file name. # i.e. D:\dev\Reports\Reports.sln param ( [parameter(Mandatory=$true)] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [string] $Solution, [parameter( ParameterSetName='Configuration', Mandatory=$true)] [string] $Configuration, [System.Management.Automation.PSCredential] $credentials ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest # Get credentials, interactive #$credentials = Get-Credential # non-interactive #$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force #$mycreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd) $Solution = ($Solution | Resolve-Path).ProviderPath $SolutionRoot = $Solution | Split-Path # Guid is for the Reports project type. $SolutionProjectPattern = @" (?x) ^ Project \( " \{ F14B399A-7131-4C87-9E4B-1186C45EF12D \} " \) \s* = \s* " (?<name> [^"]* ) " , \s+ " (?<path> [^"]* ) " , \s+ "@ Get-Content -Path $Solution | ForEach-Object { if ($_ -match $SolutionProjectPattern) { $ProjectPath = $SolutionRoot | Join-Path -ChildPath $Matches['path'] $ProjectPath = ($ProjectPath | Resolve-Path).ProviderPath #"$ProjectPath" = full path to the project file & Publish-SSRSProject -path $ProjectPath -configuration $configuration -verbose -credential $credentials } } }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/New-SSRSDataSet.ps1
New-SSRSDataSet.ps1
function New-SSRSDataSet ( $Proxy, [string]$RsdPath, [string]$Folder, [bool]$Overwrite=$false, $DataSourcePaths ) { $script:ErrorActionPreference = 'Stop' Write-Verbose "Processing DataSet '$RsdPath'..." $Folder = Normalize-SSRSFolder -Folder $Folder $Name = [System.IO.Path]::GetFileNameWithoutExtension($RsdPath) $RawDefinition = Get-Content -Encoding Byte -Path $RsdPath [xml]$Rsd = Get-Content -Path $RsdPath $properties = $null $warnings = $null #Nevermind it always uses filename # if([string]::IsNullOrEmpty($Rsd.SharedDataSet.DataSet.Name )) # { # $Rsd.SharedDataSet.DataSet.Name=$Name # } $FakeResult = New-Object -TypeName PSObject -Property @{ Name = $Rsd.SharedDataSet.DataSet.Name Path = $Folder + '/' + $Name } $exists = $Proxy.GetItemType($FakeResult.Path) -ne 'Unknown' $write = $false if ($exists) { if ($Overwrite) { Write-Verbose " - overwriting" $write = $true } else { Write-Verbose " - skipped, already exists" } } else { Write-Verbose " - creating new" $write = $true } if ($write) { # https://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010.createcatalogitem.aspx $Results = $Proxy.CreateCatalogItem("DataSet", $Name, $Folder, $Overwrite, $RawDefinition, $properties, [ref]$warnings) $DataSourcePath = $DataSourcePaths[$Rsd.SharedDataSet.DataSet.Query.DataSourceReference] if ($DataSourcePath) { $Reference = New-Object -TypeName SSRS.ReportingService2010.ItemReference $Reference.Reference = $DataSourcePath $Reference.Name = 'DataSetDataSource' #$Rsd.SharedDataSet.DataSet.Name $Proxy.SetItemReferences($Folder + '/' + $Name, @($Reference)) } } else{ $Results=$FakeResult; } return $Results }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/New-SSRSFolder.ps1
New-SSRSFolder.ps1
function New-SSRSFolder ( $Proxy, [string] $Name, [switch] $Recursing ) { $script:ErrorActionPreference = 'Stop' if (!$recursing) { Write-Verbose "Creating SSRS folder '$Name'" } $Name = Normalize-SSRSFolder -Folder $Name if ($Proxy.GetItemType($Name) -ne 'Folder') { $Parts = $Name -split '/' $Leaf = $Parts[-1] $Parent = $Parts[0..($Parts.Length-2)] -join '/' if ($Parent) { New-SSRSFolder -Proxy $Proxy -Name $Parent -Recursing } else { $Parent = '/' } # create folder, suppressing console output from proxy $Proxy.CreateFolder($Leaf, $Parent, $null) > $null } else { if (!$recursing) { Write-Verbose " - skipped, already exists" } } }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/Publish-SSRSProject.ps1
Publish-SSRSProject.ps1
function Publish-SSRSProject{ #requires -version 2.0 # https://github.com/timabell/ssrs-powershell-deploy [CmdletBinding()] param ( [parameter(Mandatory=$true)] [ValidatePattern('\.rptproj$')] [ValidateScript({ Test-Path -PathType Leaf -Path $_ })] [string] $Path, [parameter(Mandatory=$false)] [string] $Configuration, [parameter(Mandatory=$false)] [ValidatePattern('^https?://')] [string] $ServerUrl, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [parameter(Mandatory=$false)] [string] $Folder, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [parameter(Mandatory=$false)] [string] $DataSourceFolder, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [parameter(Mandatory=$false)] [string] $DataSetFolder, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [parameter(Mandatory=$false)] [string] $OutputPath, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [parameter(Mandatory=$false)] [bool] $OverwriteDataSources, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [parameter(Mandatory=$false)] [bool] $OverwriteDatasets, #THESE ARE NOW OVERRRIDES IF $Configuration is specified [System.Management.Automation.PSCredential] $Credential ) $script:ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest $Path = $Path | Convert-Path $ProjectRoot = $Path | Split-Path [xml]$Project = Get-Content -Path $Path #Argument validation if(![string]::IsNullOrEmpty($Configuration)) { $Config = Get-SSRSProjectConfiguration -Path $Path -Configuration $Configuration if([string]::IsNullOrEmpty($ServerUrl)) { Write-Verbose "Using Project Server URL: $($Config.ServerUrl)" $ServerUrl = $Config.ServerUrl } if([string]::IsNullOrEmpty($Folder)) { Write-Verbose "Using Project Folder : $($Config.Folder)" $Folder = $Config.Folder } if([string]::IsNullOrEmpty($DataSourceFolder)) { Write-Verbose "Using Project DataSourceFolder: $($Config.DataSourceFolder)" $DataSourceFolder = $Config.DataSourceFolder } if([string]::IsNullOrEmpty($DataSetFolder)) { Write-Verbose "Using Project DataSetFolder: $($Config.DataSetFolder)" $DataSetFolder = $Config.DataSetFolder } if([string]::IsNullOrEmpty($OutputPath)) { Write-Verbose "Using Project OutputPath: $($Config.OutputPath)" $OutputPath = $Config.OutputPath } if(!$PSBoundParameters.ContainsKey("OverwriteDataSources")) { Write-Verbose "Using Project OverwriteDataSources: $($Config.OverwriteDataSources)" $OverwriteDataSources = $Config.OverwriteDataSources } if(!$PSBoundParameters.ContainsKey("OverwriteDatasets")) { Write-Verbose "Using Project OverwriteDatasets: $($Config.OverwriteDatasets)" $OverwriteDatasets = $Config.OverwriteDatasets } } $Project.SelectNodes('Project/Reports/ProjectItem') | ForEach-Object { $CompiledRdlPath = $ProjectRoot | Join-Path -ChildPath $OutputPath | join-path -ChildPath $_.FullPath $RdlPath = $ProjectRoot | join-path -ChildPath $_.FullPath if ((test-path $CompiledRdlPath) -eq $false) { write-error ('Report "{0}" is listed in the project but wasn''t found in the bin\ folder. Rebuild your project before publishing.' -f $CompiledRdlPath) break; } $RdlLastModified = (get-item $RdlPath).LastWriteTime $CompiledRdlLastModified = (get-item $CompiledRdlPath).LastWriteTime if ($RdlLastModified -gt $CompiledRdlLastModified) { write-error ('Report "{0}" in bin\ is older than source file "{1}". Rebuild your project before publishing.' -f $CompiledRdlPath,$RdlPath) break; } } $Folder = Normalize-SSRSFolder -Folder $Folder $DataSourceFolder = Normalize-SSRSFolder -Folder $DataSourceFolder $Proxy = New-SSRSWebServiceProxy -Uri $ServerUrl -Credential $Credential $FullServerPath = $Proxy.Url Write-Verbose "Connecting to: $FullServerPath" New-SSRSFolder -Proxy $Proxy -Name $Folder New-SSRSFolder -Proxy $Proxy -Name $DataSourceFolder New-SSRSFolder -Proxy $Proxy -Name $DataSetFolder $DataSourcePaths = @{} $Project.SelectNodes('Project/DataSources/ProjectItem') | ForEach-Object { $RdsPath = $ProjectRoot | Join-Path -ChildPath $_.FullPath $DataSource = New-SSRSDataSource -Proxy $Proxy -RdsPath $RdsPath -Folder $DataSourceFolder -Overwrite $OverwriteDataSources $DataSourcePaths.Add($DataSource.Name, $DataSource.Path) } $DataSetPaths = @{} $Project.SelectNodes('Project/DataSets/ProjectItem') | ForEach-Object { $RsdPath = $ProjectRoot | Join-Path -ChildPath $_.FullPath $DataSet = New-SSRSDataSet -Proxy $Proxy -RsdPath $RsdPath -Folder $DataSetFolder -DataSourcePaths $DataSourcePaths -Overwrite $OverwriteDatasets if(-not $DataSetPaths.Contains($DataSet.Name)) { $DataSetPaths.Add($DataSet.Name, $DataSet.Path) } } $Project.SelectNodes('Project/Reports/ResourceProjectItem') | ForEach-Object { if($_.MimeType.StartsWith('image/')) { $Path = $ProjectRoot | Join-Path -ChildPath $_.FullPath $RawDefinition = Get-Content -Encoding Byte -Path $Path $DescProp = New-Object -TypeName SSRS.ReportingService2010.Property $DescProp.Name = 'Description' $DescProp.Value = '' $HiddenProp = New-Object -TypeName SSRS.ReportingService2010.Property $HiddenProp.Name = 'Hidden' $HiddenProp.Value = 'false' $MimeProp = New-Object -TypeName SSRS.ReportingService2010.Property $MimeProp.Name = 'MimeType' $MimeProp.Value = $_.MimeType $Properties = @($DescProp, $HiddenProp, $MimeProp) if($_.FullPath.StartsWith('_')) { $HiddenProp.Value = 'true' } $Name = $_.FullPath Write-Verbose "Creating resource $Name" $warnings = $null $Results = $Proxy.CreateCatalogItem("Resource", $_.FullPath, $Folder, $true, $RawDefinition, $Properties, [ref]$warnings) } } $Project.SelectNodes('Project/Reports/ProjectItem') | ForEach-Object { $CompiledRdlPath = $ProjectRoot | Join-Path -ChildPath $OutputPath | join-path -ChildPath $_.FullPath New-SSRSReport -Proxy $Proxy -RdlPath $CompiledRdlPath } Write-host "Completed." }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/New-SSRSDataSource.ps1
New-SSRSDataSource.ps1
function New-SSRSDataSource ( $Proxy, [string]$RdsPath, [string]$Folder, [bool]$Overwrite ) { $script:ErrorActionPreference = 'Stop' Write-Verbose "Processing DataSource '$RdsPath'..." $Folder = Normalize-SSRSFolder -Folder $Folder [xml]$Rds = Get-Content -Path $RdsPath $ConnProps = $Rds.RptDataSource.ConnectionProperties $Definition = New-Object -TypeName SSRS.ReportingService2010.DataSourceDefinition $Definition.ConnectString = $ConnProps.ConnectString $Definition.Extension = $ConnProps.Extension #Does the IntegratedSecurity property exist $integratedproperty = $ConnProps | Get-Member -MemberType Property | where {$_.name -like 'IntegratedSecurity'} if($integratedproperty -ne $null) { if ([Convert]::ToBoolean($ConnProps.IntegratedSecurity)) { $Definition.CredentialRetrieval = 'Integrated' } } else{ write-verbose "IntegratedSecurity Missing" } $DataSource = New-Object -TypeName PSObject -Property @{ Name = $Rds.RptDataSource.Name Path = $Folder + '/' + $Rds.RptDataSource.Name } $exists = $Proxy.GetItemType($DataSource.Path) -ne 'Unknown' $write = $false if ($exists) { if ($Overwrite) { Write-Verbose " - overwriting" $write = $true } else { Write-Verbose " - skipped, already exists" } } else { Write-Verbose " - creating new" $write = $true } if ($write) { # assign result to avoid polluting return value. http://stackoverflow.com/a/23225503/10245 # Oh what an ugly language powerhell is. :-/ $foo = $Proxy.CreateDataSource($DataSource.Name, $Folder, $Overwrite, $Definition, $null) } return $DataSource }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/New-SSRSReport.ps1
New-SSRSReport.ps1
function New-SSRSReport ( $Proxy, [string]$RdlPath ) { $script:ErrorActionPreference = 'Stop' [xml]$Definition = Get-Content -Path $RdlPath $NsMgr = New-XmlNamespaceManager $Definition d $RawDefinition = Get-Content -Encoding Byte -Path $RdlPath $Name = $_.Name -replace '\.rdl$','' $DescProp = New-Object -TypeName SSRS.ReportingService2010.Property $DescProp.Name = 'Description' $DescProp.Value = '' $HiddenProp = New-Object -TypeName SSRS.ReportingService2010.Property $HiddenProp.Name = 'Hidden' $HiddenProp.Value = 'false' $Properties = @($DescProp, $HiddenProp) $Xpath = 'd:Report/d:Description' $DescriptionNode = $Definition.SelectSingleNode($Xpath, $NsMgr) if($DescriptionNode) { $DescProp.Value = $DescriptionNode.Value } if($Name.StartsWith('_')) { $HiddenProp.Value = 'true' } Write-Verbose "Creating report $Name" $warnings = $null $Results = $Proxy.CreateCatalogItem("Report", $Name, $Folder, $true, $RawDefinition, $Properties, [ref]$warnings) $Xpath = 'd:Report/d:DataSources/d:DataSource/d:DataSourceReference/..' $DataSources = $Definition.SelectNodes($Xpath, $NsMgr) | ForEach-Object { $DataSourcePath = $DataSourcePaths[$_.DataSourceReference] if (-not $DataSourcePath) { throw "Invalid data source reference '$($_.DataSourceReference)' in $RdlPath" } $Reference = New-Object -TypeName SSRS.ReportingService2010.DataSourceReference $Reference.Reference = $DataSourcePath $DataSource = New-Object -TypeName SSRS.ReportingService2010.DataSource $DataSource.Item = $Reference $DataSource.Name = $_.Name $DataSource } if ($DataSources) { $Proxy.SetItemDataSources($Folder + '/' + $Name, $DataSources) } $Xpath = 'd:Report/d:DataSets/d:DataSet/d:SharedDataSet/d:SharedDataSetReference/../..' $References = $Definition.SelectNodes($Xpath, $NsMgr) | ForEach-Object { $DataSetPath = $DataSetPaths[$_.SharedDataSet.SharedDataSetReference] if ($DataSetPath) { $Reference = New-Object -TypeName SSRS.ReportingService2010.ItemReference $Reference.Reference = $DataSetPath $Reference.Name = $_.Name $Reference } } if ($References) { $Proxy.SetItemReferences($Folder + '/' + $Name, $References) } }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/Get-SSRSProjectConfiguration.ps1
Get-SSRSProjectConfiguration.ps1
function Get-SSRSProjectConfiguration{ #requires -version 2.0 [CmdletBinding()] param ( [parameter(Mandatory=$true)] [ValidatePattern('\.rptproj$')] [ValidateScript({ Test-Path -PathType Leaf -Path $_ })] [string] $Path, [parameter(Mandatory=$true)] [string] $Configuration ) $script:ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest Write-Verbose "Reading '$Configuration' config from '$Path'" [xml]$Project = Get-Content -Path $Path $Config = $Project.SelectNodes('Project/Configurations/Configuration') | Where-Object { $_.Name -eq $Configuration } | Select-Object -First 1 if (-not $Config) { throw "Could not find configuration $Configuration." } $OverwriteDataSources = $false if ($Config.Options.SelectSingleNode('OverwriteDataSources')) { $OverwriteDataSources = [Convert]::ToBoolean($Config.Options.OverwriteDataSources) } $OverwriteDatasets = $false if ($Config.Options.SelectSingleNode('OverwriteDatasets')) { $OverwriteDatasets = [Convert]::ToBoolean($Config.Options.OverwriteDatasets) } return New-Object -TypeName PSObject -Property @{ ServerUrl = $Config.Options.TargetServerUrl Folder = Normalize-SSRSFolder -Folder $Config.Options.TargetFolder DataSourceFolder = Normalize-SSRSFolder -Folder $Config.Options.TargetDataSourceFolder DataSetFolder = Normalize-SSRSFolder -Folder $Config.Options.TargetDataSetFolder OutputPath = $Config.Options.OutputPath OverwriteDataSources = $OverwriteDataSources OverwriteDatasets = $OverwriteDatasets } }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/New-XmlNamespaceManager.ps1
New-XmlNamespaceManager.ps1
function New-XmlNamespaceManager ($XmlDocument, $DefaultNamespacePrefix) { $script:ErrorActionPreference = 'Stop' $NsMgr = New-Object -TypeName System.Xml.XmlNamespaceManager -ArgumentList $XmlDocument.NameTable $DefaultNamespace = $XmlDocument.DocumentElement.GetAttribute('xmlns') if ($DefaultNamespace -and $DefaultNamespacePrefix) { $NsMgr.AddNamespace($DefaultNamespacePrefix, $DefaultNamespace) } return ,$NsMgr # unary comma wraps $NsMgr so it isn't unrolled }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/Get-SSRSCredential.ps1
Get-SSRSCredential.ps1
Function Get-SSRSCredential { [CmdletBinding(SupportsShouldProcess=$true)] param ( [string] $username, [string] $password ) $script:ErrorActionPreference = 'Stop' $pass = ConvertTo-SecureString -AsPlainText -Force -String $password $user = $username $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pass return $cred }
PowerShellCorpus/PowerShellGallery/SSRS/1.3.0/New-SSRSWebServiceProxy.ps1
New-SSRSWebServiceProxy.ps1
Function New-SSRSWebServiceProxy { #requires -version 2.0 [CmdletBinding()] param ( [parameter(Mandatory=$true)] [ValidatePattern('^https?://')] [string] $Uri, [System.Management.Automation.PSCredential] $Credential ) $script:ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest if (-not $Uri.EndsWith('.asmx')) { if (-not $Uri.EndsWith('/')) { $Uri += '/' } $Uri += 'ReportService2010.asmx' } $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetType('SSRS.ReportingService2010.ReportingService2010') } if (($Assembly | Measure-Object).Count -gt 1) { throw 'AppDomain contains multiple definitions of the same type. Restart PowerShell host.' } if (-not $Assembly) { if ($Credential) { $CredParams = @{ Credential = $Credential } } else { $CredParams = @{ UseDefaultCredential = $true } } $Proxy = New-WebServiceProxy -Uri $Uri -Namespace SSRS.ReportingService2010 @CredParams } else { $Proxy = New-Object -TypeName SSRS.ReportingService2010.ReportingService2010 if ($Credential) { $Proxy.Credentials = $Credential.GetNetworkCredential() } else { $Proxy.UseDefaultCredentials = $true } } $Proxy.Url = $Uri return $Proxy }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Eventbrite.Full.Tests.ps1
Eventbrite.Full.Tests.ps1
$Here = Split-Path -Parent $MyInvocation.MyCommand.Path $PrivateFunctions = Get-ChildItem "$here\Private\" -Filter '*.ps1' -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $PublicFunctions = Get-ChildItem "$here\Public\" -Filter '*.ps1' -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $PrivateFunctionsTests = Get-ChildItem "$here\Private\" -Filter '*Tests.ps1' -Recurse $PublicFunctionsTests = Get-ChildItem "$here\Public\" -Filter '*Tests.ps1' -Recurse $Rules = Get-ScriptAnalyzerRule $manifest = Get-Item "$Here\*.psd1" $module = $manifest.BaseName Import-Module "$Here\*.psd1" $ModuleData = Get-Module $Module $AllFunctions = & $moduleData {Param($modulename) Get-command -CommandType Function -Module $modulename} $module if ($PrivateFunctions.count -gt 0) { foreach($PrivateFunction in $PrivateFunctions) { Describe "Testing Private Function - $($PrivateFunction.BaseName) for Standard Processing" { It "Is valid Powershell (Has no script errors)" { $contents = Get-Content -Path $PrivateFunction.FullName -ErrorAction Stop $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) $errors.Count | Should Be 0 } foreach ($rule in $rules) { It “passes the PSScriptAnalyzer Rule $rule“ { (Invoke-ScriptAnalyzer -Path $PrivateFunction.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0 } } } $function = $AllFunctions.Where{ $_.Name -eq $PrivateFunction.BaseName} $PrivateFunctionTests = $PrivateFunctionstests.Where{$_.Name -match $PrivateFunction.BaseName } foreach ($PrivateFunctionTest in $PrivateFunctionTests) { . $($PrivateFunctionTest.FullName) $function } } } if ($PublicFunctions.count -gt 0) { foreach($PublicFunction in $PublicFunctions) { Describe "Testing Public Function - $($PublicFunction.BaseName) for Standard Processing" { It "Is valid Powershell (Has no script errors)" { $contents = Get-Content -Path $PublicFunction.FullName -ErrorAction Stop $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) $errors.Count | Should Be 0 } foreach ($rule in $rules) { It “passes the PSScriptAnalyzer Rule $rule“ { (Invoke-ScriptAnalyzer -Path $PublicFunction.FullName -IncludeRule $rule.RuleName ).Count | Should Be 0 } } } $function = $AllFunctions.Where{ $_.Name -eq $PublicFunction.BaseName} $publicfunctionTests = $Publicfunctionstests.Where{$_.Name -match $PublicFunction.BaseName } foreach ($publicfunctionTest in $publicfunctionTests) { . $($PublicFunctionTest.FullName) $function } } }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Eventbrite.Min.Tests.ps1
Eventbrite.Min.Tests.ps1
$Here = Split-Path -Parent $MyInvocation.MyCommand.Path $PrivateFunctions = Get-ChildItem "$here\Private\" -Filter '*.ps1' -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $PublicFunctions = Get-ChildItem "$here\Public\" -Filter '*.ps1' -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $PrivateFunctionsTests = Get-ChildItem "$here\Private\" -Filter '*Tests.ps1' -Recurse $PublicFunctionsTests = Get-ChildItem "$here\Public\" -Filter '*Tests.ps1' -Recurse $Rules = Get-ScriptAnalyzerRule $manifest = Get-Item "$Here\*.psd1" $module = $manifest.BaseName Import-Module "$Here\*.psd1" $ModuleData = Get-Module $Module $AllFunctions = & $moduleData {Param($modulename) Get-command -CommandType Function -Module $modulename} $module $PublicFunctionPath = "$here\Public\" $PrivateFunctionPath = "$here\Private\" if ($PrivateFunctions.count -gt 0) { foreach($PrivateFunction in $PrivateFunctions) { Describe "Testing Private Function - $($PrivateFunction.BaseName) for Standard Processing" { It "Is valid Powershell (Has no script errors)" { $contents = Get-Content -Path $PrivateFunction.FullName -ErrorAction Stop $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) $errors.Count | Should Be 0 } } } } if ($PublicFunctions.count -gt 0) { foreach($PublicFunction in $PublicFunctions) { Describe "Testing Public Function - $($PublicFunction.BaseName) for Standard Processing" { It "Is valid Powershell (Has no script errors)" { $contents = Get-Content -Path $PublicFunction.FullName -ErrorAction Stop $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) $errors.Count | Should Be 0 } } $function = $AllFunctions.Where{ $_.Name -eq $PublicFunction.BaseName} $publicfunctionTests = $Publicfunctionstests.Where{$_.Name -match $PublicFunction.BaseName } foreach ($publicfunctionTest in $publicfunctionTests) { . $($PublicFunctionTest.FullName) $function } } } Describe 'ScriptAnalyzer Rule Testing' { Context 'Public Functions' { It 'Passes the Script Analyzer ' { (Invoke-ScriptAnalyzer -Path $PublicFunctionPath -Recurse ).Count | Should Be 0 } } Context 'Private Functions' { It 'Passes the Script Analyzer ' { (Invoke-ScriptAnalyzer -Path $PrivateFunctionPath ).Count | Should Be 0 } } }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Eventbrite.Norm.Tests.ps1
Eventbrite.Norm.Tests.ps1
$Here = Split-Path -Parent $MyInvocation.MyCommand.Path $PrivateFunctions = Get-ChildItem "$here\Private\" -Filter '*.ps1' -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $PublicFunctions = Get-ChildItem "$here\Public\" -Filter '*.ps1' -Recurse | Where-Object {$_.name -NotMatch "Tests.ps1"} $PrivateFunctionsTests = Get-ChildItem "$here\Private\" -Filter '*Tests.ps1' -Recurse $PublicFunctionsTests = Get-ChildItem "$here\Public\" -Filter '*Tests.ps1' -Recurse $Rules = Get-ScriptAnalyzerRule $manifest = Get-Item "$Here\*.psd1" $module = $manifest.BaseName Import-Module "$Here\*.psd1" $ModuleData = Get-Module $Module $AllFunctions = & $moduleData {Param($modulename) Get-command -CommandType Function -Module $modulename} $module $PublicFunctionPath = "$here\Public\" $PrivateFunctionPath = "$here\Private\" if ($PrivateFunctions.count -gt 0) { foreach($PrivateFunction in $PrivateFunctions) { Describe "Testing Private Function - $($PrivateFunction.BaseName) for Standard Processing" { It "Is valid Powershell (Has no script errors)" { $contents = Get-Content -Path $PrivateFunction.FullName -ErrorAction Stop $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) $errors.Count | Should Be 0 } } $function = $AllFunctions.Where{ $_.Name -eq $PrivateFunction.BaseName} $PrivateFunctionTests = $PrivateFunctionstests.Where{$_.Name -match $PrivateFunction.BaseName } foreach ($PrivateFunctionTest in $PrivateFunctionTests) { . $($PrivateFunctionTest.FullName) $function } } } if ($PublicFunctions.count -gt 0) { foreach($PublicFunction in $PublicFunctions) { Describe "Testing Public Function - $($PublicFunction.BaseName) for Standard Processing" { It "Is valid Powershell (Has no script errors)" { $contents = Get-Content -Path $PublicFunction.FullName -ErrorAction Stop $errors = $null $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors) $errors.Count | Should Be 0 } } $function = $AllFunctions.Where{ $_.Name -eq $PublicFunction.BaseName} $publicfunctionTests = $Publicfunctionstests.Where{$_.Name -match $PublicFunction.BaseName } foreach ($publicfunctionTest in $publicfunctionTests) { . $($PublicFunctionTest.FullName) $function } } } Describe 'ScriptAnalyzer Rule Testing' { Context 'Public Functions' { It 'Passes the Script Analyzer ' { (Invoke-ScriptAnalyzer -Path $PublicFunctionPath -Recurse ).Count | Should Be 0 } } Context 'Private Functions' { It 'Passes the Script Analyzer ' { (Invoke-ScriptAnalyzer -Path $PrivateFunctionPath ).Count | Should Be 0 } } }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Get-EventbriteEvents.ps1
Get-EventbriteEvents.ps1
function Get-EventbriteEvents { <# .Synopsis This Function will Get all EventBrite Events .DESCRIPTION To be completed .EXAMPLE Get-EventbriteEvents -EventbrightToken $env:EventbriteToken .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages #> [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $EventbriteToken ) $Events = Invoke-RestMethod https://www.eventbriteapi.com/v3/users/me/owned_events/?token=$EventbriteToken Foreach ($event in $events.events ) { $event.Name = $event.Name.Text $event.start = (([DateTime]($event.start.local)).ToUniversalTime()) $event.end = (([DateTime]($event.end.local)).ToUniversalTime()) Add-Member -Name Year -InputObject $event -MemberType NoteProperty -Value $event.start.Year } $Events }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Get-EventbriteEvent.ps1
Get-EventbriteEvent.ps1
function Get-EventbriteEvent { <# .Synopsis This Function will Get a specific EventBrite Event .DESCRIPTION To be completed .EXAMPLE Get-EventbriteEvent -EventbrightToken $env:EventbriteToken -EventID 1234376727438 .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages .PARAMETER EventID Unique Token as can be obtained from the EventBrite API Pages #> [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $EventbriteToken, [Parameter(Mandatory=$true)] [string]$EventID ) $Event = Invoke-RestMethod https://www.eventbriteapi.com/v3/events/$eventid/?token=$EventbriteToken $event.Name = $event.Name.Text $event.start = (([DateTime]($event.start.local)).ToUniversalTime()) $event.end = (([DateTime]($event.end.local)).ToUniversalTime()) $myevents += $event $myevents }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Get-EventbriteOrders.ps1
Get-EventbriteOrders.ps1
function Get-EventbriteOrders { <# .Synopsis This Function will Get all EventBrite Orders .DESCRIPTION To be completed .EXAMPLE Get-EventbriteOrders -EventbrightToken $env:EventbriteToken .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages #> [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $EventbriteToken ) $orders = Invoke-RestMethod https://www.eventbriteapi.com/v3/users/me/orders/?token=$EventbriteToken foreach ($order in $orders.orders) { Get-EventbriteEvent -EventbriteToken $EventbriteToken -EventID $order.event_id } $orders }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Get-EventbriteVenue.ps1
Get-EventbriteVenue.ps1
function Get-EventbriteVenue { <# .Synopsis This Function will return the venue object from an EventBrite event .DESCRIPTION To be completed .EXAMPLE Get-EventbriteVenue -EventbrightToken $env:EventbriteToken -VenueID $venueID .PARAMETER VenueID An interger that uniquely identifies the venue .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages #> [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $EventbriteToken, [Parameter(Mandatory=$true)] [string] $VenueID ) $Venue = Invoke-RestMethod https://www.eventbriteapi.com/v3/venues/$VenueID/?token=$EventbriteToken $Venue }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Get-EventbriteEventQuestions.ps1
Get-EventbriteEventQuestions.ps1
function Get-EventbriteEventQuestions { <# .Synopsis This Function will Get all Questions from a specificed EventBrite Event .DESCRIPTION To be completed .EXAMPLE Get-EventbriteEventQuestions -EventbrightToken $env:EventbriteToken -EventID 1232786423 .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages .PARAMETER EventID Unique identifer for the event listing #> [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $EventbriteToken, [Parameter(Mandatory=$true)] [string] $EventID ) $questions = (Invoke-RestMethod https://www.eventbriteapi.com/v3/events/$eventid/questions/?token=$EventbriteToken ).questions $questions }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Get-EventAttendee.ps1
Get-EventAttendee.ps1
function Get-EventAttendee { <# .Synopsis This Function will return the attendees for an EventBrite event .DESCRIPTION To be completed .EXAMPLE Get-EventAttendees -EventbrightToken $env:EventbriteToken -Location Manchester -Month February -Year 2016 .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages .PARAMETER Unique Token as can be obtained from the EventBrite API Pages .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages .PARAMETER EventbriteToken Unique Token as can be obtained from the EventBrite API Pages #> [cmdletbinding()] param ( [Parameter(Mandatory=$true)] [string] $EventbriteToken ) Get-EventbriteEvents -EventbriteToken $EventbriteToken $event = $($events.events.Where({$_.Name.contains($location)}).where({$_.name.contains($month)}).where({$_.Year -eq $year})) $AttendeesOutput = New-Object System.Collections.Arraylist $eventid = $event.id $Attendees = Invoke-RestMethod -Uri https://www.eventbriteapi.com/v3/events/$eventID/attendees/?token=$EventbriteToken $Orders = Invoke-RestMethod -Uri https://www.eventbriteapi.com/v3/events/$eventID/orders/?token=$EventbriteToken $pscustom = [PSCustomObject]@{Attendees = $Attendees.attendees ; Orders = $Orders.orders} foreach ($attendee in $pscustom.Attendees) { if($attendee.status -eq 'Attending') { if ($pscustom.Orders.Id -contains $attendee.order_id) { $details = $pscustom.Orders | Where-Object {$_.Id -eq $attendee.order_id} | Select-Object name,first_name,last_name,email $AttendeesOutput.add($details) | Out-Null } } } $AttendeesOutput }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Tests/Get-EventbriteOrders.Tests.ps1
Get-EventbriteOrders.Tests.ps1
Describe 'Get-EventbriteOrders Tests' { Context 'Parameters for Get-EventbriteOrders'{ It 'Has a Parameter called EventbriteToken' { $Function.Parameters.Keys.Contains('EventbriteToken') | Should Be 'True' } It 'EventbriteToken Parameter is Identified as Mandatory being True' { [String]$Function.Parameters.EventbriteToken.Attributes.Mandatory | Should be 'True' } It 'EventbriteToken Parameter is of String Type' { $Function.Parameters.EventbriteToken.ParameterType.FullName | Should be 'System.String' } It 'EventbriteToken Parameter is member of ParameterSets' { [String]$Function.Parameters.EventbriteToken.ParameterSets.Keys | Should Be '__AllParameterSets' } It 'EventbriteToken Parameter Position is defined correctly' { [String]$Function.Parameters.EventbriteToken.Attributes.Position | Should be '0' } It 'Does EventbriteToken Parameter Accept Pipeline Input?' { [String]$Function.Parameters.EventbriteToken.Attributes.ValueFromPipeline | Should be 'False' } It 'Does EventbriteToken Parameter Accept Pipeline Input by PropertyName?' { [String]$Function.Parameters.EventbriteToken.Attributes.ValueFromPipelineByPropertyName | Should be 'False' } It 'Does EventbriteToken Parameter use advanced parameter Validation? ' { $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateNotNullOrEmptyAttribute' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateNotNullAttribute' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateScript' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateRangeAttribute' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidatePatternAttribute' | Should Be 'False' } It 'Has Parameter Help Text for EventbriteToken '{ $function.Definition.Contains('.PARAMETER EventbriteToken') | Should Be 'True' } } Context "Function $($function.Name) - Help Section" { It "Function $($function.Name) Has show-help comment block" { $function.Definition.Contains('<#') | should be 'True' $function.Definition.Contains('#>') | should be 'True' } It "Function $($function.Name) Has show-help comment block has a.SYNOPSIS" { $function.Definition.Contains('.SYNOPSIS') -or $function.Definition.Contains('.Synopsis') | should be 'True' } It "Function $($function.Name) Has show-help comment block has an example" { $function.Definition.Contains('.EXAMPLE') | should be 'True' } It "Function $($function.Name) Is an advanced function" { $function.CmdletBinding | should be 'True' $function.Definition.Contains('param') -or $function.Definition.Contains('Param') | should be 'True' } } }
PowerShellCorpus/PowerShellGallery/Eventbrite/0.0.2/Public/Get/Tests/Get-EventbriteVenue.Tests.ps1
Get-EventbriteVenue.Tests.ps1
Describe 'Get-EventbriteVenue Tests' { Context 'Parameters for Get-EventbriteVenue'{ It 'Has a Parameter called EventbriteToken' { $Function.Parameters.Keys.Contains('EventbriteToken') | Should Be 'True' } It 'EventbriteToken Parameter is Identified as Mandatory being True' { [String]$Function.Parameters.EventbriteToken.Attributes.Mandatory | Should be 'True' } It 'EventbriteToken Parameter is of String Type' { $Function.Parameters.EventbriteToken.ParameterType.FullName | Should be 'System.String' } It 'EventbriteToken Parameter is member of ParameterSets' { [String]$Function.Parameters.EventbriteToken.ParameterSets.Keys | Should Be '__AllParameterSets' } It 'EventbriteToken Parameter Position is defined correctly' { [String]$Function.Parameters.EventbriteToken.Attributes.Position | Should be '0' } It 'Does EventbriteToken Parameter Accept Pipeline Input?' { [String]$Function.Parameters.EventbriteToken.Attributes.ValueFromPipeline | Should be 'False' } It 'Does EventbriteToken Parameter Accept Pipeline Input by PropertyName?' { [String]$Function.Parameters.EventbriteToken.Attributes.ValueFromPipelineByPropertyName | Should be 'False' } It 'Does EventbriteToken Parameter use advanced parameter Validation? ' { $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateNotNullOrEmptyAttribute' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateNotNullAttribute' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateScript' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidateRangeAttribute' | Should Be 'False' $Function.Parameters.EventbriteToken.Attributes.TypeID.Name -contains 'ValidatePatternAttribute' | Should Be 'False' } It 'Has Parameter Help Text for EventbriteToken '{ $function.Definition.Contains('.PARAMETER EventbriteToken') | Should Be 'True' } It 'Has a Parameter called VenueID' { $Function.Parameters.Keys.Contains('VenueID') | Should Be 'True' } It 'VenueID Parameter is Identified as Mandatory being True' { [String]$Function.Parameters.VenueID.Attributes.Mandatory | Should be 'True' } It 'VenueID Parameter is of String Type' { $Function.Parameters.VenueID.ParameterType.FullName | Should be 'System.String' } It 'VenueID Parameter is member of ParameterSets' { [String]$Function.Parameters.VenueID.ParameterSets.Keys | Should Be '__AllParameterSets' } It 'VenueID Parameter Position is defined correctly' { [String]$Function.Parameters.VenueID.Attributes.Position | Should be '1' } It 'Does VenueID Parameter Accept Pipeline Input?' { [String]$Function.Parameters.VenueID.Attributes.ValueFromPipeline | Should be 'False' } It 'Does VenueID Parameter Accept Pipeline Input by PropertyName?' { [String]$Function.Parameters.VenueID.Attributes.ValueFromPipelineByPropertyName | Should be 'False' } It 'Does VenueID Parameter use advanced parameter Validation? ' { $Function.Parameters.VenueID.Attributes.TypeID.Name -contains 'ValidateNotNullOrEmptyAttribute' | Should Be 'False' $Function.Parameters.VenueID.Attributes.TypeID.Name -contains 'ValidateNotNullAttribute' | Should Be 'False' $Function.Parameters.VenueID.Attributes.TypeID.Name -contains 'ValidateScript' | Should Be 'False' $Function.Parameters.VenueID.Attributes.TypeID.Name -contains 'ValidateRangeAttribute' | Should Be 'False' $Function.Parameters.VenueID.Attributes.TypeID.Name -contains 'ValidatePatternAttribute' | Should Be 'False' } It 'Has Parameter Help Text for VenueID '{ $function.Definition.Contains('.PARAMETER VenueID') | Should Be 'True' } } Context "Function $($function.Name) - Help Section" { It "Function $($function.Name) Has show-help comment block" { $function.Definition.Contains('<#') | should be 'True' $function.Definition.Contains('#>') | should be 'True' } It "Function $($function.Name) Has show-help comment block has a.SYNOPSIS" { $function.Definition.Contains('.SYNOPSIS') -or $function.Definition.Contains('.Synopsis') | should be 'True' } It "Function $($function.Name) Has show-help comment block has an example" { $function.Definition.Contains('.EXAMPLE') | should be 'True' } It "Function $($function.Name) Is an advanced function" { $function.CmdletBinding | should be 'True' $function.Definition.Contains('param') -or $function.Definition.Contains('Param') | should be 'True' } } }