full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/Measure-Group.ps1
Measure-Group.ps1
function Measure-Group { [CmdletBinding()] param( [Parameter(Mandatory,ValueFromPipeline)] [ValidateNotNullOrEmpty()] [Microsoft.PowerShell.Commands.GroupInfo[]] $InputObject , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $Property ) Process { $InputObject | ForEach-Object { $Measurement = Measure-Object -Data $_.Group -Property $Property Add-Member -InputObject $Measurement -MemberType NoteProperty -Name Name -Value $_.Name -PassThru } } } New-Alias -Name mg -Value Measure-Group -Force
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/Get-SlidingAverage.ps1
Get-SlidingAverage.ps1
function Get-SlidingAverage { [CmdletBinding()] Param( [Parameter(Mandatory,ValueFromPipeline)] [ValidateNotNullOrEmpty()] [array] $InputObject , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $Property , [Parameter()] [ValidateNotNullOrEmpty()] [int] $Size = 5 ) Begin { Write-Debug ('[{0}] Size of queue is <{1}>' -f $MyInvocation.MyCommand, $q.Count) $q = New-Object -TypeName System.Collections.Queue -ArgumentList $Size } Process { $InputObject | ForEach-Object { if (($_ | Select-Object -ExpandProperty $Property -ErrorAction 'SilentlyContinue') -eq $null) { throw ('[{0}] Unable to find property <{1}> in input object' -f $MyInvocation.MyCommand, $Property) } #region Enqueue new item and trim to specified size $q.Enqueue($_) Write-Debug ('[{0}] Size of queue is <{1}>' -f $MyInvocation.MyCommand, $q.Count) if ($q.Count -gt $Size) { $q.Dequeue() | Out-Null } #endregion #region Calculate average if the specified number of items is present if ($q.Count -eq $Size) { $q | Microsoft.PowerShell.Utility\Measure-Object -Property $Property -Average | Select-Object -ExpandProperty Average } #endregion } } } New-Alias -Name gsa -Value Get-SlidingAverage -Force
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/New-RangeString.ps1
New-RangeString.ps1
function New-RangeString { [CmdletBinding()] param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [int] $Width , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [int] $LeftIndex , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [int] $RightIndex , [Parameter()] [ValidateNotNullOrEmpty()] [string] $LeftIndicator = '|' , [Parameter()] [ValidateNotNullOrEmpty()] [string] $RightIndicator = '|' ) Write-Debug ('[{0}] Width={1} LeftIndex={2} RightIndex={3}' -f $MyInvocation.MyCommand, $Width, $LeftIndex, $RightIndex) if ($LeftIndex -lt 0) { $LeftIndex = 1 $LeftIndicator = '<' } if ($LeftIndex -eq 0) { $LeftIndex = 1 } Write-Debug ('[{0}] Width={1} LeftIndex={2} RightIndex={3}' -f $MyInvocation.MyCommand, $Width, $LeftIndex, $RightIndex) $line = ' ' * ($LeftIndex - 1) + $LeftIndicator if ($RightIndex -gt $Width) { $RightIndex = $Width $RightIndicator = '>' } Write-Debug ('[{0}] Width={1} LeftIndex={2} RightIndex={3}' -f $MyInvocation.MyCommand, $Width, $LeftIndex, $RightIndex) if ($RightIndex -gt $LeftIndex) { $line += '-' * ($RightIndex - $LeftIndex - 1) } $line += $RightIndicator $line }
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/Add-Bar.ps1
Add-Bar.ps1
function Add-Bar { [CmdletBinding()] Param( [Parameter(Mandatory, ValueFromPipeline)] [ValidateNotNullOrEmpty()] [array] $InputObject , [Parameter()] [ValidateNotNullOrEmpty()] [string] $Property = 'Count' , [Parameter()] [ValidateNotNullOrEmpty()] [int] $Width = $( if ($Host.UI.RawUI.MaxWindowSize.Width) { $Host.UI.RawUI.MaxWindowSize.Width - 20 } else { 50 } ) ) Begin { Write-Verbose ('[{0}] Initializing' -f $MyInvocation.MyCommand) $Data = New-Object -TypeName System.Collections.ArrayList } Process { if ($PSBoundParameters.ContainsKey('InputObject')) { $Data = $InputObject foreach ($_ in $Data) { if (($_ | Select-Object -ExpandProperty $Property -ErrorAction SilentlyContinue) -eq $null) { throw ('Input object does not contain a property called <{0}>.' -f $Property) } } } else { Write-Verbose ('[{0}] Processing {1} items' -f $MyInvocation.MyCommand, $InputObject.Length) $InputObject | ForEach-Object { if (($_ | Select-Object -ExpandProperty $Property -ErrorAction SilentlyContinue) -eq $null) { throw ('Input object does not contain a property called <{0}>.' -f $Property) } [void]$Data.Add($_) } } } End { Write-Verbose ('[{0}] Adding bars' -f $MyInvocation.MyCommand) $Count = $Data | Microsoft.PowerShell.Utility\Measure-Object -Maximum -Property $Property | Select-Object -ExpandProperty Maximum Write-Debug ('[{0}] Maximum value is {1}. This value will be {2} characters long.' -f $MyInvocation.MyCommand, $Count, $Width) $Bars = foreach ($_ in $Data) { $RelativeCount = [math]::Round($_.$Property / $Count * $Width, 0) Write-Debug ('[{0}] Value of {1} will be displayed using {2} characters.' -f $MyInvocation.MyCommand, $_.Property, $RelativeCount) Write-Debug ('[{0}] Adding member to input object.' -f $MyInvocation.MyCommand) $Item = $_ | Select-Object -Property Index,Count | Add-Member -MemberType NoteProperty -Name Bar -Value ('#' * $RelativeCount) -PassThru Write-Debug ('[{0}] Adding type name to output object.' -f $MyInvocation.MyCommand) $Item.PSTypeNames.Insert(0, 'HistogramBar') Write-Debug ('[{0}] Returning output object.' -f $MyInvocation.MyCommand) $Item } Write-Debug ('[{0}] Returning input objects with bars.' -f $MyInvocation.MyCommand) $Bars } } New-Alias -Name ab -Value Add-Bar -Force
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/ConvertFrom-PerformanceCounter.ps1
ConvertFrom-PerformanceCounter.ps1
function ConvertFrom-PerformanceCounter { [CmdletBinding()] param( [Parameter(Mandatory,ValueFromPipeline)] [ValidateNotNullOrEmpty()] [array] $InputObject , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $Instance ) Process { $InputObject | ForEach-Object { [pscustomobject]@{ Timestamp = $_.Timestamp Value = $_.CounterSamples | Where-Object { $_.InstanceName -ieq $Instance } | Select-Object -ExpandProperty CookedValue } } } } New-Alias -Name cfpc -Value ConvertFrom-PerformanceCounter -Force
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/Get-WeightedValue.ps1
Get-WeightedValue.ps1
function Get-WeightedValue { [CmdletBinding()] Param( [Parameter(Mandatory,ValueFromPipeline)] [ValidateNotNullOrEmpty()] [array] $InputObject , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $Property , [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $WeightProperty ) Process { $InputObject | ForEach-Object { if (($_ | Select-Object -ExpandProperty $Property -ErrorAction 'SilentlyContinue') -eq $null) { throw ('[{0}] Unable to find property <{1}> in input object' -f $MyInvocation.MyCommand, $Property) } if (($_ | Select-Object -ExpandProperty $WeightProperty -ErrorAction 'SilentlyContinue') -eq $null) { throw ('[{0}] Unable to find weight property <{1}> in input object' -f $MyInvocation.MyCommand, $WeightProperty) } [pscustomobject]@{ Value = $_.$WeightProperty * $_.$Property } } } } New-Alias -Name gwv -Value Get-WeightedValue -Force
PowerShellCorpus/PowerShellGallery/Statistics/1.1.63/Expand-DateTime.ps1
Expand-DateTime.ps1
function Expand-DateTime { [CmdletBinding()] Param( [Parameter(Mandatory,ValueFromPipeline)] [ValidateNotNullOrEmpty()] [array] $InputObject , [Parameter()] [ValidateNotNullOrEmpty()] [string] $Property = 'Timestamp' ) Process { Write-Debug ('[{0}] Entering process block' -f $MyInvocation.MyCommand) $InputObject | ForEach-Object { Write-Debug 'inside foreach' if (($_ | Select-Object -ExpandProperty $Property -ErrorAction 'SilentlyContinue') -eq $null) { throw ('[{0}] Unable to find property <{1}> in input object' -f $MyInvocation.MyCommand, $Property) } $DateTimeExpanded = $_.$Property if ($DateTimeExpanded -isnot [System.DateTime]) { Write-Debug 'inside if' $DateTimeExpanded = Get-Date -Date $_.$Property $_.$Property = $DateTimeExpanded } foreach ($DateTimeProperty in @('DayOfWeek')) { Add-Member -InputObject $_ -MemberType NoteProperty -Name $DateTimeProperty -Value $DateTimeExpanded.$DateTimeProperty } foreach ($DateTimeProperty in @('Year', 'Month', 'Hour')) { Add-Member -InputObject $_ -MemberType NoteProperty -Name $DateTimeProperty -Value ([int]($DateTimeExpanded.$DateTimeProperty)) } Add-Member -InputObject $_ -MemberType NoteProperty -Name WeekOfYear -Value ([int](Get-Date -Date $_.$Property -UFormat '%V')) $_ } } } New-Alias -Name edt -Value Expand-DateTime -Force
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.0.7/Examples/Install-IIM.ps1
Install-IIM.ps1
#requires -Version 5 Configuration IIM { Import-DSCResource -module cIBMInstallationManager -ModuleVersion '1.0.6' Package SevenZip { Ensure = 'Present' Name = '7-Zip 9.20 (x64 edition)' ProductId = '23170F69-40C1-2702-0920-000001000000' Path = 'C:\Media\7z920-x64.msi' } cIBMInstallationManager iimInstall { Ensure = 'Present' InstallationDirectory = 'C:\IBM\IIM' Version = '1.8.3' SourcePath = 'C:\Media\agent.installer.win32.win32.x86_1.8.3000.20150606_0047.zip' DependsOn= "[Package]SevenZip" } } IIM Start-DscConfiguration -Wait -Force -Verbose IIM
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.0.7/Classes/IBMProductMedia.ps1
IBMProductMedia.ps1
<# PowerShell Classes to Model IBM Installation Media Key features: - Model product configuration that can be extracted as Clixml files for later use - Expand IBM media from local or network shares - Get estimated size of the product installation - Get list of repository locations once media has been extracted #> <# PowerShell Object Model for IBM Installation Manager media files. Typically media files are zip files provided by IBM. #> Class MediaFile { #Filename of the media file [String] $Name #(Optional) Location of the repository.config file within the zip file [String] $RepositoryConfigPath #(Optional) Size of media on disk once extracted [Long] $SizeOnDisk #Zip files inside this media file that may need to be extracted [MediaFile[]] $SubMediaFiles <# Extract this media file to the target path (Requires 7-Zip) #> [Bool] ExtractMedia([String] $TargetPath, [String] $SourcePath, [bool] $DeepScan = $false) { Return ($this._ExtractMedia($this, $TargetPath, $SourcePath, $DeepScan)) } hidden [Bool] _ExtractMedia([MediaFile] $mediaFile, [String] $TargetPath, [String] $SourcePath, [bool] $DeepScan) { $extracted = $false $fullMediaPath = Join-Path $SourcePath -ChildPath ($mediaFile.Name) if (!(Test-Path alias:zip)) { #Setup 7-Zip Alias $sevenZipExe = Get-SevenZipExecutable if (!([string]::IsNullOrEmpty($sevenZipExe)) -and (Test-Path($sevenZipExe))) { Set-Alias zip $sevenZipExe -Scope 'Script' } else { Write-Error "MediaFile depends on 7-Zip, please ensure 7-Zip is installed first" Return $false } } if (Test-Path($fullMediaPath)) { Write-Verbose "Extracting installation media from: $fullMediaPath" zip x "-o$TargetPath" "$fullMediaPath" | Out-Null # Some media have an additional zip file needed to extract, find it, expand it, and delete it to save disk space if ($DeepScan) { $childZipFiles = Get-ChildItem *.zip -Path $TargetPath foreach ($childZipFile in $childZipFiles) { zip x "-o$TargetPath" $childZipFile.FullName | Out-Null Remove-Item $childZipFile.FullName -force } } Write-Verbose "Completed extracting media files to directory: $TargetPath" $extracted = $true } else { Write-Error "Unable to access media files. Media Path is: $SourcePath" $extracted = $false } if ($extracted) { if ($mediaFile.SubMediaFiles -and ($mediaFile.SubMediaFiles.Count -gt 0)) { Foreach ($subMediaFile in $mediaFile.SubMediaFiles) { $extracted = $subMediaFile._ExtractMedia($subMediaFile, $TargetPath, $SourcePath) } } } Return $extracted } <# Returns a list of paths to the repository locations of this media file and its children #> [String[]] GetRepositoryLocations([String] $BasePath, [Bool] $Validate) { Return ($this._GetRepositoryLocations($this, $BasePath, $Validate)) } hidden [String[]] _GetRepositoryLocations([MediaFile] $mediaFile, [String] $BasePath, [Bool] $Validate) { [String[]] $repositories = @(); if ($mediaFile.RepositoryConfigPath) { $repositoryFullPath = Join-Path -Path $BasePath -ChildPath $mediaFile.RepositoryConfigPath if ($Validate) { try { if (Test-Path($repositoryFullPath)) { $repositories += $repositoryFullPath } else { Write-Error "Repository location not found: $repositoryFullPath" } } catch [System.Exception] { Write-Error "Repository location not found or could not be reached: $repositoryFullPath" } } else { $repositories += $repositoryFullPath } } if ($mediaFile.SubMediaFiles -and ($mediaFile.SubMediaFiles.Count -gt 0)) { Foreach ($subMediaFile in $mediaFile.SubMediaFiles) { $repositories += $subMediaFile._GetRepositoryLocations($subMediaFile, $BasePath, $Validate) } } Return $repositories } } <# PowerShell Object Model for IBM Products that will be installed via IBM Installation Manager #> Class IBMProductMedia { # Name of the IBM product, should match offering name in repository.xml [String] $Name # (optional) Shortname of the IBM product, will be added to the path when media is extracted. [String] $ShortName # Version of the IBM product, should match offering version in repository.xml [System.Version] $Version # List of media files that make up this product [MediaFile[]] $MediaFiles # List of fixes required for the installation [MediaFile[]] $RequiredFixesMediaFiles # List of other products that this product depends on as part of the installation [IBMProductMedia[]] $RequiredProducts <# Extracts all the required media for this product to be installed. #> [Bool] ExtractMedia([String] $TargetPath, [String] $SourcePath, [System.Management.Automation.PSCredential] $SourcePathCredential, [Bool] $CleanUp, [bool] $DeepScan = $false) { if (([string]::IsNullOrEmpty($SourcePath)) -or ([string]::IsNullOrEmpty($TargetPath))) { Write-Error "TargetPath and SourcePath are required parameters" Return $false } #Make sure media is available, map to random drive if network drive $networkShare = $false try { if (($SourcePath.StartsWith("\\")) -and (!(Test-Path($SourcePath)))) { $networkShare = $true } } catch [System.UnauthorizedAccessException] { $networkShare = $true } if ($networkShare) { Write-Verbose "Network Share detected, need to map" Set-NetUse -SharePath (Split-Path($SourcePath)) -SharePathCredential $SourcePathCredential -Ensure "Present" | Out-Null } if (!(Test-Path $SourcePath -PathType Container)) { Write-Error "Invalid SourcePath (Not A Folder). SourcePath should be a folder where the IBM media is residing" } if (($CleanUp) -and (Test-Path($TargetPath))) { Write-Verbose "Cleaning up existing target path for installation media: $TargetPath" Remove-Item $TargetPath -Recurse -Force } if (!(Test-Path($TargetPath))) { New-Item -ItemType directory -Path $TargetPath | Out-Null } try { $this._ExtractMedia($this, $TargetPath, $SourcePath, $DeepScan) } catch { $ErrorMessage = $_.Exception.Message Write-Error "An error occurred while extracting the media: $SourcePath \n Error Message: $ErrorMessage" } finally { if ($networkShare) { try { Set-NetUse -SharePath (Split-Path($SourcePath)) -SharePathCredential $SourcePathCredential -Ensure "Absent" | Out-Null } catch { Write-Warning "Unable to disconnect share: $SourcePath" } } } Return ($this._GetRepositoryLocations($this, $TargetPath, $CleanUp)) } hidden [Bool] _ExtractMedia([IBMProductMedia] $ibmProductMedia, [String] $TargetPath, [String] $SourcePath, [bool] $DeepScan) { [Bool] $extracted = $false [Bool] $hasMedia = $false [Bool] $mediaExtracted = $false [Bool] $hasFixes = $false [Bool] $fixesExtracted = $false [String[]] $productTargetPath = $TargetPath if ($ibmProductMedia.ShortName) { $productTargetPath = Join-Path -Path $TargetPath -ChildPath $ibmProductMedia.ShortName } if ($ibmProductMedia.MediaFiles -and ($ibmProductMedia.MediaFiles.Count -gt 0)) { $hasMedia = $true $mediaExtracted = $true Foreach ($mediaFile in $ibmProductMedia.MediaFiles) { if ($mediaExtracted) { $mediaExtracted = $mediaFile.ExtractMedia($productTargetPath, $SourcePath, $DeepScan) } } $extracted = $mediaExtracted } if (!$extracted -or ($hasMedia -and $mediaExtracted)) { if ($ibmProductMedia.RequiredFixesMediaFiles -and ($ibmProductMedia.RequiredFixesMediaFiles.Count -gt 0)) { $hasFixes = $true $fixesExtracted = $true Foreach ($mediaFile in $ibmProductMedia.RequiredFixesMediaFiles) { if ($fixesExtracted) { $fixesExtracted = $mediaFile.ExtractMedia($productTargetPath, $SourcePath, $DeepScan) } } $extracted = $fixesExtracted } } if (!$extracted -or (($hasFixes -or $hasMedia) -and $extracted)) { if ($ibmProductMedia.RequiredProducts -and ($ibmProductMedia.RequiredProducts.Count -gt 0)) { Foreach ($ibmProduct in $ibmProductMedia.RequiredProducts) { $extracted = $this._ExtractMedia($ibmProduct, $TargetPath, $SourcePath, $DeepScan) } } } Return $extracted } <# Returns a list of paths to the repository locations of this product and its dependent products #> [String[]] GetRepositoryLocations([String] $BasePath, [Bool] $Validate) { Return ($this._GetRepositoryLocations($this, $BasePath, $Validate)) } hidden [String[]] _GetRepositoryLocations([IBMProductMedia] $ibmProductMedia, [String] $BasePath, [Bool] $Validate) { [String[]] $repositories = @(); [String[]] $productBasePath = $BasePath if ($ibmProductMedia.ShortName) { $productBasePath = Join-Path -Path $BasePath -ChildPath $ibmProductMedia.ShortName } if ($ibmProductMedia.MediaFiles -and ($ibmProductMedia.MediaFiles.Count -gt 0)) { Foreach ($mediaFile in $ibmProductMedia.MediaFiles) { $repositories += $mediaFile.GetRepositoryLocations($productBasePath, $Validate) } } if ($ibmProductMedia.RequiredFixesMediaFiles -and ($ibmProductMedia.RequiredFixesMediaFiles.Count -gt 0)) { Foreach ($mediaFile in $ibmProductMedia.RequiredFixesMediaFiles) { $repositories += $mediaFile.GetRepositoryLocations($productBasePath, $Validate) } } if ($ibmProductMedia.RequiredProducts -and ($ibmProductMedia.RequiredProducts.Count -gt 0)) { Foreach ($ibmProduct in $ibmProductMedia.RequiredProducts) { $repositories += $this._GetRepositoryLocations($ibmProduct, $BasePath, $Validate) } } Return $repositories } <# Returns the estimated disk space that this product will consume once extracted #> [Long] GetTotalSizeOnDisk() { Return ($this._GetTotalSizeOnDisk($this)) } hidden [Long] _GetTotalSizeOnDisk([IBMProductMedia] $ibmProductMedia) { [Long] $sizeOnDisk = 0; if ($ibmProductMedia.MediaFiles -and ($ibmProductMedia.MediaFiles.Count -gt 0)) { Foreach ($mediaFile in $ibmProductMedia.MediaFiles) { $sizeOnDisk += $mediaFile.SizeOnDisk } } if ($ibmProductMedia.RequiredFixesMediaFiles -and ($ibmProductMedia.RequiredFixesMediaFiles.Count -gt 0)) { Foreach ($mediaFile in $ibmProductMedia.RequiredFixesMediaFiles) { $sizeOnDisk += $mediaFile.SizeOnDisk } } if ($ibmProductMedia.RequiredProducts -and ($ibmProductMedia.RequiredProducts.Count -gt 0)) { Foreach ($ibmProduct in $ibmProductMedia.RequiredProducts) { $sizeOnDisk += $this._GetTotalSizeOnDisk($ibmProduct) } } Return $sizeOnDisk } }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Private/Get-IBMInstallationManagerRegistryPath.ps1
Get-IBMInstallationManagerRegistryPath.ps1
# Global Variables / Resource Configuration $IIM_PATH = "HKLM:\Software\IBM\Installation Manager" $IIM_PATH_64 = "HKLM:\Software\Wow6432Node\IBM\Installation Manager" $IIM_PATH_USER = "HKCU:\Software\IBM\Installation Manager" $IIM_PATH_USER_64 = "HKCU:\Software\Wow6432Node\IBM\Installation Manager" ############################################################################################################## # Get-IBMInstallationManagerRegistryPath # Returns the registry path for IBM Installation Manager or $null if there isn't any ############################################################################################################## Function Get-IBMInstallationManagerRegistryPath() { [CmdletBinding(SupportsShouldProcess=$False)] Param() $iimPath = $null if ([IntPtr]::Size -eq 8) { $iimPath = $IIM_PATH_64 if (!(Test-Path($iimPath))) { $iimPath = $IIM_PATH_USER_64 if (!(Test-Path($iimPath))) { $iimPath = $IIM_PATH if (!(Test-Path($iimPath))) { $iimPath = $IIM_PATH_USER if (!(Test-Path($iimPath))) { $iimPath = $null } } } } } else { $iimPath = $IIM_PATH if (!(Test-Path($iimPath))) { $iimPath = $IIM_PATH_USER if (!(Test-Path($iimPath))) { $iimPath = $null } } } Write-Debug "Get-IBMInstallationManagerRegistryPath returning path: $iimPath" Return $iimPath }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Private/Invoke-IBMInstallationManagerCmdLine.ps1
Invoke-IBMInstallationManagerCmdLine.ps1
############################################################################################################## # Invoke-IBMInstallationManagerCmdLine # Invokes the IBM InstallationManager Command Line (imcl) - accepts licenses automatically ############################################################################################################## Function Invoke-IBMInstallationManagerCmdLine() { [CmdletBinding(SupportsShouldProcess=$False)] [OutputType([Boolean])] param ( [parameter(Mandatory=$true,position=0)] [System.String[]] $Arguments, [parameter(Mandatory=$false,position=1)] [System.String] $OutputLog ) [bool] $success = $false #Validate Parameters $iimHome = Get-IBMInstallationManagerHome if (!(Test-Path($iimHome) -PathType Container)) { Write-Error "IBM Installation Manager Home Location is invalid: $iimHome" } else { #Setup Process $imclExe = Join-Path -Path $iimHome -ChildPath "\eclipse\tools\imcl.exe" $Arguments += '-acceptLicense' if ($OutputLog -and (!([string]::IsNullOrEmpty($OutputLog)))) { [string] $logArg = '"' + $OutputLog + '"' $Arguments += @('-log', $logArg) } $installProc = Invoke-ProcessHelper $imclExe $Arguments if ($installProc -and ($installProc.ExitCode -eq 0)) { $stdout = $installProc.StdOut if ($stdout) { # Look for any potential error codes on stdout (based on IBM's error message IDs) $errorFound = $stdout -match "CRIM[A-Z]?\d{0,5}?E" if ($errorFound) { Write-Error "An error was found while invoking the IIM cmd line: $stdout" } else { # Look for any potential error codes on stdout (based on IBM's error message IDs) $warningFound = $stdout -match "CRIM[A-Z]?\d{0,5}?W" if ($warningFound) { Write-Warning "Warning detected, please look at the IIM log for more information: $OutputLog" } else { Write-Verbose "imcl.exe ran successfully" } $success = $true } } } else { $errorMsg = (&{if($installProc.StdErr) {$installProc.StdErr} else {$installProc.StdOut}}) Write-Error "An error occurred while invoking the IIM cmd line: $errorMsg" } } Return $success }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Get-IBMInstallationManagerVersion.ps1
Get-IBMInstallationManagerVersion.ps1
############################################################################################################## # Get-IBMInstallationManagerVersion # Returns the version of IIM if installed ############################################################################################################## Function Get-IBMInstallationManagerVersion() { [CmdletBinding(SupportsShouldProcess=$False)] Param() $iimVersion = $null $iimPath = Get-IBMInstallationManagerRegistryPath if (($iimPath) -and (Test-Path($iimPath))) { $iimVersion = (Get-ItemProperty($iimPath)).version } Return $iimVersion }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Update-IBMInstallationManager.ps1
Update-IBMInstallationManager.ps1
############################################################################################################## # Update-IBMInstallationManager # Updates IBM Installation Mananger to a newer version ############################################################################################################## Function Update-IBMInstallationManager() { [CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact="Medium")] param ( [parameter(Mandatory = $true)] [System.String] $iimHome, [parameter(Mandatory = $true)] [System.String] $iimMedia, [parameter(Mandatory = $true)] [System.String] $Version, [System.Management.Automation.PSCredential] $iimMediaCredential, [System.String] $TempDir ) PROCESS { if ($PSCmdLet.ShouldProcess($Path)) { Write-Verbose "Updating IBM Installation Manager" #Make temp directory for IIM files $iimTempDir = $null if ($TempDir -and (Test-Path $TempDir)) { $iimTempDir = Join-Path $TempDir -ChildPath "iim_update" } else { $iimTempDir = Join-Path (Get-IBMTempDir) -ChildPath "iim_update" } $localMediaPath = Copy-RemoteItemLocally $iimMedia (Split-Path($iimTempDir)) $iimMediaCredential if ($localMediaPath -and (Test-Path $localMediaPath)) { if (!(Test-Path $iimTempDir)) { New-Item -ItemType Directory -Force -Path $iimTempDir | Out-Null } $iimTempDir = Expand-ZipFile $localMediaPath $iimTempDir -Force -Clean $updateLog = Join-Path -Path (Split-Path($iimTempDir)) -ChildPath "IIM_update_log.txt" $repoFile = Join-Path -Path $iimTempDir -ChildPath "repository.config" $iimupdate_args = @("install", "com.ibm.cic.agent", "-repositories", ($repoFile), "-preferences", "offering.service.repositories.areUsed=false", "-log", $updateLog, "-acceptLicense") # Update IIM $iimToolsDir = Join-Path -Path $iimTempDir -ChildPath "tools" $iimCLExe = Join-Path -Path $iimToolsDir -ChildPath "imcl.exe" $updateProc = Invoke-ProcessHelper $iimCLExe $iimupdate_args $iimToolsDir if ($updateProc -and ($updateProc.ExitCode -eq 0)) { $updatedVersion = (Get-ItemProperty(Get-IBMInstallationManagerRegistryPath)).version if($Version -eq $updatedVersion) { Write-Verbose "IBM Installation Manager updated successfully" Remove-ItemBackground -Path $iimTempDir } else { Write-Error "IBM Installation Manager was not updated. Please check the update logs" } } else { $errorMsg = (&{if($updateProc) {$updateProc.StdOut} else {$null}}) Write-Error "An error occurred while updating IBM Installation Manager: $errorMsg" } } } } }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Install-IBMProductViaCmdLine.ps1
Install-IBMProductViaCmdLine.ps1
############################################################################################################## # Install-IBMProductViaCmdLine # Extracts product media, installs the product via cmdline, and finally performs some clean up ############################################################################################################## Function Install-IBMProductViaCmdLine() { [CmdletBinding(SupportsShouldProcess=$False)] [OutputType([Boolean])] param ( [parameter(Mandatory = $true)] [System.String] $ProductId, [parameter(Mandatory = $true)] [System.String] $InstallationDirectory, [parameter(Mandatory = $false)] [Hashtable] $Properties, [parameter(Mandatory = $true)] [System.String[]] $SourcePath, [System.Management.Automation.PSCredential] $SourcePathCredential ) $installed = $false Write-Verbose "Installing IBM Product via Command Line" $ibmTempDir = Join-Path (Get-IBMTempDir) -ChildPath $ProductId [MediaFile[]] $mediaFiles = @() [string] $parentSourcePath = $null [bool] $singleRepo = $false foreach ($sourcePathLocation in $SourcePath) { [MediaFile] $mediaFile = [MediaFile]::new() if (!($singleRepo)) { $mediaFile.RepositoryConfigPath = "repository.config" $singleRepo = $true } $mediaFile.Name = (Split-Path $sourcePathLocation -Leaf) $mediaFiles += $mediaFile $parentSourcePath = (Split-Path $sourcePathLocation -Parent) } [IBMProductMedia] $productMedia = [IBMProductMedia]::new() $productMedia.Name = $ProductId $productMedia.MediaFiles = $mediaFiles Write-Verbose "Extracting media to $parentSourcePath" $mediaExtracted = $productMedia.ExtractMedia($ibmTempDir, $parentSourcePath, $SourcePathCredential, $true, $true) if ($mediaExtracted) { # Generate installation arguments $repos = $productMedia.GetRepositoryLocations($ibmTempDir, $true) [string] $productIdArg = '"' + $ProductId + '"' [string] $instDirArg = '"' + $InstallationDirectory + '"' [string] $reposArg = '"' + ($repos -join ' ') + '"' [string[]] $installArgs = @('install', $productIdArg, '-repositories', $reposArg, '-installationDirectory', $instDirArg) if ($Properties) { foreach ($property in $Properties) { $installArgs += ($property, $Properties[$property]) } } $productInstallLog = Join-Path -Path (Split-Path($ibmTempDir)) -ChildPath "$ProductId-$(get-date -f yyyyMMddHHmmss).log" $installed = Invoke-IBMInstallationManagerCmdLine $installArgs $productInstallLog if ($installed) { Remove-ItemBackground -Path $ibmTempDir } } else { Write-Error "Unable to extrace media" } Return $installed }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Install-IBMProduct.ps1
Install-IBMProduct.ps1
############################################################################################################## # Install-IBMProduct # Extracts product media, generates response file, installs the product, and finally performs some clean up ############################################################################################################## Function Install-IBMProduct() { [CmdletBinding(SupportsShouldProcess=$False)] [OutputType([Boolean])] param ( [parameter(Mandatory = $true)] [System.String] $InstallMediaConfig, [parameter(Mandatory = $true)] [System.String] $ResponseFileTemplate, [parameter(Mandatory = $false)] [Hashtable] $Variables, [parameter(Mandatory = $true)] [System.String] $SourcePath, [System.Management.Automation.PSCredential] $SourcePathCredential ) $installed = $false Write-Verbose "Installing IBM Product" if (!(Test-Path($InstallMediaConfig) -PathType Leaf)) { Write-Error "Invalid install media configuration: $InstallMediaConfig" Return $false } if (!(Test-Path($ResponseFileTemplate) -PathType Leaf)) { Write-Error "Invalid response file: $ResponseFileTemplate" Return $false } [IBMProductMedia] $productMediaConfig = $null [string] $productShortName = "ibmProduct" [string] $ibmprodTempDir = $null # Load media configuration and verify disk space for media extraction try { $productMediaConfig = Import-Clixml $InstallMediaConfig if ($productMediaConfig) { $productShortName = $productMediaConfig.ShortName #Make temp directory for IIM files $ibmprodTempDir = Join-Path -Path (Get-IBMTempDir) -ChildPath "$productShortName-install" if ($ibmprodTempDir -and (Test-Path $ibmprodTempDir)) { Remove-Item -Path $ibmprodTempDir -Recurse -Force } New-Item -ItemType Directory -Path $ibmprodTempDir | Out-Null $sizeNeededInMB = (($productMediaConfig.GetTotalSizeOnDisk()+500MB)/1MB) $sizeAvailable = (Get-PSDrive ((Get-Item $ibmprodTempDir).PSDrive.Name) | Select-Object Free).Free/1MB if ($sizeNeededInMB -ge $sizeAvailable) { Write-Error "Insufficient disk space to extract the product media, size needed: $sizeNeededInMB MB size available: $sizeAvailable MB" Return $false } } } catch { Write-Error "Error occured while parsing file $InstallMediaConfig : $_" } if ($productMediaConfig) { # Extract media $mediaExtracted = $productMediaConfig.ExtractMedia($ibmprodTempDir, $SourcePath, $SourcePathCredential, $true, $false) if ($mediaExtracted) { # Create Response File $tempResponseFile = Join-Path -Path (Split-Path($ibmprodTempDir)) -ChildPath "$productShortName-responsefile-$(get-date -f yyyyMMddHHmmss).xml" $responseFileCreated = New-IBMInstallationManagerResponseFile -TargetPath $tempResponseFile ` -ResponseFileTemplate $ResponseFileTemplate -ProductMedia $productMediaConfig ` -ExtractedMediaDirectory $ibmprodTempDir -Variables $Variables if ($responseFileCreated) { # Install Product $productInstallLog = Join-Path -Path (Split-Path($ibmprodTempDir)) -ChildPath "$productShortName-install-$(get-date -f yyyyMMddHHmmss).log" $installed = Install-IBMProductViaResponseFile -ResponseFile $tempResponseFile -InstallLog $productInstallLog if ($installed) { Remove-ItemBackground -Path $ibmprodTempDir } } else { Write-Error "Error occured creating response file from template $ResponseFileTemplate" } } else { Write-Error "Error occured while extracting media from $SourcePath to $ibmprodTempDir" } } Return $installed }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Get-IBMInstallationManagerHome.ps1
Get-IBMInstallationManagerHome.ps1
############################################################################################################## # Get-IBMInstallationManagerHome # Returns the location where IBM Installation Manager is installed ############################################################################################################## Function Get-IBMInstallationManagerHome() { [CmdletBinding(SupportsShouldProcess=$False)] Param() $iimPath = Get-IBMInstallationManagerRegistryPath if (($iimPath) -and (Test-Path($iimPath))) { $iimHome = (Get-ItemProperty($iimPath)).location if (Test-Path $iimHome) { Write-Debug "Get-IBMInstallationManagerHome returning $iimHome" Return $iimHome } } Return $null }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/New-IBMInstallationManagerResponseFile.ps1
New-IBMInstallationManagerResponseFile.ps1
############################################################################################################## # New-IBMInstallationManagerResponseFile # Generates a new response file based on the template specified. # - Updates the repository locations from the ProductMedia parameter along with the extracted media folder # - Updates variables in response file from the Variables hashtable # - Converts credential variables to hashed passwords ############################################################################################################## Function New-IBMInstallationManagerResponseFile { [CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact="Low")] [OutputType([Boolean])] param ( [parameter(Mandatory = $true)] [String] $TargetPath, [parameter(Mandatory = $true)] [String] $ResponseFileTemplate, [parameter(Mandatory = $true)] [IBMProductMedia] $ProductMedia, [parameter(Mandatory = $true)] [String] $ExtractedMediaDirectory, [parameter(Mandatory = $false)] [Hashtable] $Variables ) PROCESS { if ($PSCmdLet.ShouldProcess($Path)) { $fileCreated = $false Write-Verbose "Creating new response file from template: $ResponseFileTemplate" if (([string]::IsNullOrEmpty($ResponseFileTemplate)) -and (!(Test-Path($ResponseFileTemplate)))) { Write-Verbose "Response File template not found: $ResponseFileTemplate" Return $false } [XML] $responseFileXML = Get-Content $ResponseFileTemplate $rootNode = $responseFileXML.ChildNodes[1] #Update response file with the product specific repository locations $serverNode = $responseFileXML.SelectSingleNode("//agent-input/server") if (!($serverNode)) { $serverNode = $responseFileXML.CreateElement("server") $rootNode.InsertBefore($serverNode, $rootNode.FirstChild) | Out-Null } else { $serverNode.RemoveAll() } $repositoryList = $ProductMedia.GetRepositoryLocations($ExtractedMediaDirectory, $true) if ($repositoryList -and ($repositoryList.Count -gt 0)) { Foreach ($repositoryLocation in $repositoryList) { $repositoryNode = $responseFileXML.CreateElement("repository") $locationAttr = $responseFileXML.CreateAttribute("location") $locationAttr.Value = $repositoryLocation $repositoryNode.Attributes.Append($locationAttr) | Out-Null $serverNode.AppendChild($repositoryNode) | Out-Null } #Update variables in new response files with the values provided $variablesNode = $responseFileXML.SelectSingleNode("//agent-input/variables") if (!($variablesNode) -and $Variables -and ($Variables.Count -gt 0)) { $variablesNode = $responseFileXML.CreateElement("variables") $rootNode.InsertBefore($variablesNode, $rootNode.FirstChild) | Out-Null } Foreach ($varName in $Variables.Keys) { $varType = ($Variables[$varName]).GetType().Name $varValue = $null if ($varType -eq "String") { $varValue = $Variables[$varName] } elseif ($varType -eq "PSCredential") { # Credential object passed as variable, hash its password and added to response file $cred = [System.Management.Automation.PSCredential] $Variables[$varName] [string]$hashedPwd = ConvertTo-HashedPassword $cred if (!([string]::IsNullOrEmpty($hashedPwd))) { $varValue = $hashedPwd } } elseif ($varType -eq "Boolean") { $varValue = (&{if($Variables[$varName]) {"true"} else {"false"}}) } else { $varValue = $Variables[$varName] } $varNode = $responseFileXML.SelectSingleNode("//agent-input/variables/variable[@name='$varName']") if ($varNode) { $varValueAttr = $varNode.Attributes.GetNamedItem("value") $varValueAttr.Value = $varValue } else { $varNode = $responseFileXML.CreateElement("variable") $varNameAttr = $responseFileXML.CreateAttribute("name") $varValueAttr = $responseFileXML.CreateAttribute("value") $varNameAttr.Value = $varName $varValueAttr.Value = $varValue $varNode.Attributes.Append($varNameAttr) | Out-Null $varNode.Attributes.Append($varValueAttr) | Out-Null $variablesNode.AppendChild($varNode) | Out-Null } } } else { Write-Error "No media repositories found in the extracted media folder based on the ProductMedia specified" $responseFileXML = $false } try { Write-Verbose "Saving new response file to the following location: $TargetPath" $responseFileXML.Save($TargetPath) | Out-Null $fileCreated = $true } catch { Write-Error "Unable to save the response file to the target location specified: $TargetPath" } Return $fileCreated } } }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Install-IBMInstallationManager.ps1
Install-IBMInstallationManager.ps1
############################################################################################################## # Install-IBMInstallationManager # Installs IBM Installation Mananger ############################################################################################################## Function Install-IBMInstallationManager() { [CmdletBinding(SupportsShouldProcess=$False)] param ( [parameter(Mandatory = $true)] [System.String] $iimHome, [parameter(Mandatory = $true)] [System.String] $iimMedia, [System.Management.Automation.PSCredential] $iimMediaCredential, [System.String] $TempDir ) Write-Verbose "Installing IBM Installation Manager" #Make temp directory for IIM files $iimTempDir = $null if ($TempDir -and (Test-Path $TempDir)) { $iimTempDir = Join-Path $TempDir -ChildPath "iim_install" } else { $iimTempDir = Join-Path (Get-IBMTempDir) -ChildPath "iim_install" } $localMediaPath = Copy-RemoteItemLocally $iimMedia (Split-Path($iimTempDir)) $iimMediaCredential if (Test-Path $localMediaPath) { if (!(Test-Path $iimTempDir)) { New-Item -ItemType Directory -Force -Path $iimTempDir | Out-Null } $iimTempDir = Expand-ZipFile $localMediaPath $iimTempDir -Force -Clean $installLog = Join-Path -Path $iimTempDir -ChildPath "IIM_install_log.txt" $installExe = Join-Path -Path $iimTempDir -ChildPath "install.exe" $installArgs = @("--launcher.ini","silent-install.ini","-installationDirectory",$iimHome,"-log",$installLog,"-acceptLicense") $installProc = Invoke-ProcessHelper $installExe $installArgs $iimTempDir if ($installProc -and ($installProc.ExitCode -eq 0)) { if((Test-Path($iimHome)) -and (Get-IBMInstallationManagerRegistryPath)) { Write-Verbose "IBM Installation Manager installed successfully" Remove-ItemBackground -Path $iimTempDir } else { Write-Error "IBM Installation Manager was not installed. Please check the installation logs" } } else { $errorMsg = (&{if($installProc) {$installProc.StdOut} else {$null}}) Write-Error "An error occurred while installing IBM Installation Manager: $errorMsg" } } else { Write-Error "Unable to copy remote media locally to folder: $iimTempDir" } }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Install-IBMProductViaResponseFile.ps1
Install-IBMProductViaResponseFile.ps1
############################################################################################################## # Install-IBMProductViaResponseFile # Installs and IBM Product based on the response file specified ############################################################################################################## Function Install-IBMProductViaResponseFile() { [CmdletBinding(SupportsShouldProcess=$False)] param ( [parameter(Mandatory = $true)] [System.String] $ResponseFile, [parameter(Mandatory = $false)] [System.String] $InstallLog ) Write-Verbose "Installing IBM Product via Response File" [bool] $installed = $false #Validate Parameters if (!(Test-Path($ResponseFile) -PathType Leaf)) { Write-Error "Parameter ResponseFile with value=$ResponseFile could not be found or is not a valid process path" } else { [string[]] $installArgs = @('input', $ResponseFile) $installed = Invoke-IBMInstallationManagerCmdLine $installArgs $InstallLog } Return $installed }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Get-IBMInstallationManagerTempDir.ps1
Get-IBMInstallationManagerTempDir.ps1
############################################################################################################## # Get-IBMInstallationManagerTempDir # Retrieves the temporary directory that IBM Installation Manager uses for installing products ############################################################################################################## Function Get-IBMInstallationManagerTempDir() { [CmdletBinding(SupportsShouldProcess=$False)] Param () $tempDir = $null $iimHome = Get-IBMInstallationManagerHome if ($iimHome) { $iimIniPath = Join-Path -Path $iimHome -ChildPath "eclipse\IBMIM.ini" if (Test-Path $iimIniPath) { $iniFile = Get-Content $iimIniPath [string] $tmpdirJavaOption = "-Djava.io.tmpdir" foreach($line in $iniFile) { if ($line.Contains($tmpdirJavaOption)) { $tempDir = $line.substring($line.IndexOf($tmpdirJavaOption)+$tmpdirJavaOption.Length+1) } } } } if ($tempDir -and !(Test-Path $tempDir)) { New-Item -ItemType Directory -Force -Path $tempDir | Out-Null } Return $tempDir }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/ConvertTo-HashedPassword.ps1
ConvertTo-HashedPassword.ps1
############################################################################################################## # ConvertTo-HashedPassword # Generates a hashed password from password specified using the IBM Installation Manager Command Line ############################################################################################################## Function ConvertTo-HashedPassword() { [CmdletBinding(SupportsShouldProcess=$False)] [OutputType([String])] Param ( [Parameter(Mandatory=$True, Position=0)] [System.Management.Automation.PSCredential] $UserCredential ) [String] $hashedPwd = $null Write-Verbose "ConvertTo-HashedPassword called" $iimHome = Get-IBMInstallationManagerHome if ($iimHome) { $iimcPath = Join-Path -Path $iimHome -ChildPath "eclipse\IBMIMc.exe" if (Test-Path($iimcPath)) { $plainpwd = $UserCredential.GetNetworkCredential().Password [String[]] $imArgs = @('-noSplash','-silent','encryptstring','"' + $plainpwd + '"') $imcl = Invoke-ProcessHelper $iimcPath $imArgs if ($imcl -and ($imcl.ExitCode -eq 0)) { $hashedPwd = $imcl.StdOut if ($hashedPwd) { Write-Verbose "ConvertTo-HashedPassword returning hashed password $hashedPwd" } else { Write-Error "ConvertTo-HashedPassword did not return anything" } } else { $errorMsg = (&{if($imcl) {$imcl.StdOut} else {$null}}) Write-Error "An error occurred while generating the hashed passwordr: $errorMsg" } } else { Write-Error "Unable to find path to the IBM Installation Manager Cmd Line: $iimcPath" } } else { Write-Error "Unable to find IBM Installation Manager: $iimHome" } Return $hashedPwd }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Set-IBMInstallationManagerTempDir.ps1
Set-IBMInstallationManagerTempDir.ps1
############################################################################################################## # Set-IBMInstallationManagerTempDir # Updates the temporary directory that IBM Installation Manager ############################################################################################################## Function Set-IBMInstallationManagerTempDir() { [CmdletBinding(SupportsShouldProcess=$True,ConfirmImpact="Low")] Param ( [parameter(Mandatory=$true,position=0)] [string] $tempDir ) PROCESS { if ($PSCmdLet.ShouldProcess($Path)) { #Make Temp if not exists if(!(Test-Path $tempDir)){ New-Item -ItemType Directory -Force -Path $tempDir | Out-Null } $iimHome = Get-IBMInstallationManagerHome $iimIniPath = Join-Path -Path $iimHome -ChildPath "eclipse\IBMIM.ini" if (Test-Path $iimIniPath) { [string] $updatedIniFile = "" [bool] $afterVMArgs = $false [bool] $hasTempDir = $false $iniFile = Get-Content $iimIniPath foreach($line in $iniFile) { if ($afterVMArgs) { if ($line.Contains("java.io.tmpdir")) { # Replace Temp Dir setting $line = "-Djava.io.tmpdir=$tempDir" } else { # Append temp dir setting $updatedIniFile += "-Djava.io.tmpdir=$tempDir`n" } $afterVMArgs = $false } if ($line.StartsWith("-vmargs")) { $afterVMArgs = $true } if ([string]::IsNullOrEmpty($line)) { $updatedIniFile += "$line" } else { $updatedIniFile += "$line`n" } } $updatedIniFile | out-file "$iimIniPath" -encoding "ASCII" } else { Write-Error "$iimIniPath could not be located" } } } }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/IBMIM/Public/Get-IBMTempDir.ps1
Get-IBMTempDir.ps1
############################################################################################################## # Get-IBMTempDir # Retrieves the current temporary directory used for IBM. Fallsback to the environment temp directory ############################################################################################################## Function Get-IBMTempDir() { [CmdletBinding(SupportsShouldProcess=$False)] Param () $tempDir = Get-IBMInstallationManagerTempDir if (!$tempDir -or !(Test-Path $tempDir)) { $tempDir = $env:TEMP } Return $tempDir }
PowerShellCorpus/PowerShellGallery/cIBMInstallationManager/1.1.0/Examples/cIBMInstallationManagerInstall_Example.ps1
cIBMInstallationManagerInstall_Example.ps1
#requires -Version 5 Configuration IIM { Import-DSCResource -module cIBMInstallationManager Package SevenZip { Ensure = 'Present' Name = '7-Zip 9.20 (x64 edition)' ProductId = '23170F69-40C1-2702-0920-000001000000' Path = 'C:\Media\7z920-x64.msi' } cIBMInstallationManager iimInstall { Ensure = 'Present' InstallationDirectory = 'C:\IBM\IIM' Version = '1.8.4.1' SourcePath = 'C:\Media\IBM\InstallationManager\agent.installer.win32.win32.x86_64_1.8.4001.20160217_1716.zip' DependsOn= "[Package]SevenZip" } } IIM Start-DscConfiguration -Wait -Force -Verbose IIM
PowerShellCorpus/PowerShellGallery/MrACredential/1.0/Import-Credential.ps1
Import-Credential.ps1
<# .Synopsis Import credential object from disk. .DESCRIPTION Import credential object from disk to be used with automation. .NOTES Created by: Jason Wasser @wasserja Modified: 4/20/2017 11:41:26 AM .EXAMPLE PS C:\> $Credential = Import-Credential .EXAMPLE PS C:\> $Credential = Import-Credential -CredentialFilePath C:\Credentials\jsmith.xml -EncryptionKeyPath C:\Keys\jsmith.key #> function Import-Credential { [cmdletbinding()] param ( [ValidateScript({Test-Path -Path $_})] $CredentialFilePath = 'C:\Scripts\Logon.xml', [ValidateScript({Test-Path -Path $_})] $EncryptionKeyPath ) begin { $ErrorActionPreference = 'Stop' Write-Verbose "ErrorActionPreference: $ErrorActionPreference" } process { if ($EncryptionKeyPath) { try { Write-Verbose -Message 'Encryption Key Path specified.' $EncryptionKey = [byte[]](Get-Content $EncryptionKeyPath) $ImportObject = Import-Clixml -Path $CredentialFilePath $SecurePassword = ConvertTo-SecureString -String $ImportObject.Password -Key $EncryptionKey $Credential = New-Object -type System.Management.Automation.PSCredential($ImportObject.UserName,$SecurePassword) $Credential } catch { Write-Error $Error[0].Exception.Message return } } else { try { Write-Verbose -Message 'No encryption key specified, importing credential from file.' $Credential = Import-Clixml -Path $CredentialFilePath $Credential } catch { Write-Error $Error[0].Exception.Message return } } } }
PowerShellCorpus/PowerShellGallery/MrACredential/1.0/New-EncryptionKey.ps1
New-EncryptionKey.ps1
<# .Synopsis Generate a new random encryption key. .DESCRIPTION Generate a new random encryption key to be used with encrypting/decrypting stored credential files. .NOTES Created by: Jason Wasser Modified: 4/20/2017 11:34:25 AM .EXAMPLE PS C:\> New-EncryptionKey 217 154 250 143 74 79 214 255 233 70 76 16 73 145 50 209 235 24 217 156 130 188 88 127 18 243 121 206 52 3 248 64 .EXAMPLE PS C:\> New-EncryptionKey -KeyLength 16 206 152 255 54 205 81 218 131 0 100 122 160 141 126 82 110 #> function New-EncryptionKey { param ( [ValidateSet(16,24,32)] [int]$KeyLength = 32 ) begin {} process { $EncryptKey = New-Object Byte[] $KeyLength #An example of 16 bytes key [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($EncryptKey) $EncryptKey } end {} }
PowerShellCorpus/PowerShellGallery/MrACredential/1.0/Save-Credential.ps1
Save-Credential.ps1
<# .Synopsis Store credential object to disk. .DESCRIPTION Store credential object to disk to be used with automation. .NOTES Created by: Jason Wasser @wasserja Modified: 4/20/2017 11:39:09 AM .EXAMPLE PS C:\> Save-Credential .EXAMPLE PS C:\> Save-Credential -Username jsmith -EncryptionKeyPath c:\Keys\jsmith.key #> function Save-Credential { [cmdletbinding()] param ( $CredentialFilePath = 'C:\Scripts\Logon.xml', [string]$UserName = $env:USERNAME, [securestring]$Password, $Message = 'Enter credentials', $EncryptionKeyPath ) begin { $ErrorActionPreference = 'Stop' Write-Verbose "ErrorActionPreference: $ErrorActionPreference" } process { # We'll do code later for username and password if ($Password) { Write-Verbose -Message 'Password has been supplied' try { $Credential = New-Object -type System.Management.Automation.PSCredential($UserName,$Password) } catch { Write-Error $Error[0].Exception.Message return } } else { Write-Verbose -Message 'No Password has been supplied. Prompting for Credential.' try { $Credential = Get-Credential -UserName $UserName -Message $Message } catch { Write-Error $Error[0].Exception.Message return } } if ($EncryptionKeyPath) { try { Write-Verbose -Message 'Encryption Key Path Specified.' $EncryptionKey = [byte[]](Get-Content $EncryptionKeyPath) Write-Verbose -Message 'Building exportable object using encryption key.' $ExportCredential = New-Object psobject -Property @{ UserName = $Credential.UserName Password = ConvertFrom-SecureString -SecureString $Credential.Password -Key $EncryptionKey } Write-Verbose -Message "Exporting credential to $CredentialFilePath with encryption key." $ExportCredential | Export-Clixml -Path $CredentialFilePath -Force } catch { Write-Error $Error[0].Exception.Message return } } else { try { if ($Credential) { Write-Verbose -Message "Exporting credential to $CredentialFilePath" $Credential | Export-Clixml -Path $CredentialFilePath -Force } else { Write-Verbose 'No Credential object created.' } } catch { Write-Error $Error[0].Exception.Message return } } } end {} }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Private/PSAppVeyor.Classes.ps1
PSAppVeyor.Classes.ps1
# https://www.appveyor.com/docs/api/ #region Classes Class AppVeyorProject { [Int]$ProjectId [Int]$AccountId [String]$AccountName [AppVeyorBuild[]]$Builds [String]$Name [String]$Slug [AppVeyorProjectRepositoryType]$RepositoryType [String]$RepositoryScm [String]$RepositoryName [String]$RepositoryBranch [Bool]$IsPrivate [Bool]$SkipBranchesWithoutAppVeyorYml [Bool]$EnableSecureVariablesInPullRequests [Bool]$EnableDeploymentInPullRequests [Bool]$AlwaysBuildClosedPullRequests [Bool]$RollingBuilds [AppVeyorNuGetFeed]$NuGetFeed [AppVeyorSecurityDescriptor]$SecurityDescriptor [Nullable[DateTime]]$Created [Nullable[DateTime]]$Updated AppVeyorProject([Object]$object) { $this.ProjectId = $object.projectId $this.AccountId = $object.accountId $this.AccountName = $object.accountName $this.Builds = $object.builds $this.Name = $object.name $this.Slug = $object.slug $this.RepositoryType = $object.repositoryType $this.RepositoryScm = $object.repositoryScm $this.RepositoryName = $object.repositoryName $this.RepositoryBranch = $object.repositoryBranch $this.IsPrivate = $object.isPrivate $this.SkipBranchesWithoutAppVeyorYml = $object.skipBranchesWithoutAppveyorYml $this.EnableSecureVariablesInPullRequests = $object.enableSecureVariablesInPullRequests $this.EnableDeploymentInPullRequests = $object.enableDeploymentInPullRequests $this.AlwaysBuildClosedPullRequests = $object.alwaysBuildClosedPullRequests $this.RollingBuilds = $object.rollingBuilds $this.NuGetFeed = $object.nuGetFeed $this.SecurityDescriptor = $object.securityDescriptor $this.Created = $object.created $this.Updated = $object.updated } } Class AppVeyorBuild { [Int]$BuildId [AppVeyorJob[]]$Jobs [Int]$BuildNumber [Version]$Version [String]$Message [String]$MessageExtended [String]$Branch [String]$CommitId [String]$AuthorName [String]$AuthorUserName [String]$CommitterName [String]$CommitterUserName [Nullable[DateTime]]$Committed [Object[]]$Messages [String]$Status [Nullable[DateTime]]$Started [Nullable[DateTime]]$Finished [Nullable[DateTime]]$Created [Nullable[DateTime]]$Updated AppVeyorBuild([Object]$object) { $this.BuildId = $object.buildId $this.Jobs = $object.jobs $this.BuildNumber = $object.buildNumber $this.Version = $object.version $this.Message = $object.message $this.MessageExtended = $object.messageExtended $this.Branch = $object.branch $this.CommitId = $object.commitId $this.AuthorName = $object.authorName $this.AuthorUserName = $object.authorUsername $this.CommitterName = $object.committerName $this.CommitterUserName = $object.committerUsername $this.Committed = $object.committed $this.Messages = $this.messages $this.Status = $object.status $this.Started = $object.started $this.Finished = $object.finished $this.Created = $object.created $this.Updated = $object.updated } } Class AppVeyorProjectSetting : AppVeyorProject { [String]$VersionFormat [Int]$NextBuildNumber [String]$WebhookId [Uri]$WebhookUrl [AppVeyorConfiguration]$Configuration [Object[]]$Tags AppVeyorProjectSetting([Object]$object) : Base([Object]$object) { $this.VersionFormat = $object.versionFormat $This.NextBuildNumber = $object.nextBuildNumber $this.WebhookId = $object.webhookId $this.WebhookUrl = $object.webhookUrl $this.Configuration = $object.configuration $this.Tags = $object.tags } } Class AppVeyorConfiguration { [Bool]$DoNotIncrementBuildNumberOnPullRequests [Object[]]$InitScripts [Object[]]$IncludeBranches [Object[]]$ExcludeBranches [Bool]$SkipTags [Bool]$SkipNonTags [Object[]]$SkipCommitsFiles [Object[]]$OnlyCommitsFiles [Object[]]$CloneScripts [Object[]]$OnBuildSuccessScripts [Object[]]$OnBuildErrorScripts [Object[]]$OnBuildFinishScripts [Bool]$PatchAssemblyInfo [Object]$AssemblyInfoFile [Object]$AssemblyVersionFormat [Object]$AssemblyFileVersionFormat [Object]$AssemblyInformationalVersionFormat [Object[]]$OperatingSystem [Object[]]$Services [Bool]$ShallowClone [Bool]$ForceHttpsClone [Object[]]$EnvironmentVariables [Object[]]$EnvironmentVariablesMatrix [Object[]]$InstallScripts [Object[]]$HostEntries [Object[]]$CacheEntries [Bool]$ConfigrueNuGetProjectSource [Bool]$ConfigureNuGetAccountSource [Bool]$DisableNuGetPublishOnPullRequests [String]$BuildMode [Object[]]$Platform [Object[]]$Configuration [Bool]$PackageWebApplicationProjects [Bool]$PackageWebApplicationProjectsXCopy [Bool]$PackageAzureCloudServiceProjects [Bool]$PackageNuGetProjects [Bool]$PackageNuGetSymbols [Bool]$IncludeNuGetReferences [Bool]$MSBuildInParallel [String]$MSBuildVerbosity [Object[]]$BuildScripts [Object[]]$BeforeBuildScripts [Object[]]$AfterBuildScripts [String]$TestMode [Object[]]$TestAssemblies [Object[]]$TestCategories [Object[]]$TestCategoriesMatrix [Object[]]$TestScripts [Object[]]$BeforeTestScripts [Object[]]$AfterTestScripts [String]$DeployMode [Object[]]$Deployments [Object[]]$DeployScripts [Object[]]$BeforeDeployScripts [Object[]]$AfterDeployScripts [Bool]$XamarianRegisterAndroidProduct [Bool]$XamarianRegisterIosProduct [Bool]$MatrixFastFinish [Object[]]$MatrixAllowFailures [Object[]]$Artifacts [Object[]]$Notifications AppVeyorConfiguration([Object]$object) { $this.DoNotIncrementBuildNumberOnPullRequests = $object.DoNotIncrementBuildNumberOnPullRequests $this.InitScripts = $object.initScripts $this.IncludeBranches = $object.includeBranches $this.ExcludeBranches = $object.ExcludeBranches $this.OnBuildSuccessScripts = $object.onBuildSuccessScripts $this.OnBuildErrorScripts = $object.onBuildErrorScripts $this.OnBuildFinishScripts = $object.onBuildFinishScripts $this.PatchAssemblyInfo = $object.patchAssemblyInfo $this.AssemblyInfoFile = $object.assemblyInfoFile $this.AssemblyFileVersionFormat = $object.assemblyFileVersionFormat $this.AssemblyInformationalVersionFormat = $object.assemblyInformationalVersionFormat $this.OperatingSystem = $object.operatingSystem $this.Services = $object.services $this.ShallowClone = $object.shallowClone $this.ForceHttpsClone = $object.forceHttpsClone $this.EnvironmentVariables = $object.environmentVariables $this.EnvironmentVariablesMatrix = $object.environmentVariablesMatrix $this.InstallScripts = $object.installScripts $this.HostEntries = $object.hostEntries $this.CacheEntries = $object.cacheEntries $this.ConfigrueNuGetProjectSource = $object.configureNuGetProjectSource $this.ConfigureNuGetAccountSource = $object.configureNuGetAccountSource $this.DisableNuGetPublishOnPullRequests = $object.disableNuGetPublishOnPullRequests $this.BuildMode = $object.buildMode $this.Platform = $object.platform $this.Configuration = $object.configuration $this.PackageWebApplicationProjects = $object.packageWebApplicationProjects $this.PackageWebApplicationProjectsXCopy = $object.packageWebApplicationProjectsXCopy $this.PackageAzureCloudServiceProjects = $object.packageAzureCloudServiceProjects $this.PackageNuGetProjects = $object.packageNuGetProjects $this.PackageNuGetSymbols = $object.packageNuGetSymbols $this.IncludeNuGetReferences = $object.includeNuGetReferences $this.MSBuildInParallel = $object.msBuildInParallel $this.MSBuildVerbosity = $object.msBuildVerbosity $this.BuildScripts = $object.buildScripts $this.BeforeBuildScripts = $object.beforeBuildScripts $this.AfterBuildScripts = $object.afterBuildScripts $this.TestMode = $object.testMode $this.TestAssemblies = $object.testAssemblies $this.TestCategories = $object.testCategories $this.TestCategoriesMatrix = $object.testCategoriesMatrix $this.TestScripts = $object.testScripts $this.BeforeTestScripts = $object.beforeTestScripts $this.AfterTestScripts = $object.afterTestScripts $this.DeployMode = $object.deployMode $this.Deployments = $object.deployments $this.BeforeDeployScripts = $object.beforeDeployScripts $this.AfterDeployScripts = $object.afterDeployScripts $this.XamarianRegisterAndroidProduct = $object.xamarianRegisterAndroidProduct $this.XamarianRegisterIosProduct = $object.xamarianRegisterIosProduct $this.MatrixFastFinish = $object.matrixFastFinish $this.MatrixAllowFailures = $object.matrixAllowFailures $this.Artifacts = $object.atrifacts $this.Notifications = $object.notifications } AppVeyorConfiguration() { } } Class AppVeyorJob { [String]$JobId [String]$Name [Bool]$AllowFailure [Int]$MessagesCount [Int]$CompilationMessagesCount [Int]$CompilationErrorsCount [Int]$CompilationWarningsCount [Int]$TestsCount [Int]$PassedTestsCount [Int]$FailedTestsCount [Int]$ArtifactsCount [String]$Status [Nullable[DateTime]]$Started [Nullable[DateTime]]$Finished [Nullable[DateTime]]$Created [Nullable[DateTime]]$Updated AppVeyorJob([Object]$object) { $this.JobId = $object.jobId $this.Name = $object.name $this.AllowFailure = $object.allowFailure $this.MessagesCount = $object.messagesCount $this.CompilationMessagesCount = $object.compilationMessagesCount $this.CompilationErrorsCount = $object.compilationErrorsCount $this.CompilationWarningsCount = $object.compilationWarningsCount $this.TestsCount = $object.testsCount $this.PassedTestsCount = $object.passedTestsCount $this.FailedTestsCount = $object.failedTestsCount $this.ArtifactsCount = $object.artifactsCount $this.Status = $object.status $this.Started = $object.started $this.Finished = $object.finished $this.Created = $object.created $this.Updated = $object.updated } } Class AppVeyorNuGetFeed { [String]$Id [String]$Name [Bool]$PublishingEnabled [DateTime]$Created AppVeyorNuGetFeed([Object]$object) { $this.Id = $object.id $this.Name = $object.name $this.PublishingEnabled = $object.publishingEnabled $this.Created = $object.created } } Class AppVeyorSecurityDescriptor { [AppVeyorAccessRightsDefinition[]]$AccessRightDefinitions [AppVeyorRoleAce[]]$RoleAces AppVeyorSecurityDescriptor([Object]$object) { $this.AccessRightDefinitions = $object.accessRightDefinitions $this.RoleAces = $object.roleAces } } Class AppVeyorRoleAce { [Int]$RoleId [String]$Name [Bool]$IsAdmin [AppVeyorAccessRight[]]$AccessRights AppVeyorRoleAce([Object]$object) { $this.RoleId = $object.roleId $this.Name = $object.name $this.IsAdmin = $object.isAdmin $this.AccessRights = $object.accessRights } } Class AppVeyorAccessRightsDefinition { [String]$Name [String]$Description AppVeyorAccessRightsDefinition([Object]$object) { $this.Name = $object.name $this.Description = $object.description } } Class AppVeyorAccessRight { [String]$Name [Bool]$Allowed AppVeyorAccessRight([Object]$object) { $this.Name = $object.name $this.Allowed = $object.allowed } } Class AppVeyorEnvironment { [Int]$DeploymentEnvironmentId [String]$Name [String]$Provider [String]$EnvironmentAccessKey [AppVeyorEnvironmentSetting[]]$Settings [Nullable[DateTime]]$Created [Nullable[DateTime]]$Updated AppVeyorEnvironment([Object]$object) { $this.DeploymentEnvironmentId = $object.deploymentEnvironmentId $this.Name = $object.name $this.Provider = $object.provider $this.EnvironmentAccessKey = $object.environmentAccessKey $this.Settings = $object.settings $this.Created = $object.created $this.Updated = $object.updated } } Class AppVeyorEnvironmentSetting { [AppVeyorProviderSetting[]]$ProviderSettings [Object[]]$EnvironmentVairables AppVeyorEnvironmentSetting([Object]$object) { $this.ProviderSettings = $object.providerSettings $this.EnvironmentVariables = $object.environmentVariables } } Class AppVeyorProviderSetting { [String]$Name [AppVeyourProviderSettingValue]$Value AppVeyorProviderSetting([Object]$object) { $this.Name = $object.name $this.Value = $object.value } } Class AppVeyourProviderSettingValue { [Bool]$IsEncrypted [String]$Value AppVeyourProviderSettingValue([Object]$object) { $this.IsEncrypted = $object.isEncrypted $this.Value = $object.value } } Class AppVeyorUser { [Int]$AccountId [String]$AccountName [Bool]$IsOwner [Bool]$IsCollaborator [Int]$UserId [String]$FullName [String]$Email [Int]$RoleId [String]$RoleName [AppVeyorUserRole[]]$Roles [String]$SuccessfulBuildNotification [String]$FailedBuildNotification [Bool]$NotifyWhenBuildStatusChangedOnly [Nullable[DateTime]]$Created [Nullable[DateTime]]$Updated AppVeyorUser([Object]$object) { $this.AccountId = $object.accountId $this.AccountName = $object.accountName $this.IsOwner = $object.isOwner $this.IsCollaborator = $object.isCollaborator $this.UserId = $object.userId $this.FullName = $object.fullName $this.Email = $object.email $this.RoleId = $object.roleId $this.RoleName = $object.roleName $this.SuccessfulBuildNotification = $object.successfulBuildNotification $this.FailedBuildNotification = $object.FailedBuildNotification $this.NotifyWhenBuildStatusChangedOnly = $object.notifyWhenBuildStatusChangedOnly $this.Created = $object.created $this.Updated = $object.updated $this.Roles = $this.GetUserRoles() } [AppVeyorUserRole[]] GetUserRoles() { return Invoke-AppVeyorApi -Method 'GET' -RestMethod ('users/{0}' -f $this.UserId) | Select-Object -ExpandProperty 'roles' } } Class AppVeyorUserRole { [Int]$RoleId [String]$Name [Bool]$IsSystem [Nullable[DateTime]]$Created [AppVeyorUserGroup[]]$Groups AppVeyorUserRole([Object]$object) { $this.RoleId = $object.roleId $this.Name = $object.name $this.IsSystem = $object.isSystem $this.Created = $object.created $this.Groups = $object.groups } AppVeyorUserRole([Object]$object, [Switch]$includeGroups) { $this.RoleId = $object.roleId $this.Name = $object.name $this.IsSystem = $object.isSystem $this.Created = $object.created $this.Groups = $this.GetUserGroups() } [AppVeyorUserGroup[]] GetUserGroups() { return Invoke-AppVeyorApi -Method 'GET' -RestMethod ('roles/{0}' -f $this.RoleId) | Select-Object -ExpandProperty 'groups' } } Class AppVeyorUserGroup { [String]$Name [AppVeyorUserGroupPermission[]]$Permissions AppVeyorUserGroup([Object]$object) { $this.Name = $object.name $this.Permissions = $object.permissions } } Class AppVeyorUserGroupPermission { [String]$Name [String]$Description [Bool]$Allowed AppVeyorUserGroupPermission([Object]$object) { $this.Name = $object.name $this.Description = $object.description $this.Allowed = $object.allowed } } #endregion Classes #region Enums Enum AppVeyorProjectRepositoryType { GitHub BitBucket VSO GitLab Kiln Stash GitHubMercurial SubVersion } #endregion Enums
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Private/Invoke-AppVeyorApi.ps1
Invoke-AppVeyorApi.ps1
Function Invoke-AppVeyorApi { [CmdletBinding( ConfirmImpact = "Low", SupportsShouldProcess = $true )] [OutputType()] Param ( [Parameter( Mandatory = $false )] [HashTable] $Headers = @{}, [Parameter( Mandatory = $true )] [String] $Method, [Parameter( Mandatory = $true )] [String] $RestMethod, [Parameter()] [String] $Body = $null ) Begin { # Starting with version 0.2, the Api Token is now stored in the Windows Credential Manager. # If the xml file containing the Api Token exists, it is loaded into the Credential Manager, and the xml is deleted. # As of 20160630 there have only been 8 downloads of this module from the PSGallery, so this code can be removed with 1.0 release. if (Test-Path -Path "$env:APPDATA\PSAppVeyor\Private\ApiToken.xml") { $token = (Import-Clixml -Path $env:AppData\PSAppVeyor\Private\ApiToken.xml -ErrorAction Stop).GetNetworkCredential().Password Set-AppVeyorApiToken -Token $token -Confirm:$false Remove-Item -Path "$env:APPDATA\PSAppVeyor\Private\ApiToken.xml" -Confirm:$false } try { [Void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime] $token = (New-Object -TypeName Windows.Security.Credentials.PasswordVault -ErrorAction Stop).Retrieve( 'https://appveyor.com', 'PSAppVeyor' ).Password } catch { $_ return } $Headers.Add( 'Authorization', "Bearer $token" ) $Headers.Add( 'Content-type', 'application/json' ) $request = @{ Headers = $Headers Uri = "https://ci.appveyor.com/api/${RestMethod}" Method = $Method ErrorAction = 'Stop' } if (-not ([String]::IsNullOrEmpty($Body))) { $request.Add( 'Body', $Body ) } try { if ($PSCmdlet.ShouldProcess($request)) { Invoke-RestMethod @request } } catch { $message = ConvertFrom-Json -InputObject $_.ErrorDetails.Message | Select-Object -ExpandProperty message if ($null -ne $message) { Write-Error -Message $message return } else { Write-Error $_ return } } } End { Remove-Variable -Name token -Force [GC]::Collect() } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorBuild.ps1
Get-AppVeyorBuild.ps1
Function Get-AppVeyorBuild { [CmdletBinding( DefaultParameterSetName = '__AllParameterSets' )] [OutputType( [AppVeyorBuild] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $ProjectName, [Parameter( ParameterSetName = 'Branch', ValueFromPipelineByPropertyName = $true )] [Alias( 'RepositoryBranch' )] [String] $BuildBranch, [Parameter( ParameterSetName = 'Version', ValueFromPipeline = $true )] [Version] $BuildVersion ) Process { switch ($PSCmdlet.ParameterSetName) { 'Branch' { $restMethod = "projects/${AccountName}/${ProjectName}/branch/${BuildBranch}" } 'Version' { $restMethod = "projects/${AccountName}/${ProjectName}/build/${BuildVersion}" } default { $restMethod = "projects/${AccountName}/${ProjectName}" } } [AppVeyorBuild]::new( (Invoke-AppVeyorApi -Method 'GET' -RestMethod $restMethod | Select-Object -ExpandProperty build) ) } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Remove-AppVeyorEnvironment.ps1
Remove-AppVeyorEnvironment.ps1
Function Remove-AppVeyorEnvironment { [CmdletBinding( ConfirmImpact = 'High', SupportsShouldProcess = $true )] [OutputType()] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [Int[]] $DeploymentEnvironmentID ) Process { foreach ($item in $DeploymentEnvironmentID) { if ($PSCmdlet.ShouldProcess($item)) { Invoke-AppVeyorApi -Method 'DELETE' -RestMethod "environments/${item}" } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorCollaborator.ps1
Get-AppVeyorCollaborator.ps1
Function Get-AppVeyorCollaborator { [CmdletBinding()] [OutputType( [AppVeyorUser] )] Param ( [Parameter( ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [Int[]] $UserId ) Process { if ($null -ne $UserId) { foreach ($item in $UserId) { [AppVeyorUser]::new( (Invoke-AppVeyorApi -Method 'Get' -RestMethod "collaborators/${item}") ) } } else { foreach ($result in (Invoke-AppVeyorApi -Method 'Get' -RestMethod 'collaborators')) { [AppVeyorUser]::new( $result ) } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Remove-AppVeyorCollaborator.ps1
Remove-AppVeyorCollaborator.ps1
Function Remove-AppVeyorCollaborator { [CmdletBinding( ConfirmImpact = 'High', SupportsShouldProcess = $true )] [OutputType()] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [Int[]] $UserId ) Process { foreach ($item in $UserId) { if ($PSCmdlet.ShouldProcess($item)) { Invoke-AppVeyorApi -Method 'DELETE' -RestMethod "collaborators/${item}" } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/New-AppVeyorProject.ps1
New-AppVeyorProject.ps1
Function New-AppVeyorProject { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType( [AppVeyorProject] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true` )] [String] $ProjectName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [AppVeyorProjectRepositoryType] $RepositoryProvider ) Process { if ($PSCmdlet.ShouldProcess($ProjectName)) { $body = @{ repositoryProvider = $RepositoryProvider.ToString() repositoryName = "${AccountName}/${ProjectName}" } [AppVeyorProject]::new( (Invoke-AppVeyorApi -Method 'POST' -RestMethod projects -Body (ConvertTo-Json -InputObject $body)) ) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorEnvironment.ps1
Get-AppVeyorEnvironment.ps1
Function Get-AppVeyorEnvironment { [CmdletBinding()] [OutputType( [AppVeyorEnvironment] )] Param ( [Parameter( ValueFromPipelineByPropertyName = $true )] [Int] $DeploymentEnvironmentID = $null ) Process { $restMethod = "environments" if ($null -ne $PSCmdlet.DeploymentEnvironmentId) { $restMethod += "/${DeploymentEnvironmentId}/settings" } [AppVeyorEnvironment]::new( (Invoke-AppVeyorApi -Method 'GET' -RestMethod $restMethod) ) } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Update-AppVeyorProjectBuildNumber.ps1
Update-AppVeyorProjectBuildNumber.ps1
Function Update-AppVeyorProjectBuildNumber { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Alias( 'Slug' )] [String] $ProjectName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Int] $BuildNumber ) Process { if ($PSCmdlet.ShouldProcess($ProjectName)) { $body = @{ nextBuildNumber = $BuildNumber } Invoke-AppVeyorApi -Method 'PUT' -RestMethod "projects/${AccountName}/${ProjectName}/settings/build-number" -Body (ConvertTo-Json -InputObject $body) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/New-AppVeyorUser.ps1
New-AppVeyorUser.ps1
Function New-AppVeyorUser { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType()] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $FullName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $Email, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Int] $RoleId ) Process { if ($PSCmdlet.ShouldProcess($FullName)) { $body = @{ 'fullName' = $FullName 'email' = $Email 'roleId' = $RoleId 'generatePassword' = $true 'password' = $null 'confirmPassword' = $null } Invoke-AppVeyorApi -Method 'POST' -RestMethod 'users' -Body (ConvertTo-Json -InputObject $body) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Update-AppVeyorUser.ps1
Update-AppVeyorUser.ps1
Function Update-AppVeyorUser { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Int] $UserId, [Parameter( ValueFromPipelineByPropertyName = $true )] [ValidateNotNull()] [String] $FullName = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [ValidateNotNull()] [String] $Email = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [ValidateNotNull()] [Int] $RoleId = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [ValidateNotNull()] [String] $SuccessfulBuildNotification = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [ValidateNotNull()] [String] $FailedBuildNotification = $null, [Parameter( ValueFromPipelineByPropertyName = $true )] [Bool] $NotifyWhenBuildStatusChangedOnly ) Process { if ($PSCmdlet.ShouldProcess($UserId)) { try { $currentUser = Get-AppVeyorUser -UserId $UserId } catch { $_ return } $body = @{ userId = $UserId fullName = $currentUser.FullName email = $currentUser.Email password = $null roleId = $currentUser.RoleId successfulBuildNotification = $currentUser.SuccessfulBuildNotification failedBuildNotification = $currentUser.FailedBuildNotification notifyWhenBuildStatusChangedOnly = $currentUser.NotifyWhenBuildStatusChangedOnly } foreach ($parameter in $PSBoundParameters) { if ($null -ne $parameter) { $body.$($parameter.Keys) = $parameter.Values } } Invoke-AppVeyorApi -Method 'POST' -RestMethod 'users' -Body (ConvertTo-Json -InputObject $body) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/New-AppVeyorCollaborator.ps1
New-AppVeyorCollaborator.ps1
Function New-AppVeyorCollaborator { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType()] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $Email, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Int] $RoleId ) Process { if ($PSCmdlet.ShouldProcess($Email)) { $body = @{ 'email' = $Email 'roleId' = $RoleId } Invoke-AppVeyorApi -Method 'POST' -RestMethod 'collaborators' -Body (ConvertTo-Json -InputObject $body) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorUserRole.ps1
Get-AppVeyorUserRole.ps1
Function Get-AppVeyorUserRole { [CmdletBinding( DefaultParameterSetName = '__AllParameterSets' )] [OutputType( [AppVeyorUserRole] )] Param ( [Parameter( HelpMessage = 'Also retreives the groups associated to each role.', ParameterSetName = 'IncludeGroups' )] [Switch] $IncludeGroups, [Parameter( HelpMessage = 'The Id of a specific role.', ParameterSetName = 'RoleId', ValueFromPipelineByPropertyName = $true )] [Int[]] $RoleId = $null ) Process { if ($null -ne $RoleId) { foreach ($item in $RoleId) { [AppVeyorUserRole]::new( (Invoke-AppVeyorApi -Method 'GET' -RestMethod "roles/${item}") ) } } else { foreach ($result in (Invoke-AppVeyorApi -Method 'GET' -RestMethod 'roles')) { [AppVeyorUserRole]::new( $result, $IncludeGroups.IsPresent ) } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Update-AppVeyorEnvironment.ps1
Update-AppVeyorEnvironment.ps1
Function Update-AppVeyorEnvironment { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType()] Param ( ) Process { if ($PSCmdlet.ShouldProcess()) { } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Remove-AppVeyorUser.ps1
Remove-AppVeyorUser.ps1
Function Remove-AppVeyorUser { [CmdletBinding( ConfirmImpact = 'High', SupportsShouldProcess = $true )] [OutputType()] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [Int[]] $UserId ) Process { foreach ($item in $UserId) { if ($PSCmdlet.ShouldProcess($item)) { Invoke-AppVeyorApi -Method 'DELETE' -RestMethod "users/${item}" } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Remove-AppVeyorProject.ps1
Remove-AppVeyorProject.ps1
Function Remove-AppVeyorProject { [CmdletBinding( ConfirmImpact = 'High', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Alias( 'Slug' )] [String] $ProjectName, [Parameter()] [Switch] $BuildCacheOnly ) Process { if ($PSCmdlet.ShouldProcess($ProjectName)) { $restMethod = "projects/${AccountName}/${ProjectName}" if ($BuildCacheOnly.IsPresent) { $restMethod += '/buildcache' } Invoke-AppVeyorApi -Method 'DELETE' -RestMethod $restMethod } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorProject.ps1
Get-AppVeyorProject.ps1
Function Get-AppVeyorProject { [CmdletBinding()] [OutputType( [AppVeyorProject] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $ProjectName ) Process { [AppVeyorProject]::new( (Invoke-AppVeyorApi -Method 'GET' -RestMethod "projects/${AccountName}/${ProjectName}" | Select-Object -ExpandProperty project) ) } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Set-AppVeyorApiToken.ps1
Set-AppVeyorApiToken.ps1
Function Set-AppVeyorApiToken { [CmdletBinding( ConfirmImpact = 'High', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param ( [Parameter( HelpMessage = 'The value of a token from https://ci.appveyor.com/api-token.', Mandatory = $true )] [String] $Token ) Begin { try { [Void][Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime] $vault = New-Object -TypeName Windows.Security.Credentials.PasswordVault -ErrorAction Stop } catch { $_ return } try { if ($vault.FindAllByUserName('PSAppVeyor').Count -ne 0) { if ($PSCmdlet.ShouldProcess($vault, 'Setting PSAppVeyor Api Token. There is already an Api Token present, do you wish to update the value?')) { $vault.Add((New-Object -TypeName Windows.Security.Credentials.PasswordCredential -ArgumentList 'https://appveyor.com', 'PSAppVeyor', $Token)) } } } catch { try { $vault.Add((New-Object -TypeName Windows.Security.Credentials.PasswordCredential -ArgumentList 'https://appveyor.com', 'PSAppVeyor', $Token)) } catch { $_ return } } } End { Remove-Variable -Name Token -Force [GC]::Collect() } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorProjectSetting.ps1
Get-AppVeyorProjectSetting.ps1
Function Get-AppVeyorProjectSetting { [CmdletBinding()] [OutputType( [AppVeyorProjectSetting] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Alias( 'Slug' )] [String] $ProjectName, [Parameter()] [Switch] $Yaml ) Process { if ($Yaml.IsPresent) { Invoke-AppVeyorApi -Method 'GET' -RestMethod "projects/${AccountName}/${ProjectName}/settings/yaml" } else { [AppVeyorProjectSetting]::new( (Invoke-AppVeyorApi -Method 'GET' -RestMethod "projects/${AccountName}/${ProjectName}/settings" | Select-Object -ExpandProperty settings) ) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Stop-AppVeyorProjectBuild.ps1
Stop-AppVeyorProjectBuild.ps1
Function Stop-AppVeyorProjectBuild { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $ProjectName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Int] $BuildId ) Process { if ($PSCmdlet.ShouldProcess($ProjectName)) { Invoke-AppVeyorApi -Method 'DELETE' -RestMethod "builds/${AccountName}/${ProjectName}/${BuildId}" } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorUser.ps1
Get-AppVeyorUser.ps1
Function Get-AppVeyorUser { [CmdletBinding()] [OutputType( [AppVeyorUser] )] Param ( [Parameter( ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [Int[]] $UserId ) Process { if ($null -ne $UserId) { foreach ($item in $UserId) { [AppVeyorUser]::new( (Invoke-AppVeyorApi -Method 'Get' -RestMethod "users/${item}") ) } } else { foreach ($result in (Invoke-AppVeyorApi -Method 'Get' -RestMethod 'users')) { [AppVeyorUser]::new( $result ) } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Start-AppVeyorProjectBuild.ps1
Start-AppVeyorProjectBuild.ps1
Function Start-AppVeyorProjectBuild { [CmdletBinding( SupportsShouldProcess = $true )] [OutputType( [AppVeyorBuild] )] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [Alias( 'Slug' )] [String] $ProjectName, [Parameter( Mandatory = $true, ParameterSetName = 'Branch', ValueFromPipelineByPropertyName = $true )] [String] $Branch, [Parameter( ParameterSetName = 'Branch' )] [Parameter( ParameterSetName = 'GitHubPullRequest' )] [HashTable] $EnvironmentVariable = $null, [Parameter( ParameterSetName = 'Branch' )] [String] $CommitId, [Parameter( ParameterSetName = 'GitHubPullRequest' )] [Int] $GitHubPullRequestId ) Process { $body = @{ 'accountName' = $AccountName 'projectSlug' = $ProjectName } switch ($PSCmdlet.ParameterSetName) { 'Branch' { $body.Add( 'branch', $Branch ) if ($null -ne $CommitId) { $body.Add('commitId', $CommitId) } } 'GitHubPullRequest' { $body.Add( 'pullRequestId', $GitHubPullRequestId ) } } if ($null -ne $EnvironmentVariable) { $body.Add('environmentVariables', $EnvironmentVariable) } if ($PSCmdlet.ShouldProcess($body)) { [AppVeyorBuild]::new( (Invoke-AppVeyorApi -Method 'POST' -RestMethod 'builds' -Body (ConvertTo-Json -InputObject $body)) ) } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/New-AppVeyorEnvironment.ps1
New-AppVeyorEnvironment.ps1
Function New-AppVeyorEnvironment { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType()] Param ( ) Process { if ($PSCmdlet.ShouldProcess()) { } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Get-AppVeyorProjectDeployment.ps1
Get-AppVeyorProjectDeployment.ps1
Function Get-AppVeyorProjectDeployment { [CmdletBinding()] [OutputType()] Param ( [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $AccountName, [Parameter( Mandatory = $true, ValueFromPipelineByPropertyName = $true )] [String] $ProjectName ) Process { Invoke-AppVeyorApi -Method 'GET' -RestMethod "projects/${AccountName}/${ProjectName}/deployments" | Select-Object -ExpandProperty project } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Remove-AppVeyorUserRole.ps1
Remove-AppVeyorUserRole.ps1
Function Remove-AppVeyorUserRole { [CmdletBinding( ConfirmImpact = 'High', SupportsShouldProcess = $true )] [OutputType( [Void] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [Int[]] $RoleId ) Process { foreach ($item in $RoleId) { if ($PSCmdlet.ShouldProcess($item)) { Invoke-AppVeyorApi -Method 'DELETE' -RestMethod "roles/${item}" } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/Update-AppVeyorUserRole.ps1
Update-AppVeyorUserRole.ps1
Function Update-AppVeyorUserRole { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType( [AppVeyorUserRole] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [AppVeyorUserRole[]] $AppVeyorUserRole ) Process { foreach ($item in $AppVeyorUserRole) { if ($PSCmdlet.ShouldProcess($item)) { [AppVeyorUserRole]::new( (Invoke-AppVeyorApi -Method 'PUT' -RestMethod 'roles' -Body (ConvertTo-Json -InputObject $item -Depth 4)) ) } } } }
PowerShellCorpus/PowerShellGallery/PSAppVeyor/0.2.11/Public/New-AppVeyorUserRole.ps1
New-AppVeyorUserRole.ps1
Function New-AppVeyorUserRole { [CmdletBinding( ConfirmImpact = 'Medium', SupportsShouldProcess = $true )] [OutputType( [AppVeyorUserRole] )] Param ( [Parameter( Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true )] [String[]] $Name ) Process { foreach ($item in $Name) { if ($PSCmdlet.ShouldProcess($item)) { $body = @{ name = $item } [AppVeyorUserRole]::new( (Invoke-AppVeyorApi -Method 'POST' -RestMethod 'roles' -Body (ConvertTo-Json -InputObject $body)) ) } } } }
PowerShellCorpus/PowerShellGallery/FormatPx/1.1.3.15/scripts/Export-BinaryModule.ps1
Export-BinaryModule.ps1
<############################################################################# FormatPx separates the formatting layer from the data processing layer in PowerShell. By default, PowerShell's native Format-* cmdlets convert data objects into format objects when are then rendered in the console. This reduces the usefulness of the Format-* cmdlets, making it harder to work with formatting in PowerShell. FormatPx fixes this problem by attaching format data to objects rather than replacing objects with format data. This allows for data processing to continue beyond Format-* cmdlets, without losing any of the capabilities of the formatting engine in PowerShell. FormatPx also removes formatting limitations in the output layer, allowing multiple contiguous formats returned by a single command to render properly in PowerShell. 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 Format-Custom,Format-Default,Format-List,Format-Table,Format-Wide,Out-Default,Out-File,Out-Host,Out-Printer,Out-String # Define a fd alias so that using Format-Default is easier. if (-not (Get-Alias -Name fd -ErrorAction Ignore)) { New-Alias -Name fd -Value Format-Default Export-ModuleMember -Alias fd } # SIG # Begin sign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EyzAw78sp5X0DL7DEarD7ds1LI # 1GbqJfXdZ3FIsabvgTFEDV0AXm9xbNPjZdOm8y/takddwCIKS7rNmsckxsMtEzs2 # 7ipWpO+U4hx2Y8ef8cgs73hY7KRsgbu7+RRVUFOMO5dDWCDzvX8PpuXxXT1Y36GC # AgswggIHBgkqhkiG9w0BCQYxggH4MIIB9AIBATByMF4xCzAJBgNVBAYTAlVTMR0w # GwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEwMC4GA1UEAxMnU3ltYW50ZWMg # VGltZSBTdGFtcGluZyBTZXJ2aWNlcyBDQSAtIEcyAhAOz/Q4yP6/NW4E2GqYGxpQ # MAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3 # DQEJBTEPFw0xNjAxMjMxNTAxMjBaMCMGCSqGSIb3DQEJBDEWBBQYXfWwFDE7R/hr # ATyRL4l21qLvcDANBgkqhkiG9w0BAQEFAASCAQAHa2gwIYHodX9QwHC/A2GmFyOg # TlMoRaFWmuHAkN69xUeKk6b48uOWG/UkRThE46ieFaIeFsbLLOPVUWCi3qZng4Jh # vaQivOG7BjdRemuI3LILtiW/cW/xt/iyW2uOpHZm+yv8tXVV2JBKQ3aIFuq5XsL7 # 5068UMT9FqecGMinV7qjZrgLpTmalmHxpr2rZW6tfIy66FNBvrvpWvjjDQ+hggu0 # xUNGcf1nhgWY/JZQBGlOax7KxTuWYpmZKlDRLogMWUzd9T6Cx+/NSbcgdFN6WZ5i # BGSCDhmkLc9nMTOH3R3lFBxiMc2Incc+yPa9ERNDFW+/GnemGpjVnKVO7AKw # SIG # End signature block
PowerShellCorpus/PowerShellGallery/sthTools/0.15/Test-sthWindowsUpdateRebootRequired.ps1
Test-sthWindowsUpdateRebootRequired.ps1
<# .synopsis Function for testing and rebooting computers on reboot pending after update installation .description Function for testing local and remote computers on reboot pending after update installation. Checks Component Based Servicing registry key - HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending and Windows Update registry key - HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired. Also have the possibility to initiate reboot on remote computers (not local) which need it by specifying -Restart and -YesRestart parameters. Does not initiate reboot on local computer (can be specified as 'localhost', 'hostname' or 'hostname.domainname.com') By default function skips computers, that can not be accessed. You can see, which computers were skipped by specifying -ShowInaccessible. .example Test-sthWindowsUpdateRebootRequired ComputerName ComponentBasedServicing WindowsUpdate ------------ ----------------------- ------------- localhost False False Get information about localhost. .example Test-sthWindowsUpdateRebootRequired -ComputerName comp-1, comp-2, localhost ComputerName ComponentBasedServicing WindowsUpdate ------------ ----------------------- ------------- comp-1 False False comp-2 True True localhost False False Get information from several computers by specifying -ComputerName parameter. .example 'comp-1', 'comp-2', 'localhost' | Test-sthWindowsUpdateRebootRequired ComputerName ComponentBasedServicing WindowsUpdate ------------ ----------------------- ------------- comp-1 False False comp-2 True True localhost False False Get information from several computers by piping names of the computers into the function. .example Test-sthWindowsUpdateRebootRequired -ComputerName comp-1,comp-2,localhost,Inaccessiblecomputer -ShowInaccessible ComputerName ComponentBasedServicing WindowsUpdate ------------ ----------------------- ------------- comp-1 False False comp-2 True True Inaccessiblecomputer Inaccessible Inaccessible False False Get information from several computers by specifying -ComputerName. Also get information about inaccessible computers by specifying -Inaccessible parameter. (By default inaccessible computers is silently skipped.) .example Test-sthWindowsUpdateRebootRequired -ComputerName comp-1,comp-2,localhost -Restart -YesRestart ComputerName ComponentBasedServicing WindowsUpdate ------------ ----------------------- ------------- comp-1 False False comp-2 True True localhost True True Get information from several computers and restart computers that needs it. (does not restarts localhost) In this example comp-2 will be restarted. (Both -Restart and -YesRestart parameters must be specified.) #> function Test-sthWindowsUpdateRebootRequired { [CmdletBinding()] Param( #Computer Name. #By default = 'localhost' [Parameter(ValueFromPipeline=$True)] [string[]]$ComputerName = 'localhost', #Restart computers which need it (remote only) [switch]$Restart, #Explicit reboot confirmation [switch]$YesRestart, #Show inaccessible computers in results [switch]$ShowInaccessible ) begin { $Inaccessible = @() $WMI = Get-WmiObject -Class Win32_ComputerSystem $Name = $WMI.Name $Domain = $WMI.Domain } process { foreach ($c in $ComputerName) { Write-Progress -Activity "Testing computers" -CurrentOperation $c if(($c -eq 'localhost') -or ($c -eq $Name) -or ($c -eq $($Name, $Domain -join '.'))) { $CBS = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' $WU = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' } else { if($sess = New-PSSession -ComputerName $c -ErrorAction SilentlyContinue) { $CBS = Invoke-Command -ScriptBlock {Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'} -Session $sess $WU = Invoke-Command -ScriptBlock {Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'} -Session $sess if($Restart -and $YesRestart -and ($CBS -or $WU)) { Invoke-Command -ScriptBlock {Restart-Computer -Force} -Session $sess } Remove-PSSession -Session $sess } else { $Inaccessible += $c continue } } New-Object -TypeName PSCustomObject -Property $([ordered]@{ ComputerName = $c ComponentBasedServicing = $CBS WindowsUpdate = $WU }) } } end { if($ShowInaccessible) { foreach($i in $Inaccessible) { New-Object -TypeName PSCustomObject -Property $([ordered]@{ ComputerName = $i ComponentBasedServicing = 'Inaccessible' WindowsUpdate = 'Inaccessible' }) } } } }
PowerShellCorpus/PowerShellGallery/xDatabase/1.6.0.0/Examples/Sample_xDBPackage.ps1
Sample_xDBPackage.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingComputerNameHardcoded", "")] Param( ) configuration DbBackup { param ( [PSCredential]$Credentials, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$DatabaseName, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$SqlServer, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(Mandatory)] [ValidateSet("DACPAC","BACPAC")] [ValidateNotNullOrEmpty()] [String]$Type, [Parameter(Mandatory)] [ValidateSet("2008-R2","2012","2014")] [ValidateNotNullOrEmpty()] [String]$SqlServerVersion ) Node 'localhost' { xDBPackage Backup { SqlServer = $SqlServer SqlServerVersion = $SqlServerVersion Credentials = $Credentials Type = $Type DatabaseName = $DatabaseName Path = $Path } } } $ConfigurationData = @{ AllNodes = @( @{ NodeName="*" PSDscAllowPlainTextPassword=$true } @{ NodeName="localhost" } ) } $password = "Zodiac!99" | ConvertTo-SecureString -asPlainText -Force $username = "sa" $credential = New-Object System.Management.Automation.PSCredential($username,$password) DbBackup -ConfigurationData $ConfigurationData -DatabaseName "dac_db" -Credentials $credential -Path "c:\dsc\apmauth.dacpac" -SqlServer ".\sqlexpress" -SqlServerVersion "2012" -Type "DACPAC" Start-DscConfiguration -ComputerName "localhost" -Path ".\DbBackup" -Wait -Force -Verbose
PowerShellCorpus/PowerShellGallery/xDatabase/1.6.0.0/Examples/Sample_xDatabase.ps1
Sample_xDatabase.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingComputerNameHardcoded", "")] Param( ) $assemblylist = "Microsoft.SqlServer.Dac.dll", "Microsoft.SqlServer.Smo.dll" $sqlpsreg110="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps110" $sqlpsreg100="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps" configuration DacDeploy { param ( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$Ensure, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$DatabaseName, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$SqlServer, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$SqlServerVersion, [String]$DacPacPath, [String]$BacPacPath, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String]$NodeName, [PSCredential] $Credentials, [string]$DacPacApplicationName ) Node 'localhost' { xDatabase DeployDac { Ensure = $Ensure SqlServer = $SqlServer SqlServerVersion = $SqlServerVersion DatabaseName = $DatabaseName Credentials = $Credentials BacPacPath = $BacPacPath } } } $ConfigurationData = @{ AllNodes = @( @{ NodeName="*" PSDscAllowPlainTextPassword=$true } @{ NodeName="localhost" } ) } $password = "Zodiac!99" | ConvertTo-SecureString -asPlainText -Force $username = "sa" $credential = New-Object System.Management.Automation.PSCredential($username,$password) DacDeploy -ConfigurationData $ConfigurationData -Ensure "Absent" -DatabaseName "dbr1" -SqlServer ".\sqlexpress" -SqlServerVersion "2012" -NodeName "localhost" -Credentials $credential -BacPacPath C:\bacpac\Database.bacpac Start-DscConfiguration -ComputerName "localhost" -Path .\DacDeploy -Wait -Force -Verbose
PowerShellCorpus/PowerShellGallery/xDatabase/1.6.0.0/Tests/MSFT_xDatabase.Tests.ps1
MSFT_xDatabase.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path $leaf = Split-Path -Leaf $MyInvocation.MyCommand.Path $source = "..\DSCResources\$($leaf.Split(".")[0])\$($leaf -replace ".Tests.ps1$",".psm1")" $common = "..\DSCResources\xDatabase_Common\xDatabase_Common.psm1" $testParameter = @{ Ensure = "Present" SqlServer = "localhost" SqlServerVersion = "2014" DatabaseName = "test" } Describe "Testing xDatabase resource execution" { Copy-Item -Path "$here\$source" -Destination TestDrive:\script.ps1 Copy-Item -Path "$here\$common" -Destination TestDrive:\helper.ps1 $connectionObj = New-Object -TypeName psobject $connectionObj | Add-Member -MemberType NoteProperty -Name connectionString -Value $null $connectionObj | Add-Member -MemberType ScriptMethod -Name Close -Value {return $null} Mock -CommandName New-Object -ParameterFilter { $TypeName -eq "system.Data.SqlClient.SqlConnection" } -MockWith {return $connectionObj} Mock -CommandName Export-ModuleMember -MockWith {return $true} Mock -CommandName Import-Module -MockWith {return $true} . TestDrive:\script.ps1 . TestDrive:\helper.ps1 It "Get-TargetResource should return [Hashtable]" { (Get-TargetResource @testParameter).GetType() -as [String] | Should Be "hashtable" } Context "database does not exist" { $connectionObj | Add-Member -MemberType ScriptMethod -Name Open -Value {throw [System.Data.SqlClient.SqlException]} It "Test-TargetResource should return false" { Test-TargetResource @testParameter | Should Be $false } } Context "database does exist" { $connectionObj | Add-Member -MemberType ScriptMethod -Name Open -Value {return $null} -Force It "Test-TargetResource should return false" { Test-TargetResource @testParameter | Should Be $true } } }
PowerShellCorpus/PowerShellGallery/Azure.Storage/3.1.0/AzureStorageStartup.ps1
AzureStorageStartup.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. # ---------------------------------------------------------------------------------- $script:aliases = @{ # Storage aliases "Get-AzureStorageContainerAcl" = "Get-AzureStorageContainer"; "Start-CopyAzureStorageBlob" = "Start-AzureStorageBlobCopy"; "Stop-CopyAzureStorageBlob" = "Stop-AzureStorageBlobCopy"; } $aliases.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkGgYJKoZIhvcNAQcCoIIkCzCCJAcCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG #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qISm04R9 # PiBhkNE6MIHiBgsqhkiG9w0BCRACDDGB0jCBzzCBzDCBsQQUvf/FlWOQ8ROcYNYZ # wK/puJ4eIB0wgZgwgYCkfjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGlu # Z3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBv # cmF0aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EgMjAxMAIT # MwAAALI1BWg3IhwNpwAAAAAAsjAWBBRLNABI5NOpWQlxhBdOTLJLdcJSNTANBgkq # hkiG9w0BAQsFAASCAQA2imxa2MyR79pKoARLFjUvt0xPso4vbEFLsvCJycQBKrBW # 46QNdX7mPsTJ9QEnGGbO0fgsHPXTMYfprlXE8rDFf01duu++QGgCKxZDfPNsJP29 # o8+WcAnhNR/52UlqhLSwSDtjc2daMpHio9yiD5POWVmXX8iwK67YAF+FY7q9LGA9 # gD24SD9IfvOkDvQUQ77QB2EOO3+eVNyFiZEFELOlpzcFBnjc7XcNdocFNZNJXwXR # 0XOOG1ItnyFW7css1++NS5C8XxMp/aAVaFeFey1T2SAW0NYMjtzAQ30ig96Sr0jf # N4XpoB2c0d6zEiI0YOlupgmmJ7zul9R11FsS2Y6c # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Azure.Storage/2.8.0/AzureStorageStartup.ps1
AzureStorageStartup.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. # ---------------------------------------------------------------------------------- $script:aliases = @{ # Storage aliases "Get-AzureStorageContainerAcl" = "Get-AzureStorageContainer"; "Start-CopyAzureStorageBlob" = "Start-AzureStorageBlobCopy"; "Stop-CopyAzureStorageBlob" = "Stop-AzureStorageBlobCopy"; } $aliases.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkFwYJKoZIhvcNAQcCoIIkCDCCJAQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBQhmpJAhps63hq # Wx1NAq8sjlKZ/STNYAB9gNtQKoh4H6CCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD # VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy # b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p # bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL # MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v # bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UECxMETU9Q # UjEeMBwGA1UEAxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkqhkiG9w0B # AQEFAAOCAQ8AMIIBCgKCAQEA0IfUQit+ndnGetSiw+MVktJTnZUXyVI2+lS/qxCv # 6cnnzCZTw8Jzv23WAOUA3OlqZzQw9hYXtAGllXyLuaQs5os7efYjDHmP81LfQAEc # wsYDnetZz3Pp2HE5m/DOJVkt0slbCu9+1jIOXXQSBOyeBFOmawJ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DVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdS # ZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xJjAkBgNVBAMT # HU1pY3Jvc29mdCBUaW1lLVN0YW1wIFBDQSAyMDEwAhMzAAAAtEM6HP62ulKJAAAA # AAC0MA0GCWCGSAFlAwQCAQUAoIIBMjAaBgkqhkiG9w0BCQMxDQYLKoZIhvcNAQkQ # AQQwLwYJKoZIhvcNAQkEMSIEIBUhfEjE6N/SpriL21ZjtCLkd8lQciGw6+1CFTml # +NL/MIHiBgsqhkiG9w0BCRACDDGB0jCBzzCBzDCBsQQUB8CVl64uTm7J03X22YlR # mIsgbTowgZgwgYCkfjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv # bjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0 # aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EgMjAxMAITMwAA # ALRDOhz+trpSiQAAAAAAtDAWBBQFTh0ly8mTkwWSF0VPt41Rk5T5aTANBgkqhkiG # 9w0BAQsFAASCAQAA/D82+RKVF9irlNWLgfCPEVUuAwXe9n1KEfiDzLKmvbmvFwSF # r9YOtV5BQJHzvNFIxxIH+3QHANA+kuf2mNWZiN14tcqtdI7Zw3xqZeqxvciKwPe1 # UaxSK+RFYILSCb56ngogyXeCa0XPfb4SheaO8fEd97Rw9KAyQMWr748HvawtoqFe # LxS74aGASxQZjnED6PT2kSgAPRmYs93JyEUZ3VXvAsuwug+duM3V/0P1YZeklV93 # z6GE3t16z1a/h4ceYgZGM7weZiR8IrMFf0+x8n26xQgcEZA9yTycphQau1wHZQpk # Sx9VD1CbTQjSJFaZyVvecY59xFJxWyBRPNuV # SIG # End signature block
PowerShellCorpus/PowerShellGallery/MeasureTrace/0.41.0/MakePsModuleDirFromBuildDir.ps1
MakePsModuleDirFromBuildDir.ps1
<# Written and shared by Microsoft employee Matthew Reynolds in the spirit of "Small OSS libraries, tool, and sample code" OSS policy MIT license https://github.com/MatthewMWR/MeasureTrace/blob/master/LICENSE #> param($Source = $psscriptroot, $InstallScope = 'CurrentUser', $Filter = '*.psd1') foreach($moduleFile in Get-CHildItem $Source -Recurse -Filter $Filter){ $tempModDir = (Join-Path $env:TEMP $moduleFile.BaseName) if(Test-Path $tempModDir -ErrorAction SilentlyContinue){ rd $tempModDir -Force -Recurse -ErrorAction Stop } Copy-Item -Path $moduleFile.Directory -Destination $tempModDir -Recurse $targetInstallDir = if([string]::IsNullOrEmpty($InstallScope)){ $null } elseif ($InstallScope -eq 'CurrentUser'){ $env:psmodulepath -split ';' | ?{ $_.StartsWith($env:userprofile) } | select -First 1 } elseif ($InstallScope -eq 'Machine'){ Join-Path $pshome "Modules" } else{ throw "Only blank, CurrentUser, or Machine are valid for InstallScope" } if(-not [string]::IsNullOrEmpty($targetInstallDir ) ){ Remove-Item (Join-Path $targetInstallDir $moduleFile.BaseName) -Recurse -Force -ErrorAction SilentlyContinue New-Item $targetInstallDir -ItemType Directory -ErrorAction SilentlyContinue Copy-Item $tempModDir $targetInstallDir -Container -Recurse } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/init.ps1
init.ps1
# use this file to define global variables on module scope # or perform other initialization procedures. # this file will not be touched when new functions are exported to # this module.
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Start-DirSync.ps1
Start-DirSync.ps1
function Start-DirSync { <# .SYNOPSIS Kicks off AD Connect Sync Cycle .DESCRIPTION Kicks off AD Connect Sync Cycle of specified type on specified server. .EXAMPLE Start-DirSync -SyncType Initial Starts Initial (Full) DirSync on AD Sync Server scrp-nettools01 (Default Value) .EXAMPLE Start-DirSync -SyncType Delta -ADSyncServer scrp-dirsync01 -Debug Starts Delta DirSync on AD Sync Server scrp-dirsync01 with debugging options (Writes output of current steps.) #> [CmdletBinding()] param ( # Define type of sync to start [Parameter(Mandatory = $true, Position = 0)] [ValidateSet('Delta','Initial')] [string] $SyncType, # Define AD Connect Server [Parameter(Mandatory = $true, Position = 1)] [System.String] $ADSyncServer, # Wait switch [Parameter(Mandatory = $false, Position = 2)] [switch] $Wait = $false, [Parameter(Mandatory = $false, Position = 3)] [switch] $Debug = $false ) $colors = 'Black', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkRed', 'DarkMagenta', 'DarkYellow', 'Gray', 'DarkGray', 'Blue', 'Green', 'Cyan', 'Red', 'Magenta', 'Yellow', 'White' if ($SyncType -eq 'Delta') { $sb = { Start-ADSyncSyncCycle -PolicyType Initial } } if ($SyncType -eq 'Initial') { $sb = { Start-ADSyncSyncCycle -PolicyType Delta } } Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Connecting to AD Sync Server $($ADSyncServer)" -PercentComplete 10 if ($Debug) { Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object '-----------------------------------------------------' Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object "-----Initiating Delta AADsync on $($ADSyncServer)-----" Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object '-----------------------------------------------------' } Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Creating PSSession to $($ADSyncServer)" -PercentComplete 15 $DirSyncServerSession = New-PSSession -ComputerName $ADSyncServer if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Session opened' } Start-Sleep -Seconds 5 Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Entering PSSession to AD Sync Server $($ADSyncServer)" -PercentComplete 20 Enter-PSSession $DirSyncServerSession Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Starting AD Sync Cyle on $($ADSyncServer)" -PercentComplete 50 if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Entered Session' } Start-Sleep -Seconds 5 if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Initiating AADsync' } Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "AD Sync Cyle finished starting on $($ADSyncServer)" -PercentComplete 80 #icm -ScriptBlock {cmd /C "C:\Program Files\Microsoft Azure AD Sync\Bin\DirectorySyncClientCmd.exe" initial} -Session $nettools01session Invoke-Command -ScriptBlock $sb -Session $DirSyncServerSession if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'AADsync Completed' Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Exiting PSSession' } Exit-PSSession Start-Sleep -Seconds 5 Remove-PSSession -Session $DirSyncServerSession -Verbose Write-Progress -Activity 'Invoking a DirSync Cycle' -Status "Exited & Closed PSSession on $($ADSyncServer)" -PercentComplete 100 if ($Debug) { Write-Host -ForegroundColor Magenta -BackgroundColor Black -Object 'Session Removed' Write-Host Run the following command to check status of the latest 20 messages associated with Azure AD Connect. -ForegroundColor Magenta -BackgroundColor Black } Write-Output -Object "Get-EventLog -ComputerName $($ADSyncServer) -LogName Application -Source `"Directory Synchronization`" -Newest 20 | select TimeGenerated,EntryType,Message" if ($Wait) { Write-Host "Wait flag set. Beginning query of $ADSyncServer Logs..." -ForegroundColor Green -BackgroundColor Black Start-Sleep -Seconds 5 Write-Host "Still Working." -NoNewline -ForegroundColor Gray -BackgroundColor Black while ((Get-EventLog -ComputerName $ADSyncServer -LogName Application -Source "Directory Synchronization" -Newest 20 | select TimeGenerated, EntryType, Message | ? {$_.Message -contains "Finished" -and $_.TimeGenerated -gt (Get-Date).AddMinutes(-1)}).count -eq 0) { Write-Host '.' -NoNewline -ForegroundColor (Get-Random $colors) -BackgroundColor Black Start-Sleep -Seconds 3 } #Print out finished message (Get-EventLog -ComputerName $ADSyncServer -LogName Application -Source "Directory Synchronization" -Newest 20 | select TimeGenerated, EntryType, Message | ? {$_.Message -contains "Finished" -and $_.TimeGenerated -gt (Get-Date).AddMinutes(-1)}) } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Connect-SPOL.ps1
Connect-SPOL.ps1
function Connect-SPOL { <# .SYNOPSIS Connects to SharePoint Online .DESCRIPTION Connects to SharePoint Online REF: https://technet.microsoft.com/library/fp161372%28v=office.15%29.aspx?f=255&MSPPError=-2147217396 REF: https://www.microsoft.com/en-us/download/confirmation.aspx?id=35588 .EXAMPLE Connect-SPOL -adminUPN myaccount@myorg.co -orgName myco1 #> [CmdletBinding()] param ( [Parameter(Mandatory=$true, Position=0)] [System.String] $adminUPN = "", [Parameter(Mandatory=$true, Position=1)] [System.String] $orgName = "" ) $userCredential = Get-Credential -UserName $adminUPN -Message "Type the password." Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Start-ExternalEmailTester.ps1
Start-ExternalEmailTester.ps1
Function Start-ExternalEmailTester { param( [Parameter(Mandatory=$true)] [System.Management.Automation.PsCredential] $Cred = $Host.UI.PromptForCredential('Enter Outlook.com Credential', 'Enter the username and password of your outlook.com account.', '', 'userCreds'), [String] [Parameter(Mandatory=$true)] $DestinationEmailAddress, [int32] $SecondDelay = 180 ) $counter = 0 $subjectBase = 'Test Email ' $SMTPServer = 'smtp-mail.outlook.com' #$Cred = Get-Credential while (1) { $subject = "[TESTING]External Email Tester - POSH on $($env:COMPUTERNAME)"; $subjectBase + $counter + "- $(Get-Date -DisplayHint Time)" $body = "$($subjectBase) $($counter) - $(Get-Date -DisplayHint Time) Test sent at $(Get-Date -DisplayHint DateTime) Next Email Expected at $((Get-Date).AddSeconds(180))" Send-MailMessage -SmtpServer $SMTPServer -Subject $subject -Body $body -Credential $Cred ` -To $DestinationEmailAddress ` -From $cred.UserName ` -UseSsl $counter++ Start-Sleep -Seconds $SecondDelay } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Add-SendAsPermission.ps1
Add-SendAsPermission.ps1
function Add-SendAsPermission { <# .SYNOPSIS Adds SendAs Extended Right to target user .EXAMPLE Add-SendAsPermission -enduser steve -targetmailbox bob Adds SendAs permission on bob's mailbox for end user steve. #> param ( [String] [Parameter(Mandatory)] $enduser, [Parameter(Mandatory)] [String] $targetmailbox ) Confirm-ExchangeOnlineConnection -ConnectIfDisconnected try { #Add-RecipientPermission -Identity "$($targetmailbox.samaccountname)" -Trustee "$($enduser.samaccountname)" -AccessRights SendAs -Verbose Add-RecipientPermission -Identity $targetmailbox -Trustee $enduser -AccessRights SendAs -Verbose } catch { Write-Output -InputObject 'Error in adding Recipient permissions.' Return $_.Exception } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Disconnect-ExchangeOnline.ps1
Disconnect-ExchangeOnline.ps1
Function Disconnect-ExchangeOnline { Get-PSSession | ?{$_.ComputerName -like '*outlook.office365.com'} | Remove-PSSession }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Watch-EOLMigrationStatus.ps1
Watch-EOLMigrationStatus.ps1
function Watch-EOLMigrationStatus { <# .SYNOPSIS Connects to Exchange Online and grabs the status of any pending migrations. .DESCRIPTION Connects to Exchange Online and grabs the status of any pending migrations. .EXAMPLE Watch-EOLMigrationStatus -SleepingMinutes 5 Connects to EOL, reports back pending transfers, then sleeps 5 minutes. #> [CmdletBinding()] param ( [Parameter(Mandatory=$false, Position=0)] [System.Int32] $SleepingMinutes = 5 ) if ((Get-ExchangeOnlineConnectionState) -eq 'Connected') {} ELSE {Connect-ExchangeOnline} while (1) { $MSGs = Get-MessageTrace -Status Pending; if ($MSGs.count -gt 10) { Write-Host 10 messages pending. Consider a reboot Write-Host '' $MSGs $n = 0 while ($n -lt 10) { Start-Sleep -Seconds 3 $n++ } } Write-Host "Acceptable count of Pending Messages. PENDING: $(($MSGs).count). Sleeping for 5 minutes. $(Get-Date -displayhint datetime)" Start-Sleep -Seconds ($SleepingMinutes*60) } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Get-DailyEmailCounts.ps1
Get-DailyEmailCounts.ps1
function Get-DailyEmailCounts { <# .SYNOPSIS Gathers a simple report of number/basic info of emails received by a certain Exchange Online address. .DESCRIPTION Connects to Exchange Online and gathers daily email counts for the last day ("Number of emails sent TO this email box from Midnight Yesterday to Midnight this morning") and sends an email report .EXAMPLE Get-DailyEmailCounts -AddressToQuery example@company.com -username admin@company.com -password 'Pa$$w0rd!' -SMTPServer webmail.company.com -email_from me@company.com -email_to you@company.com Sends a report for number of messages received, who from, and subject, for example@company.com and emails you@company.com a report .EXAMPLE Get-DailyEmailCounts -AddressToQuery example@company.com,example2@company.com,example3@company.com -username admin@company.com -password Pa$$w0rd! -SMTPServer webmail.company.com -email_from me@company.com -email_to you@company.com -DaysToQuery 3 Sends a report for number of messages received, who from, and subject, for the last 3 days, for example@company.com, example2@company.com, and example3@company.com and emails you@company.com a report .EXAMPLE Get-DailyEmailCounts -AddressToQuery example@company.com -username admin@company.com -password 'Pa$$w0rd!' -SMTPServer webmail.company.com -email_from me@company.com -email_to you@company.com -Uri https://customURI.microsoft.com Sends a report for number of messages received, who from, and subject, for example@company.com and emails you@company.com a report. Utilizes the custom URI switch. #> [CmdletBinding()] param ( [Parameter(Mandatory=$True, Position=0)] [String[]] $AddressToQuery, [Parameter(Mandatory=$True, Position=1, HelpMessage='Enter in an Administrator account that is able to query Exchange Online.')] [System.String] $username, [Parameter(Mandatory=$True, Position=2, HelpMessage='Enter the password for the Exchange Online Administrator Account')] [Object] $password, [Parameter(Mandatory=$false, Position=3, HelpMessage='Optionally specify the URI used to connect to Exchange Online. Default: https://outlook.office365.com/powershell-liveid/')] [System.Uri] $Uri = 'https://outlook.office365.com/powershell-liveid/', [Parameter(Mandatory=$True, Position=4, HelpMessage='Specify the SMTP Server address to use to send the email report')] [System.String] $SMTPServer, [Parameter(Mandatory=$True, Position=5, HelpMessage='Specify the sender address to use to send the email report')] [System.String] $email_from, [Parameter(Mandatory=$True, Position=6, HelpMessage='Specify the recipient address(es) to use to send the email report')] [System.String] $email_to, [Parameter(Mandatory=$false, Position=7, HelpMessage='Specify the Email subject address to use to send the email report')] [System.String] $email_subject = 'Daily Email Counts', [Parameter(Mandatory=$false, Position=8, HelpMessage='Number of historical Days to Query')] $DaysToQuery = 1 ) $spwd = ConvertTo-SecureString -AsPlainText $password -Force $Credential = New-Object System.Management.Automation.PSCredential $username,$spwd $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection #-Verbose Import-PSSession -Session $session -AllowClobber #-Verbose $body = " <strong>Script Runtime: $(Get-Date -DisplayHint DateTime)</strong><br/> <strong>Emails from: </strong>$(((Get-Date -Hour 0 -Minute 0 -Second 0).AddDays(-$DaysToQuery)))<br> <strong>Emails to: </strong>$(((Get-Date -Hour 0 -Minute 0 -Second 0)))<br/><p/> <table style=`"width: 100%;`" border=`"1`"> <tbody> <tr> <td style=`"width: 20%;`"><strong>Email</strong></td> <td style=`"width: 80%;`"><strong>Information</strong></td> </tr>" $body_emailrow = " <tr> <td>{0}</td> <td>Daily Count = <strong><font color=`"blue`">{1}</font></strong><br> <br> {2}</td> </tr>" $body_Footer = ' </tbody> </table>' foreach ($email in $AddressToQuery) { $email_results = Get-MessageTrace -RecipientAddress $email -StartDate ((Get-Date -Hour 0 -Minute 0 -Second 0).AddDays(-$DaysToQuery)) -EndDate ((Get-Date -Hour 0 -Minute 0 -Second 0)) [String]$html_fragment = ($email_results | sort SenderAddress | Select SenderAddress,Subject | ConvertTo-Html -Fragment -As Table) $body += $body_emailrow -f $email, $($email_results.count), $($html_fragment); #$body } $body += $body_Footer Send-MailMessage -SmtpServer $SMTPServer -From $email_from -To $email_to -Subject $email_subject -Body $body -BodyAsHtml Remove-PSSession $session }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Disconnect-ExchangeComplianceOnline.ps1
Disconnect-ExchangeComplianceOnline.ps1
Function Disconnect-ExchangeComplianceOnline { Get-PSSession | ?{$_.ComputerName -like '*ps.compliance.protection.outlook.com'} | Remove-PSSession }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Connect-ExchangeComplianceOnline.ps1
Connect-ExchangeComplianceOnline.ps1
Function Connect-ExchangeComplianceOnline { [CmdletBinding()] param ( [Parameter(Mandatory = $False)] [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential('Enter Global Admin Credential', 'Enter the username and password of an Exchange Online Global Administrator account.', '', 'userCreds'), [Parameter(Mandatory = $False)] [System.Uri]$Uri = 'https://ps.compliance.protection.outlook.com/powershell-liveid/' ) $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection Import-PSSession -Session $session -AllowClobber Return $session }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Confirm-ExchangeOnlineConnection.ps1
Confirm-ExchangeOnlineConnection.ps1
function Confirm-ExchangeOnlineConnection { <# .SYNOPSIS Confirms there is an active connection to Exchange Online. Connects if prompted. .DESCRIPTION Confirms there is an active connection to Exchange Online. Connects if prompted. .EXAMPLE Confirm-ExchangeOnlineConnection -ConnectIfDisconnected Confirms connection. If disconnected, we connect. .EXAMPLE Confirm-ExchangeOnlineConnection Only confirms connection. #> [CmdletBinding()] param ( [Parameter(Mandatory=$false, Position=0)] [Switch] $ConnectIfDisconnected ) #Confirm we are connected to EOL. If not, connect. $ConnectionState = (Get-PSSession | ? {$_.ConfigurationName -eq "Microsoft.Exchange" -and $_.State -eq "Opened" -and $_.ComputerName -eq "outlook.office365.com"}).count if ($ConnectionState -eq 0) { #return "Disconnected" Write-Output 'Not connected to Exchange Online.' if ($ConnectIfDisconnected) { Write-Output 'Connecting...' Connect-ExchangeOnline -Verbose #Import-PSSession (Get-PSSession | ? {$_.ComputerName -like "*outlook*" -and $_.State -eq 'Opened'}) #return $session } } Else {return 'Already Connected'} }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Get-ExchangeOnlineConnectionState.ps1
Get-ExchangeOnlineConnectionState.ps1
Function Get-ExchangeOnlineConnectionState { $ConnectionState = (Get-PSSession | ? {$_.ConfigurationName -eq 'Microsoft.Exchange' -and $_.State -eq 'Opened' -and $_.ComputerName -eq 'ps.outlook.com'}).count if ($ConnectionState -eq 0) { return 'Disconnected' } if ($ConnectionState -eq 1) { return 'Connected' } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Add-FullAccessPermission.ps1
Add-FullAccessPermission.ps1
function Add-FullAccessPermission { <# .SYNOPSIS Adds FullAccess to target user .EXAMPLE Add-FullAccessPermission -enduser steve -targetmailbox bob Adds SendAs permission on bob's mailbox for end user steve WITHOUT AutoMapping. .EXAMPLE Add-FullAccessPermission -enduser steve -targetmailbox bob -AutoMapping Adds SendAs permission on bob's mailbox for end user steve WITH AutoMapping #> param ( [String] [Parameter(Mandatory)] $enduser, [Parameter(Mandatory)] [String] $targetmailbox, [Switch] $AutoMapping ) Confirm-ExchangeOnlineConnection -ConnectIfDisconnected try { if ($AutoMapping) { Write-Output 'AutoMapping Flag Set. Automapping = $true' Add-MailboxPermission ` -Identity $targetmailbox ` -User $enduser ` -AutoMapping $true ` -AccessRights FullAccess ` -Verbose } if (!$AutoMapping) { Write-Output 'AutoMapping Flag NOT Set. Automapping = $false' Add-MailboxPermission ` -Identity $targetmailbox ` -User $enduser ` -AutoMapping $false ` -AccessRights FullAccess ` -Verbose } } catch { Write-Output -InputObject 'Error in adding FullAccess permissions.' Return $_.Exception } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Connect-ExchangeOnline.ps1
Connect-ExchangeOnline.ps1
Function Connect-ExchangeOnline { [CmdletBinding()] param ( [Parameter(Mandatory = $False)] [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential('Enter Global Admin Credential', 'Enter the username and password of an Exchange Online Global Administrator account.', '', 'userCreds'), [Parameter(Mandatory = $False)] [System.Uri]$Uri = 'https://outlook.office365.com/powershell-liveid/' #'https://ps.outlook.com/powershell/' ) $progressActivity = 'Connecting to Exchange Online' $prog_pctcomplete = 0 $prog_numofupdates = 3 $pctIncrement = (100 / $prog_numofupdates) Write-Progress -Activity $progressActivity -Status 'Creating Session Link to Exchange Online' -PercentComplete ($prog_pctcomplete += $pctIncrement) $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection -Verbose Write-Progress -Activity $progressActivity -Status 'Sleeping' -PercentComplete ($prog_pctcomplete += $pctIncrement) Start-Sleep -Seconds 1 Write-Progress -Activity $progressActivity -Status 'Importing the PowerShell Session' -PercentComplete ($prog_pctcomplete += $pctIncrement) Import-PSSession -Session $session -AllowClobber -Verbose Return $session }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Backup-Whitelist.ps1
Backup-Whitelist.ps1
Function Backup-Whitelist { param( [System.Diagnostics.Switch] $Debugging, [Switch] $SendEmail, [Parameter(Mandatory = $False)] [String] $BackupPath = 'C:\scripts\powershell\EOL_WhitelistBackups\', [Parameter(Mandatory = $true)] [String] $EmailRecipient, [Parameter(Mandatory = $true)] [String] $EmailSenders, [Parameter(Mandatory = $true)] [String] $SMTPServer ) #region Varialbes New-Item $BackupPath -ItemType Directory -ErrorAction SilentlyContinue -Force [String]$Runtime = Get-Date -Format yyyy.MM.dd_HH.mm.sstt $BackupZip = $BackupPath + $Runtime + '.zip' $StartingLocation = Get-Location #endregion #region Connect to Exchange Online [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential('Enter Global Admin Credential', 'Enter the username and password of an Exchange Online Global Administrator account.', '', 'userCreds') [System.Uri]$Uri = 'https://outlook.office365.com/powershell-liveid/' #'https://ps.outlook.com/powershell/' $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication Basic -AllowRedirection -Verbose Import-PSSession -Session $session -AllowClobber -Verbose #endregion Connect to Exchange Online $AllPolicies = Get-HostedContentFilterPolicy foreach ($SpamPolicy in $AllPolicies) { $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_AllowedSenderDomains.csv' $SpamPolicy.AllowedSenderDomains | Export-Csv -Path $OutFile -NoTypeInformation $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_AllowedSenders.csv' $SpamPolicy.AllowedSenders | Export-Csv -Path $OutFile -NoTypeInformation $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_BlockedSenderDomains.csv' $SpamPolicy.BlockedSenderDomains | Export-Csv -Path $OutFile -NoTypeInformation $OutFile = $BackupPath + $Runtime + '_' + $SpamPolicy.Name + '_BlockedSenders.csv' $SpamPolicy.BlockedSenders | Export-Csv -Path $OutFile -NoTypeInformation } Set-Location $BackupPath $BackupFiles = Get-ChildItem -Path $BackupPath*csv $BackupFiles | Write-Zip -Level 9 -OutputPath $BackupZip $BackupFiles | Remove-Item -Force -ErrorAction SilentlyContinue Set-Location $StartingLocation if ($SendEmail) { Send-MailMessage -SmtpServer $SMTPServer -To $EmailRecipient -From $EmailSenders -Subject "Exchange Spam Filter Backups - $($Runtime)" -Attachments $BackupZip } }
PowerShellCorpus/PowerShellGallery/365Admin/1.0.2.1/Get-Wasted365License.ps1
Get-Wasted365License.ps1
function Get-Wasted365License { <# .SYNOPSIS Checks EOL for users with associated licenses who are also disabled in AD .DESCRIPTION This script is meant to find disabled users in Active Directory who are burning a 365 license. .EXAMPLE Get-Wasted365License -ProductType EnterprisePack -LicensePrefix SPANG1 Gets all users who are disabled that have an associated SPANG1:ENTERPRISEPACK license #> [CmdletBinding()] param ( # IFS Instance Selection [Parameter(ParameterSetName = 'ParameterSet1', Mandatory = $true, HelpMessage = 'Select the 365 License Type')] [ValidateSet('EnterprisePack','Visio','Project')] [string] $ProductType, [Parameter(Mandatory = $True)] [string] $LicensePrefix ) if ((Get-ExchangeOnlineConnectionState) -eq 'Disconnected') { $Cred = Get-Credential -Message "Enter your username and password for connecting to Exchange & Azure." Connect-ExchangeOnline -Credential $Cred; Connect-MsolService -Credential $Cred} switch ($ProductType) { EnterprisePack { $SKU = 'ENTERPRISEPACK' } Visio { $SKU = 'VISIOCLIENT' } Project { $SKU = 'PROJECTCLIENT' } } $ProductCompleteSKU = "$($LicensePrefix):$($SKU)" $MSOLUsers = Get-MsolUser -All $LicensedUsers = $MSOLUsers | Where-Object -FilterScript { $_.Licenses.AccountSKUId -eq $ProductCompleteSKU } $wastedLicense = @() foreach ($user in $LicensedUsers) { $name = ($user.UserPrincipalName.Split('@')[0]) if ((Get-ADUser -Identity $name -ErrorAction SilentlyContinue).Enabled -eq $false) { $wastedLicense += $name } } Remove-Variable -Name ProductType, SKU, LicensedUsers, user, name, ProductCompleteSKU return $wastedLicense Write-host "You must be connected to Exchange Online and MSOLService." -ForegroundColor Green -BackgroundColor Black Write-host "Use Connect-ExchangeOnline & Connect-MSOLService to ensure you are connected as required." -ForegroundColor Green -BackgroundColor Black }
PowerShellCorpus/PowerShellGallery/PSForge/1.1.0/UnitTest.ps1
UnitTest.ps1
Import-Module Pester Remove-Module PSForge -ErrorAction SilentlyContinue Import-Module $PSScriptRoot/PSForge.psm1 Invoke-Pester $PSScriptRoot/PSForge.Tests.ps1
PowerShellCorpus/PowerShellGallery/PSForge/1.1.0/MyGet.ps1
MyGet.ps1
param( [string] $packageVersion = $env:PackageVersion, [bool] $fakeBuildRunner = $false ) Invoke-Expression ".\paket restore -f" Import-Module -Force .\PowershellDSCWorkflow.psm1 Import-Module -Force .\packages\Plaster\Plaster.psm1 Export-DSCModule -Version $packageVersion Remove-Item -Recurse .\packages
PowerShellCorpus/PowerShellGallery/PSForge/1.1.0/PSForge.Tests.ps1
PSForge.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") InModuleScope PSForge { # Describe "PSForge" { # It "PSForge is available to be imported when called" { # Get-Module –ListAvailable | where { $_.Name –eq 'PSForge' } | should not be $null # } # } Describe "OS Detection" { Context "Windows" { Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} It "Should detect Windows installation" { getOSPlatform | should be "windows" isWindows | should be $True isUnix | should be $False } } Context "Linux" { Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} Mock Invoke-Expression { "Linux" } -Verifiable -ParameterFilter {$Command -eq "uname"} It "Should detect Linux installation" { getOSPlatform | should be "linux" isWindows | should be $False isUnix | should be $True Assert-VerifiableMocks } } Context "MacOS" { Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} Mock Invoke-Expression { "Darwin" } -Verifiable -ParameterFilter {$Command -eq "uname"} It "Should detect Linux installation" { getOSPlatform | should be "mac" isWindows | should be $False isUnix | should be $True Assert-VerifiableMocks } } } Describe "Dependency checking"{ Context "Mono is not installed" { It "Should throw exception if Mono not installed on Unix" { Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} Mock Invoke-Expression { "Linux" } -Verifiable -ParameterFilter {$Command -eq "uname"} Mock isOnPath { $False } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "ruby" } Mock Invoke-Expression { "ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]"} -ParameterFilter { $Command -eq "ruby --version" } { CheckDependencies } | Should Throw "PSForge has a dependency on 'mono' on Linux and MacOS - please install mono via the system package manager." } It "Should not throw exception if Mono not installed on Windows" { Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} Mock isOnPath { $False } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "ruby" } Mock Invoke-Expression { "ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]"} -ParameterFilter { $Command -eq "ruby --version" } { CheckDependencies } | Should not Throw } } Context "Ruby is not installed" { $rubyException = "PSForge has a dependency on 'ruby' 2.3 or higher - please install ruby via the system package manager." $rubyVersionException = "PSForge has a dependency on 'ruby' 2.3 or higher. Current version of ruby is 2.2.2p222 - please update ruby via the system package manager." It "Should throw exception if Ruby not installed on Unix" { Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} Mock Invoke-Expression { "Linux" } -Verifiable -ParameterFilter {$Command -eq "uname"} Mock isOnPath { $True } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $False } -ParameterFilter { $cmd -eq "ruby" } { CheckDependencies } | Should Throw $rubyException } It "Should not throw exception if Ruby not installed on Windows" { Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} Mock isOnPath { $True } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $False } -ParameterFilter { $cmd -eq "ruby" } { CheckDependencies } | Should Throw $rubyException } It "Should throw exception if wrong Ruby installed on Unix" { Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} Mock Invoke-Expression { "Linux" } -Verifiable -ParameterFilter {$Command -eq "uname"} Mock isOnPath { $True } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "ruby" } Mock Invoke-Expression { "ruby 2.2.2p222 (2016-11-21 revision 56859) [x86_64-darwin16]"} -ParameterFilter { $Command -eq "ruby --version" } { CheckDependencies } | Should Throw $rubyVersionException } It "Should throw exception if wrong Ruby installed on Windows" { Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} Mock isOnPath { $True } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "ruby" } Mock Invoke-Expression { "ruby 2.2.2p222 (2016-11-21 revision 56859) [x86_64-darwin16]"} -ParameterFilter { $Command -eq "ruby --version" } { CheckDependencies } | Should Throw $rubyVersionException } } Context "Git is not installed" { $gitException = "PSForge has a dependency on 'git' - please install git via the system package manager." It "Should throw exception if Git not installed on Unix" { Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} Mock Invoke-Expression { "Linux" } -Verifiable -ParameterFilter {$Command -eq "uname"} Mock isOnPath { $True } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $False } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "ruby" } Mock Invoke-Expression { "ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]"} -ParameterFilter { $Command -eq "ruby --version" } { CheckDependencies } | Should Throw $gitException } It "Should not throw exception if Git not installed on Windows" { Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} Mock isOnPath { $True } -ParameterFilter { $cmd -eq "mono" } Mock isOnPath { $False } -ParameterFilter { $cmd -eq "git" } Mock isOnPath { $True } -ParameterFilter { $cmd -eq "ruby" } Mock Invoke-Expression { "ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin16]"} -ParameterFilter { $Command -eq "ruby --version" } { CheckDependencies } | Should Throw $gitException } } } Describe "Invoke-Paket" { Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} Mock generatePaketFiles {} Mock getProjectRoot {} Mock Invoke-Expression {} -ParameterFilter { $Command -eq ".paket\paket.exe" } Mock clearPaketFiles {} Mock Test-Path { $True } -ParameterFilter { $Path -eq ".\.paket\paket.exe" } Mock BootstrapDSCModule {} It "Should run Bootstrap by default" { Invoke-Paket Assert-MockCalled BootstrapDSCModule -Exactly 1 -Scope It } It "Should generate Paket files" { Invoke-Paket Assert-MockCalled generatePaketFiles -Exactly 1 -Scope It } It "Should try and change directory to project root" { Invoke-Paket Assert-MockCalled getProjectRoot -Exactly 1 -Scope It } It "Should execute Paket with mono on Unix" { Mock Invoke-Expression { } -ParameterFilter { $Command -eq "mono .paket\paket.exe" } -Scope It Mock getEnvironmentOSVersion { @{"Platform" = "Unix" }} -Scope It Invoke-Paket Assert-MockCalled Invoke-Expression -ParameterFilter { $Command -eq "mono .paket\paket.exe" } -Exactly 1 -Scope It } It "Should execute Paket directly on Windows" { Mock Invoke-Expression {} -ParameterFilter { $Command -eq ".paket\paket.exe" } -Scope It Mock getEnvironmentOSVersion { @{"Platform" = "Windows" }} -Scope It Invoke-Paket Assert-MockCalled Invoke-Expression -ParameterFilter { $Command -eq ".paket\paket.exe" } -Exactly 1 -Scope It } } }
PowerShellCorpus/PowerShellGallery/PSForge/1.1.0/appveyor.ps1
appveyor.ps1
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted Install-Module Pester -Scope CurrentUser Install-Module Plaster -Scope CurrentUser Import-Module .\PSForge.psm1 $res = Invoke-Pester -Path .\PSForge.Tests.ps1 -OutputFormat NUnitXml -OutputFile TestsResults.xml -PassThru (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\TestsResults.xml)) if ($res.FailedCount -gt 0) { throw "$($res.FailedCount) tests failed."}
PowerShellCorpus/PowerShellGallery/PSForge/1.1.0/plaster-powershell-dsc-module/test/Default.Tests.ps1
Default.Tests.ps1
describe 'When setting up a webserver' { context 'to start the default website' { it 'verifies IIS is installed' { (Get-WindowsFeature web-server).installed | should be $true } it 'installs a default website' { Get-Website 'Default Web Site' | should not be $null } } }
PowerShellCorpus/PowerShellGallery/PSForge/1.1.0/helper_scripts/fixRubyCertStore.ps1
fixRubyCertStore.ps1
$SSL_DIR = "C:\RUBY_SSL" $CA_FILE = "cacert.pem" $CA_URL = "https://curl.haxx.se/ca/${CA_FILE}" New-Item -Type Directory -Force $SSL_DIR [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12; [Environment]::SetEnvironmentVariable("SSL_CERT_FILE", "${SSL_DIR}\${CA_FILE}", "User") $Env:SSL_CERT_FILE = [Environment]::GetEnvironmentVariable("SSL_CERT_FILE", "User") (New-Object System.Net.WebClient).DownloadFile($CA_URL, "${SSL_DIR}\${CA_FILE}") Write-Output "Latest ${CA_FILE} from ${CA_URL} has been downloaded to ${SSL_DIR}" Write-Output "Environment variable SSL_CERT_FILE set to $($Env:SSL_CERT_FILE)" Write-Output "Ruby for Windows should now be able to verify remote SSL connections"
PowerShellCorpus/PowerShellGallery/Gab/1.0/Gab.Tests.ps1
Gab.Tests.ps1
# # This is a PowerShell Unit Test file. # You need a unit test framework such as Pester to run PowerShell Unit tests. # You can download Pester from http://go.microsoft.com/fwlink/?LinkID=534084 #
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Get-IotDeviceKey.ps1
Get-IotDeviceKey.ps1
function Get-IoTDeviceKey { <# .SYNOPSIS Get the device key for the device. .DESCRIPTION See the Synopsis. .EXAMPLE Get-IoTDeviceKey -iotConnString "HostName=myiothub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=HwbPu8ZhK8sdfdsfgdsgdfsfdgM2KvRE=" -deviceId "MyFirstDevice" #> [cmdletbinding()] param( $iotConnString, $deviceId ) $registryManager = [Microsoft.Azure.Devices.RegistryManager]::CreateFromConnectionString($iotConnString) $device = $registryManager.GetDeviceAsync($deviceId) $device = $device.Result $returndevice = New-Object -TypeName psobject -Property @{ DeviceId = $device.Id DevicePrimaryKey = $device.Authentication.SymmetricKey.PrimaryKey DeviceSecondaryKey = $device.Authentication.SymmetricKey.SecondaryKey } return $returndevice }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Register-IoTDevice.ps1
Register-IoTDevice.ps1
function Register-IoTDevice { <# .SYNOPSIS Registers an device to IoT Hub. .DESCRIPTION See the Synopsis. .EXAMPLE Register-IoTDevice -iotConnString "HostName=myiothub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=HwbPu8ZhK8sdfdsfgdsgdfsfdgM2KvRE=" -deviceId "MyFirstDevice" #> [cmdletbinding()] param( $iotConnString, $deviceId ) $registryManager = [Microsoft.Azure.Devices.RegistryManager]::CreateFromConnectionString($iotConnString) $newdevice = New-Object -TypeName Microsoft.Azure.Devices.Device -ArgumentList $deviceId $device = $registryManager.AddDeviceAsync($newdevice) $device.Exception $device = $device.Result $returndevice = New-Object -TypeName psobject -Property @{ DeviceId = $device.Id DevicePrimaryKey = $device.Authentication.SymmetricKey.PrimaryKey DeviceSecondaryKey = $device.Authentication.SymmetricKey.SecondaryKey } return $returndevice }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Receive-IoTCloudMessage.ps1
Receive-IoTCloudMessage.ps1
function Receive-IoTCloudMessage { <# .SYNOPSIS Receives a message from the cloud to the device. .DESCRIPTION See the Synopsis. .EXAMPLE $message = Receive-IoTCloudMessage -deviceClient $deviceClient $message #> [cmdletbinding()] param( $deviceClient ) while ($true) { $asyncOperation = $deviceClient.ReceiveAsync() $message = $asyncOperation.Result if ($message) { try { $text = [System.Text.Encoding]::ASCII.GetString($message.GetBytes()) $deviceClient.CompleteAsync($message) return $text } catch { $deviceClient.AbandonAsync($message) } } else { Start-Sleep -Seconds 5 } } }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Get-IoTDeviceClient.ps1
Get-IoTDeviceClient.ps1
function Get-IoTDeviceClient { <# .SYNOPSIS Create a connection object to interact with IoT Hub. .DESCRIPTION See the Synopsis. .EXAMPLE $deviceClient = Get-IoTDeviceClient -iotHubUri myiothub.azure-devices.net -deviceId SampleDevice -deviceKey klsdjkjfdsfh8weifjkhauwhfre= #> [cmdletbinding()] param( $iotHubUri, $deviceId, $deviceKey ) $deviceAuthToken = New-Object Microsoft.Azure.Devices.Client.DeviceAuthenticationWithRegistrySymmetricKey($deviceId, $deviceKey) $deviceClient = [Microsoft.Azure.Devices.Client.DeviceClient]::Create($iotHubUri, $deviceAuthToken) return $deviceClient }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Receive-IoTDeviceMessage.ps1
Receive-IoTDeviceMessage.ps1
function Receive-IoTDeviceMessage { <# .SYNOPSIS Receives a message from the device to cloud. .DESCRIPTION See the Synopsis. .EXAMPLE $message = Receive-IoTDeviceMessage -iotConnString "HostName=myIotHub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=HwbPu8ZhKsdfgdgdsgdfg1cxmbHh7w1QM2KvRE=" #> [cmdletbinding()] param( $iotConnString ) $eventHubClient = [Microsoft.ServiceBus.Messaging.EventHubClient]::CreateFromConnectionString($iotConnString, "messages/events") $eventHubPartitions = $eventHubClient.GetRuntimeInformation().PartitionIds foreach ($partition in $eventHubPartitions) { $eventHubReceiver = $eventHubClient.GetDefaultConsumerGroup().CreateReceiver($partition, [DateTime]::UtcNow) while ($true) { $asyncOperation = $eventHubReceiver.ReceiveAsync() $eventData = $asyncOperation.Result $message = [System.Text.Encoding]::UTF8.GetString($eventData.GetBytes()) return $message } } }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Get-IoTCloudClient.ps1
Get-IoTCloudClient.ps1
function Get-IoTCloudClient { <# .SYNOPSIS Create a connection object to interact with IoT Hub. .DESCRIPTION See the Synopsis. .EXAMPLE $cloudClient = Get-IoTCloudClient - "HostName=myiothub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=jkgyfjhhuytghji876tghj7w1QM2KvRE=" #> [cmdletbinding()] param( $iotConnString ) $cloudClient = [Microsoft.Azure.Devices.ServiceClient]::CreateFromConnectionString($iotConnString) return $cloudClient }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Send-IoTDeviceMessage.ps1
Send-IoTDeviceMessage.ps1
function Send-IoTDeviceMessage { <# .SYNOPSIS Sends a message from the device to the IoT Hub. .DESCRIPTION See the Synopsis. .EXAMPLE Send-IoTDeviceMessage -messageString "Hello world" -deviceClient $deviceClient #> [cmdletbinding()] param( $messageString, $deviceClient ) $messagetosend = [Microsoft.Azure.Devices.Client.Message]([Text.Encoding]::ASCII.GetBytes($messageString)) $deviceClient.SendEventAsync($messagetosend) }
PowerShellCorpus/PowerShellGallery/AzureIoT/1.0.0.3/Functions/Send-IoTCloudMessage.ps1
Send-IoTCloudMessage.ps1
function Send-IoTCloudMessage { <# .SYNOPSIS Sends a message from the cloud to the Device. .DESCRIPTION See the Synopsis. .EXAMPLE Send-IoTCloudMessage -messageString "Hello world" -cloudClient $cloudClient #> [cmdletbinding()] param( $deviceId, $messageString, $cloudClient ) $messagetosend = [Microsoft.Azure.Devices.Message]([Text.Encoding]::ASCII.GetBytes($messageString)) $cloudClient.SendAsync($deviceId, $messagetosend) }
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/publish.ps1
publish.ps1
[cmdletbinding()] Param( [Parameter(Mandatory)] [string] $APIkey ) $tags = @( "hashtable" , "serialize" , "deserialize" , "pscustomobject" , "import" , "export" , "convert" , "Convertto" , "String" ) Publish-Module -NuGetApiKey $APIkey -Name .\hashdata.psd1
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Functions/ConvertTo-HashString.ps1
ConvertTo-HashString.ps1
#Requires -Version 4.0 function ConvertTo-HashString { <# .SYNOPSIS Convert an hashtable or and OrderedDictionary to a string .DESCRIPTION Convert an hashtable or and OrderedDictionary to a string .PARAMETER InputObject The object that is to be converted .EXAMPLE $hashObject = @{ Name = "Tore" Goal = "Rule the World" } $hashObject | ConvertTo-HashString This will convert the hashtable to the following string @{Name = "Tore";Goal = "Rule the World";} .INPUTS Hashtable .OUTPUTS string .NOTES Author: Tore Groneng Website: www.firstpoint.no Twitter: @ToreGroneng #> [cmdletbinding()] Param ( [Parameter(ValueFromPipeLine)] $InputObject ) Begin { $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" } Process { $out = "@{" if (-not $InputObject -or $InputObject.keys.count -eq 0) {return "@{}"} foreach ($key in $InputObject.Keys) { Write-Verbose -Message "$f - Processing key [$key]" if ($key.Contains('$')) { $DisplayKey = "'$key'" } $value = $InputObject.$key $objType = $value.GetType().Name Write-Verbose -Message "$f - ObjectType = $objType" $mode = "stringValue" if ($objType -eq "Hashtable" -or $objType -eq "OrderedDictionary") { $mode = "hashtable" } if ($value -is [array]) { if ($value[0]) { $arrayType = $value[0].GetType().Name Write-Verbose -Message "$f - arrayType is [$arrayType]" if ($arrayType -eq "Hashtable" -or $arrayType -eq "OrderedDictionary") { $mode = "HashTableValue" } else { $mode = "ArrayValue" } } } Write-Verbose -Message "$f - Mode is [$mode]" if ($DisplayKey) { $key = $DisplayKey $DisplayKey = $null } $out += "$key = " switch ($mode) { 'stringValue' { if ($value -is [int] -or $value -is [double]) { $out += "$value;" } elseif ($value -is [bool]) { $out += '$' + "$value;" } elseif ($value -is [datetime]) { $ticks = $value.Ticks $out += "New-Date $ticks;" } else { $out += '"' + $value + '";' } } 'hashtable' { $stringValue = ConvertTo-HashString -InputObject $value $out += $stringValue + ";" } 'HashTableValue' { $stringValue = "" foreach ($arrayHash in $value) { $hashString = ConvertTo-HashString -InputObject $arrayHash $hash = "$hashString" $hash = "$hash," $stringValue += $hash } $separatorIndex = $stringValue.LastIndexOf(",") $stringValue = $stringValue.Remove($separatorIndex,1) $out += $stringValue + ";" } 'ArrayValue' { if ($value[0] -is [int] -or $value[0] -is [double]) { $out += ($value -join ",") + ";" } else { $out += '"' +($value -join '","') + '";' } } default { Write-Error -Message "Invalid mode in funtion $f" } } } $out += "}" $out } End { Write-Verbose -Message "$f - End" } }
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Functions/Import-HashData.ps1
Import-HashData.ps1
#Requires -Version 4.0 function Import-HashData { <# .SYNOPSIS Import serialized objects from disk. .DESCRIPTION Import serialized objects from disk. The import will check the content of the file for RestrictedLanguage. Only New-Date function is allowed in the script. Other commands will result in an error and the import will fail. .PARAMETER Path The target file that contains the Serialized object(s). .PARAMETER UnsafeMode If supplied, no you allow any command to be executed in the runspace when the object is deserialized. .EXAMPLE $objects = Import-Hashdata -Path c:\temp\Hash.txt This will deserialize the content/objects in the hash.txt file .INPUTS String .OUTPUTS hashtable .NOTES Author: Tore Groneng Website: www.firstpoint.no Twitter: @ToreGroneng #> [cmdletbinding( SupportsShouldProcess=$true, ConfirmImpact='medium' )] Param ( [string] $Path , [switch] $UnsafeMode ) $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" if (-not (Test-Path -Path $Path)) { Write-Error -Message "Unable to find file [$path]" -ErrorAction Stop } Write-Verbose -Message "$f - Importing data from [$path]" [string]$data = Get-Content -Path $path -Encoding UTF8 -Raw -ReadCount 0 if ($UnsafeMode.IsPresent) { #fixme this is a hack $PreviousConfirmPreference = $ConfirmPreference $ConfirmPreference = "low" if ($PScmdlet.ShouldProcess($path, "Unsafe script invokation")) { $ConfirmPreference = $PreviousConfirmPreference Write-Warning -Message "You are importing persisted data without cheching RestrictedLanguage because you supplied the UnSafeMode switch." $script = [scriptblock]::Create($data) & $script } } else { #fixme this is a hack $PreviousConfirmPreference = $ConfirmPreference $ConfirmPreference = "high" if ($PScmdlet.ShouldProcess($path, "Safe script invokation")) { $ConfirmPreference = $PreviousConfirmPreference Write-Verbose -Message "$f - Asserting script content" Assert-ScriptString -Data $data -ErrorAction Stop } } Write-Verbose -Message "$f - END" }
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Functions/Assert-ScriptString.ps1
Assert-ScriptString.ps1
#Requires -Version 4.0 function Assert-ScriptString { <# .SYNOPSIS Validate a scriptblock before execution into current runspace .DESCRIPTION Validate a string before execution into current runspace. The only allowed allowed command/cmdlet is New-Date included in this module. The string is converted to a scriptblock and is only executed if the validation passes. .PARAMETER Data The string that is to be validated for restricted language. .EXAMPLE $string = @" @{ Name = "Tore" Goal = "Rule the World" } "@ $scriptOutput = Assert-ScriptString -Data $string .INPUTS String .OUTPUTS .NOTES Author: Tore Groneng Website: www.firstpoint.no Twitter: @ToreGroneng #> [cmdletbinding()] Param ( [Parameter(ValueFromPipeline)] [string] $Data ) $previousErrorAction = $ErrorActionPreference $ErrorActionPreference = "Stop" try { $script = [scriptblock]::Create($data) [string[]]$allowedCommands = @("New-Date") [string[]]$allowedVariables = @() $script.CheckRestrictedLanguage($allowedCommands, $allowedVariables, $false) & $script } catch { if ($previousErrorAction -ne "SilentlyContinue") { Write-Error -Exception $_.Exception -ErrorAction Stop } } Finally { $ErrorActionPreference = $previousErrorAction } }
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Functions/Export-HashData.ps1
Export-HashData.ps1
#Requires -Version 4.0 function Export-HashData { <# .SYNOPSIS Serialize an object to a file as an HashTable. .DESCRIPTION Serialize an object to a file as an HashTable. The majority of the types of the object is preserved in the output. To handle datetime, the module have a function New-Date that only can create a date from a long tick value. .PARAMETER Path The target file that will store the serialized object .PARAMETER InputObject The object that should be Serialized. .PARAMETER Append Append the Serialized object to the file. .EXAMPLE $obj = [pscustomobject]@{ Name = "Tore" Age = 45 CodeCoverage = 11.21 Date = (Get-Date) IntArray = 1,2,3 } Export-HashData -Path C:\Temp\hash.txt -InputObject $obj This will serialize the $obj variable and save this string in the file hash.txt @{Name = "Tore";Age = 45;CodeCoverage = 11.21;Date = New-Date 636221857704582734;IntArray = 1,2,3;} .INPUTS .OUTPUTS .NOTES Author: Tore Groneng Website: www.firstpoint.no Twitter: @ToreGroneng #> [cmdletbinding( SupportsShouldProcess=$true, ConfirmImpact='High' )] Param ( [string] $Path , [Parameter(ValueFromPipeline)] $InputObject , [switch] $Append ) Begin { $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" } Process { $fileContent = "" Write-Verbose -Message "$f - Converting inputobject to string" if ($InputObject -is [hashtable] -or $InputObject -is [System.Collections.Specialized.OrderedDictionary]) { $fileContent = $InputObject | ConvertTo-HashString } else { foreach ($input in $InputObject) { $fileContent += $input | ConvertTo-Hashtable | ConvertTo-HashString } } $file = @{ Path = $Path Value = $fileContent Encoding = "UTF8" } if ($Append.IsPresent) { if ($PSCmdlet.ShouldProcess("$Path", "$f - Append to file")) { Write-Verbose -Message "$f - Appending to file [$Path]" Add-Content @file } } else { if ($PSCmdlet.ShouldProcess("$Path", "$f - Overwriting file")) { Write-Verbose -Message "$f - Writing to file [$Path]" Set-Content @file } } } End { Write-Verbose -Message "$f - END" } }
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Functions/New-Date.ps1
New-Date.ps1
#Requires -Version 4.0 function New-Date { [cmdletbinding()] Param ( [Parameter(Position=0)] [int64] $Ticks ) [datetime]$Ticks }
PowerShellCorpus/PowerShellGallery/hashdata/1.0.0.0/Functions/ConvertTo-Hashtable.ps1
ConvertTo-Hashtable.ps1
#Requires -Version 4.0 function ConvertTo-Hashtable { <# .SYNOPSIS Converts a PScustomobject to a hashtable .DESCRIPTION Converts a PScustomobject to a hashtable .PARAMETER InputObject The PSCustomObject you want to convert to a hashtable .EXAMPLE $obj = [PSCustomobject]@{ Name = "Tore" Value = "Test" } $obj | ConvertTo-Hashtable This will create a hashtable with keys matching the properties of the object. .INPUTS PSCustomObject .OUTPUTS System.Collections.Specialized.OrderedDictionary .NOTES Author: Tore Groneng Website: www.firstpoint.no Twitter: @ToreGroneng #> [cmdletbinding()] Param ( [Parameter(ValueFromPipeline)] [PSCustomObject]$InputObject ) Begin { $f = $MyInvocation.InvocationName Write-Verbose -Message "$f - START" } Process { Write-Verbose -Message "$F - Processing [$($inputobject.GetType().Name)]" if ($InputObject -is [array]) { Write-Verbose -Message "Is array object" foreach ($item in $value) { $item | ConvertTo-Hash } } if ($InputObject -is [hashtable] -or $InputObject -is [System.Collections.Specialized.OrderedDictionary]) { return $InputObject } $hash = [ordered]@{} if ($InputObject -is [System.Management.Automation.PSCustomObject]) { Write-Verbose -Message "$f - Processing [pscustomobject]" foreach ($prop in $InputObject.psobject.Properties) { $name = $prop.Name $value = $prop.Value Write-Verbose -Message "$f - Property [$name]" if ($value -is [System.Management.Automation.PSCustomObject]) { Write-Verbose -Message "$f - Value is PScustomobject" $value = $value | ConvertTo-Hash } if ($value -is [array]) { Write-Verbose -Message "$f - Value is array" $hashValue = @() if ($value[0] -is [hashtable] -or $value[0] -is [System.Collections.Specialized.OrderedDictionary] -or $value[0] -is [PSCustomObject]) { foreach ($item in $value) { $hashValue += ($item | ConvertTo-Hash) } } else { $hashValue = $value } $value = $hashValue } $hash.Add($name,$value) } } $hash } End { Write-Verbose -Message "$f - END" } }