full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/MrAAzure/1.8.1/Copy-AzureItem.ps1
Copy-AzureItem.ps1
function Copy-AzureItem { <# .SYNOPSIS This function simplifies the process of uploading files to an Azure storage account. In order for this function to work you must have already logged into your Azure subscription with Login-AzureAccount. The file uploaded will be called the file name as the storage blob. .PARAMETER FilePath The local path of the file(s) you'd like to upload to an Azure storage account container. .PARAMETER ContainerName The name of the Azure storage account container the file will be placed in. .PARAMETER DestinationName The name of the file stored as an Azure blob. By default, it will be the same name as as the local file. Use this parameter to give it a different name once uploaded. .PARAMETER BlobType The type of blob you'd like the file to become when it gets uploaded to the storage account. For example, when uploading VHDs, you should only use Page. .PARAMETER ResourceGroupName The name of the resource group the storage account is in. .PARAMETER StorageAccountName The name of the storage account the container that will hold the file is in. #> [CmdletBinding()] param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [ValidateScript({ Test-Path -Path $_ -PathType Leaf })] [Alias('FullName')] [string]$FilePath, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$ContainerName, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$ResourceGroupName, [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$StorageAccountName, [Parameter()] [ValidateNotNullOrEmpty()] [string]$DestinationName, [Parameter()] [ValidateNotNullOrEmpty()] [ValidateSet('Page', 'Block')] [string]$BlobType = 'Page' ) begin { $ErrorActionPreference = 'Stop' } process { try { $saParams = @{ 'ResourceGroupName' = $ResourceGroupName 'Name' = $StorageAccountName } $storageContainer = Get-AzureRmStorageAccount @saParams | Get-AzureStorageContainer -Container $ContainerName if (-not $PSBoundParameters.ContainsKey('DestinationName')) { $DestinationName = $FilePath | Split-Path -Leaf } ## Use Add-AzureRmVhd if the file is a VHD. Set-AzureStorageBlobContent is known to corrupt the large VHD when uploading if ($FilePath.EndsWith('.vhd')) { $destination = ('{0}{1}/{2}' -f $storageContainer.Context.BlobEndPoint, $ContainerName, $DestinationName) $vhdParams = @{ 'ResourceGroupName' = $ResourceGroupName 'Destination' = $destination 'LocalFilePath' = $FilePath } Write-Verbose -Message "Uploading [$($vhdParams.LocalFilePath)] to [$($vhdParams.Destination)] in resource group [$($vhdParams.ResourceGroupName)]..." Add-AzureRmVhd @vhdParams } else { $bcParams = @{ 'File' = $FilePath 'BlobType' = $BlobType 'Blob' = $DestinationName } $storageContainer | Set-AzureStorageBlobContent @bcParams } } catch { Write-Error -Message $_.Exception.Message } } }
PowerShellCorpus/PowerShellGallery/MrAAzure/1.8.1/Install-AzureRmVMExtensionLegacy.ps1
Install-AzureRmVMExtensionLegacy.ps1
<# .Synopsis Install-AzureRmVmExtension simplifies the process of installing VM extensions on Azure IaaS resource manager VM's. .DESCRIPTION Install-AzureRmVmExtension simplifies the process of installing VM extensions on Azure IaaS resource manager VM's. .NOTES Created by: Jason Wasser @wasserja Modified: 3/14/2016 11:53:40 AM Version 1.0 .EXAMPLE Install-AzureRmVmExtension -VMName server01 -ResourceGroupName rg01 -Location eastus -Extension bginfo RequestId IsSuccessStatusCode StatusCode ReasonPhrase --------- ------------------- ---------- ------------ True OK OK Installs the bginfo extension on server01 in resource group rg01 located in the East US Azure Datacenter. .EXAMPLE Install-AzureRmVmExtension -VMName server01 -ResourceGroupName rg01 -Location eastus Opens a grid view of available extensions that you can install on server01. #> #Requires -module Azure,AzureRM.profile,AzureRM.Compute function Install-AzureRmVMExtensionLegacy { [CmdletBinding()] [Alias()] Param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName=$true, Position=0)] [string[]]$VMName, $ResourceGroupName = 'we-use-rg-prd', $Location = 'eastus', [string[]]$ExtensionName ) Begin { # Verify we are signed into an Azure account try { $Subscriptions = Get-AzureRmSubscription -ErrorAction Stop } catch [System.Management.Automation.PSInvalidOperationException] { Login-AzureRmAccount } catch { Write-Error $Error[0].Exception } # Get All Extensions $AzureVMAvailableExtensions = Get-AzureVMAvailableExtension # If an extension was provided as a parameter, filter by the provided paramater extension name. if ($ExtensionName) { $Extensions = $AzureVMAvailableExtensions | Where-Object -FilterScript {$_.ExtensionName -like $ExtensionName} } # Else pop up a gridview of all of the available extensions to be selected. else { $Extensions = $AzureVMAvailableExtensions | Out-GridView -PassThru } # Register TrendMicro Example # Cmd /c "c:\Program Files\Trend Micro\Deep Security Agent\dsa_control.cmd" -a dsm://agents.deepsecurity.trendmicro.com:443/ tenantID:20698506-a2d9-4ff5-9e53-026a54d71262 tenantPassword:771119ca-125d-4893-86fa-d7f82e2f2729 } Process { foreach ($VM in $VMName) { foreach ($Extension in $Extensions) { Set-AzureRmVMExtension -ExtensionName $Extension.ExtensionName -Publisher $Extension.Publisher -ExtensionType $Extension.ExtensionName -Version $Extension.Version -Location $Location -ResourceGroupName $ResourceGroupName -VMName $VM } } } End {} }
PowerShellCorpus/PowerShellGallery/AzureRM.RecoveryServices/3.1.0/AzureRmRecoveryServicesStartup.ps1
AzureRmRecoveryServicesStartup.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. # ---------------------------------------------------------------------------------- @{ "Get-AzureRmRecoveryServicesBackupProperty" = "Get-AzureRmRecoveryServicesBackupProperties"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkHQYJKoZIhvcNAQcCoIIkDjCCJAoCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIB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1zlsisVlfYqz # 1wrkNY+r1IAEMIHiBgsqhkiG9w0BCRACDDGB0jCBzzCBzDCBsQQUGA2ss4xoMLP4 # dBmyeM6AKzUvCPowgZgwgYCkfjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2Fz # aGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENv # cnBvcmF0aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EgMjAx # MAITMwAAAJ0gnFZ3VdQomgAAAAAAnTAWBBRoFpuEdEUWojsFxAdQ15qcNRJMOjAN # BgkqhkiG9w0BAQsFAASCAQBXLMfBnypzcMMKHqhqnI0EBhthblzk/oTQHb1ZatMs # nBsCrqxSJc+qlNDBzxpRNaSfHPQzn2r5dbbAOtGqFoEsbYduYm+v1yJpEVf02OGx # NNw8963l8Yx7FpC62PDBdYICvoZqTGinf+kTXfU8g0ZcGibcyoGe7SrY1EG04l/E # mH/FukUIsHsQOiVnLmFWXz6yelWbSyN42F/zrdFhod2OEzM52iDWfryj5q/+dW73 # x+griCnYEHNzE0wJG/As3EJjpEjGYXrl2djp0M7HEb4Ux6o/MzBiIv+kb7mMPjqf # XTA4RdzwCmdiwPHV1DCL7EqRTTov4fc3M2IYBSVfvvIB # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Await/0.8/Tests/Await.Tests.ps1
Await.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path Describe "Basics" { It "Doesn't leak processes" { $beforeProcesses = Get-Process -Name PowerShell Start-AwaitSession do { $midProcesses = Get-Process -Name PowerShell } while($midProcesses.Count -eq $beforeProcesses.Count) Stop-AwaitSession do { $endProcesses = Get-Process -Name PowerShell } while($endProcesses.Count -gt $beforeProcesses.Count) $midProcesses.Count - $beforeProcesses.Count | Should be 2 $midProcesses.Count - $endProcesses.Count | Should be 2 } It "Doesn't leave processes behind" { $beforeProcesses = Get-Process -Name PowerShell PowerShell -NoProfile -Command 'Start-AwaitSession; Remove-Module Await' do { $endProcesses = Get-Process -Name PowerShell } while($endProcesses.Count -gt $beforeProcesses.Count) $beforeProcesses.Count | Should be $endProcesses.Count } } Describe "FullScreenOutput" { Start-AwaitSession try { It "Captures initial logo" { $output = Wait-AwaitResponse 'All rights reserved.' -All $output -match 'PowerShell'| Should be $true } It "Evaluates simple command" { Send-AwaitCommand '111+222' do { $output = Receive-AwaitResponse -All } while(-not ($output -match '333')) $output -match '333'| Should be $true } It "Supports Stream parameter" { $null = Receive-AwaitResponse Send-AwaitCommand 'cls' $null = Wait-AwaitResponse "PS" Send-AwaitCommand '"`n"*5; "AAA"*2' $output = Wait-AwaitResponse "AAAAAA" -Stream ($output.Count) -gt 1 | Should be $true Send-AwaitCommand 'cls' $null = Wait-AwaitResponse "PS" Send-AwaitCommand '"`n"*5; "AAA"*2' Start-Sleep -m 500 $output = Receive-AwaitResponse -Stream ($output.Count) -gt 1 | Should be $true } It "Retains previous output" { Send-AwaitCommand '333+444' do { $output = Wait-AwaitResponse 777 -All } while(-not ($output -match '777')) $output -match '333'| Should be $true $output -match '777'| Should be $true } It "Produces identical output for multiple invocations" { $output1 = Receive-AwaitResponse -All $output2 = Receive-AwaitResponse -All $output1 -eq $output2 | Should be $true } It "Captures cleared screens" { Send-AwaitCommand cls $null = Wait-AwaitResponse "PS" Send-AwaitCommand "'1234567'" $output = Wait-AwaitResponse '1234567' -All $output -match 1234567 | Should be $true Send-AwaitCommand cls $null = Wait-AwaitResponse "PS" Send-AwaitCommand "'12121212'" $output = Wait-AwaitResponse 12121212 -All $output -match 1234567 | Should be $false $output -match 12121212 | Should be $true } } finally { Stop-AwaitSession } } Describe "IncrementalOutput" { It "Captures initial logo" { Start-AwaitSession $output = Wait-AwaitResponse 'All rights reserved.' $output -match 'PowerShell'| Should be $true Stop-AwaitSession } Start-AwaitSession try { It "Clears output on multiple invocations" { Send-AwaitCommand '11*11' $output = Wait-AwaitResponse 121 $output -match 121 | Should be $true $output2 = Receive-AwaitResponse $output2 | Should be "" } It "Captures secondary invocation" { Send-AwaitCommand '5*5' $output = Wait-AwaitResponse 25 $output -match 25 | Should be $true Send-AwaitCommand '6*6' $output = Wait-AwaitResponse 36 $output -match 36 | Should be $true } It "Handles cleared screens" { Send-AwaitCommand '"`n"*50' Send-AwaitCommand '"AAA"*2' $output = Wait-AwaitResponse AAAAAA $output -match 'AAAAAA' | Should be $true Send-AwaitCommand 'cls' $null = Wait-AwaitResponse "PS" Send-AwaitCommand '"BBB"*2' $output = Wait-AwaitResponse BBBBBB $output -match 'BBBBBB' | Should be $true } It "Captures output at the end of the buffer" { Send-AwaitCommand 'cls' $null = Receive-AwaitResponse Send-AwaitCommand '[Console]::BufferHeight = [Console]::WindowHeight' Send-AwaitCommand '"`n" * [Console]::BufferHeight * 2' Send-AwaitCommand '"AAA"*2' $output = Wait-AwaitResponse AAAAAA $output -match 'AAAAAA' | Should be $true Send-AwaitCommand '"BBB"*2' $output = Wait-AwaitResponse BBBBBB $output -match 'BBBBBB' | Should be $true Send-AwaitCommand '"CCC"*2' $output = Wait-AwaitResponse CCCCCC $output -match 'CCCCCC' | Should be $true } It "Captures input at the end of the buffer" { Send-AwaitCommand 'cls' $null = Receive-AwaitResponse Send-AwaitCommand '[Console]::BufferHeight = [Console]::WindowHeight' Send-AwaitCommand '"`n" * [Console]::BufferHeight * 2' Send-AwaitCommand '"AAA"*2' $output = Wait-AwaitResponse AAAAAA $output -match 'AAAAAA' | Should be $true ## Should have original input line Send-AwaitCommand '"BBB"*2' $output = Wait-AwaitResponse '"BBB"*2' -All $output -match ([Regex]::Escape('"BBB"*2')) | Should be $true } } finally { Stop-AwaitSession } } Describe "Scenarios" { Start-AwaitSession try { It "Does Something" { } } finally { Stop-AwaitSession } }
PowerShellCorpus/PowerShellGallery/xPrinter/1.0.0.1/DSCResources/xPrinter/%E6%97%A0%E6%A0%87%E9%A2%981.ps1
%E6%97%A0%E6%A0%87%E9%A2%981.ps1
$Printername = New-xDscResourceProperty -Name PrinterName -Type String -Attribute Key -Description "要添加的打印机" $PrinterPort = New-xDscResourceProperty -Name PrinterPort -Type String -Attribute Required -Description "要添加的打印机端口" $PortIP = New-xDscResourceProperty -Name PortIP -Type String -Attribute Required -Description "要添加的打印机IP" $DirverName = New-xDscResourceProperty -Name DirverName -Type String -Attribute Required -Description "打印机驱动名称 该驱动必须已经安装" $Ensure =New-xDscResourceProperty -Name Ensure -Type String -Attribute Required -ValidateSet "Absent","Present" #New-xDscResource -Name xPrinter -Property $Printername,$PrinterPort,$PortIP,$PortDirver -Path c:\xPrinter Update-xDscResource -Property $Ensure,$Printername,$PrinterPort,$PortIP,$DirverName -Path C:\xPrinter\DSCResources\xPrinter
PowerShellCorpus/PowerShellGallery/xPrinter/1.0.0.1/DSCResources/xPrinter/DSCPrinter.ps1
DSCPrinter.ps1
Configuration Printer { node LocalHost { xPrinter A { Ensure = "present" PortIP = "192.168.2.1" PrinterPort = "Publicx" PrinterName = "XX" DirverName = "Canon iR2002/2202 UFRII LT" } } } Configuration Printer { node LocalHost { xPrinter A { Ensure = "Absent" PortIP = "192.168.2.1" PrinterPort = "Public" PrinterName = "XXx" DirverName = "Canon iR2002/2202 UFRII LT" } } } Get-ChildItem C:\1 -Recurse | Remove-Item -Force Printer -OutputPath C:\1 Start-DscConfiguration -Path c:\1 -Wait -Verbose -Force Get-Process wmi* |Stop-Process -Force Get-Printer xx |Remove-Printer Get-PrinterPort Public |Remove-PrinterPort
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/install.ps1
install.ps1
Write-Host -Object 'Installing ISESteroids' $version = $PSVersionTable.PSVersion.Major if ($version -lt 3) { Write-Warning 'ISESteroids requires PowerShell 3 or better.' Write-Warning "Your current PowerShell version is $version." return } $isepath = Join-Path -Path $pshome -ChildPath 'powershell_ise.exe' $iseExists = Test-Path -Path $isepath if (!$iseExists) { Write-Warning 'The built-in PowerShell ISE editor is not available on your system.' Write-Warning 'You may have to enable it in Windows Features first.' } $currentFolder = $PSScriptRoot # running as script? if ($currentFolder -eq '') { Write-Warning -Message 'You need to run this code as a script. Make sure you opened the script from inside the unpacked ISESteroids ZIP folder!' return } # is in extracted zip folder? $binaryExists = Test-Path -Path "$currentFolder\isesteroids.dll" if (!$binaryExists) { Write-Warning -Message 'Do not copy this script elsewhere! Run it from inside the extracted ZIP folder!' return } # unblock content of extracted zip folder Get-ChildItem -Path $currentFolder -Recurse | Unblock-File # copy module to user profile $PSUserProfile = Split-Path $profile $ModulesFolder = Join-Path -Path $PSUserProfile -ChildPath 'Modules' $DestinationFolder = Join-Path -Path $ModulesFolder -ChildPath 'ISESteroids' # create folder if not present $exists = Test-Path -Path $DestinationFolder if (!$exists) { $null = New-Item -Path $DestinationFolder -Force -ItemType Directory } # current and destination folder identical? if ($currentFolder -eq $DestinationFolder) { Write-Host 'ISESteroids is installed already.' -ForegroundColor DarkYellow Write-Host 'Run "Start-Steroids" from inside the ISE editor to load ISESteroids.' -ForegroundColor DarkYellow return } Copy-Item -Path $currentFolder\* -Destination $DestinationFolder -Recurse -Force -ErrorVariable copyErrors -ErrorAction SilentlyContinue if ($copyErrors.Count -gt 0) { Write-Host 'There was a problem copying the module files onto your computer:' -ForegroundColor Yellow $copyErrors | ForEach-Object { Write-Host $_.Message -ForegroundColor Red } Write-Host 'Make sure you are not running another version of ISESteroids while installing.' -ForegroundColor Yellow Write-Host 'Run this script again once you solved the issue.' } else { Write-Host -Object 'ISESteroids successfully installed.' -ForegroundColor Green Write-Host -Object 'To run, launch ISE editor:' -ForegroundColor Green Write-Host -Object '' Write-Host -Object 'ise' Write-Host -Object '' Write-Host -Object 'From inside the ISE editor, run:' -ForegroundColor Green Write-Host -Object '' Write-Host -Object 'Start-Steroids' Write-Host -Object '' Write-Host -Object '' Write-Host -Object 'Run "Start-Steroids" from INSIDE THE ISE EDITOR, not from here!' -ForegroundColor Green Write-Host -Object '' Write-Host -Object '' } # SIG # Begin signature block # MIIccwYJKoZIhvcNAQcCoIIcZD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# x1V7+OxRKYSruht+Sz7el/tNnuQCP/q+QMmQCrFBhMdPxE/9G5ocz54poIrlAVPE # dt1edDJX5GPm7wT0nBNtBafo0hs3y/D731X9BsZnJJTu8wj1zjafEhYYewF5JnoL # lgIr5Td4kbf1RZA1LHBD6iFDS/3GI4dPQdNt0OONHWVqQcKOYwE9J1QSPcBK5pbo # bfUUzWNXaxJ4xo9ORzC1D9qZewuD32/Tzae9+hNWO7QtZNKP46JA # SIG # End signature block
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Pester/defaultheader.tests.ps1
defaultheader.tests.ps1
# this is a Pester test file #region Further Reading # http://www.powershellmagazine.com/2014/03/27/testing-your-powershell-scripts-with-pester-assertions-and-more/ #endregion #region LoadScript # load the script file into memory # attention: make sure the script only contains function definitions # and no active code. The entire script will be executed to load # all functions into memory . ($PSCommandPath -replace '\.tests\.ps1$', '.ps1') #endregion
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Pester/default.tests.ps1
default.tests.ps1
# describes the function {0} Describe '{0}' { # scenario 1: call the function without arguments Context 'Running without arguments' { # test 1: it does not throw an exception: It 'runs without errors' { # Gotcha: to use the "Should Not Throw" assertion, # make sure you place the command in a # scriptblock (braces): { {0} } | Should Not Throw } It 'does something' { # call function {0} and pipe the result to an assertion # Example: # {0} | Should Be 'Expected Output' # Hint: # Once you typed "Should", press CTRL+J to see # available code snippets. You can also click anywhere # inside a "Should" and press CTRL+J to change assertion. # However, make sure the module "Pester" is # loaded to see the snippets. If the module is not loaded yet, # no snippets will show. } # test 2: it returns nothing ($null): It 'does not return anything' { {0} | Should BeNullOrEmpty } } }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/TemplateScripts/XAML/Create XAML Action Table.ps1
Create XAML Action Table.ps1
# nachladen von WPF (nötig für powershell.exe, weil hier # anders als in der ISE die WPF Bibliotheken nicht # automatisch geladen werden: Add-Type -AssemblyName PresentationFramework $xaml = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="72*"/> <RowDefinition Height="85*"/> <RowDefinition Height="162*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="54*"/> <ColumnDefinition Width="80*"/> <ColumnDefinition Width="175*"/> <ColumnDefinition Width="208*"/> </Grid.ColumnDefinitions> <Button Name="button1" Content="Aktion1" HorizontalAlignment="Left" Height="40" Margin="0,22,0,0" VerticalAlignment="Top" Width="60" Grid.ColumnSpan="2"/> <Button Name="button2" Content="Machwas" Grid.Column="2" HorizontalAlignment="Left" Height="34" Margin="30,27,0,0" Grid.Row="1" VerticalAlignment="Top" Width="70"/> <Button Name="button3" Content="Button3" Grid.Column="3" HorizontalAlignment="Left" Height="34" Margin="108,83,0,0" VerticalAlignment="Top" Width="70" Grid.Row="2"/> </Grid> </Window> "@ $reader = [System.XML.XMLReader]::Create([System.IO.StringReader] $xaml) $window = [System.Windows.Markup.XAMLReader]::Load($reader) $window.TopMost = $true $window.WindowStartupLocation = 'CenterScreen' $button1 = $window.FindName("button1") $code1 = { Write-Host "Button 1" } $button1.add_Click($code1) $button2 = $window.FindName("button2") $code2 = { Write-Host "Button 2" } $button2.add_Click($code2) $button3 = $window.FindName("button3") $code3 = { Write-Host "Button 3" } $button3.add_Click($code3) # Fenster anzeigen $null = $window.ShowDialog()
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/TemplateScripts/XAML/Display XAML.ps1
Display XAML.ps1
# nachladen von WPF (nötig für powershell.exe, weil hier # anders als in der ISE die WPF Bibliotheken nicht # automatisch geladen werden: Add-Type -AssemblyName PresentationFramework $xaml = @" <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <ComboBox HorizontalAlignment="Left" Margin="10,30,0,0" VerticalAlignment="Top" Width="120"> <ComboBoxItem Content="Test1" IsSelected="True"/> <ComboBoxItem Content="Test2"/> <ComboBoxItem Content="Test3"/> <ComboBoxItem Content="Test4"/> </ComboBox> <Button Content="Send" HorizontalAlignment="Left" Margin="10,70,0,0" VerticalAlignment="Top" Width="75"/> </Grid> </Window> "@ $reader = [System.XML.XMLReader]::Create([System.IO.StringReader] $xaml) $window = [System.Windows.Markup.XAMLReader]::Load($reader) $window.TopMost = $true $window.WindowStartupLocation = 'CenterScreen' # Fenster anzeigen $null = $window.ShowDialog()
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/WPFSamples/Full Examples/Dialog with Textboxes.ps1
Dialog with Textboxes.ps1
#region XAML window definition # Right-click XAML and choose WPF/Edit... to edit WPF Design # in your favorite WPF editing tool $xaml = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinWidth="200" Width ="400" SizeToContent="Height" Title="New Mail" Topmost="True"> <Grid Margin="10,40,10,10"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Margin="5">Please enter your details:</TextBlock> <TextBlock Grid.Column="0" Grid.Row="1" Margin="5">Name</TextBlock> <TextBlock Grid.Column="0" Grid.Row="2" Margin="5">Email</TextBlock> <TextBox Name="TxtName" Grid.Column="1" Grid.Row="1" Margin="5"></TextBox> <TextBox Name="TxtEmail" Grid.Column="1" Grid.Row="2" Margin="5"></TextBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,10,0,0" Grid.Row="3" Grid.ColumnSpan="2"> <Button Name="ButOk" MinWidth="80" Height="22" Margin="5">OK</Button> <Button Name="ButCancel" MinWidth="80" Height="22" Margin="5">Cancel</Button> </StackPanel> </Grid> </Window> '@ #endregion #region Code Behind function Convert-XAMLtoWindow { param ( [Parameter(Mandatory)] [string] $XAML, [string[]] $NamedElement=$null, [switch] $PassThru ) Add-Type -AssemblyName PresentationFramework $reader = [XML.XMLReader]::Create([IO.StringReader]$XAML) $result = [Windows.Markup.XAMLReader]::Load($reader) foreach($Name in $NamedElement) { $result | Add-Member NoteProperty -Name $Name -Value $result.FindName($Name) -Force } if ($PassThru) { $result } else { $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } } function Show-WPFWindow { param ( [Parameter(Mandatory)] [Windows.Window] $Window ) $result = $null $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } #endregion Code Behind #region Convert XAML to Window $window = Convert-XAMLtoWindow -XAML $xaml -NamedElement 'TxtName', 'TxtEmail', 'ButOk', 'ButCancel' -PassThru #endregion #region Define Event Handlers # Right-Click XAML Text and choose WPF/Attach Events to # add more handlers $window.ButCancel.add_Click( { $window.DialogResult = $false } ) $window.ButOk.add_Click( { $window.DialogResult = $true } ) #endregion Event Handlers #region Manipulate Window Content $window.TxtName.Text = $env:username $window.TxtEmail.Text = 'test@test.com' $null = $window.TxtName.Focus() #endregion # Show Window $result = Show-WPFWindow -Window $window #region Process results if ($result -eq $true) { $hash = [Ordered]@{ EmployeeName = $window.TxtName.Text EmployeeMail = $window.TxtEmail.Text } New-Object -TypeName PSObject -Property $hash } else { Write-Warning 'User aborted dialog.' } #endregion Process results
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/WPFSamples/Full Examples/Dropdown list and data binding.ps1
Dropdown list and data binding.ps1
#region XAML window definition # Right-click XAML and choose WPF/Edit... to edit WPF Design # in your favorite WPF editing tool $xaml = @' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinWidth="200" Width ="400" SizeToContent="Height" Title="Service Stopper" Topmost="True"> <Grid Margin="10,40,10,10"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TextBlock Grid.Column="1" Margin="10">Choose Service to Stop:</TextBlock> <TextBlock Grid.Column="0" Grid.Row="1" Margin="5">Service</TextBlock> <ComboBox Name="ComboService" Grid.Column="1" Grid.Row="1" Margin="5"></ComboBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,10,0,0" Grid.Row="2" Grid.ColumnSpan="2"> <Button Name="ButOk" MinWidth="80" Height="22" Margin="5">Stop Service</Button> <Button Name="ButCancel" MinWidth="80" Height="22" Margin="5">Cancel</Button> </StackPanel> </Grid> </Window> '@ function Convert-XAMLtoWindow { param ( [Parameter(Mandatory)] [string] $XAML, [string[]] $NamedElement=$null, [switch] $PassThru ) Add-Type -AssemblyName PresentationFramework $reader = [XML.XMLReader]::Create([System.IO.StringReader]$XAML) $result = [Windows.Markup.XAMLReader]::Load($reader) foreach($Name in $NamedElement) { $result | Add-Member NoteProperty -Name $Name -Value $result.FindName($Name) -Force } if ($PassThru) { $result } else { $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } } function Show-WPFWindow { param ( [Parameter(Mandatory)] [Windows.Window] $Window ) $result = $null $null = $window.Dispatcher.InvokeAsync{ $result = $window.ShowDialog() Set-Variable -Name result -Value $result -Scope 1 }.Wait() $result } $window = Convert-XAMLtoWindow -XAML $xaml -NamedElement 'ButCancel', 'ButOk', 'ComboService' -PassThru # add click handlers $window.ButOk.add_Click{ # when clicked, take the selected item from the combo box and stop the service # using -whatif to just simulate for now # TODO: Remove -whatif in next line to actually stop a service $window.ComboService.SelectedItem | Stop-Service -WhatIf # update the combo box (if we really stopped a service, the list would now be shorter) $window.ComboService.ItemsSource = Get-Service | Where-Object Status -eq Running | Sort-Object -Property DisplayName } $window.ButCancel.add_Click{ # close window $window.DialogResult = $false } # fill the combobox with some powershell objects $window.ComboService.ItemsSource = Get-Service | Where-Object Status -eq Running | Sort-Object -Property DisplayName # tell the combobox to use the property "DisplayName" to display the object in its list $window.ComboService.DisplayMemberPath = 'DisplayName' # tell the combobox to preselect the first element $window.ComboService.SelectedIndex = 0 Show-WPFWindow -Window $window #endregion
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/FixerOnDemand/Fix Content/Convert String To Variable/ConvertTextToEnvironmentVariable.ps1
ConvertTextToEnvironmentVariable.ps1
# replaces literal strings with environment variables where appropriate & { function GetBestMatch($Text) { foreach($environmentString in $lookup) { if ($Text -match ([RegEx]::Escape($environmentString.Value) + '\b')) { return $environmentString } } } # get all environment variables # the key is the environment variable value # check from longest to smallest to get best match $lookup = @(Get-ChildItem -Path env:\ | Where-Object { $_.Value.Length -gt 5 } | Sort-Object { $_.Value.Length} -Descending) # get all strings $Strings = [ISESteroids.SteroidsFixer.Helpers]::GetAST('String') # check each string to see whether it starts with one of the environment variables foreach($StringAst in $Strings) { $String = $StringAst.Extent.Text # get the environment variable that best matches the string (or part of it) $environmentVar = GetBestMatch -Text $String if ($environmentVar) { # is it a complete match? if ($String -eq $environmentVar.Value) { # replace extent with the environment variable Add-SteroidsTextChange -PositionInfo $StringAST.extent -ReplacementText ('$env:' + $environmentVar.Name) } else { # find the exact match position $matchInfo = [RegEx]::Match($String, '(?i)' + [Regex]::Escape($environmentVar.Value)) $NewString = $String.Remove($matchInfo.Index, $matchInfo.Length).Insert($matchInfo.Index, '$env:' + $environmentVar.Name) if ($NewString.StartsWith("'")) { $NewString = '"' + $NewString.SubString(1, $NewString.Length -2) + '"' } elseif ($NewString.StartsWith('"') -eq $false) { $NewString = '"' + $NewString + '"' } Add-SteroidsTextChange -PositionInfo $StringAST.extent -ReplacementText $NewString } } } # finalize changes: Invoke-SteroidsTextChange } # SIG # Begin signature block # MIId1AYJKoZIhvcNAQcCoIIdxTCCHcECAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUE4v3vgs88ImqjzfCX7Ph4MrR # ohagghkGMIIFHDCCBASgAwIBAgIQAp+oNhrWxpP858ywp8f2ezANBgkqhkiG9w0B # AQUFADBvMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYD # VQQLExB3d3cuZGlnaWNlcnQuY29tMS4wLAYDVQQDEyVEaWdpQ2VydCBBc3N1cmVk # IElEIENvZGUgU2lnbmluZyBDQS0xMB4XDTE0MDkwNDAwMDAwMFoXDTE1MDkwOTEy # MDAwMFowcjELMAkGA1UEBhMCREUxFjAUBgNVBAgTDU5pZWRlcnNhY2hzZW4xETAP # BgNVBAcTCEhhbm5vdmVyMRswGQYDVQQKExJUb2JpYXMgRHIuIFdlbHRuZXIxGzAZ # BgNVBAMTElRvYmlhcyBEci4gV2VsdG5lcjCCASIwDQYJKoZIhvcNAQEBBQADggEP # ADCCAQoCggEBAJUaFBmSOaJ2atB6X772tQWjbFYSUPeKkcQ6piLwrA2TS1I/175p # R7UzgpPpuJ2/Gkqag/uZOS0SUwQm+Z6Y2TfkyzcyOJdO0kuwsl+/nJqVN97xIABt # P3a3oVwxjo7BDmLFxMIPxint8bu5zy9LL2e3AUtH1ikTOrzo0qbJSJLorMlRZcgp # dDg1gSloEUHeZBOBX3hgMQQFnk5lK6UeopqaxBd0S1BCYUEI2hJxJKerns0MmX9O # ZppYz8giZo5Q7/bnRB73jT5YZjVQr2bnCuci1sz12KshwXvc6If+QqqKy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lkrHv2vtSyDR8NaawvWUTKzwfgQa+dckLJ3bPBR32p7QwaV # A21Hl5y4oWP22wETVuWsQ5t5DDj3P+v50OKNkQYhbuXoCJCE7z2eNFonvZcXS+hq # n5M9xqrQWY+zVlS+kuB3oa5eV4NDwONCBtPfp/Hgac26mJopm3NldMgjLT2dYGm5 # VglOESmhggIPMIICCwYJKoZIhvcNAQkGMYIB/DCCAfgCAQEwdjBiMQswCQYDVQQG # EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl # cnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBBc3N1cmVkIElEIENBLTECEAMBmgI6 # /1ixa9bV6uYX8GYwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0B # BwEwHAYJKoZIhvcNAQkFMQ8XDTE0MTExODEwMzYyM1owIwYJKoZIhvcNAQkEMRYE # FLeM6W95Bm8gS3jHH6OyNrDGwLfYMA0GCSqGSIb3DQEBAQUABIIBAC7ovkC1hW/p # dCXUv3u1YZuel5dI7m3oVKlbZiQAEkgc6k5Adq3jd3ISklLaqosJb2q9r7TDcodp # JGmVfYSHzK48y+hDZPIZSt5VPNge6QJVR+zUPLPpM0tlBQywF8XyJ2WcYXl5DMn9 # NFlQbMgis+a6PUQc75tboKXuzdS/G7EyIO0ULpDxTrr4ZS8GQeuDwwEXSFwcY/mH # uSxHgyXbaCn9Z2GTm6icOK6fRKC0r8OkP/RHri45/jHI0Wd4arPybkCoLGRF8UJ3 # 8SlLaS1Ku0PMz7ac8TDM6oYNOxf+RZwXpb5tBdm7ydO3FCi91kdBpWw3sY5fhQoI # b2gGwlL9RJQ= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/PSSharper/Syntax/MissingExpressionAfterToken.ps1
MissingExpressionAfterToken.ps1
param($StartOffset,$Length,$Ast) # is the error at the very end of the file? $isEnd = $Ast.Extent.EndOffset - ($StartOffset + $Length) -lt 1 # then move the insertion point one to the right if (!$isEnd) { $StartOffset-- } # is it inside a hash? $hash = $AST.FindAll({$args[0] -is [System.Management.Automation.Language.HashtableAst] -and $args[0].Extent.StartOffset -lt $StartOffset -and $args[0].Extent.EndOffset -gt $StartOffset }, $true) if ($hash.Count -gt 0) { return New-Object -TypeName ISESteroids.PSSharper.FixInformation($StartOffset, 1, ';') } else { return New-Object -TypeName ISESteroids.PSSharper.FixInformation($StartOffset, 1) }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/PSSharper/Syntax/MissingEndParenthesisInMethodCall.ps1
MissingEndParenthesisInMethodCall.ps1
param($StartOffset,$Length,$Ast) # is the error at the very end of the file? $isEnd = $Ast.Extent.EndOffset - ($StartOffset + $Length) -lt 1 # then move the insertion point one to the right if ($isEnd) { $StartOffset++ } # add a closing parenthesis return New-Object -TypeName ISESteroids.PSSharper.FixInformation($StartOffset, ')')
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/PSSharper/Syntax/MissingEndParenthesisInFunctionParameterList.ps1
MissingEndParenthesisInFunctionParameterList.ps1
param($StartOffset,$Length,$Ast) # add a comma return New-Object -TypeName ISESteroids.PSSharper.FixInformation($StartOffset, ',')
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Quality Improvement/DoubleQuotes/DoubleQuotes.ps1
DoubleQuotes.ps1
& { Set-StrictMode -Off # fixes double quoted strings that do not really need double quotes $Strings = [ISESteroids.SteroidsFixer.Helpers]::GetAST('DoubleQuotedString') foreach($string in $strings) { if ($string.Extent.Text -notmatch '[$`'']') { $text = $string.Extent.Text.SubString(1) $text = $text.SubString(0, $text.Length-1) Add-SteroidsTextChange -PositionInfo $string.extent -ReplacementText "'$text'" } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Final Touches/Requires/AddRequirements.ps1
AddRequirements.ps1
& { # do not update #requires statement for .psm1 files $extension = [IO.Path]::GetExtension($psise.PowerShellTabs.SelectedPowerShellTab.Files.SelectedFile.FullPath) if ($extension -ne '.psm1') { $editor = Get-SteroidsEditor Update-SteroidsRequiresStatement -ISEEditor $editor } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Spaces/OperatorAdjustSpace/OperatorAdjustSpace.ps1
OperatorAdjustSpace.ps1
& { $unary = [Management.Automation.Language.TokenFlags]::UnaryOperator $info = Get-SteroidsAST $tokenCount = $info.TokenList.Count # we need a minimum of three tokens for this test if ($tokenCount -ge 3) { for ($i=1; $i -lt $tokenCount-1; $i++) { $token = $info.TokenList[$i] $previoustoken = $info.TokenList[$i-1] $nexttoken = $info.TokenList[$i+1] if ($token.TokenFlags -like '*Operator') { # exclude unary operators if (($token.TokenFlags -band $unary) -eq $unary) { continue } $start = $previoustoken.Extent.EndOffset $end = $token.Extent.StartOffset if ($end-$start -eq 0) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, ' ', $false) } $start = $token.Extent.EndOffset $end = $nexttoken.Extent.StartOffset if ($end-$start -ne 1) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, ' ', $false) } $i++ } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Spaces/ArrayAdjustSpace/ArrayAdjustSpace.ps1
ArrayAdjustSpace.ps1
& { # get all ArrayLiteralASTs $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Array') foreach($item in $items) { $tokenlist = [ISESteroids.SteroidsFixer.Helpers]::GetToken($item.Extent.StartOffset, $item.Extent.EndOffset) $tokenCount = $tokenlist.Count for($i=0; $i-lt$tokenCount-1;$i++) { $token = $tokenlist[$i] # do we have a comma that is not at the beginning? if ($token.Kind -eq 'Comma' -and $i -gt 0) { # remove space between comma and preceeding token $previoustoken = $tokenList[$i-1] $start = $previoustoken.Extent.EndOffset $end = $token.Extent.StartOffset if ($end-$start -gt 1) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, '', $false) } # make sure there is exactly one space after each comma $nexttoken = $tokenList[$i+1] $start = $token.Extent.EndOffset $end = $nexttoken.Extent.StartOffset if ($end-$start -ne 1) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, ' ', $false) } } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/ScriptBlock/ScriptBlockRemoveEmptyLines/ScriptBlockRemoveEmptyLines.ps1
ScriptBlockRemoveEmptyLines.ps1
& { Set-StrictMode -Off # removes any empty (blank) line that is positioned # - between opening brace and content # - between content and closing brace $crlf = -join [Char[]](13,10) $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('ScriptAndStatementblock') foreach($ScriptBlock in $items) { # are start and end on the same line (one-liner)? if ($ScriptBlock.Extent.StartLineNumber -eq $ScriptBlock.Extent.EndLineNumber) { continue } # get scriptblock content $text = $ScriptBlock.Extent.Text.Trim() # is the scriptblock enclosed by braces? # the top scriptblock in a script is not enclosed, to exit in this case: if ($text.StartsWith('{') -eq $false) { continue } # at this point, we have a scriptblock that may need reformatting # how many real lines are in this block? $nonwhitespace = $ScriptBlock.Extent.Text.SubString(1, $ScriptBlock.Extent.Text.Length-2) -replace '[^\S\n]' -split '\n' | Where-Object { $_.Trim() } $lines = $nonwhitespace.Count $linebreak = '' if ($lines -gt 1 ) { $linebreak = "`n" } # is there empty space between opening brace and content? $token = [ISESteroids.SteroidsFixer.Helpers]::GetNextNonWhitespaceToken($ScriptBlock.Extent.StartOffset, $ScriptBlock.Extent.EndOffset, 'Forward') if ($token -ne $null) { $start = $ScriptBlock.Extent.StartOffset + 1 $end = $token.Extent.StartOffset if ($start -ne $end) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $linebreak) } } # is there empty space between content and closing brace? $token = [ISESteroids.SteroidsFixer.Helpers]::GetNextNonWhitespaceToken($ScriptBlock.Extent.EndOffset-1, $ScriptBlock.Extent.StartOffset+1, 'Backwards') if ($token -ne $null) { # is this a regular comment token? In this case, brace cannot be moved $isComment = (($token.Kind -eq 'Comment') -and ($token.Extent.Text.StartsWith('<#') -eq $false)) $start = $token.Extent.EndOffset $end = $ScriptBlock.Extent.EndOffset - 1 # if the token is a classic comment, add one linebreak or else the brace will be in the comment line (thus commented out) $addText = '' if ($isComment -or $Lines -gt 1) { $addText = $crlf } if ($start -ne $end) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $addText) } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/ScriptBlock/ScriptBlockAlignBracesSome/ScriptBlockAlignBracesSome.ps1
ScriptBlockAlignBracesSome.ps1
& { # purpose is to reformat scriptblocks # scriptblocks are a common element in many PowerShell structures # and can also be used standalone # to improve readability, this unit identifies the opening and # closing braces and makes sure these braces exist on individual lines # separated from other content (to improve brace alignment) # if a scriptblock is a "one-liner" (start and end brace exist on same line), # then no optimization is done because one-liner are often desired. # the unit also determines whether or not the scriptblock is a parameter # argument. If a scriptblock is a parameter argument, then the opening # brace must be on the same line with the parameter $crlf = -join [Char[]](13,10) $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('ScriptAndStatementblock') foreach($ScriptBlock in $items) { # are start and end on the same line (one-liner)? if ($ScriptBlock.Extent.StartLineNumber -eq $ScriptBlock.Extent.EndLineNumber) { continue } # get scriptblock content $text = $ScriptBlock.Extent.Text.Trim() # is the scriptblock enclosed by braces? # the top scriptblock is not if ($text.StartsWith('{') -eq $false) { continue } # at this point, we have a scriptblock that may need reformatting if ($ScriptBlock.Parent -ne $null) { $parentStructure = $ScriptBlock.Parent.GetType().Name } else { $parentStructure = '' } # INSERT LINEBREAK BEFORE OPENING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.StartOffset, 'Backwards') if ($token.Count -gt 0 -and $parentStructure -ne 'ScriptBlockExpressionAst') { $start = $ScriptBlock.Extent.StartOffset $end = $ScriptBlock.Extent.StartOffset [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } # INSERT LINEBREAK AFTER OPENING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.StartOffset,'Forward') if ($token.Count -gt 0) { # add crlf after opening brace $start = $ScriptBlock.Extent.StartOffset+1 $end = $ScriptBlock.Extent.StartOffset+1 [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } # INSERT LINEBREAK BEFORE CLOSING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.EndOffset-1, 'Backwards') if ($token.Count -gt 0) { # add crlf before closing brace $start = $ScriptBlock.Extent.EndOffset-1 $end = $ScriptBlock.Extent.EndOffset-1 [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } # INSERT LINEBREAK AFTER CLOSING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.EndOffset-1, 'Forward') if ($token.Count -gt 0 -and $parentStructure -ne 'ScriptBlockExpressionAst') { if (-not($token.Kind -eq 'Pipe' -or $token.Kind -eq 'Comment' -or $token.Kind -eq 'LineContinuation' -or $token.Kind -eq 'Parameter')) { $start = $ScriptBlock.Extent.EndOffset $end = $ScriptBlock.Extent.EndOffset [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/ScriptBlock/ScriptBlockAlignBracesAll/ScriptBlockAlignBracesAll.ps1
ScriptBlockAlignBracesAll.ps1
& { Set-StrictMode -Off # purpose is to reformat scriptblocks # scriptblocks are a common element in many PowerShell structures # and can also be used standalone # to improve readability, this unit identifies the opening and # closing braces and makes sure these braces exist on individual lines # separated from other content (to improve brace alignment) # if a scriptblock is a "one-liner" (start and end brace exist on same line), # then no optimization is done because one-liner are often desired. # the unit also determines whether or not the scriptblock is a parameter # argument. If a scriptblock is a parameter argument, then the opening # brace must be on the same line with the parameter $crlf = -join [Char[]](13,10) $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('ScriptAndStatementblock') foreach($ScriptBlock in $items) { # get scriptblock content $text = $ScriptBlock.Extent.Text.Trim() # is the scriptblock enclosed by braces? # the top scriptblock is not if ($text.StartsWith('{') -eq $false) { continue } # at this point, we have a scriptblock that may need reformatting if ($ScriptBlock.Parent -ne $null) { $parentStructure = $ScriptBlock.Parent.GetType().Name } else { $parentStructure = '' } # INSERT LINEBREAK BEFORE OPENING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.StartOffset, 'Backwards') # do not do this if scriptblock is part of a parameter assignment if ($token.Count -gt 0 -and $parentStructure -ne 'ScriptBlockExpressionAst') { $start = $ScriptBlock.Extent.StartOffset $end = $ScriptBlock.Extent.StartOffset [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } # INSERT LINEBREAK AFTER OPENING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.StartOffset,'Forward') if ($token.Count -gt 0 ) { # add crlf after opening brace $start = $ScriptBlock.Extent.StartOffset+1 $end = $ScriptBlock.Extent.StartOffset+1 [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } # INSERT LINEBREAK BEFORE CLOSING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.EndOffset-1, 'Backwards') if ($token.Count -gt 0) { # add crlf before closing brace $start = $ScriptBlock.Extent.EndOffset-1 $end = $ScriptBlock.Extent.EndOffset-1 [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } # INSERT LINEBREAK AFTER CLOSING BRACE? $token = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($ScriptBlock.Extent.EndOffset-1, 'Forward') if ($token.Count -gt 0 -and $parentStructure -ne 'ScriptBlockExpressionAst') { if (-not($token.Kind -eq 'Pipe' -or $token.Kind -eq 'Comment' -or $token.Kind -eq 'LineContinuation' -or $token.Kind -eq 'Parameter')) { $start = $ScriptBlock.Extent.EndOffset $end = $ScriptBlock.Extent.EndOffset [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Character Operations/Illegal Characters/IllegalCharacters.ps1
IllegalCharacters.ps1
# Replaces individual ASCII and UNICODE characters # use this to change illegal characters # illegal characters may be introduced when scripts are copied from # web pages or text editors, and typographic changes were made & { # get access to the editor: $Editor = Get-SteroidsEditor # get script content: $text = $Editor.Text # this table controls character replacements # the KEY is the hexadecimal value of the character to replace # four-digit numbers represent UNICODE characters # the VALUE is the character that is used as replacement $replacementTable = @{ # UNICODE characters to replace: '2013' = '-' '2014' = '-' '2015' = '-' '201C' = '"' '201D' = '"' '201E' = '"' '2018' = "'" '2019' = "'" '201A' = "'" '201B' = "'" '2033' = '"' '00BB' = '"' '02BA' = '"' '02BB' = "'" '02BC' = "'" '02BD' = "'" '02DD' = '"' '02EE' = '"' '02F5' = '"' '02F6' = '"' '030B' = '"' '030F' = '"' '0312' = "'" '0313' = "'" '0314' = "'" '0315' = "'" # ASCII Codes to replace: '0001' = '' '0002' = '' '0003' = '' '0004' = '' '0005' = '' '0006' = '' '0007' = '' '0008' = '' '000B' = '' '000C' = '' '000E' = '' '000F' = '' } # loop through the characters that need replacements foreach($UnicodeChar in $replacementTable.Keys) { # find the instances using a regular expression # the return value is always a pair of two: # - a MatchCollection returned by Match() # - and a string containing the desired replacement character [Regex]::Matches($text, "\u$UnicodeChar") | Add-SteroidsTextChange -ReplacementText $replacementTable[$UnicodeChar] } # finalize all changes: Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Character Operations/BacktickPlusSpace/BacktickSpace.ps1
BacktickSpace.ps1
# makes sure all lines end CRLF (ASCII code 13 and 10) & { # makes sure all lines end CRLF (ASCII code 13 and 10) & { # get access to editor: $Editor = Get-SteroidsEditor # RegEx pattern for various types of line endings: $pattern = '(?m)\`\s{1,}$' # find these line endings and replace them with a normalized line ending: [Regex]::Matches($Editor.text, $pattern) | Add-SteroidsTextChange -ReplacementText '`' # finalize changes: Invoke-SteroidsTextChange } }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Character Operations/NormalizeLineEndings/NormalizeLineEndings.ps1
NormalizeLineEndings.ps1
# makes sure all lines end CRLF (ASCII code 13 and 10) & { # get access to editor: $Editor = Get-SteroidsEditor # RegEx pattern for various types of line endings: $pattern = '\r\n|\n\r|\n|\r' # find these line endings and replace them with a normalized line ending: [Regex]::Matches($Editor.text, $pattern) | Add-SteroidsTextChange -ReplacementText "`r`n" # finalize changes: Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Command/CommandPositionalParameter/CommandPositionalParameter.ps1
CommandPositionalParameter.ps1
& { Set-StrictMode -Off $commands = @{} # get all commands available foreach($command in (Get-Command -CommandType Function, Cmdlet)) { # add each unique command to a hash table $name = $command.Name if ($commands.ContainsKey($name) -eq $false) { $commands.Add($name, $command) } } # get all commands found in script $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Command') $SplattedItems = @() # examine each command found in script :outer foreach($item in $items) { $namedparameters = @{} $positionalparameters = @{} # get command name... $CommandName = $item.CommandElements[0].Extent.Text # ...is it known? if ($commands.ContainsKey($CommandName)) { # yes, check parameter definitions $Command = $commands[$CommandName] if ($Command.Parameters -ne $null) { # identify parameters used in the command $position = 0 $elements = $item.CommandElements.Count -1 for($i=1; $i -le $elements; $i++) { $element = $item.CommandElements[$i] # is it a non-splatted parameter? if ($element -is [System.Management.Automation.Language.CommandParameterAst]) { # look up the parameter in the parameter definition $parameterName = $element.ParameterName $ParameterObject = $null if ($command.Parameters.ContainsKey($parameterName) -eq $false) { # not found, is it a dynamic parameter? $ParameterName = ($command.Parameters.Values | Where-Object { $_.isDynamic -eq $false } | Select-Object -ExpandProperty Name) -like "$ParameterName*" if ($command.Parameters.ContainsKey($parameterName) -eq $false) { continue outer } } # static parameter $ParameterObject = $Command.Parameters[$ParameterName] if ($ParameterObject.SwitchParameter -eq $false) { # no switch parameter $namedparameters.Add($ParameterName, $item.CommandElements[$i+1]) $i++ } else { # switch parameter $namedparameters.Add($parameterName, $null) } } else { # is it a splatted parameter? if ($item.CommandElements[$i] -is [System.Management.Automation.Language.VariableExpressionAst] -and $item.CommandElements[$i].Splatted ) { $SplattedItems += $position } $positionalparameters.Add($position, $item.CommandElements[$i]) $position++ } } } # identify the correct parameterset $validSets = :setloop foreach($set in $Command.ParameterSets) { # all named parameters must be in foreach($par in $namedparameters.Keys) { if ($set.Parameters.Name -contains $par -eq $false) { continue setloop } } $set } if ($validSets.Count -eq 0) { continue outer } :parameterSets foreach($set in ($validSets | Sort-Object { $_.IsDefault } -Descending)) { # find positional parameters $changes = @() $shift = 0 foreach($parameter in ($set.Parameters | Sort-Object -Property Position)) { $position = $parameter.Position if ($position -ge 0) { $name = $parameter.Name if ($namedparameters.ContainsKey($name)) { $shift-- } else { $realposition = $position + $shift # if a paremeter takes values from remaining arguments, then do not turn it into a named parameter if ($positionalparameters.ContainsKey($realposition) -and ($parameter.ValueFromRemainingArguments -eq $false -or ($positionalparameters.Count -lt 2))) { # does the data type fit? $skip = $false if ($validSets.Count -eq 1) { # one set remaining, do always } elseif ($positionalparameters[$realposition].GetType() -eq [System.Management.Automation.Language.ScriptBlockExpressionAst]) { if ($parameter.ParameterType -ne [ScriptBlock] -and $parameter.ParameterType -ne [ScriptBlock[]]) { $changes = @() continue parameterSets } } elseif ($positionalparameters[$realposition].GetType() -eq [System.Management.Automation.Language.StringConstantExpressionAst]) { if ($parameter.ParameterType -ne [String] -and $parameter.ParameterType -ne [String[]] -and $parameter.ParameterType -ne [Object] -and $parameter.ParameterType -ne [Object[]]) { $changes = @() continue parameterSets } } elseif ($positionalparameters[$realposition].GetType() -eq [System.Management.Automation.Language.ParenExpressionAst]) { if ($parameter.ParameterType -ne [Object] -and $parameter.ParameterType -ne [Object[]]) { $changes = @() continue parameterSets } } elseif ($positionalparameters[$realposition].GetType() -eq [System.Management.Automation.Language.ArrayLiteralAst]) { if ($parameter.ParameterType -ne [Object] -and $parameter.ParameterType -ne [Object[]]) { $changes = @() continue parameterSets } } elseif ($positionalparameters[$realposition].GetType() -eq [System.Management.Automation.Language.VariableExpressionAst]) { if ($parameter.ParameterType -ne $positionalparameters[$realposition].StaticType -and $parameter.ParameterType.GetElementType() -ne $positionalparameters[$realposition].StaticType) { $changes = @() continue parameterSets } } else { $i = 1 } if ($skip -eq $false) { if ($SplattedItems -notcontains $realposition) { $changes += 1 $padding = ' ' $statement = $positionalparameters[$realposition].Parent $offset = $positionalparameters[$realposition].Extent.StartOffset - $statement.Extent.StartOffset if ($statement.Extent.Text.SubString($offset-1, 1) -eq ' ') { $padding = '' } $changes[$changes.Count-1] = @($positionalparameters[$realposition].Extent.StartOffset, $positionalparameters[$realposition].Extent.StartOffset, ($padding + '-' + $parameter.Name + ' ')) } } } } } } foreach($change in $changes) { [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($change[0], $change[1], $change[2]) } break } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Command/CommandCase/CommandCase.ps1
CommandCase.ps1
# Case-corrects command names & { # array that holds all known command names: $commands = @{} # include all functions that are defined in the script $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Function') # add each function that is defined in the script foreach($item in $items) { $name = $item.Name if ($commands.ContainsKey($name) -eq $false) { $commands.Add($name, $name) } } # add all known commands from the powershell environment: foreach($command in (Get-Command -CommandType Alias, Function, Cmdlet, Application)) { $name = $command.Name if ($commands.ContainsKey($name) -eq $false) { $commands.Add($name, $name) } } # add all application names without extension: foreach($command in (Get-Command -CommandType Application)) { $name = $command.Name $name2 = [System.IO.Path]::GetFileNameWithoutExtension($name) if ($commands.ContainsKey($name2) -eq $false) { $commands.Add($name2, $name) } } # find all commands used in the current script: $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Command') foreach($item in $items) { $name = $item.CommandElements[0].Extent.Text # if the command is known... if ($commands.ContainsKey($name)) { # ...replace command with the correctly cased command name: Add-SteroidsTextChange -PositionInfo $item.CommandElements[0].Extent -ReplacementText $commands.$name } } # finalize changes: Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Command/CommandParameter/CommandParameter.ps1
CommandParameter.ps1
# Case-correct command parameter names & { # array that will hold all commands that are going to be fixed: $commands = @{} # get all functions and cmdlets (these command types use Powershell-style parameters): foreach($command in (Get-Command -CommandType Function, Cmdlet)) { $name = $command.Name if ($commands.ContainsKey($name) -eq $false) { $commands.Add($name, $command) } } # get all commands used in the current script: $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Command') foreach($item in $items) { $name = $item.CommandElements[0].Extent.Text # is it a known command? if ($commands.ContainsKey($name)) { # find command parameter names $command = $commands.$name # find used parameters $item.CommandElements | Where-Object { $_ -is [System.Management.Automation.Language.CommandParameterAst]} | ForEach-Object { $parameterAST = $_ $ParameterName = $parameterAST.ParameterName # matching parameter if (($command.Parameters -ne $null) -and $command.Parameters.ContainsKey($ParameterName)) { # find the case-correct official parameter name $RealParameterName = $Command.Parameters[$ParameterName].Name # is there a difference in casing? if ($ParameterName -cne $RealParameterName) { # yes, replace with case-corrected version: # but make sure to add an argument if this was a switch parameter if ($parameterAST.Extent.Text.Contains(':')) { if ($parameterAST.Argument -ne $null -and $parameterAST.Argument -ne '') { $RealParameterName += ':' + $parameterAST.Argument } } Add-SteroidsTextChange -PositionInfo $_.Extent -ReplacementText "-$RealParameterName" } } else # check for incomplete parameter { # do we have a parameter that starts with the parameter used? $RealParameterName = ($command.Parameters.Values | Where-Object { $_.isDynamic -eq $false } | Select-Object -ExpandProperty Name) -like "$ParameterName*" # is it an unambiguous parameter? if ($RealParameterName.Count -eq 1) { # yes, replace the abbreviated parameter with the full parameter # but make sure to add an argument if this was a switch parameter if ($parameterAST.Extent.Text.Contains(':')) { if ($parameterAST.Argument -ne $null -and $parameterAST.Argument -ne '') { $RealParameterName[0] += ':' + $parameterAST.Argument } } Add-SteroidsTextChange -PositionInfo $_.Extent -ReplacementText "-$($RealParameterName[0])" } } } } } # finalize changes: Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Command/ReplaceAliases/ReplaceAliases.ps1
ReplaceAliases.ps1
# searches for Aliases and replaces them with the underlying # original command & { Set-StrictMode -Off # get access to the AST (abstract syntax tree): $info = Get-SteroidsAST # find commands in the script: $Commands = $info.Ast.FindAll({ $args[0] -is [System.Management.Automation.Language.CommandAst]}, $true) # get a list of all aliases: $Aliases = Get-Alias | Group-Object -Property Name -AsHashTable -AsString # examine each command: foreach($command in $Commands) { # get the command name: $name = $command.CommandElements[0].Value # if there is a name... if ($name -ne $null) { # try and get an alias with that name: if ($aliases.ContainsKey($name)) { # yes, so replace the current command with the alias definition: Add-SteroidsTextChange -PositionInfo $command.CommandElements[0].extent -ReplacementText $aliases[$name].ResolvedCommand.Name } } } # finalize changes: Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Pipeline/PipelineBreakAfterPipe/PipelineBreakAfterPipe.ps1
PipelineBreakAfterPipe.ps1
& { $crlf = -join [Char[]](13,10) $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Pipeline') foreach($item in $items) { # do optimization only with 3 or more pipeline elements if ($item.PipelineElements.Count -le 2) { continue } $tokenList = [ISESteroids.SteroidsFixer.Helpers]::GetToken($item.Extent.StartOffset, $item.Extent.EndOffset) $tokenCount = $tokenlist.Count for($i=0; $i-lt$tokenCount-1;$i++) { $token = $tokenlist[$i] # do we have a comma that is not at the beginning? if ($token.Kind -eq 'Pipe' -and $i -gt 0) { $nexttokens = [ISESteroids.SteroidsFixer.Helpers]::GetTokenUntilLineBreak($Token.Extent.EndOffset-1, 'Forward') if ($nexttokens.Count -gt 0 ) { $start = $token.Extent.EndOffset $end = $nexttokens[0].Extent.StartOffset [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($start, $end, $crlf) } } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Pipeline/PipelineRemoveOutNull/PipelineRemoveOutNull.ps1
PipelineRemoveOutNull.ps1
& { $items = [ISESteroids.SteroidsFixer.Helpers]::GetAST('Pipeline') foreach($item in $items) { if ($item.PipelineElements[-1].Extent.Text -eq 'Out-Null') { # remove last pipeline element [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($item.PipelineElements[-2].Extent.EndOffset, $item.PipelineElements[-1].Extent.EndOffset, '') # add $null assignment [ISESteroids.SteroidsFixer.Helpers]::AddTextChange($item.PipelineElements[0].Extent.StartOffset, $item.PipelineElements[0].Extent.StartOffset, '$null = ') } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Reformat Structures/Reformat Hashtable/ReformatHashtable.ps1
ReformatHashtable.ps1
& { foreach($hashtable in [ISESteroids.SteroidsFixer.Helpers]::GetAST('Hashtable')) { if ($hashtable.Extent.Text.TrimStart().StartsWith('@') -eq $false -or $hashtable.KeyValuePairs.Count -eq 0) { continue } $sb = New-Object -TypeName System.Text.StringBuilder $null = $sb.AppendLine('@{') # find maximal length for keys $length = -1 foreach($item in $hashtable.KeyValuePairs.Item1.Value) { if ($item.Length -gt $length) { $length = $item.Length } } $length = [Math]::Max($length, 0) foreach($KeyValuePair in $hashtable.KeyValuePairs) { $null = $sb.AppendLine(' ' + $KeyValuePair.Item1.ToString().PadRight($length) + ' = ' + $KeyValuePair.Item2) } $null = $sb.Append('}') Add-SteroidsTextChange -PositionInfo $hashtable.Extent -ReplacementText $sb.ToString() } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Reformat Structures/RemoveSemicolon/RemoveSemicolon.ps1
RemoveSemicolon.ps1
& { $info = Get-SteroidsAST $Tokens = $info.TokenList $i = $Tokens.Count for($x=0; $x -lt $i; $x++) { # is this a semicolon? if ($Tokens[$x].Kind -eq 'Semi') { # is this token inside a structure where semicolons are useful? $DoReplace = Test-SteroidsTextChange -Extent $Tokens[$x].Extent -Ast $info.Ast -IllegalParent ForStatementAst, HashtableAst -ExpectedParent StatementBlockAst if ($DoReplace) { # is there a token following on same line? if ($Tokens[$x].Extent.EndLineNumber -eq $Tokens[$x+1].Extent.StartLineNumber -and $Tokens[$x+1].Kind -ne 'NewLine' -and $Tokens[$x+1].Kind -ne 'EndOfInput') { Add-SteroidsTextChange -PositionInfo $Tokens[$x].Extent -ReplacementText "`r`n" } else { Add-SteroidsTextChange -PositionInfo $Tokens[$x].Extent } } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Fixer/Variables/NormalizeVariables/NormalizeVariables.ps1
NormalizeVariables.ps1
& { $variables = [ISESteroids.SteroidsFixer.Helpers]::GetAST('VariableExpression') $lookup = @{} foreach($variable in $variables) { if ($variable.Extent.Text.StartsWith('$') -or $variable.Extent.Text.StartsWith('@')) { $name = $variable.VariablePath.toString() if ($variable.Splatted) { $prefix = '@' } else { if ($variable.Extent -like '$using:*') { $prefix = '$using:' } else { $prefix = '$' } } if ($lookup.ContainsKey($name)) { if ($name -cne $lookup[$name]) { Add-SteroidsTextChange -PositionInfo $variable.Extent -ReplacementText ($prefix + $lookup[$name]) } } else { $lookup.Add($name, $variable.Extent.Text.Substring(1)) } } } Invoke-SteroidsTextChange }
PowerShellCorpus/PowerShellGallery/ISESteroids/2.6.3.30/Templates/Generic Header.ps1
Generic Header.ps1
<# Author: Version: Version History: Purpose: #>
PowerShellCorpus/PowerShellGallery/PesterMatchHashtable/0.0.1/RunPester.ps1
RunPester.ps1
function GetLineNumber($stackTrace){ if($stackTrace -match "at line: (\d*)"){ $matches[1]; } else { $null } } function GetFileName($stackTrace){ if($stackTrace -match "at line: (?:\d*) in (.*)$"){ $matches[1]; } else { $null } } function FormatResult ($result){ process { $lineNumber = GetLineNumber $_.StackTrace $file = GetFileName $_.StackTrace | Resolve-Path -Relative $collapsedMessage = $_.FailureMessage -replace "`n"," " $testDescription = "$($_.Describe):$($_.Name)" "$file;$lineNumber;${testDescription}:$collapsedMessage" } } Write-Output "Running tests..." $results = Invoke-Pester -PassThru # can use -Quiet to suppress the default Pester output $results.TestResult | ?{ -not $_.Passed} | FormatResult Write-Output "Done"
PowerShellCorpus/PowerShellGallery/PesterMatchHashtable/0.0.1/Publish.ps1
Publish.ps1
Param( [Parameter(Mandatory=$true)] [string]$powershellGalleryKey ) Publish-Module -NuGetApiKey $powershellGalleryKey -Path ./
PowerShellCorpus/PowerShellGallery/PesterMatchHashtable/0.0.1/Examples.ps1
Examples.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path Import-Module "$here\PesterMatchHashtable.psm1" -Force Describe "MatchHashtable examples" { It "single item hashtables match" { @{"a"=1} | Should MatchHashtable @{"a"=1} } It "hashtables with the same contents match" { @{"a"=1;"b"="wibble"} | Should MatchHashtable @{"b"="wibble";"a"=1} } It "hashtables with different lengths do not match" { @{"a"=1} | Should Not MatchHashtable @{"b"="wibble";"a"=1} } It "hashtables with different lengths do not match" { @{"a"=1;"b"="wibble"} | Should Not MatchHashtable @{"b"="wibble"} } It "hashtables with different values do not match" { @{"a"=1;"b"="wibble"} | Should Not MatchHashtable @{"a"=123; "b"="wibble"} } }
PowerShellCorpus/PowerShellGallery/PesterMatchHashtable/0.0.1/PesterMatchHashtable.Tests.ps1
PesterMatchHashtable.Tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") . "$here\$sut" ## Test Assertion functions takenb from: https://github.com/pester/Pester/blob/ebfb0997365fea29f25b2aa3065378a3765eff4c/Functions/Assertions/Test-Assertion.ps1 function Test-PositiveAssertion($result) { if (-not $result) { throw "Expecting expression to pass, but it failed" } } function Test-NegativeAssertion($result) { if ($result) { throw "Expecting expression to pass, but it failed" } } Describe "PesterMatchHashtable" { It "returns true for matching single item hashtable with same values" { Test-PositiveAssertion (PesterMatchHashtable @{"a"=1} @{"a"=1}) } It "returns true for hashtable with the same contents" { Test-PositiveAssertion (PesterMatchHashtable @{"a"=1; "b"="test"} @{"a"=1; "b"="test"}) } It "returns true for hashtable with the same contents in different orders" { Test-PositiveAssertion (PesterMatchHashtable @{"a"=1; "b"="test"} @{"b"="test";"a"=1}) } It "returns false if hashtable differ in content" { Test-NegativeAssertion (PesterMatchHashtable @{"a"=1; "b"="test"} @{"a"=1; "b"="different value"}) } It "returns false if hashtable differ in length - input2 longer" { Test-NegativeAssertion (PesterMatchHashtable @{"a"=1} @{"a"=1; "b"="test"}) } It "returns false if hashtable differ in length - input1 longer" { Test-NegativeAssertion (PesterMatchHashtable @{"a"=1; "b"="test"} @{"a"=1}) } }
PowerShellCorpus/PowerShellGallery/PesterMatchHashtable/0.0.1/PesterMatchHashtable.ps1
PesterMatchHashtable.ps1
function PesterMatchHashtable($value, $expectedMatch) { # Write-Host "foo: $(ConvertTo-Json $value); $(ConvertTo-Json $expectedMatch)" if($value.Count -ne $expectedMatch.Count){ return $false; } foreach($expectedKey in $expectedMatch.Keys) { if (-not($value.Keys -contains $expectedKey)){ return $false; } if (-not ($value[$expectedKey] -eq $expectedMatch[$expectedKey])){ return $false; } } return $true; } function PesterMatchHashtableFailureMessage($value, $expectedMatch) { foreach($expectedKey in $expectedMatch.Keys) { if (-not($value.Keys -contains $expectedKey)){ return "Expected key: {$expectedKey}, but missing in actual" } $expectedValue = $expectedMatch[$expectedKey] $actualValue = $value[$expectedKey] if (-not ($actualValue -eq $expectedValue)) { return "Value differs for key {$expectedKey}. Expected value: {$expectedValue}, actual value: {$actualValue}" } } foreach($actualKey in $value.Keys) { if (-not($expectedMatch.Keys -contains $actualKey)){ return "Actual key: {$actualKey}, but missing in expected" } $expectedValue = $expectedMatch[$actualKey] $actualValue = $value[$actualKey] if (-not ($actualValue -eq $expectedValue)) { return "Value differs for key {$actualKey}. Expected value: {$expectedValue}, actual value: {$actualValue}" } } # for($i=0; $i -lt $expectedMatch.Keys.Length; $i++){ # $expectedKey = $expectedMatch.Keys[$_] # if($value.Keys -contains $expectedKey){ # $expectedValue = $expectedMatch[$expectedKey] # $actualValue = $value[$expectedKey] # if (-not ($actualValue -eq $expectedValue)) { # return "Value differs for key {$expectedKey}. Expected value: {$expectedValue}, actual value: {$actualValue}" # } # } else { # return "Expected key: {$expectedMatch}, but missing in actual" # } # } # for($i=0; $i -lt $value.Keys.Length; $i++){ # $actualKey = $value.Keys[$_] # if($expectedMatch.Keys -contains $actualKey){ # $expectedValue = $expectedMatch[$actualKey] # $actualValue = $value[$actualKey] # if (-not ($actualValue -eq $expectedValue)) { # return "Value differs for key {$actualKey}. Expected value: {$expectedValue}, actual value: {$actualValue}" # } # } else { # return "Actual contains key: {$actualKey}, but not expected" # } # } } function NotPesterMatchHashtableFailureMessage($value, $expectedMatch) { return "Expected: ${value} to not match the expression ${expectedMatch}" }
PowerShellCorpus/PowerShellGallery/Azure.ToolKit/1.3/PSScriptAnalyzer.ps1
PSScriptAnalyzer.ps1
# To get latest PSScriptAnalyzer run # Install-Module -Name PSScriptAnalyzer Import-Module PSScriptAnalyzer -Force Invoke-ScriptAnalyzer -Path $PSScriptRoot -Recurse
PowerShellCorpus/PowerShellGallery/Plaster/1.0.1/GetModuleExtension.ps1
GetModuleExtension.ps1
function Get-ModuleExtension { [CmdletBinding()] param( [string] $ModuleName, [Version] $ModuleVersion ) $modules = Get-Module -ListAvailable Write-Verbose "`nFound $($modules.Length) installed modules to scan for extensions." function ParseVersion($versionString) { $parsedVersion = $null if ($versionString) { # We're targeting Semantic Versioning 2.0 so make sure the version has # at least 3 components (X.X.X). This logic ensures that the "patch" # (third) component has been specified. $versionParts = $versionString.Split('.'); if ($versionParts.Length -lt 3) { $versionString = "$versionString.0" } if ($PSVersionTable.PSEdition -eq "Core") { $parsedVersion = New-Object -TypeName "System.Management.Automation.SemanticVersion" -ArgumentList $versionString } else { $parsedVersion = New-Object -TypeName "System.Version" -ArgumentList $versionString } } return $parsedVersion } foreach ($module in $modules) { if ($module.PrivateData -and $module.PrivateData.PSData -and $module.PrivateData.PSData.Extensions) { Write-Verbose "Found module with extensions: $($module.Name)" foreach ($extension in $module.PrivateData.PSData.Extensions) { Write-Verbose "Comparing against module extension: $($extension.Module)" $minimumVersion = ParseVersion $extension.MinimumVersion $maximumVersion = ParseVersion $extension.MaximumVersion if (($extension.Module -eq $ModuleName) -and (!$minimumVersion -or $ModuleVersion -ge $minimumVersion) -and (!$maximumVersion -or $ModuleVersion -le $maximumVersion)) { # Return a new object with the extension information [PSCustomObject]@{ Module = $module MinimumVersion = $minimumVersion MaximumVersion = $maximumVersion Details = $extension.Details } } } } } } # SIG # Begin signature block # MIIasAYJKoZIhvcNAQcCoIIaoTCCGp0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUmLjeddBf4Dj1P92+mz6ytQai # IZygghWDMIIEwzCCA6ugAwIBAgITMwAAALfuAa/68MeouwAAAAAAtzANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw # HwYDVQQDExhNaWNyb3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ned/e/3DcM4Dsj+dBY5KtcmMFmqJm2R6a7zE2lLv3SHjtbVPYOeIYsZuF5 # kCsHcZeSftjPEPfBuV9FpIN+Y+tPyppb5MxTqwa0mditlFlPJfxQKgVyvEqWVfoZ # Rie425kO25HhShm9Rcqpv05M1oKzXoiCV1pmoxDZW/jZr8DEjI58oHKVXNhruKbO # gAg5RDCW41Jt2Oafg9k7fFzkk42U6d+kuql9/0wps3RKakbZB9XKlQsd+UrheRbY # 6cktDI6MRHP1bVcVGZxLRkjwM+HqvVXD0t7AQ4xiqjKJybtwsoQg7V+++uO7dxX5 # 5opc/6urfyghjdVJo5dbo6elHoM= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Plaster/1.0.1/InvokePlaster.ps1
InvokePlaster.ps1
## DEVELOPERS NOTES & CONVENTIONS ## ## 1. All text displayed to the user except for Write-Debug (or $PSCmdlet.WriteDebug()) text must be added to the ## string tables in: ## en-US\Plaster.psd1 ## Plaster.psm1 ## 2. If a new manifest element is added, it must be added to the Schema\PlasterManifest-v1.xsd file and then ## processed in the appropriate function in this script. Any changes to <parameter> attributes must be ## processed not only in the ProcessParameter function but also in the dynamicparam function. ## ## 3. Non-exported functions should avoid using the PowerShell standard Verb-Noun naming convention. ## They should use PascalCase instead. ## ## 4. Please follow the scripting style of this file when adding new script. function Invoke-Plaster { [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidShouldContinueWithoutForce', '', Scope='Function', Target='CopyFileWithConflictDetection')] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingConvertToSecureStringWithPlainText', '', Scope='Function', Target='ProcessParameter')] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope='Function', Target='CopyFileWithConflictDetection')] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope='Function', Target='ProcessFile')] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope='Function', Target='ProcessModifyFile')] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSShouldProcess', '', Scope='Function', Target='ProcessNewModuleManifest')] [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Position = 0, Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $TemplatePath, [Parameter(Position = 1, Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $DestinationPath, [Parameter()] [switch] $Force, [Parameter()] [switch] $NoLogo ) # Process the template's Plaster manifest file to convert parameters defined there into dynamic parameters. dynamicparam { $paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary $manifest = $null $manifestPath = $null $templateAbsolutePath = $null # Nothing to do until the TemplatePath parameter has been provided. if ($null -eq $TemplatePath) { return } try { # Let's convert non-terminating errors in this function to terminating so we # catch and format the error message as a warning. $ErrorActionPreference = 'Stop' # The constrained runspace is not available in the dynamicparam block. Shouldn't be needed # since we are only evaluating the parameters in the manifest - no need for EvaluateConditionAttribute as we # are not building up multiple parametersets. And no need for EvaluateAttributeValue since we are only # grabbing the parameter's value which is static. $templateAbsolutePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($TemplatePath) if (!(Test-Path -LiteralPath $templateAbsolutePath -PathType Container)) { throw ($LocalizedData.ErrorTemplatePathIsInvalid_F1 -f $templateAbsolutePath) } # Load manifest file using culture lookup $manifestPath = GetPlasterManifestPathForCulture $templateAbsolutePath $PSCulture if (($null -eq $manifestPath) -or (!(Test-Path $manifestPath))) { return } $manifest = Plaster\Test-PlasterManifest -Path $manifestPath -ErrorAction Stop 3>$null # The user-defined parameters in the Plaster manifest are converted to dynamic parameters # which allows the user to provide the parameters via the command line. # This enables non-interactive use cases. foreach ($node in $manifest.plasterManifest.parameters.ChildNodes) { if ($node -isnot [System.Xml.XmlElement]) { continue } $name = $node.name $type = $node.type $prompt = $node.prompt if (!$name -or !$type) { continue } # Configure ParameterAttribute and add to attr collection $attributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] $paramAttribute = New-Object System.Management.Automation.ParameterAttribute $paramAttribute.HelpMessage = $prompt $attributeCollection.Add($paramAttribute) switch -regex ($type) { 'text|user-fullname|user-email' { $param = New-Object System.Management.Automation.RuntimeDefinedParameter ` -ArgumentList ($name, [string], $attributeCollection) break } 'choice|multichoice' { $choiceNodes = $node.ChildNodes $setValues = New-Object string[] $choiceNodes.Count $i = 0 foreach ($choiceNode in $choiceNodes){ $setValues[$i++] = $choiceNode.value } $validateSetAttr = New-Object System.Management.Automation.ValidateSetAttribute $setValues $attributeCollection.Add($validateSetAttr) $type = if ($type -eq 'multichoice') { [string[]] } else { [string] } $param = New-Object System.Management.Automation.RuntimeDefinedParameter ` -ArgumentList ($name, $type, $attributeCollection) break } default { throw ($LocalizedData.UnrecognizedParameterType_F2 -f $type,$name) } } $paramDictionary.Add($name, $param) } } catch { Write-Warning ($LocalizedData.ErrorProcessingDynamicParams_F1 -f $_) } $paramDictionary } begin { # Write out the Plaster logo if necessary $plasterLogo = @' ____ _ _ | _ \| | __ _ ___| |_ ___ _ __ | |_) | |/ _` / __| __/ _ \ '__| | __/| | (_| \__ \ || __/ | |_| |_|\__,_|___/\__\___|_| '@ if (!$NoLogo) { $versionString = "v$PlasterVersion" Write-Host $plasterLogo Write-Host ((" " * (50 - $versionString.Length)) + $versionString) Write-Host ("=" * 50) } } process { $boundParameters = $PSBoundParameters $constrainedRunspace = $null $templateCreatedFiles = @{} $defaultValueStore = @{} $fileConflictConfirmNoToAll = $false $fileConflictConfirmYesToAll = $false $flags = @{ DefaultValueStoreDirty = $false } # Verify TemplatePath parameter value is valid. $templateAbsolutePath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($TemplatePath) if (!(Test-Path -LiteralPath $templateAbsolutePath -PathType Container)) { throw ($LocalizedData.ErrorTemplatePathIsInvalid_F1 -f $templateAbsolutePath) } # We will have a null manifest if the dynamicparam scriptblock was unable to load the template manifest # or it wasn't valid. If so, let's try to load it here. If anything, we can provide better errors here. if ($null -eq $manifest) { if ($null -eq $manifestPath) { $manifestPath = GetPlasterManifestPathForCulture $templateAbsolutePath $PSCulture } if (Test-Path -LiteralPath $manifestPath -PathType Leaf) { $manifest = Plaster\Test-PlasterManifest -Path $manifestPath -ErrorAction Stop 3>$null $PSCmdlet.WriteDebug("In begin, loading manifest file '$manifestPath'") } else { throw ($LocalizedData.ManifestFileMissing_F1 -f $manifestPath) } } # If the destination path doesn't exist, create it. $destinationAbsolutePath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath) if (!(Test-Path -LiteralPath $destinationAbsolutePath)) { New-Item $destinationAbsolutePath -ItemType Directory > $null } # Create the pre-defined Plaster variables. InitializePredefinedVariables $templateAbsolutePath $destinationAbsolutePath # Check for any existing default value store file and load default values if file exists. $templateId = $manifest.plasterManifest.metadata.id $templateVersion = $manifest.plasterManifest.metadata.version $templateName = $manifest.plasterManifest.metadata.name $storeFilename = "$templateName-$templateVersion-$templateId.clixml" $defaultValueStorePath = Join-Path $ParameterDefaultValueStoreRootPath $storeFilename if (Test-Path $defaultValueStorePath) { try { $PSCmdlet.WriteDebug("Loading default value store from '$defaultValueStorePath'.") $defaultValueStore = Import-Clixml $defaultValueStorePath -ErrorAction Stop } catch { Write-Warning ($LocalizedData.ErrorFailedToLoadStoreFile_F1 -f $defaultValueStorePath) } } function NewConstrainedRunspace() { $iss = [System.Management.Automation.Runspaces.InitialSessionState]::Create() if (!$IsCoreCLR) { $iss.ApartmentState = [System.Threading.ApartmentState]::STA } $iss.LanguageMode = [System.Management.Automation.PSLanguageMode]::ConstrainedLanguage $iss.DisableFormatUpdates = $true $sspe = New-Object System.Management.Automation.Runspaces.SessionStateProviderEntry 'Environment',([Microsoft.PowerShell.Commands.EnvironmentProvider]),$null $iss.Providers.Add($sspe) $sspe = New-Object System.Management.Automation.Runspaces.SessionStateProviderEntry 'FileSystem',([Microsoft.PowerShell.Commands.FileSystemProvider]),$null $iss.Providers.Add($sspe) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Content',([Microsoft.PowerShell.Commands.GetContentCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Date',([Microsoft.PowerShell.Commands.GetDateCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-ChildItem',([Microsoft.PowerShell.Commands.GetChildItemCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Item',([Microsoft.PowerShell.Commands.GetItemCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-ItemProperty',([Microsoft.PowerShell.Commands.GetItemPropertyCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Module',([Microsoft.PowerShell.Commands.GetModuleCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Get-Variable',([Microsoft.PowerShell.Commands.GetVariableCommand]),$null $iss.Commands.Add($ssce) $ssce = New-Object System.Management.Automation.Runspaces.SessionStateCmdletEntry 'Test-Path',([Microsoft.PowerShell.Commands.TestPathCommand]),$null $iss.Commands.Add($ssce) $scopedItemOptions = [System.Management.Automation.ScopedItemOptions]::AllScope $plasterVars = Get-Variable -Name PLASTER_* foreach ($var in $plasterVars) { $ssve = New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry ` $var.Name,$var.Value,$var.Description,$scopedItemOptions $iss.Variables.Add($ssve) } # Create new runspace with the above defined entries. Then open and set its working dir to $destinationAbsolutePath # so all condition attribute expressions can use a relative path to refer to file paths e.g. # condition="Test-Path src\${PLASTER_PARAM_ModuleName}.psm1" $runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss) $runspace.Open() if ($destinationAbsolutePath) { $runspace.SessionStateProxy.Path.SetLocation($destinationAbsolutePath) > $null } $runspace } function ExecuteExpressionImpl([string]$Expression) { try { $powershell = [PowerShell]::Create() if ($null -eq $constrainedRunspace) { $constrainedRunspace = NewConstrainedRunspace } $powershell.Runspace = $constrainedRunspace try { $powershell.AddScript($Expression) > $null $res = $powershell.Invoke() $res } catch { throw ($LocalizedData.ExpressionInvalid_F2 -f $Expression,$_) } # Check for non-terminating errors. if ($powershell.Streams.Error.Count -gt 0) { $err = $powershell.Streams.Error[0] throw ($LocalizedData.ExpressionNonTermErrors_F2 -f $Expression,$err) } } finally { if ($powershell) { $powershell.Dispose() } } } function InterpolateAttributeValue([string]$Value, [string]$Location) { if ($null -eq $Value) { return [string]::Empty } elseif ([string]::IsNullOrWhiteSpace($Value)) { return $Value } try { $res = @(ExecuteExpressionImpl "`"$Value`"") [string]$res[0] } catch { throw ($LocalizedData.InterpolationError_F3 -f $Value.Trim(),$Location,$_) } } function EvaluateConditionAttribute([string]$Expression, [string]$Location) { if ($null -eq $Expression) { return [string]::Empty } elseif ([string]::IsNullOrWhiteSpace($Expression)) { return $Expression } try { $res = @(ExecuteExpressionImpl $Expression) [bool]$res[0] } catch { throw ($LocalizedData.ExpressionInvalidCondition_F3 -f $Expression,$Location,$_) } } function EvaluateExpression([string]$Expression, [string]$Location) { if ($null -eq $Expression) { return [string]::Empty } elseif ([string]::IsNullOrWhiteSpace($Expression)) { return $Expression } try { $res = @(ExecuteExpressionImpl $Expression) [string]$res[0] } catch { throw ($LocalizedData.ExpressionExecError_F2 -f $Location,$_) } } function EvaluateScript([string]$Script, [string]$Location) { if ($null -eq $Script) { return @([string]::Empty) } elseif ([string]::IsNullOrWhiteSpace($Script)) { return $Script } try { $res = @(ExecuteExpressionImpl $Script) [string[]]$res } catch { throw ($LocalizedData.ExpressionExecError_F2 -f $Location,$_) } } function GetErrorLocationFileAttrVal([string]$ElementName, [string]$AttributeName) { $LocalizedData.ExpressionErrorLocationFile_F2 -f $ElementName,$AttributeName } function GetErrorLocationModifyAttrVal([string]$AttributeName) { $LocalizedData.ExpressionErrorLocationModify_F1 -f $AttributeName } function GetErrorLocationNewModManifestAttrVal([string]$AttributeName) { $LocalizedData.ExpressionErrorLocationNewModManifest_F1 -f $AttributeName } function GetErrorLocationParameterAttrVal([string]$ParameterName, [string]$AttributeName) { $LocalizedData.ExpressionErrorLocationParameter_F2 -f $ParameterName,$AttributeName } function GetErrorLocationRequireModuleAttrVal([string]$ModuleName, [string]$AttributeName) { $LocalizedData.ExpressionErrorLocationRequireModule_F2 -f $ModuleName,$AttributeName } function ConvertToDestinationRelativePath($Path) { $fullDestPath = $DestinationPath if (![System.IO.Path]::IsPathRooted($fullDestPath)) { $fullDestPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath) } $fullPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) if (!$fullPath.StartsWith($fullDestPath, 'OrdinalIgnoreCase')) { throw ($LocalizedData.ErrorPathMustBeUnderDestPath_F2 -f $fullPath, $fullDestPath) } $fullPath.Substring($fullDestPath.Length).TrimStart('\','/') } function VerifyPathIsUnderDestinationPath([ValidateNotNullOrEmpty()][string]$FullPath) { if (![System.IO.Path]::IsPathRooted($FullPath)) { $PSCmdlet.WriteDebug("The FullPath parameter '$FullPath' must be an absolute path.") } $fullDestPath = $DestinationPath if (![System.IO.Path]::IsPathRooted($fullDestPath)) { $fullDestPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DestinationPath) } if (!$FullPath.StartsWith($fullDestPath, [StringComparison]::OrdinalIgnoreCase)) { throw ($LocalizedData.ErrorPathMustBeUnderDestPath_F2 -f $FullPath, $fullDestPath) } } function WriteContentWithEncoding([string]$path, [string[]]$content, [string]$encoding) { if ($encoding -match '-nobom') { $encoding,$dummy = $encoding -split '-' $noBomEncoding = $null switch ($encoding) { 'utf8' { $noBomEncoding = New-Object System.Text.UTF8Encoding($false) } } if ($null -eq $content) { $content = [string]::Empty } [System.IO.File]::WriteAllLines($path, $content, $noBomEncoding) } else { Set-Content -LiteralPath $path -Value $content -Encoding $encoding } } function ColorForOperation($operation) { switch ($operation) { $LocalizedData.OpConflict { 'Red' } $LocalizedData.OpCreate { 'Green' } $LocalizedData.OpForce { 'Yellow' } $LocalizedData.OpIdentical { 'Cyan' } $LocalizedData.OpModify { 'Magenta' } $LocalizedData.OpUpdate { 'Green' } $LocalizedData.OpMissing { 'Red' } $LocalizedData.OpVerify { 'Green' } default { $Host.UI.RawUI.ForegroundColor } } } function GetMaxOperationLabelLength { ($LocalizedData.OpCreate, $LocalizedData.OpIdentical, $LocalizedData.OpConflict, $LocalizedData.OpForce, $LocalizedData.OpMissing, $LocalizedData.OpModify, $LocalizedData.OpUpdate, $LocalizedData.OpVerify | Measure-Object -Property Length -Maximum).Maximum } function WriteOperationStatus($operation, $message) { $maxLen = GetMaxOperationLabelLength Write-Host ("{0,$maxLen} " -f $operation) -ForegroundColor (ColorForOperation $operation) -NoNewline Write-Host $message } function WriteOperationAdditionalStatus([string[]]$Message) { $maxLen = GetMaxOperationLabelLength foreach ($msg in $Message) { $lines = $msg -split "`n" foreach ($line in $lines) { Write-Host ("{0,$maxLen} {1}" -f "",$line) } } } function GetGitConfigValue($name) { # Very simplistic git config lookup # Won't work with namespace, just use final element, e.g. 'name' instead of 'user.name' # The $Home dir may not be reachable e.g. if on network share and/or script not running as admin. # See issue https://github.com/PowerShell/Plaster/issues/92 if (!(Test-Path -LiteralPath $Home)) { return } $gitConfigPath = Join-Path $Home '.gitconfig' $PSCmdlet.WriteDebug("Looking for '$name' value in Git config: $gitConfigPath") if (Test-Path -LiteralPath $gitConfigPath) { $matches = Select-String -LiteralPath $gitConfigPath -Pattern "\s+$name\s+=\s+(.+)$" if (@($matches).Count -gt 0) { $matches.Matches.Groups[1].Value } } } function PromptForInput($prompt, $default) { do { $value = Read-Host -Prompt $prompt if (!$value -and $default) { $value = $default } } while (!$value) $value } function PromptForChoice([string]$ParameterName, [ValidateNotNull()]$ChoiceNodes, [string]$prompt, [int[]]$defaults, [switch]$IsMultiChoice) { $choices = New-Object 'System.Collections.ObjectModel.Collection[System.Management.Automation.Host.ChoiceDescription]' $values = New-Object object[] $ChoiceNodes.Count $i = 0 foreach ($choiceNode in $ChoiceNodes) { $label = InterpolateAttributeValue $choiceNode.label (GetErrorLocationParameterAttrVal $ParameterName label) $help = InterpolateAttributeValue $choiceNode.help (GetErrorLocationParameterAttrVal $ParameterName help) $value = InterpolateAttributeValue $choiceNode.value (GetErrorLocationParameterAttrVal $ParameterName value) $choice = New-Object System.Management.Automation.Host.ChoiceDescription -Arg $label,$help $choices.Add($choice) $values[$i++] = $value } $retval = [PSCustomObject]@{Values=@(); Indices=@()} if ($IsMultiChoice) { $selections = $Host.UI.PromptForChoice('', $prompt, $choices, $defaults) foreach ($selection in $selections) { $retval.Values += $values[$selection] $retval.Indices += $selection } } else { if ($defaults.Count -gt 1) { throw ($LocalizedData.ParameterTypeChoiceMultipleDefault_F1 -f $ChoiceNodes.ParentNode.name) } $selection = $Host.UI.PromptForChoice('', $prompt, $choices, $defaults[0]) $retval.Values = $values[$selection] $retval.Indices = $selection } $retval } # All Plaster variables should be set via this method so that the ConstrainedRunspace can be # configured to use the new variable. This method will null out the ConstrainedRunspace so that # later, when we need to evaluate script in that runspace, it will get recreated first with all # the latest Plaster variables. function SetPlasterVariable() { param( [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name, [Parameter(Mandatory=$true)] $Value, [Parameter()] [bool] $IsParam = $true ) # Variables created from a <parameter> in the Plaster manifset are prefixed PLASTER_PARAM all others # are just PLASTER_. $variableName = if ($IsParam) { "PLASTER_PARAM_$Name" } else { "PLASTER_$Name" } Set-Variable -Name $variableName -Value $Value -Scope Script -WhatIf:$false # If the constrained runspace has been created, it needs to be disposed so that the next string # expansion (or condition eval) gets an updated runspace that contains this variable or its new value. if ($null -ne $script:ConstrainedRunspace) { $script:ConstrainedRunspace.Dispose() $script:ConstrainedRunspace = $null } } function ProcessParameter([ValidateNotNull()]$Node) { $name = $Node.name $type = $Node.type $store = $Node.store $prompt = InterpolateAttributeValue $Node.prompt (GetErrorLocationParameterAttrVal $name prompt) $default = InterpolateAttributeValue $Node.default (GetErrorLocationParameterAttrVal $name default) # Check if parameter was provided via a dynamic parameter. if ($boundParameters.ContainsKey($name)) { $value = $boundParameters[$name] } else { # Not a dynamic parameter so prompt user for the value but first check for a stored default value. if ($store -and ($null -ne $defaultValueStore[$name])) { $default = $defaultValueStore[$name] $PSCmdlet.WriteDebug("Read default value '$default' for parameter '$name' from default value store.") if (($store -eq 'encrypted') -and ($default -is [System.Security.SecureString])) { try { $cred = New-Object -TypeName PSCredential -ArgumentList 'jsbplh',$default $default = $cred.GetNetworkCredential().Password $PSCmdlet.WriteDebug("Unencrypted default value for parameter '$name'.") } catch [System.Exception] { Write-Warning ($LocalizedData.ErrorUnencryptingSecureString_F1 -f $name) } } } # Some default values might not come from the template e.g. some are harvested from .gitconfig if it exists. $defaultNotFromTemplate = $false # Now prompt user for parameter value based on the parameter type. switch -regex ($type) { 'text' { # Display an appropriate "default" value in the prompt string. if ($default) { if ($store -eq 'encrypted') { $obscuredDefault = $default -replace '(....).*', '$1****' $prompt += " ($obscuredDefault)" } else { $prompt += " ($default)" } } # Prompt the user for text input. $value = PromptForInput $prompt $default $valueToStore = $value } 'user-fullname' { # If no default, try to get a name from git config. if (!$default) { $default = GetGitConfigValue('name') $defaultNotFromTemplate = $true } if ($default) { if ($store -eq 'encrypted') { $obscuredDefault = $default -replace '(....).*', '$1****' $prompt += " ($obscuredDefault)" } else { $prompt += " ($default)" } } # Prompt the user for text input. $value = PromptForInput $prompt $default $valueToStore = $value } 'user-email' { # If no default, try to get an email from git config if (-not $default) { $default = GetGitConfigValue('email') $defaultNotFromTemplate = $true } if ($default) { if ($store -eq 'encrypted') { $obscuredDefault = $default -replace '(....).*', '$1****' $prompt += " ($obscuredDefault)" } else { $prompt += " ($default)" } } # Prompt the user for text input. $value = PromptForInput $prompt $default $valueToStore = $value } 'choice|multichoice' { $choices = $Node.ChildNodes $defaults = [int[]]($default -split ',') # Prompt the user for choice or multichoice selection input. $selections = PromptForChoice $name $choices $prompt $defaults -IsMultiChoice:($type -eq 'multichoice') $value = $selections.Values $OFS = "," $valueToStore = "$($selections.Indices)" } default { throw ($LocalizedData.UnrecognizedParameterType_F2 -f $type, $Node.LocalName) } } # If parameter specifies that user's input be stored as the default value, # store it to file if the value has changed. if ($store -and (($default -ne $valueToStore) -or $defaultNotFromTemplate)) { if ($store -eq 'encrypted') { $PSCmdlet.WriteDebug("Storing new, encrypted default value for parameter '$name' to default value store.") $defaultValueStore[$name] = ConvertTo-SecureString -String $valueToStore -AsPlainText -Force } else { $PSCmdlet.WriteDebug("Storing new default value '$valueToStore' for parameter '$name' to default value store.") $defaultValueStore[$name] = $valueToStore } $flags.DefaultValueStoreDirty = $true } } # Make template defined parameters available as a PowerShell variable PLASTER_PARAM_<parameterName>. SetPlasterVariable -Name $name -Value $value -IsParam $true } function ProcessMessage([ValidateNotNull()]$Node) { $text = InterpolateAttributeValue $Node.InnerText '<message>' $nonewline = $Node.nonewline -eq 'true' # Eliminate whitespace before and after the text that just happens to get inserted because you want # the text on different lines than the start/end element tags. $trimmedText = $text -replace '^[ \t]*\n','' -replace '\n[ \t]*$','' $condition = $Node.condition if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) { $debugText = $trimmedText -replace '\r|\n',' ' $maxLength = [Math]::Min(40, $debugText.Length) $PSCmdlet.WriteDebug("Skipping message '$($debugText.Substring(0, $maxLength))', condition evaluated to false.") return } Write-Host $trimmedText -NoNewline:($nonewline -eq 'true') } function CopyModuleManifestPropertyToHashtable([PSModuleInfo]$oldModuleManifest, [hashtable]$hashtable, [string[]]$Property) { foreach ($prop in $Property) { if ($oldModuleManifest.$prop) { $hashtable["$prop"] = $oldModuleManifest.$prop } } } function ProcessNewModuleManifest([ValidateNotNull()]$Node) { $moduleVersion = InterpolateAttributeValue $Node.moduleVersion (GetErrorLocationNewModManifestAttrVal moduleVersion) $rootModule = InterpolateAttributeValue $Node.rootModule (GetErrorLocationNewModManifestAttrVal rootModule) $author = InterpolateAttributeValue $Node.author (GetErrorLocationNewModManifestAttrVal author) $companyName = InterpolateAttributeValue $Node.companyName (GetErrorLocationNewModManifestAttrVal companyName) $description = InterpolateAttributeValue $Node.description (GetErrorLocationNewModManifestAttrVal description) $dstRelPath = InterpolateAttributeValue $Node.destination (GetErrorLocationNewModManifestAttrVal destination) # We could choose to not check this if the condition eval'd to false # but I think it is better to let the template author know they've broken the # rules for any of the file directives (not just the ones they're testing/enabled). if ([System.IO.Path]::IsPathRooted($dstRelPath)) { throw ($LocalizedData.ErrorPathMustBeRelativePath_F2 -f $dstRelPath,$Node.LocalName) } $dstPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath((Join-Path $DestinationPath $dstRelPath)) $condition = $Node.condition if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) { $PSCmdlet.WriteDebug("Skipping module manifest generation for '$dstPath', condition evaluated to false.") return } $encoding = $Node.encoding if (!$encoding) { $encoding = $DefaultEncoding } if ($PSCmdlet.ShouldProcess($dstPath, $LocalizedData.ShouldProcessNewModuleManifest)) { $manifestDir = Split-Path $dstPath -Parent if (!(Test-Path $manifestDir)) { VerifyPathIsUnderDestinationPath $manifestDir Write-Verbose ($LocalizedData.NewModManifest_CreatingDir_F1 -f $manifestDir) New-Item $manifestDir -ItemType Directory > $null } $newModuleManifestParams = @{} # If there is an existing module manifest, load it so we can reuse old values not specified by # template. if (Test-Path -LiteralPath $dstPath) { $oldModuleManifest = Test-ModuleManifest -Path $dstPath -ErrorAction SilentlyContinue if ($? -and $oldModuleManifest) { $props = 'Guid', 'Description', 'DefaultCommandPrefix', 'RootModule', 'AliasesToExport', 'CmdletsToExport', 'DscResourcesToExport', 'VariablesToExport', 'FormatsToProcess', 'TypesToProcess', 'ScriptsToProcess' CopyModuleManifestPropertyToHashtable $oldModuleManifest $newModuleManifestParams $props } } if (![string]::IsNullOrWhiteSpace($moduleVersion)) { $newModuleManifestParams['ModuleVersion'] = $moduleVersion } if (![string]::IsNullOrWhiteSpace($rootModule)) { $newModuleManifestParams['RootModule'] = $rootModule } if (![string]::IsNullOrWhiteSpace($author)) { $newModuleManifestParams['Author'] = $author } if (![string]::IsNullOrWhiteSpace($companyName)) { $newModuleManifestParams['CompanyName'] = $companyName } if (![string]::IsNullOrWhiteSpace($description)) { $newModuleManifestParams['Description'] = $description } $tempFile = $null try { $tempFileBaseName = "moduleManifest-" + [Guid]::NewGuid() $tempFile = [System.IO.Path]::GetTempPath() + "${tempFileBaseName}.psd1" $PSCmdlet.WriteDebug("Created temp file for new module manifest - $tempFile") $newModuleManifestParams['Path'] = $tempFile # Generate manifest into a temp file. New-ModuleManifest @newModuleManifestParams # Typically the manifest is re-written with a new encoding (UTF8-NoBOM) because Git hates UTF-16. $content = Get-Content -LiteralPath $tempFile -Raw # Replace the temp filename in the generated manifest file's comment header with the actual filename. $dstBaseName = [System.IO.Path]::GetFileNameWithoutExtension($dstPath) $content = $content -replace "(?<=\s*#.*?)$tempFileBaseName", $dstBaseName WriteContentWithEncoding -Path $tempFile -Content $content -Encoding $encoding CopyFileWithConflictDetection $tempFile $dstPath } finally { if ($tempFile -and (Test-Path $tempFile)) { Remove-Item -LiteralPath $tempFile $PSCmdlet.WriteDebug("Removed temp file for new module manifest - $tempFile") } } } } # # Begin ProcessFile helper methods # function NewBackupFilename([string]$Path) { $dir = [System.IO.Path]::GetDirectoryName($Path) $basename = [System.IO.Path]::GetFileNameWithoutExtension($Path) $backupPath = Join-Path -Path $dir -ChildPath "${basename}.bak" $i = 1; while (Test-Path -LiteralPath $backupPath) { $backupPath = Join-Path -Path $dir -ChildPath "${basename}.bak$i" $i++ } $backupPath } function AreFilesIdentical($Path1, $Path2) { $file1 = Get-Item -LiteralPath $Path1 -Force $file2 = Get-Item -LiteralPath $Path2 -Force if ($file1.Length -ne $file2.Length) { return $false } $hash1 = (Get-FileHash -LiteralPath $path1 -Algorithm SHA1).Hash $hash2 = (Get-FileHash -LiteralPath $path2 -Algorithm SHA1).Hash $hash1 -eq $hash2 } function NewFileSystemCopyInfo([string]$srcPath, [string]$dstPath) { [PSCustomObject]@{SrcFileName=$srcPath; DstFileName=$dstPath} } function ExpandFileSourceSpec([string]$srcRelPath, [string]$dstRelPath) { $srcPath = Join-Path $templateAbsolutePath $srcRelPath $dstPath = Join-Path $destinationAbsolutePath $dstRelPath if ($srcRelPath.IndexOfAny([char[]]('*','?')) -lt 0) { # No wildcard spec in srcRelPath so return info on single file. # Also, if dstRelPath is empty, then use source rel path. if (!$dstRelPath) { $dstPath = Join-Path $destinationAbsolutePath $srcRelPath } return NewFileSystemCopyInfo $srcPath $dstPath } # Prepare parameter values for call to Get-ChildItem to get list of files based on wildcard spec. $gciParams = @{} $parent = Split-Path $srcPath -Parent $leaf = Split-Path $srcPath -Leaf $gciParams['LiteralPath'] = $parent $gciParams['File'] = $true if ($leaf -eq '**') { $gciParams['Recurse'] = $true } else { if ($leaf.IndexOfAny([char[]]('*','?')) -ge 0) { $gciParams['Filter'] = $leaf } $leaf = Split-Path $parent -Leaf if ($leaf -eq '**') { $parent = Split-Path $parent -Parent $gciParams['LiteralPath'] = $parent $gciParams['Recurse'] = $true } } $srcRelRootPathLength = $gciParams['LiteralPath'].Length # Generate a FileCopyInfo object for every file expanded by the wildcard spec. $files = @(Microsoft.PowerShell.Management\Get-ChildItem @gciParams) foreach ($file in $files) { $fileSrcPath = $file.FullName $relPath = $fileSrcPath.Substring($srcRelRootPathLength) $fileDstPath = Join-Path $dstPath $relPath NewFileSystemCopyInfo $fileSrcPath $fileDstPath } # Copy over empty directories - if any. $gciParams.Remove('File') $gciParams['Directory'] = $true $dirs = @(Microsoft.PowerShell.Management\Get-ChildItem @gciParams | Where-Object {$_.GetFileSystemInfos().Length -eq 0}) foreach ($dir in $dirs) { $dirSrcPath = $dir.FullName $relPath = $dirSrcPath.Substring($srcRelRootPathLength) $dirDstPath = Join-Path $dstPath $relPath NewFileSystemCopyInfo $dirSrcPath $dirDstPath } } # Plaster zen for file handling. All file related operations should use this method # to actually write/overwrite/modify files in the DestinationPath. This method # handles detecting conflicts, gives the user a chance to determine how to handle # conflicts. The user can choose to use the Force parameter to force the overwriting # of existing files at the destination path. # File processing (expanding substitution variable, modifying file contents) should always # be done to a temp file (be sure to always remove temp file when done). That temp file # is what gets passed to this function as the $SrcPath. This allows Plaster to alert the # user when the repeated application of a template will modify any existing file. # NOTE: Plaster keeps track of which files it has "created" (as opposed to overwritten) # so that any later change to that file doesn't trigger conflict handling. function CopyFileWithConflictDetection([string]$SrcPath, [string]$DstPath) { # Just double-checking that DstPath parameter is an absolute path otherwise # it could fail the check that the DstPath is under the overall DestinationPath. if (![System.IO.Path]::IsPathRooted($DstPath)) { $DstPath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($DstPath) } # Check if DstPath file conflicts with an existing SrcPath file. $operation = $LocalizedData.OpCreate $opmessage = (ConvertToDestinationRelativePath $DstPath) if (Test-Path -LiteralPath $DstPath) { if (AreFilesIdentical $SrcPath $DstPath) { $operation = $LocalizedData.OpIdentical } elseif ($templateCreatedFiles.ContainsKey($DstPath)) { # Plaster created this file previously during template invocation # therefore, there is no conflict. We're simply updating the file. $operation = $LocalizedData.OpUpdate } elseif ($Force) { $operation = $LocalizedData.OpForce } else { $operation = $LocalizedData.OpConflict } } # Copy the file to the destination if ($PSCmdlet.ShouldProcess($DstPath, $operation)) { WriteOperationStatus $operation $opmessage if ($operation -eq $LocalizedData.OpIdentical) { # If the files are identical, no need to do anything return } if (($operation -eq $LocalizedData.OpCreate) -or ($operation -eq $LocalizedData.OpUpdate)) { Copy-Item -LiteralPath $SrcPath -Destination $DstPath $templateCreatedFiles[$DstPath] = $null } elseif ($Force -or $PSCmdlet.ShouldContinue(($LocalizedData.OverwriteFile_F1 -f $DstPath), $LocalizedData.FileConflict, [ref]$fileConflictConfirmYesToAll, [ref]$fileConflictConfirmNoToAll)) { $backupFilename = NewBackupFilename $DstPath Copy-Item -LiteralPath $DstPath -Destination $backupFilename Copy-Item -LiteralPath $SrcPath -Destination $DstPath $templateCreatedFiles[$DstPath] = $null } } } # # End ProcessFile helper methods # # Processes both the <file> and <templateFile> directives. function ProcessFile([ValidateNotNull()]$Node) { $srcRelPath = InterpolateAttributeValue $Node.source (GetErrorLocationFileAttrVal $Node.localName source) $dstRelPath = InterpolateAttributeValue $Node.destination (GetErrorLocationFileAttrVal $Node.localName destination) # We could choose to not check this if the condition eval'd to false # but I think it is better to let the template author know they've broken the # rules for any of the file directives (not just the ones they're testing/enabled). if ([System.IO.Path]::IsPathRooted($srcRelPath)) { throw ($LocalizedData.ErrorPathMustBeRelativePath_F2 -f $srcRelPath,$Node.LocalName) } if ([System.IO.Path]::IsPathRooted($dstRelPath)) { throw ($LocalizedData.ErrorPathMustBeRelativePath_F2 -f $dstRelPath,$Node.LocalName) } $condition = $Node.condition if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) { $PSCmdlet.WriteDebug("Skipping $($Node.localName) '$srcRelPath' -> '$dstRelPath', condition evaluated to false.") return } # Check if node is the specialized, <templateFile> node. # Only <templateFile> nodes expand templates and use the encoding attribute. $isTemplateFile = $Node.localName -eq 'templateFile' if ($isTemplateFile) { $encoding = $Node.encoding if (!$encoding) { $encoding = $DefaultEncoding } } # Check if source specifies a wildcard and if so, expand the wildcard # and then process each file system object (file or empty directory). $fileSystemCopyInfoObjs = ExpandFileSourceSpec $srcRelPath $dstRelPath foreach ($fileSystemCopyInfo in $fileSystemCopyInfoObjs) { $srcPath = $fileSystemCopyInfo.SrcFileName $dstPath = $fileSystemCopyInfo.DstFileName # The file's destination path must be under the DestinationPath specified by the user. VerifyPathIsUnderDestinationPath $dstPath # Check to see if we're copying an empty dir if (Test-Path -LiteralPath $srcPath -PathType Container) { if (!(Test-Path -LiteralPath $dstPath)) { if ($PSCmdlet.ShouldProcess($parentDir, $LocalizedData.ShouldProcessCreateDir)) { WriteOperationStatus $LocalizedData.OpCreate ` ($dstRelPath.TrimEnd(([char]'\'),([char]'/')) + [System.IO.Path]::DirectorySeparatorChar) New-Item -Path $dstPath -ItemType Directory > $null } } continue } # If the file's parent dir doesn't exist, create it. $parentDir = Split-Path $dstPath -Parent if (!(Test-Path -LiteralPath $parentDir)) { if ($PSCmdlet.ShouldProcess($parentDir, $LocalizedData.ShouldProcessCreateDir)) { New-Item -Path $parentDir -ItemType Directory > $null } } $tempFile = $null try { # If processing a <templateFile>, copy to a temp file to expand the template file, # then apply the normal file conflict detection/resolution handling. $target = $LocalizedData.TempFileTarget_F1 -f (ConvertToDestinationRelativePath $dstPath) if ($isTemplateFile -and $PSCmdlet.ShouldProcess($target, $LocalizedData.ShouldProcessExpandTemplate)) { $content = Get-Content -LiteralPath $srcPath -Raw # Eval script expression delimiters if ($content -and ($content.Count -gt 0)) { $newContent = [regex]::Replace($content, '(<%=)(.*?)(%>)', { param($match) $expr = $match.groups[2].value $res = EvaluateExpression $expr "templateFile '$srcRelPath'" $PSCmdlet.WriteDebug("Replacing '$expr' with '$res' in contents of template file '$srcPath'") $res }, @('IgnoreCase')) # Eval script block delimiters $newContent = [regex]::Replace($newContent, '(^<%)(.*?)(^%>)', { param($match) $expr = $match.groups[2].value $res = EvaluateScript $expr "templateFile '$srcRelPath'" $res = $res -join [System.Environment]::NewLine $PSCmdlet.WriteDebug("Replacing '$expr' with '$res' in contents of template file '$srcPath'") $res }, @('IgnoreCase', 'SingleLine', 'MultiLine')) $srcPath = $tempFile = [System.IO.Path]::GetTempFileName() $PSCmdlet.WriteDebug("Created temp file for expanded templateFile - $tempFile") WriteContentWithEncoding -Path $tempFile -Content $newContent -Encoding $encoding } else { $PSCmdlet.WriteDebug("Skipping template file expansion for $($Node.localName) '$srcPath', file is empty.") } } CopyFileWithConflictDetection $srcPath $dstPath } finally { if ($tempFile -and (Test-Path $tempFile)) { Remove-Item -LiteralPath $tempFile $PSCmdlet.WriteDebug("Removed temp file for expanded templateFile - $tempFile") } } } } function ProcessModifyFile([ValidateNotNull()]$Node) { $path = InterpolateAttributeValue $Node.path (GetErrorLocationModifyAttrVal path) # We could choose to not check this if the condition eval'd to false # but I think it is better to let the template author know they've broken the # rules for any of the file directives (not just the ones they're testing/enabled). if ([System.IO.Path]::IsPathRooted($path)) { throw ($LocalizedData.ErrorPathMustBeRelativePath_F2 -f $path,$Node.LocalName) } $filePath = $PSCmdlet.GetUnresolvedProviderPathFromPSPath((Join-Path $DestinationPath $path)) # The file's path must be under the DestinationPath specified by the user. VerifyPathIsUnderDestinationPath $filePath $condition = $Node.condition if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) { $PSCmdlet.WriteDebug("Skipping $($Node.LocalName) of '$filePath', condition evaluated to false.") return } $fileContent = [string]::Empty if (Test-Path -LiteralPath $filePath) { $fileContent = Get-Content -LiteralPath $filePath -Raw } # Set a Plaster (non-parameter) variable in this and the constrained runspace. SetPlasterVariable -Name FileContent -Value $fileContent -IsParam $false $encoding = $Node.encoding if (!$encoding) { $encoding = $DefaultEncoding } # If processing a <modify> directive, write the modified contents to a temp file, # then apply the normal file conflict detection/resolution handling. $target = $LocalizedData.TempFileTarget_F1 -f $filePath if ($PSCmdlet.ShouldProcess($target, $LocalizedData.OpModify)) { WriteOperationStatus $LocalizedData.OpModify ($LocalizedData.TempFileOperation_F1 -f (ConvertToDestinationRelativePath $filePath)) $modified = $false foreach ($childNode in $Node.ChildNodes) { if ($childNode -isnot [System.Xml.XmlElement]) { continue } switch ($childNode.LocalName) { 'replace' { $condition = $childNode.condition if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)><$($childNode.LocalName)>'")) { $PSCmdlet.WriteDebug("Skipping $($Node.LocalName) $($childNode.LocalName) of '$filePath', condition evaluated to false.") continue } if ($childNode.original -is [string]) { $original = $childNode.original } else { $original = $childNode.original.InnerText } if ($childNode.original.expand -eq 'true') { $original = InterpolateAttributeValue $original (GetErrorLocationModifyAttrVal original) } if ($childNode.substitute -is [string]) { $substitute = $childNode.substitute } else { $substitute = $childNode.substitute.InnerText } if ($childNode.substitute.expand -eq 'true') { $substitute = InterpolateAttributeValue $substitute (GetErrorLocationModifyAttrVal substitute) } $fileContent = $fileContent -replace $original,$substitute # Update the Plaster (non-parameter) variable's value in this and the constrained runspace. SetPlasterVariable -Name FileContent -Value $fileContent -IsParam $false $modified = $true } default { throw ($LocalizedData.UnrecognizedContentElement_F1 -f $childNode.LocalName) } } } $tempFile = $null try { # We could use CopyFileWithConflictDetection to handle the "identical" (not modified) case # but if nothing was changed, I'd prefer not to generate a temp file, copy the unmodified contents # into that temp file with hopefully the right encoding and then potentially overwrite the original file # (different encoding will make the files look different) with the same contents but different encoding. # If the intent of the <modify> was simple to change an existing file's encoding then the directive will # need to make a whitespace change to the file. if ($modified) { $tempFile = [System.IO.Path]::GetTempFileName() $PSCmdlet.WriteDebug("Created temp file for modified file - $tempFile") WriteContentWithEncoding -Path $tempFile -Content $PLASTER_FileContent -Encoding $encoding CopyFileWithConflictDetection $tempFile $filePath } else { WriteOperationStatus $LocalizedData.OpIdentical (ConvertToDestinationRelativePath $filePath) } } finally { if ($tempFile -and (Test-Path $tempFile)) { Remove-Item -LiteralPath $tempFile $PSCmdlet.WriteDebug("Removed temp file for modified file - $tempFile") } } } } function ProcessRequireModule([ValidateNotNull()]$Node) { $name = $Node.name $condition = $Node.condition if ($condition -and !(EvaluateConditionAttribute $condition "'<$($Node.LocalName)>'")) { $PSCmdlet.WriteDebug("Skipping $($Node.localName) for module '$name', condition evaluated to false.") return } $message = InterpolateAttributeValue $Node.message (GetErrorLocationRequireModuleAttrVal $name message) $minimumVersion = $Node.minimumVersion $maximumVersion = $Node.maximumVersion $requiredVersion = $Node.requiredVersion $getModuleParams = @{ ListAvailable = $true ErrorAction = 'SilentlyContinue' } # Configure $getModuleParams with correct parameters based on parameterset to be used. # Also construct an array of version strings that can be displayed to the user. $versionInfo = @() if ($requiredVersion) { $getModuleParams["FullyQualifiedName"] = @{ModuleName = $name; RequiredVersion = $requiredVersion} $versionInfo += $LocalizedData.RequireModuleRequiredVersion_F1 -f $requiredVersion } elseif ($minimumVersion -or $maximumVersion) { $getModuleParams["FullyQualifiedName"] = @{ModuleName = $name} if ($minimumVersion) { $getModuleParams.FullyQualifiedName["ModuleVersion"] = $minimumVersion $versionInfo += $LocalizedData.RequireModuleMinVersion_F1 -f $minimumVersion } if ($maximumVersion) { $getModuleParams.FullyQualifiedName["MaximumVersion"] = $maximumVersion $versionInfo += $LocalizedData.RequireModuleMaxVersion_F1 -f $maximumVersion } } else { $getModuleParams["Name"] = $name } # Flatten array of version strings into a single string. $versionRequirements = "" if ($versionInfo.Length -gt 0) { $OFS = ", " $versionRequirements = " ($versionInfo)" } # PowerShell v3 Get-Module command does not have the FullyQualifiedName parameter. if ($PSVersionTable.PSVersion.Major -lt 4) { $getModuleParams.Remove("FullyQualifiedName") $getModuleParams["Name"] = $name } $module = Get-Module @getModuleParams if ($null -ne $module) { if ($PSVersionTable.PSVersion.Major -gt 3) { WriteOperationStatus $LocalizedData.OpVerify ($LocalizedData.RequireModuleVerified_F2 -f $name,$versionRequirements) } else { # On V3, we have to the version matching with the results that Get-Module return. $installedVersion = $module | Sort-Object Version -Descending | Select-Object -First 1 | Foreach-Object Version if ($installedVersion.Build -eq -1) { $installedVersion = [System.Version]"${installedVersion}.0.0" } elseif ($installedVersion.Revision -eq -1) { $installedVersion = [System.Version]"${installedVersion}.0" } if (($requiredVersion -and ($installedVersion -ne $requiredVersion)) -or ($minimumVersion -and ($installedVersion -lt $minimumVersion)) -or ($maximumVersion -and ($installedVersion -gt $maximumVersion))) { WriteOperationStatus $LocalizedData.OpVerify ($LocalizedData.RequireModuleVerified_F2 -f $name,$versionRequirements) } } } else { WriteOperationStatus $LocalizedData.OpMissing ($LocalizedData.RequireModuleMissing_F2 -f $name,$versionRequirements) if ($message) { WriteOperationAdditionalStatus $message } } } } end { try { # Process parameters foreach ($node in $manifest.plasterManifest.parameters.ChildNodes) { if ($node -isnot [System.Xml.XmlElement]) { continue } switch ($node.LocalName) { 'parameter' { ProcessParameter $node } default { throw ($LocalizedData.UnrecognizedParametersElement_F1 -f $node.LocalName) } } } # Outputs the processed template parameters to the debug stream $parameters = Get-Variable -Name PLASTER_* | Out-String $PSCmdlet.WriteDebug("Parameter values are:`n$($parameters -split "`n")") # Stores any updated default values back to the store file. if ($flags.DefaultValueStoreDirty) { $directory = Split-Path $defaultValueStorePath -Parent if (!(Test-Path $directory)) { $PSCmdlet.WriteDebug("Creating directory for template's DefaultValueStore '$directory'.") New-Item $directory -ItemType Directory > $null } $PSCmdlet.WriteDebug("DefaultValueStore is dirty, saving updated values to '$defaultValueStorePath'.") $defaultValueStore | Export-Clixml -LiteralPath $defaultValueStorePath } # Output the DestinationPath $LocalizedData.DestPath_F1 -f $destinationAbsolutePath # Process content foreach ($node in $manifest.plasterManifest.content.ChildNodes) { if ($node -isnot [System.Xml.XmlElement]) { continue } switch -Regex ($node.LocalName) { 'file|templateFile' { ProcessFile $node; break } 'message' { ProcessMessage $node; break } 'modify' { ProcessModifyFile $node; break } 'newModuleManifest' { ProcessNewModuleManifest $node; break } 'requireModule' { ProcessRequireModule $node; break } default { throw ($LocalizedData.UnrecognizedContentElement_F1 -f $node.LocalName) } } } } finally { # Dispose of the ConstrainedRunspace. if ($constrainedRunspace) { $constrainedRunspace.Dispose() $constrainedRunspace = $null } } } } ############################################################################### # Helper functions ############################################################################### function InitializePredefinedVariables([string]$TemplatePath, [string]$DestPath) { # Always set these variables, even if the command has been run with -WhatIf $WhatIfPreference = $false Set-Variable -Name PLASTER_TemplatePath -Value $TemplatePath.TrimEnd('\','/') -Scope Script $destName = Split-Path -Path $DestPath -Leaf Set-Variable -Name PLASTER_DestinationPath -Value $DestPath.TrimEnd('\','/') -Scope Script Set-Variable -Name PLASTER_DestinationName -Value $destName -Scope Script Set-Variable -Name PLASTER_DirSepChar -Value ([System.IO.Path]::DirectorySeparatorChar) -Scope Script Set-Variable -Name PLASTER_HostName -Value $Host.Name -Scope Script Set-Variable -Name PLASTER_Version -Value $MyInvocation.MyCommand.Module.Version -Scope Script Set-Variable -Name PLASTER_Guid1 -Value ([Guid]::NewGuid()) -Scope Script Set-Variable -Name PLASTER_Guid2 -Value ([Guid]::NewGuid()) -Scope Script Set-Variable -Name PLASTER_Guid3 -Value ([Guid]::NewGuid()) -Scope Script Set-Variable -Name PLASTER_Guid4 -Value ([Guid]::NewGuid()) -Scope Script Set-Variable -Name PLASTER_Guid5 -Value ([Guid]::NewGuid()) -Scope Script $now = [DateTime]::Now Set-Variable -Name PLASTER_Date -Value ($now.ToShortDateString()) -Scope Script Set-Variable -Name PLASTER_Time -Value ($now.ToShortTimeString()) -Scope Script Set-Variable -Name PLASTER_Year -Value ($now.Year) -Scope Script } function GetPlasterManifestPathForCulture([string]$TemplatePath, [ValidateNotNull()][CultureInfo]$Culture) { if (![System.IO.Path]::IsPathRooted($TemplatePath)) { $TemplatePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($TemplatePath) } # Check for culture-locale first. $plasterManifestBasename = "plasterManifest" $plasterManifestFilename = "${plasterManifestBasename}_$($culture.Name).xml" $plasterManifestPath = Join-Path $TemplatePath $plasterManifestFilename if (Test-Path $plasterManifestPath) { return $plasterManifestPath } # Check for culture next. if ($culture.Parent.Name) { $plasterManifestFilename = "${plasterManifestBasename}_$($culture.Parent.Name).xml" $plasterManifestPath = Join-Path $TemplatePath $plasterManifestFilename if (Test-Path $plasterManifestPath) { return $plasterManifestPath } } # Fallback to invariant culture manifest. $plasterManifestPath = Join-Path $TemplatePath "${plasterManifestBasename}.xml" if (Test-Path $plasterManifestPath) { return $plasterManifestPath } $null } # SIG # Begin signature block # MIIasAYJKoZIhvcNAQcCoIIaoTCCGp0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEw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QDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQ # Q0ECEzMAAAC37gGv+vDHqLsAAAAAALcwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJ # AzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE2MTIxNjE5MjY1NlowIwYJ # KoZIhvcNAQkEMRYEFJIRTxtixcKDpXCVCbDCuezxpo7MMA0GCSqGSIb3DQEBBQUA # BIIBALTX1iMzgndc+cgdtmemH/l/iLJq3MtC+7e0islN3FIkcdyhSA3ea7Zes/lX # 4kQAiQqBkeQVGU167npQaLI5rFZiXeAGHhFtFrCMvvgOS93q9KSMHnd6KcWAHx1E # iMtpMtR5kx/eaWNyy4pxzLmDY9/vX+Yq0DniJ05E8MoOnWiH8wmQgZkOFnlph27B # TM1nUVHXR3MoHLSZeAug/9UUukw6cW48Zq4/j8KFH83VlwHbCT34QF2TU+d5coxh # Ra/c2g16FYJ0gZYNty8k/5I8QYChJH8shqOs48F+lT4HJyIUquvOBIJcU61fOROO # 3SOlel7kXgPx2d1f5H/tfvoAQFU= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Plaster/1.0.1/NewPlasterManifest.ps1
NewPlasterManifest.ps1
function New-PlasterManifest { [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter()] [ValidateNotNullOrEmpty()] [string] $Path = "$pwd\plasterManifest.xml", [Parameter(Mandatory=$true)] [ValidatePattern('^[0-9a-zA-Z_-]+$')] [string] $TemplateName, [Parameter()] [Guid] $Id = [guid]::NewGuid(), [Parameter()] [ValidateNotNullOrEmpty()] [ValidatePattern('^\d+\.\d+(\.\d+((\.\d+|(\+|-).*)?)?)?$')] [string] $TemplateVersion = "1.0.0", [Parameter()] [ValidateNotNullOrEmpty()] [string] $Title = $TemplateName, [Parameter()] [ValidateNotNullOrEmpty()] [string] $Description, [Parameter()] [string[]] $Tags, [Parameter()] [ValidateNotNullOrEmpty()] [string] $Author, [Parameter()] [switch] $AddContent ) begin { $resolvedPath = $PSCmdLet.GetUnresolvedProviderPathFromPSPath($Path) $manifestStr = @" <?xml version="1.0" encoding="utf-8"?> <plasterManifest schemaVersion="$LatestSupportedSchemaVersion" xmlns="http://www.microsoft.com/schemas/PowerShell/Plaster/v1"> <metadata> <name></name> <id></id> <version></version> <title></title> <description></description> <author></author> <tags></tags> </metadata> <parameters> </parameters> <content> </content> </plasterManifest> "@ } end { $manifest = [xml]$manifestStr # Set via .innerText to get .NET to encode special XML chars as entity references. $manifest.plasterManifest.metadata["name"].innerText = "$TemplateName" $manifest.plasterManifest.metadata["id"].innerText = "$Id" $manifest.plasterManifest.metadata["version"].innerText = "$TemplateVersion" $manifest.plasterManifest.metadata["title"].innerText = "$Title" $manifest.plasterManifest.metadata["description"].innerText = "$Description" $manifest.plasterManifest.metadata["author"].innerText = "$Author" $OFS = ", " $manifest.plasterManifest.metadata["tags"].innerText = "$Tags" if ($AddContent) { $baseDir = Split-Path $Path -Parent $filenames = Get-ChildItem $baseDir -Recurse -File -Name foreach ($filename in $filenames) { if ($filename -match "plasterManifest.*\.xml") { continue } $fileElem = $manifest.CreateElement('file', $TargetNamespace) $srcAttr = $manifest.CreateAttribute("source") $srcAttr.Value = $filename $fileElem.Attributes.Append($srcAttr) > $null $dstAttr = $manifest.CreateAttribute("destination") $dstAttr.Value = $filename $fileElem.Attributes.Append($dstAttr) > $null $manifest.plasterManifest["content"].AppendChild($fileElem) > $null } } # This configures the XmlWriter to put attributes on a new line $xmlWriterSettings = New-Object System.Xml.XmlWriterSettings $xmlWriterSettings.Indent = $true $xmlWriterSettings.NewLineOnAttributes = $true try { if ($PSCmdlet.ShouldProcess($resolvedPath, $LocalizedData.ShouldCreateNewPlasterManifest)) { $xmlWriter = [System.Xml.XmlWriter]::Create($resolvedPath, $xmlWriterSettings) $manifest.Save($xmlWriter) } } finally { if ($xmlWriter) { $xmlWriter.Dispose() } } } } # SIG # Begin signature block # MIIasAYJKoZIhvcNAQcCoIIaoTCCGp0CAQExCzAJBg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A1UE # CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z # b2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQ # Q0ECEzMAAAC37gGv+vDHqLsAAAAAALcwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJ # AzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE2MTIxNjE5MjY1NVowIwYJ # KoZIhvcNAQkEMRYEFF1UbHfskUdxuQHrqmoUGCrQRcyFMA0GCSqGSIb3DQEBBQUA # BIIBAJL8jvt70ocTgYo4V5/9mZhXLWWjN9x7zpbiADzhqk9zc7GBl0lJWtYW3AT3 # JpIw5EWuZ7ijblhpEDNwZ10FviUXTw9s8Wrr3cVM37Ov02IjTorWskLWU9KFBMP1 # j+J04E130sxLtPhU+6pp+ZsnAL+sKpepXK+U3dc83Lkh8lHqBvB4WIO5y3PtQgO6 # dE6nzoczqtxz1BzgZTmYxnxjppzcCnhlRidXpRebu6/mGyt7G425GgJbve/0MXeZ # Nug1IXiOP9MWdtIfgH8OJVTr4Mcn/r/0S0Cah09FxsK4pCVw/Hs3ayuhisYlFXO2 # AY5r1wMT68Ot/3sFbXC3LOE2bTY= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Plaster/1.0.1/TestPlasterManifest.ps1
TestPlasterManifest.ps1
function Test-PlasterManifest { [CmdletBinding()] [OutputType([System.Xml.XmlDocument])] param( [Parameter(Position=0, ParameterSetName="Path", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies a path to a plasterManifest.xml file.")] [Alias("PSPath")] [ValidateNotNullOrEmpty()] [string[]] $Path = @("$pwd\plasterManifest.xml") ) begin { $schemaPath = "$PSScriptRoot\Schema\PlasterManifest-v1.xsd" # Schema validation is not available on .NET Core - at the moment. if ('System.Xml.Schema.XmlSchemaSet' -as [type]) { $xmlSchemaSet = New-Object System.Xml.Schema.XmlSchemaSet $xmlSchemaSet.Add($TargetNamespace, $schemaPath) > $null } else { $PSCmdLet.WriteWarning($LocalizedData.TestPlasterNoXmlSchemaValidationWarning) } } process { foreach ($aPath in $Path) { $aPath = $PSCmdLet.GetUnresolvedProviderPathFromPSPath($aPath) if (!(Test-Path -LiteralPath $aPath)) { $ex = New-Object System.Management.Automation.ItemNotFoundException ($LocalizedData.ErrorPathDoesNotExist_F1 -f $aPath) $category = [System.Management.Automation.ErrorCategory]::ObjectNotFound $errRecord = New-Object System.Management.Automation.ErrorRecord $ex,'PathNotFound',$category,$aPath $PSCmdLet.WriteError($errRecord) return } $filename = Split-Path $aPath -Leaf # Verify the manifest has the correct filename. Allow for localized template manifest files as well. if (!(($filename -eq 'plasterManifest.xml') -or ($filename -match 'plasterManifest_[a-zA-Z]+(-[a-zA-Z]+){0,2}.xml'))) { Write-Error ($LocalizedData.ManifestWrongFilename_F1 -f $filename) return } # Verify the manifest loads into an XmlDocument i.e. verify it is well-formed. $manifest = $null try { $manifest = [xml](Get-Content $aPath) } catch { $ex = New-Object System.Exception ($LocalizedData.ManifestNotWellFormedXml_F2 -f $aPath, $_.Exception.Message), $_.Exception $category = [System.Management.Automation.ErrorCategory]::InvalidData $errRecord = New-Object System.Management.Automation.ErrorRecord $ex,'InvalidManifestFile',$category,$aPath $psCmdlet.WriteError($errRecord) return } # Validate the manifest contains the required root element and target namespace that the following # XML schema validation will apply to. if (!$manifest.plasterManifest) { Write-Error ($LocalizedData.ManifestMissingDocElement_F2 -f $aPath,$TargetNamespace) return } if ($manifest.plasterManifest.NamespaceURI -cne $TargetNamespace) { Write-Error ($LocalizedData.ManifestMissingDocTargetNamespace_F2 -f $aPath,$TargetNamespace) return } # Valid flag is stashed in a hashtable so the ValidationEventHandler scriptblock can set the value. $manifestIsValid = @{Value = $true} # Configure an XmlReader and XmlReaderSettings to perform schema validation on xml file. $xmlReaderSettings = New-Object System.Xml.XmlReaderSettings # Schema validation is not available on .NET Core - at the moment. if ($xmlSchemaSet) { $xmlReaderSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ReportValidationWarnings $xmlReaderSettings.ValidationType = [System.Xml.ValidationType]::Schema $xmlReaderSettings.Schemas = $xmlSchemaSet } # Schema validation is not available on .NET Core - at the moment. if ($xmlSchemaSet) { # Event handler scriptblock for the ValidationEventHandler event. $validationEventHandler = { param($sender, $eventArgs) if ($eventArgs.Severity -eq [System.Xml.Schema.XmlSeverityType]::Error) { Write-Verbose ($LocalizedData.ManifestSchemaValidationError_F2 -f $aPath,$eventArgs.Message) $manifestIsValid.Value = $false } } $xmlReaderSettings.add_ValidationEventHandler($validationEventHandler) } [System.Xml.XmlReader]$xmlReader = $null try { $xmlReader = [System.Xml.XmlReader]::Create($aPath, $xmlReaderSettings) while ($xmlReader.Read()) {} } catch { Write-Error ($LocalizedData.ManifestErrorReading_F1 -f $_) $manifestIsValid.Value = $false } finally { # Schema validation is not available on .NET Core - at the moment. if ($xmlSchemaSet) { $xmlReaderSettings.remove_ValidationEventHandler($validationEventHandler) } if ($xmlReader) { $xmlReader.Dispose() } } # Validate default values for choice/multichoice parameters containing 1 or more ints $xpath = "//tns:parameter[@type='choice'] | //tns:parameter[@type='multichoice']" $choiceParameters = Select-Xml -Xml $manifest -XPath $xpath -Namespace @{tns=$TargetNamespace} foreach ($choiceParameterXmlInfo in $choiceParameters) { $choiceParameter = $choiceParameterXmlInfo.Node if (!$choiceParameter.default) { continue } if ($choiceParameter.type -eq 'choice') { if ($null -eq ($choiceParameter.default -as [int])) { $PSCmdLet.WriteVerbose(($LocalizedData.ManifestSchemaInvalidChoiceDefault_F3 -f $choiceParameter.default,$choiceParameter.name,$aPath)) $manifestIsValid.Value = $false } } else { if ($null -eq (($choiceParameter.default -split ',') -as [int[]])) { $PSCmdLet.WriteVerbose(($LocalizedData.ManifestSchemaInvalidMultichoiceDefault_F3 -f $choiceParameter.default,$choiceParameter.name,$aPath)) $manifestIsValid.Value = $false } } } # Validate that the requireModule attribute requiredVersion is mutually exclusive from both # the version and maximumVersion attributes. $requireModules = Select-Xml -Xml $manifest -XPath '//tns:requireModule' -Namespace @{tns = $TargetNamespace} foreach ($requireModuleInfo in $requireModules) { $requireModuleNode = $requireModuleInfo.Node if ($requireModuleNode.requiredVersion -and ($requireModuleNode.minimumVersion -or $requireModuleNode.maximumVersion)) { $PSCmdLet.WriteVerbose(($LocalizedData.ManifestSchemaInvalidRequireModuleAttrs_F2 -f $requireModuleNode.name,$aPath)) $manifestIsValid.Value = $false } } # Validate that all the condition attribute values are valid PowerShell script. $conditionAttrs = Select-Xml -Xml $manifest -XPath '//@condition' foreach ($conditionAttr in $conditionAttrs) { $tokens = $errors = $null $null = [System.Management.Automation.Language.Parser]::ParseInput($conditionAttr.Node.Value, [ref] $tokens, [ref] $errors) if ($errors.Count -gt 0) { $msg = $LocalizedData.ManifestSchemaInvalidCondition_F3 -f $conditionAttr.Node.Value, $aPath, $errors[0] $PSCmdLet.WriteVerbose($msg) $manifestIsValid.Value = $false } } # Validate all interpolated attribute values are valid within a PowerShell string interpolation context. $interpolatedAttrs = @(Select-Xml -Xml $manifest -XPath '//tns:parameter/@default' -Namespace @{tns = $TargetNamespace}) $interpolatedAttrs += @(Select-Xml -Xml $manifest -XPath '//tns:parameter/@prompt' -Namespace @{tns = $TargetNamespace}) $interpolatedAttrs += @(Select-Xml -Xml $manifest -XPath '//tns:content/tns:*/@*' -Namespace @{tns = $TargetNamespace}) foreach ($interpolatedAttr in $interpolatedAttrs) { $name = $interpolatedAttr.Node.LocalName if ($name -eq 'condition') { continue } $tokens = $errors = $null $value = $interpolatedAttr.Node.Value $null = [System.Management.Automation.Language.Parser]::ParseInput("`"$value`"", [ref] $tokens, [ref] $errors) if ($errors.Count -gt 0) { $ownerName = $interpolatedAttr.Node.OwnerElement.LocalName $msg = $LocalizedData.ManifestSchemaInvalidAttrValue_F5 -f $name, $value, $ownerName, $aPath, $errors[0] $PSCmdLet.WriteVerbose($msg) $manifestIsValid.Value = $false } } if ($manifestIsValid.Value) { # Verify manifest schema version is supported. $manifestSchemaVersion = [System.Version]$manifest.plasterManifest.schemaVersion # Use a simplified form (no patch version) of semver for checking XML schema version compatibility. if (($manifestSchemaVersion.Major -gt $LatestSupportedSchemaVersion.Major) -or (($manifestSchemaVersion.Major -eq $LatestSupportedSchemaVersion.Major) -and ($manifestSchemaVersion.Minor -gt $LatestSupportedSchemaVersion.Minor))) { Write-Error ($LocalizedData.ManifestSchemaVersionNotSupported_F2 -f $manifestSchemaVersion,$aPath) return } # Verify that the plasterVersion is supported. if ($manifest.plasterManifest.plasterVersion) { $requiredPlasterVersion = [System.Version]$manifest.plasterManifest.plasterVersion # Is user specifies major.minor, change build to 0 (from default of -1) so compare works correctly. if ($requiredPlasterVersion.Build -eq -1) { $requiredPlasterVersion = [System.Version]"${requiredPlasterVersion}.0" } if ($requiredPlasterVersion -gt $MyInvocation.MyCommand.Module.Version) { $plasterVersion = $manifest.plasterManifest.plasterVersion Write-Error ($LocalizedData.ManifestPlasterVersionNotSupported_F2 -f $aPath,$plasterVersion) return } } $manifest } else { if ($PSBoundParameters['Verbose']) { Write-Error ($LocalizedData.ManifestNotValid_F1 -f $aPath) } else { Write-Error ($LocalizedData.ManifestNotValidVerbose_F1 -f $aPath) } } } } } # SIG # Begin signature block # MIIasAYJKoZIhvcNAQcCoIIaoTCCGp0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUz1xAYESVHqjiwyuNG9OKupG6 # haagghWDMIIEwzCCA6ugAwIBAgITMwAAALfuAa/68MeouwAAAAAAtzANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z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Y0EPGSeMA0GCSqGSIb3DQEBBQUA # BIIBABCs31g9yg0NbI8eB2yGNjqu5xAM24gsZgANW315/a/5PciPxswj5l1bEiGp # RVEaL9Iy2EVBMqKwCsi4pjZjvxstdT/BNVgWZwH3n3o9W27uSHhO3KIIRXsq4n0s # FYYsVzGWE6MFX9x1H/OeID7RHJ1t9HMSXLS1mSHsznlVRDfbcjE0olCojzWsxrXs # ZTIIowGw0zxEQ8M8ZL5Zqn4aLzwwa+ltHuHNi/U0vuNip8TLAfxIqwiiuSxHhl35 # Gkb9ckO7fnKeUxRUioX4lPZ9jPm2mrVZPOfa/L6Qx4qzZJ8W1Bzzsbdx/5Z4aIGE # VroxuZAzr8dKuo27I87Z0kUi8aU= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Plaster/1.0.1/GetPlasterTemplate.ps1
GetPlasterTemplate.ps1
. $PSScriptRoot\GetModuleExtension.ps1 function Get-PlasterTemplate { [CmdletBinding()] param( [Parameter(Position=0, ParameterSetName="Path", HelpMessage="Specifies a path to a folder containing a Plaster template or multiple template folders. Can also be a path to plasterManifest.xml.")] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter(ParameterSetName="Path", HelpMessage="Indicates that this cmdlet gets the items in the specified locations and in all child items of the locations.")] [switch] $Recurse, [Parameter(Position=0, Mandatory=$true, ParameterSetName="IncludedTemplates", HelpMessage="Initiates a search for Plaster templates inside of installed modules.")] [switch] [Alias("IncludeModules")] $IncludeInstalledModules ) process { function CreateTemplateObjectFromManifest([System.IO.FileInfo]$manifestPath) { $manifestXml = Test-PlasterManifest -Path $manifestPath $metadata = $manifestXml["plasterManifest"]["metadata"] $manifestObj = [PSCustomObject]@{ Title = $metadata["title"].InnerText Author = $metadata["author"].InnerText Version = New-Object -TypeName "System.Version" -ArgumentList $metadata["version"].InnerText Description = $metadata["description"].InnerText Tags = $metadata["tags"].InnerText.split(",") | % { $_.Trim() } TemplatePath = $manifestPath.Directory.FullName } $manifestObj.PSTypeNames.Insert(0, "Microsoft.PowerShell.Plaster.PlasterTemplate") return $manifestObj } function GetManifestsUnderPath([string]$rootPath, [bool]$recurse) { $manifestPaths = Get-ChildItem -Path $rootPath -Include "plasterManifest.xml" -Recurse:$recurse foreach ($manifestPath in $manifestPaths) { CreateTemplateObjectFromManifest $manifestPath -ErrorAction SilentlyContinue } } if ($Path) { # Is this a folder path or a Plaster manifest file path? if (!$Recurse.IsPresent) { if (Test-Path $Path -PathType Container) { $Path = Resolve-Path "$Path/plasterManifest.xml" } # Use Test-PlasterManifest to load the manifest file Write-Verbose "Attempting to get Plaster template at path: $Path" CreateTemplateObjectFromManifest $Path } else { Write-Verbose "Attempting to get Plaster templates recursively under path: $Path" GetManifestsUnderPath $Path $Recurse.IsPresent } } else { # Return all templates included with Plaster GetManifestsUnderPath "$PSScriptRoot\Templates" $true if ($IncludeInstalledModules.IsPresent) { # Search for templates in module path $extensions = Get-ModuleExtension -ModuleName Plaster -ModuleVersion $PlasterVersion foreach ($extension in $extensions) { # Scan all module paths registered in the module foreach ($templatePath in $extension.Details.TemplatePaths) { $expandedTemplatePath = [System.IO.Path]::Combine( $extension.Module.ModuleBase, $templatePath, "plasterManifest.xml") CreateTemplateObjectFromManifest $expandedTemplatePath -ErrorAction SilentlyContinue } } } } } } # SIG # Begin signature block # MIIasAYJKoZIhvcNAQcCoIIaoTCCGp0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUkJ6RdxXmaDwd+aF7CGURH1gg # YXKgghWDMIIEwzCCA6ugAwIBAgITMwAAALfuAa/68MeouwAAAAAAtzANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF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3DQEBBQUA # BIIBAHhwFgyuo1tG1PQ7WqG4md75OVxqGaVxPPvLXZXFg8M+yb4r7zAkIbumiqK+ # df9EcBV2x441/YGf6Bhk0Ftd2QMQ6/VVrQ2J1u+y2TY6rXK6jOe9deP2qSuO8Od1 # uxt2zEpp6XvMzbVcE2aADDU3tYepKb3Em5rTpNz8aEPWlSYWcAAXCXJ6Alile/5t # eg8/y7TJ9E+mptPePi8m9PB6Y/ZXxOjEezZOd2f2zhYZfF2gWBAwGnWtLYtMLmEx # R1qrclmXpsN5P78rVgElsSmdBij89kEZQ0nXtymDr3XL34yD3A2txKzl5N/mCJDx # hp2OvI+brmdE+z+9NiAULvzYM30= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/Plaster/1.0.1/Templates/NewPowerShellManifestModule/test/Module.T.ps1
Module.T.ps1
$ModuleManifestName = '<%=$PLASTER_PARAM_ModuleName%>.psd1' $ModuleManifestPath = "$PSScriptRoot\..\$ModuleManifestName" Describe 'Module Manifest Tests' { It 'Passes Test-ModuleManifest' { Test-ModuleManifest -Path $ModuleManifestPath $? | Should Be $true } }
PowerShellCorpus/PowerShellGallery/Jojoba/1.4.0.3/Write-JojobaFail.ps1
Write-JojobaFail.ps1
<# .SYNOPSIS Mark a Jojoba test as failed. .DESCRIPTION Jojoba tests pass by default, but they can fail, or be skipped. .PARAMETER Message A string. This should be a simple, short sentence, detailing exactly what has failed. Multiple failures will have their messages combined with newlines. A message must be given as it's good pracice. Keep more verbose information for the data block. .EXAMPLE Write-JojobaFail "Job 1 failed" Write-JojobaFail "Job 2 failed" This will set a Jojoba test case result to "Fail" and popluates the failure reason as: Job 1 failed Job 2 failed #> function Write-JojobaFail { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $Message ) begin { } process { [void] $jojobaTestCase.Message.Add($Message) $jojobaTestCase.Result = "Fail" } end { } }
PowerShellCorpus/PowerShellGallery/Jojoba/1.4.0.3/Write-JojobaSkip.ps1
Write-JojobaSkip.ps1
<# .SYNOPSIS Mark a Jojoba test as skipped. .DESCRIPTION Jojoba tests pass by default, but they can fail, or be skipped. .PARAMETER Message A string. This should be a simple, short sentence, detailing exactly what has been skipped or why. Multiple skips will have their messages combined with newlines. A message must be given as it's good pracice. Keep more verbose information for the data block. .EXAMPLE Write-JojobaSkip "Server skipped because it is turned off" This will set a Jojoba test case result to "Skip" and popluates the skip reason as: Server skipped because it is turned off .NOTES A test would normally be skipped if the test cannot or should not be run - for example if the test result would not be valid. It should only be used if the test result requires no further action. If action was required, this test should be marked as a fail. #> function Write-JojobaSkip { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $Message ) begin { } process { [void] $jojobaTestCase.Message.Add($Message) $jojobaTestCase.Result = "Skip" } end { } }
PowerShellCorpus/PowerShellGallery/Jojoba/1.4.0.3/Write-JojobaXml.ps1
Write-JojobaXml.ps1
<# .SYNOPSIS Converts Jojoba test case objects to a jUnit XML file Jenkins can understand. .DESCRIPTION Jenkins is best used with a jUnit XML file to provide further information on why tests have passed, failed, or been skipped. This function provides that translation. .PARAMETER Test One or more Jojoba test case outputs. This would normally be generated by Start-Jojoba and sent here by Publish-Jojoba. .PARAMETER OutputPath Override the output path. It defaults to ".\Jojoba.xml". .PARAMETER PassThru Pass on the incoming object to the output stream. This is not recommended because under normal use cases Start-Jojoba outputs the case and this is streamed to the screen by Publish-Jojoba, and separately passed to Write-JojobaXml. If Write-JojobaXml is used to output then it would only be at the very end of all processing. .EXAMPLE [PSCustomObject] @{ Suite = "Suite" Timestamp = Get-Date Time = 0 ClassName = "Test" Name = "Server1" Result = "Pass" ErrorMessage = New-Object Collections.ArrayList Data = New-Object Collections.ArrayList } | Write-JojobaXml #> function Write-JojobaXml { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline=$true)] $Test, $OutputPath = ".\Jojoba.xml", [switch] $PassThru ) begin { $xmlDocument = New-Object System.Xml.XmlDocument $xmlDocument.LoadXml('<testsuites></testsuites>') $templateSuite = New-Object System.Xml.XmlDocument $templateSuite.LoadXml('<testsuite name="" tests="0"></testsuite>') $templateCase = New-Object System.Xml.XmlDocument $templateCase.LoadXml('<testcase classname="" name="" timestamp="" time="0"></testcase>') $templateFailure = New-Object System.Xml.XmlDocument $templateFailure.LoadXml('<failure message=""></failure>') $templateSkipped = New-Object System.Xml.XmlDocument $templateSkipped.LoadXml('<skipped message=""></skipped>') } process { foreach ($suite in ($Test | Group-Object Suite | Sort-Object Case)) { # This wouldn't normally be required but is to get around an edge # case of users running scripts instead of modules. $suiteName = [string] $Suite.Name if (!$suiteName) { $suiteName = "Jojoba" } $xmlSuite = $xmlDocument.ImportNode($templateSuite.testsuite, $false) $xmlSuite.name = [string] $suiteName $xmlSuite.tests = [string] $suite.Group.Count foreach ($case in $suite.Group) { $xmlCase = $xmlDocument.ImportNode($templateCase.testcase, $false) $xmlCase.timestamp = [string] $case.Timestamp $xmlCase.time = [string] $case.Time # Some of these ToString's don't seem necessary, but, it seems # in some cases the parameters are a NoteProperty and it really # demands they are exactly a string. Sometimes they're $null... $xmlCase.classname = [string] $suiteName + "." + $case.ClassName $xmlCase.name = [string] $case.Name if ($case.Result -eq "Fail") { $xmlFailure = $xmlDocument.ImportNode($templateFailure.failure, $false) if ($case.Message) { $xmlFailure.message = $case.Message -join [Environment]::NewLine } if ($case.Data) { $xmlFailure.InnerText = $case.Data -join [Environment]::NewLine } [void] $xmlCase.AppendChild($xmlFailure) } elseif ($case.Result -eq "Skip") { $xmlSkipped = $xmlDocument.ImportNode($templateSkipped.skipped, $false) if ($case.Message) { $xmlSkipped.message = $case.Message -join [Environment]::NewLine } if ($case.Data) { $xmlSkipped.InnerText = $case.Data -join [Environment]::NewLine } [void] $xmlCase.AppendChild($xmlSkipped) } [void] $xmlSuite.AppendChild($xmlCase) } [void] $xmlDocument.ChildNodes.AppendChild($xmlSuite) } if ($PassThru) { $Test } } end { $xmlDocument.Save($OutputPath) } }
PowerShellCorpus/PowerShellGallery/Jojoba/1.4.0.3/Publish-Jojoba.ps1
Publish-Jojoba.ps1
<# .SYNOPSIS Retrieve results from Jojoba parallel runs and optionally package them for Jenkins. .DESCRIPTION For a Jojoba template function a call to Publish-Jojoba must be in the end {} block. If parallel processing has been used, this script will wait for all jobs to complete before outputting the test data. It may also write a Jojoba.xml for processing by Jenkins. .PARAMETER OutputPath Output path for Jojoba XML. This is only triggered if JojobaThrottle -ne 0, $JojobaJenkins = $true, or it is executing under Jenkins. .INPUTS None. All inputs are taken from the calling function ($JojobaBatch, $JojobaJenkins, and $JojobaThrottle). .OUTPUTS Test case data from all processed jobs. If a job fails, which should not happen, its output will be returned also. #> function Publish-Jojoba { [CmdletBinding()] param ( $OutputPath = ".\Jojoba.xml" ) begin { } process { #region Retrieve and clean up results if run in parallel mode if ($PSCmdlet.GetVariableValue("JojobaThrottle")) { $completedJobs = New-Object Collections.ArrayList $jobErrors = New-Object Collections.ArrayList # Get, receive, and remove jobs as they complete. Any errors should be caught # and encapsulated as part of a test result. But in case they don't, then we # deal with them separately. Get-RSJob -Batch $PSCmdlet.GetVariableValue("JojobaBatch") | Wait-RSJob -ShowProgress | ForEach-Object { if ($_.State -ne "Failed" -and !$_.HasErrors) { [void] $completedJobs.Add((Receive-RSJob $_)) } else { [void] $jobErrors.Add((Receive-RSJob $_)) } $_ } | Remove-RSJob # Write out the XML file if there's output, and we're either asked or Jenkins is in use if ($completedJobs -and ($PSCmdlet.GetVariableValue("JojobaJenkins") -or $env:JENKINS_SERVER_COOKIE)) { Write-JojobaXml $completedJobs -OutputPath $OutputPath } # Write out all the good test information if ($completedJobs) { $completedJobs } if ($jobErrors) { # Write out any failed information. This will mess up the pipeline, but that's # okay, because if this happens then something has gone seriously wrong, and it # can show up in the Jenkins build console $jobErrors # Mark any Jenkins build as failed $global:LASTEXITCODE = 1 } else { # Mark the build as a success (though Jenkins may interpret the test results # and mark it as failed for other reasons) $global:LASTEXITCODE = 0 } } #endregion } end { } }
PowerShellCorpus/PowerShellGallery/Jojoba/1.4.0.3/Start-Jojoba.ps1
Start-Jojoba.ps1
<# .SYNOPSIS Parallel processing with test case output and Jenkins integration. .DESCRIPTION For a Jojoba template function this will be the main call in the process {} block. All processing should occur within here. .PARAMETER ScriptBlock The test to carry out. It must use $InputObject or $_. .INPUTS All inputs aside from the ScriptBlock are taken from the calling function. $JojobaBatch $JojobaCallback (optional, for writing events elsewhere) $JojobaJenkins (optional, for forcing a write of XML) $JojobaThrottle (required for batch runs, optional for testing) $JojobaSuite (optional) .OUTPUTS A test case object. #> function Start-Jojoba { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [ScriptBlock] $ScriptBlock ) begin { } process { # Gather information about the caller $jojobaModuleName = $PSCmdlet.GetVariableValue("MyInvocation").MyCommand.ModuleName $jojobaClassName = $PSCmdlet.GetVariableValue("MyInvocation").MyCommand.Name $jojobaName = $PSCmdlet.GetVariableValue("InputObject") if ($jojobaClassNameFolder = $PSCmdlet.GetVariableValue("PSCommandPath")) { $jojobaClassNameFolder = Split-Path -Leaf (Split-Path -Parent $jojobaClassNameFolder) } # Inherit Jojoba parameters from the caller $JojobaBatch = $PSCmdlet.GetVariableValue("JojobaBatch") if (!($JojobaCallback = $PSCmdlet.GetVariableValue("JojobaCallback"))) { $JojobaCallback = "Write-JojobaCallback" } $JojobaJenkins = $PSCmdlet.GetVariableValue("JojobaJenkins") if (!($JojobaSuite = $PSCmdlet.GetVariableValue("JojobaSuite"))) { if ($JojobaSuite = $jojobaModuleName) { if ($jojobaClassNameFolder -and $jojobaClassNameFolder -ne $jojobaModuleName) { $JojobaSuite += "\$jojobaClassNameFolder" } } else { $JojobaSuite = "(Root)" } } $JojobaThrottle = $PSCmdlet.GetVariableValue("JojobaThrottle") # You'd almost always specify JojobaThrottle. If you didn't, well, it's allowed, but if ($JojobaThrottle -and !$JojobaBatch) { Write-Error "When running in PoshRSJob mode the caller must have a unique `$JojobaBatch per pipeline" } if (!$JojobaThrottle -and $JojobaJenkins) { Write-Error "When running in direct mode the caller cannot use `$JojojobaJenkins" } if (!$JojobaThrottle) { #region Direct run Write-Verbose "Starting inside thread for $JojobaName" # Fill out the base test case, named after parts of the original caller $jojobaTestCase = [PSCustomObject] @{ UserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name Suite = $JojobaSuite Timestamp = Get-Date Time = 0 ClassName = $JojobaClassName Name = $JojobaName Result = "Pass" Message = New-Object Collections.ArrayList Data = New-Object Collections.ArrayList } $jojobaMessages = try { &$ScriptBlock *>&1 } catch { # Handle an uncaught stop as a test block failure. This saves # having to write test code for everything if the exception is # self explanatory Write-JojobaFail $_.ToString() Resolve-Error $_ -AsString } foreach ($jojobaMessage in ($jojobaMessages | Where-Object { $null -ne $_ })) { if ($jojobaMessage -is [string]) { [void] $jojobaTestCase.Data.Add($jojobaMessage) } elseif ($jojobaMessage.GetType().FullName -eq "System.Management.Automation.InformationRecord") { # Used in PS5 to capture Write-Host output if ($jojobaMessage.Tags.Contains("PSHOST")) { [void] $jojobaTestCase.Data.Add($jojobaMessage) } else { [void] $jojobaTestCase.Data.Add($jojobaMessage) } } elseif ($jojobaMessage -is [System.Management.Automation.VerboseRecord]) { [void] $jojobaTestCase.Data.Add("VERBOSE: $jojobaMessage") } elseif ($jojobaMessage -is [System.Management.Automation.WarningRecord]) { [void] $jojobaTestCase.Data.Add("WARNING: $jojobaMessage") } elseif ($jojobaMessage -is [System.Management.Automation.ErrorRecord]) { # Exceptions also get wrapped in an ErrorRecord [void] $jojobaTestCase.Data.Add((Resolve-Error $jojobaMessage -AsString)) } else { [void] $jojobaTestCase.Data.Add(($jojobaMessage | Format-List | Out-String)) } } # Calculate other useful information for the test case for use by Jenkins $jojobaTestCase.Time = ((Get-Date) - $jojobaTestCase.Timestamp).TotalSeconds # If the calling function has a Write-Jojoba then send them a copy of the test. If this fails, # it also makes the test fail and which is at least output somewhere. if ($jojobaCallbackReference = Get-Command -Module $JojobaModuleName | Where-Object { $_.Name -eq $JojobaCallback }) { try { &$jojobaCallbackReference $jojobaTestCase } catch { Write-JojobaFail $_.ToString() [void] $jojobaTestCase.Data.Add((Resolve-Error $_ -AsString)) } } # Write out the test case after getting rid of {} marks $jojobaTestCase.Message = $jojobaTestCase.Message -join [Environment]::NewLine $jojobaTestCase.Data = $jojobaTestCase.Data -join [Environment]::NewLine $jojobaTestCase #endregion } else { #region Parallel run # These are arguments which will be splatted for use by PoshRSJob $jobArguments = @{ Throttle = $JojobaThrottle Batch = $JojobaBatch ModulesToImport = $JojobaModuleName FunctionsToLoad = if (!$jojobaModuleName) { $JojobaClassName } else { $null } ScriptBlock = [scriptblock]::Create("`$_ | $($JojobaClassName) -JojobaThrottle 0") Verbose = $VerbosePreference } # Add any extra switches and parameters to the scriptblock so they can be passed to the caller. # This can't handle complex objects - those should be piped in instead. # Some exceptions for Jojoba flags are included. $PSCmdlet.GetVariableValue("MyInvocation").BoundParameters.GetEnumerator() | ForEach-Object { if (@("InputObject", "JojobaBatch", "JojobaJenkins", "JojobaThrottle") -notcontains $_.Key) { if ($_.Value -is [System.Management.Automation.SwitchParameter]) { $jobArguments.ScriptBlock = [scriptblock]::Create("$($jobArguments.ScriptBlock) -$($_.Key):`$$($_.Value)") } elseif ($_.Value -is [string]) { $jobArguments.ScriptBlock = [scriptblock]::Create("$($jobArguments.ScriptBlock) -$($_.Key) '$($_.Value.Replace("'", "''"))'") } else { $jobArguments.ScriptBlock = [scriptblock]::Create("$($jobArguments.ScriptBlock) -$($_.Key) $($_.Value)") } } } Write-Verbose "Scheduling $($JojobaName) batch $($JojobaBatch) throttle $($jobArguments.Throttle) modules $($jobArguments.ModulesToImport) functions $($jobArguments.FunctionsToLoad) script $($jobArguments.ScriptBlock)" # Here we can continue to pipe in a complex object, or, revert back to the InputObject, for simplicity $null = @(if ($PSCmdlet.GetVariableValue("_") -and $PSCmdlet.GetVariableValue("_") -isnot [string]) { $PSCmdlet.GetVariableValue("_") } else { $PSCmdlet.GetVariableValue("InputObject") }) | Start-RSJob @jobArguments #endregion } } end { } }
PowerShellCorpus/PowerShellGallery/Jojoba/1.4.0.3/Out-JojobaSpeech.ps1
Out-JojobaSpeech.ps1
<# .SYNOPSIS Read out basic Jojoba results to a sound card. .DESCRIPTION Takes a Jojoba result and reads out each class, name, and result (and optional message). It will repeat failures twice. .PARAMETER Test A Jojoba test case. .PARAMETER VoiceGender Male or Female. .PARAMETER VoiceRate Rate of speech. 2 is a little faster than normal. .EXAMPLE function Test-DatabaseServer { param ( [Parameter(AcceptPipelineInput)] $InputObject, $JojobaThrottle = $env:NUMBER_OF_PROCESSORS ) begin { } process { Start-Jojoba { switch ($InputObject) { "FRODO" { break } "LARRY" { Write-JojobaFail "Offline for maintenance" } "CURLY" { Write-JojobaFail "Is not even resolving an IP address, oh no!" } } } } end { } } "FRODO","LARRY","CURLY" | Test-DatabaseServer | Out-JojobaSpeech Fake a database failure and listen to the results. This is only an example. Do NOT write Jojoba code like this as it skips out on many Jojobs features. Specifically it does not have multi-threading (as it has no JojobaFail) and no Jenkins output. .NOTES #> function Out-JojobaSpeech { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline=$true)] $Test, $VoiceGender = "Female", $VoiceRate = 2 ) begin { try { Add-Type -Assembly System.Speech } catch { Write-Error -Message "Speech requires NET 3.0 and above" } } process { New-DisposableObject ($speech = New-Object System.Speech.Synthesis.SpeechSynthesizer) { $speech.SelectVoiceByHints($VoiceGender) $speech.Rate = $VoiceRate # This isn't perfect, but, I want to remove - signs from the class name (as it's # often Test-Something, etc, and leaving it there results in speech oddities), # but I also want to add spaces between ACRONYMS and WordsLikeThis and numbers # as it sounds better for server names $regEx = '[^\p{Ll}\s]', ' $&' $speechString = "$($Test.ClassName.Replace("-", "`") -creplace $regEx, ' $&') on $($Test.Name -creplace $regEx, ' $&'), $($Test.Result)" $speech.Speak($speechString) if ($Test.Result -eq "Fail") { if (!$Test.Message) { $speech.Speak("Repeat, $speechString with no reason") } else { $speech.Speak("Repeat, $speechString with reason $($Test.Message)") } } } } end { } }
PowerShellCorpus/PowerShellGallery/ExifDateTime/1.0/PublishPsGalleryModule.ps1
PublishPsGalleryModule.ps1
#requires -Modules PowerShellGet Param ( [Parameter(Mandatory)] $PsGalleryApiKey ) $ReleaseNotes =@' ExifDateTime Chris Warwick, @cjwarwickps, August 2013 This version: November 2015 The module contains two functions: Get-ExifDateTaken -Path <filepaths> Takes a file (fileinfo or string) or an array of these Gets the ExifDT value (EXIF Property 36867) Update-ExifDateTaken -Path <filepaths> -Offset <TimeSpan> Takes a file (fileinfo or string) or an array of these Modifies the ExifDT value (EXIF Property 36867) as specified # Example: Rename files based on DateTaken value gci *.jpg | Get-ExifDateTaken | Rename-Item -NewName {"Holiday Snap {0:MM-dd HH.mm.ss dddd} ({1}).jpg" -f $_.ExifDateTaken, (Split-Path (Split-Path $_) -Leaf)} # Example: Correct DateTake value on a set of .jpg images by specifying a time offset gci *.jpg|Update-ExifDateTaken -Offset '-0:07:10' -PassThru|ft Path, ExifDateTaken # Example: Update DateTaken & Rename files based on Date gci *.jpg | Update-ExifDateTaken -Offset '-0:07:10' -PassThru | Rename-Item -NewName {"Holiday Snap {0:MM-dd HH.mm.ss dddd} ({1}).jpg" -f $_.ExifDateTaken, (Split-Path (Split-Path $_) -Leaf)} Script Help, Get-ExifDateTaken ------------------------------ <# .Synopsis Gets the DateTaken EXIF property in an image file. .Description This cmdlet reads the EXIF DateTaken property in an image and passes is down the pipeline attached to the PathInfo item of the image file. .Parameter Path The image file or files to process. .Example Get-ExifDateTaken img3.jpg Reads the img3.jpg file and returns the im3.jpg PathInfo item with the EXIF DateTaken attached .Example Get-ExifDateTaken *3.jpg |ft path, exifdatetaken Output the EXIF DateTaken values for all matching files in the current folder .Example gci *.jpeg,*.jpg|Get-ExifDateTaken Read multiple files from the pipeline .Example gci *.jpg|Get-ExifDateTaken|Rename-Item -NewName {"Holiday Snap {0:MM-dd HH.mm.ss}.jpg" -f $_.ExifDateTaken} Gets the EXIF DateTaken on multiple files and renames the files based on the time .Outputs The scripcmdlet outputs FileInfo objects with an additional ExifDateTaken property that can be used for later processing. .Functionality Gets the EXIF DateTaken image property on a specified image file. #> Script Help, Update-ExifDateTaken --------------------------------- <# .Synopsis Changes the DateTaken EXIF property in an image file. .Description This cmdlet updates the EXIF DateTaken property in an image by adding an offset to the existing DateTaken value. The offset (which must be able to be interpreted as a [TimeSpan] type) can be positive or negative - moving the DateTaken value to a later or earlier time, respectively. This can be useful (for example) to correct times where the camera clock was wrong for some reason - perhaps because of timezones; or to synchronise photo times from different cameras. .Parameter Path The image file or files to process. .Parameter Offset The time offset by which the EXIF DateTaken value should be adjusted. Offset can be positive or negative and must be convertible to a [TimeSpan] type. .Parameter PassThru Switch parameter, if specified the paths of the image files processed are written to the pipeline. The PathInfo objects are additionally decorated with the Old and New EXIF DateTaken values. .Example Update-ExifDateTaken img3.jpg -Offset 0:10:0 -WhatIf Update the img3.jpg file, adding 10 minutes to the DateTaken property .Example Update-ExifDateTaken *3.jpg -Offset -0:01:30 -Passthru|ft path, exifdatetaken Subtract 1 Minute 30 Seconds from the DateTaken value on all matching files in the current folder .Example gci *.jpeg,*.jpg|Update-ExifDateTaken -Offset 0:05:00 Update multiple files from the pipeline .Example gci *.jpg|Update-ExifDateTaken -Offset 0:5:0 -PassThru|Rename-Item -NewName {"Holday Snap {0:MM-dd HH.mm.ss}.jpg" -f $_.ExifDateTaken} Updates the EXIF DateTaken on multiple files and renames the files based on the new time .Outputs If -PassThru is specified, the scripcmdlet outputs FileInfo objects with additional ExifDateTaken and ExifOriginalDateTaken properties that can be used for later processing. .Notes This scriptcmdlet will overwrite files without warning - take backups first... .Functionality Modifies the EXIF DateTaken image property on a specified image file. #> Version History: --------------- V1.0 (Current Version) November 2015 > Initial release to the PowerShell Gallery V0.1-0.9 > Dev versions Other Modules: ------------ See all my other PS Gallery modules: Find-Module | Where Author -like 'Chris*Warwick' '@ $Tags = @( 'Exif' 'DateTaken' 'Date' 'Image' 'jpg' 'photo' 'DateTime' '36867' 'PowerShell' 'FileStream' ) $PublishParams = @{ Name = 'ExifDateTime' NuGetApiKey = $PsGalleryApiKey ReleaseNotes = $ReleaseNotes Tags = $Tags ProjectUri = 'https://github.com/ChrisWarwick/ExifDateTime' } Publish-Module @PublishParams # ...later # Find-Module ExifDateTime
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Src/Get-LegacyNetAdapterConfiguration.ps1
Get-LegacyNetAdapterConfiguration.ps1
function Get-LegacyNetAdapterConfiguration { [CmdletBinding(DefaultParameterSetName = 'Default')] [OutputType([System.Management.ManagementObject])] param ( [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [System.String] $Name, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Default')] [System.Management.Automation.SwitchParameter] $Physical, [Parameter(ValueFromPipeline, ParameterSetName = 'InputObject')] [System.Management.ManagementObject] $InputObject ) if ($PSCmdlet.ParameterSetName -eq 'Default') { $InputObject = Get-LegacyNetAdapter @PSBoundParameters; } if ($InputObject) { foreach ($networkAdapter in $InputObject) { Write-Verbose -Message ($localized.QueryingWmiObjectClass -f 'Win32_NetworkAdapterConfiguration'); $wmiFilter = 'Index = "{0}"' -f $networkAdapter.DeviceID; Write-Verbose -Message ($localized.ApplyingWmiQueryFilter -f $wmiFilter); Write-Output -InputObject (Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter $wmiFilter); } #end foreach network adapter } #end if network adapters } #end function Get-NetworkAdapter
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Src/Remove-LegacyNetFirewallRule.ps1
Remove-LegacyNetFirewallRule.ps1
function Remove-LegacyNetFirewallRule { [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [Alias('Name')] [System.String] $DisplayName, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateSet('Public','Private','Domain','Any')] [System.String[]] $Profile ) begin { if ($PSBoundParameters.ContainsKey('Profile')) { $PSBoundParameters['Profile'] = Resolve-ProfileParameter -Profile $Profile; } } #end begin process { $netshNameString = 'Name="{0}"' -f $DisplayName; $netshProfileString = 'Profile={0}' -f ($Profile -join ','); $netshCommands = @('advfirewall', 'firewall', 'delete', 'rule', $netshNameString, $netshProfileString); $shouldProcessMessage = 'NETSH.EXE {0}' -f ($netshCommands -join ' '); #Write-Verbose ("Executing 'NETSH.EXE {0}'." -f ($netshCommands -join ' ')); if ($PSCmdlet.ShouldProcess($shouldProcessMessage)) { $netshOutput = & netsh.exe $netshCommands; if ($LASTEXITCODE -ne 0) { $errorMessage = $netshOutput -split "`r`n"; if ([System.String]::IsNullOrEmpty($errorMessage[1])) { ## The requested operation requires elevation (Run as administrator). throw ($errorMessage[0]); } else { throw ($errorMessage[1]); } } Write-Verbose -Message (($netshOutput -join ' ').Trim()); Get-LegacyNetFirewallRule @PSBoundParameters; } } #end process } #end function Remove-FirewallRule
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Src/New-LegacyNetFirewallRule.ps1
New-LegacyNetFirewallRule.ps1
function New-LegacyNetFirewallRule { [CmdletBinding(DefaultParameterSetName = 'Default', SupportsShouldProcess)] [OutputType([System.Management.Automation.PSCustomObject])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [Alias('Name')] [System.String] $DisplayName, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateSet('Public','Private','Domain','Any')] [System.String[]] $Profile, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateSet('Inbound','Outbound')] [System.String] $Direction, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateSet('Allow','Block','Bypass')] [System.String] $Action, [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [ValidateNotNullOrEmpty()] [System.String] $Protocol, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Description, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.Boolean] $Enabled, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [System.String[]] $LocalPort, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [System.String[]] $RemotePort, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Program, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Service ) begin { $map = @( @{ Name = 'Protocol'; NetshParameter = 'protocol'; Type = [System.String]; } @{ Name = 'Direction'; NetshParameter = 'dir'; Type = [System.String]; CustomMap = @{ Inbound = 'in'; Outbound = 'out'; }; } @{ Name = 'Description'; NetshParameter = 'desc'; Type = [System.String]; } @{ Name = 'Enabled'; NetshParameter = 'enable'; Type = [System.Boolean]; CustomMap = @{ True = 'yes'; False = 'no'; }; } @{ Name = 'LocalPort'; NetshParameter = 'localport'; Type = [System.String[]]; } @{ Name = 'RemotePort'; NetshParameter = 'remoteport'; Type = [System.String[]]; } @{ Name = 'Program'; NetshParameter = 'program'; Type = [System.String]; } @{ Name = 'Service'; NetshParameter = 'service'; Type = [System.String]; } @{ Name = 'Action'; NetshParameter = 'action'; Type = [System.String]; } ) if ($PSBoundParameters.ContainsKey('Profile')) { $PSBoundParameters['Profile'] = Resolve-ProfileParameter -Profile $Profile; } } #end begin process { $netshNameString = 'Name="{0}"' -f $DisplayName; $netshProfileString = 'Profile={0}' -f ($Profile -join ','); $netshCommands = @('advfirewall', 'firewall', 'add', 'rule', $netshNameString, $netshProfileString); $parameterNames = @( 'Protocol', 'Description', 'Enabled', 'Direction', 'LocalPort', 'RemotePort', 'Program', 'Service', 'Action' ); $specificNetshCommands = @(); foreach ($parameterName in $PSBoundParameters.Keys) { foreach ($mapping in $map) { if ($parameterName -eq $mapping.Name) { $parameterValue = $PSBoundParameters[$parameterName]; if ($mapping.CustomMap) { $specificNetshCommands += '{0}="{1}"' -f $mapping.NetshParameter, $mapping.CustomMap[$parameterValue.ToString()]; } else { $specificNetshCommands += '{0}="{1}"' -f $mapping.NetshParameter, ($parameterValue -join ','); } } } } if ($specificNetshCommands.Count -eq 0) { throw ("Nothing to set."); } else { $netshCommands += $specificNetshCommands; } $shouldProcessMessage = 'NETSH.EXE {0}' -f ($netshCommands -join ' '); if ($PSCmdlet.ShouldProcess($shouldProcessMessage)) { $netshOutput = & netsh.exe $netshCommands; if ($LASTEXITCODE -ne 0) { $errorMessage = $netshOutput -split "`r`n"; if ([System.String]::IsNullOrEmpty($errorMessage[1])) { ## The requested operation requires elevation (Run as administrator). throw ($errorMessage[0]); } else { throw ($errorMessage[1]); } } Write-Verbose -Message (($netshOutput -join ' ').Trim()); Get-LegacyNetFirewallRule -DisplayName $DisplayName -Profile $Profile; } } #end process } #end function New-FirewallRule
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Src/Get-LegacyNetAdapter.ps1
Get-LegacyNetAdapter.ps1
function Get-LegacyNetAdapter { [CmdletBinding(DefaultParameterSetName = 'Default')] [OutputType([System.Management.ManagementObject])] param ( [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [System.String] $Name, [Parameter(ValueFromPipelineByPropertyName)] [System.Management.Automation.SwitchParameter] $Physical ) $filters = @();; if ($PSBoundParameters.ContainsKey('Name')) { $filters += 'NetConnectionID = "{0}"' -f $Name; } if ($PSBoundParameters.ContainsKey('Physical')) { $filters += 'PhysicalAdapter = "{0}"' -f $Physical.ToString(); } Write-Verbose -Message ($localized.QueryingWmiObjectClass -f 'Win32_NetworkAdapter'); $wmiFilters = $filters -join ' AND '; if ([System.String]::IsNullOrEmpty($wmiFilters)) { return Get-WmiObject -Class Win32_NetworkAdapter; } else { Write-Verbose -Message ($localized.ApplyingWmiQueryFilter -f $wmiFilters); return Get-WmiObject -Class Win32_NetworkAdapter -Filter $wmiFilters; } } #end function Get-NetworkAdapter
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Src/Set-LegacyNetFirewallRule.ps1
Set-LegacyNetFirewallRule.ps1
function Set-LegacyNetFirewallRule { [CmdletBinding(DefaultParameterSetName = 'Default', SupportsShouldProcess)] [OutputType([System.Management.Automation.PSCustomObject])] param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [Alias('Name')] [System.String] $DisplayName, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateSet('Public','Private','Domain','Any')] [System.String[]] $Profile, [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [ValidateNotNullOrEmpty()] [System.String] $Protocol, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Inbound','Outbound')] [System.String] $Direction, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Allow','Block','Bypass')] [System.String] $Action, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Description, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.Boolean] $Enabled, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [System.String[]] $LocalPort, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [System.String[]] $RemotePort, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Program, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Service ) begin { $map = @( @{ Name = 'Protocol'; NetshParameter = 'protocol'; Type = [System.String]; } @{ Name = 'Direction'; NetshParameter = 'dir'; Type = [System.String]; CustomMap = @{ Inbound = 'in'; Outbound = 'out'; }; } @{ Name = 'Description'; NetshParameter = 'desc'; Type = [System.String]; } @{ Name = 'Enabled'; NetshParameter = 'enable'; Type = [System.Boolean]; CustomMap = @{ True = 'yes'; False = 'no'; }; } @{ Name = 'LocalPort'; NetshParameter = 'localport'; Type = [System.String[]]; } @{ Name = 'RemotePort'; NetshParameter = 'remoteport'; Type = [System.String[]]; } @{ Name = 'Program'; NetshParameter = 'program'; Type = [System.String]; } @{ Name = 'Service'; NetshParameter = 'service'; Type = [System.String]; } @{ Name = 'Action'; NetshParameter = 'action'; Type = [System.String]; } ) if ($PSBoundParameters.ContainsKey('Profile')) { $PSBoundParameters['Profile'] = Resolve-ProfileParameter -Profile $Profile; } } #end begin process { $netshNameString = 'Name="{0}"' -f $DisplayName; $netshProfileString = 'Profile={0}' -f ($Profile -join ','); $netshCommands = @('advfirewall', 'firewall', 'set', 'rule', $netshNameString, $netshProfileString, 'new'); $parameterNames = @( 'Protocol', 'Description', 'Enabled', 'Direction', 'LocalPort', 'RemotePort', 'Program', 'Service', 'Action' ); $specificNetshCommands = @(); foreach ($parameterName in $PSBoundParameters.Keys) { foreach ($mapping in $map) { if ($parameterName -eq $mapping.Name) { $parameterValue = $PSBoundParameters[$parameterName]; if ($mapping.CustomMap) { $specificNetshCommands += '{0}="{1}"' -f $mapping.NetshParameter, $mapping.CustomMap[$parameterValue.ToString()]; } else { $specificNetshCommands += '{0}="{1}"' -f $mapping.NetshParameter, ($parameterValue -join ','); } } } } if ($specificNetshCommands.Count -eq 0) { throw ("Nothing to set."); } else { $netshCommands += $specificNetshCommands; } $shouldProcessMessage = 'NETSH.EXE {0}' -f ($netshCommands -join ' '); #Write-Verbose ("Executing 'NETSH.EXE {0}'." -f ($netshCommands -join ' ')); if ($PSCmdlet.ShouldProcess($shouldProcessMessage)) { $netshOutput = & netsh.exe $netshCommands; if ($LASTEXITCODE -ne 0) { $errorMessage = $netshOutput -split "`r`n"; if ([System.String]::IsNullOrEmpty($errorMessage[1])) { ## The requested operation requires elevation (Run as administrator). throw ($errorMessage[0]); } else { throw ($errorMessage[1]); } } Write-Verbose -Message (($netshOutput -join ' ').Trim()); Get-LegacyNetFirewallRule -DisplayName $DisplayName -Profile $Profile; } } #end process } #end function Set-FirewallRule
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Src/Get-LegacyNetFirewallRule.ps1
Get-LegacyNetFirewallRule.ps1
function Get-LegacyNetFirewallRule { [CmdletBinding(DefaultParameterSetName = 'Default')] [OutputType([System.Management.Automation.PSCustomObject])] param ( [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] #[Parameter(ParameterSetName = 'Port', ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [Alias('Name')] [System.String] $DisplayName, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Public','Private','Domain','Any')] [System.String[]] $Profile, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Inbound','Outbound')] [System.String] $Direction, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Allow','Block','Bypass')] [System.String] $Action, [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [ValidateNotNullOrEmpty()] [System.String] $Protocol, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Description, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.Boolean] $Enabled, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [System.String[]] $LocalPort, [Parameter(ValueFromPipelineByPropertyName, ParameterSetName = 'Port')] [System.String[]] $RemotePort, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Program, [Parameter(ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [System.String] $Service ) begin { $map = @( @{ Name = 'Protocol'; Regex = '^Protocol:'; Type = [System.String]; } @{ Name = 'Description'; Regex = '^Description:'; Type = [System.String]; } @{ Name = 'Enabled'; Regex = '^Enabled:'; Type = [System.Boolean]; CustomMap = @{ Yes = $true; No = $false; }; } @{ Name = 'Direction'; Regex = '^Direction:'; Type = [System.String]; CustomMap = @{ In = 'Inbound'; Out = 'Outbound'; }; } @{ Name = 'Profile'; Regex = '^Profiles:'; Type = [System.String[]]; } @{ Name = 'DisplayGroup'; Regex = '^Grouping:'; Type = [System.String]; } ## Read-only @{ Name = 'LocalPort'; Regex = '^LocalPort:'; Type = [System.String[]]; } @{ Name = 'RemotePort'; Regex = '^RemotePort:'; Type = [System.String[]]; } @{ Name = 'Program'; Regex = '^Program:'; Type = [System.String]; } @{ Name = 'Service'; Regex = '^Service:'; Type = [System.String]; } @{ Name = 'Action'; Regex = '^Action:'; Type = [System.String]; } ) if ($PSBoundParameters.ContainsKey('Profile')) { $PSBoundParameters['Profile'] = Resolve-ProfileParameter -Profile $Profile; } } #end begin end { $firewallRule = $null; if ($DisplayName.Contains('*')) { ## Retrieve all rules for parsing later Write-Verbose -Message ('Performing wildcard match'); $firewallRules = Get-NetshFirewallRule; $isWilcardMatch = $true; } else { ## Retrieve by explicit name match $firewallRules = Get-NetshFirewallRule @PSBoundParameters; $isWilcardMatch = $false; } foreach ($string in $firewallRules) { ## Do we have a new rule or reached the end? if (($string -match '^Rule Name:') -or ($string -match 'Ok.')) { $isMatch = $true; if ($null -ne $firewallRule) { ## Perform wilcard match if ($isWilcardMatch) { if ($firewallRule.Name -notlike $DisplayName) { continue; } } else { if ($firewallRule.Name -ne $DisplayName) { continue; } } ## Now compare all specified attributes.. foreach ($parameterName in $PSBoundParameters.Keys) { if ($firewallRule[$parameterName] -is [System.String[]]) { $existingMembers = $firewallRule[$parameterName]; $expectedMembers = $PSBoundParameters[$parameterName]; if (-not (Test-Members -ExistingMembers $existingMembers -Members $expectedMembers -Verbose:$false)) { Write-Debug ("Expected: {0}, Actual: {1}" -f ($expectedMembers -join ' '), ($existingMembers -join ' ')) ## Required as continue only breaks out of the current foreach loop $isMatch = $false; continue; } } elseif ($null -ne $firewallRule[$parameterName]) { if ($firewallRule[$parameterName] -ne $PSBoundParameters[$parameterName]) { Write-Debug ("Expected: {0}, Actual: {1}" -f ($PSBoundParameters[$parameterName] -join ' '), ($firewallRule[$parameterName] -join ' ')) ## Required as continue only breaks out of the current foreach loop $isMatch = $false; continue; } } } if ($isMatch) { ## Output existing object (only if we have one!).. Write-Output -InputObject ([PSCustomObject] $firewallRule); } } $firewallRule = [Ordered] @{ Name = ($string -replace '^Rule Name:').Trim() LocalPort = @('Any'); RemotePort = @('Any'); }; } else { foreach ($mapping in $map) { if ($string -match $mapping.Regex) { $firewallRuleValue = ($string -replace $mapping.Regex).Trim(); if ($mapping.CustomMap) { $firewallRule[$mapping.Name] = $mapping.CustomMap[$firewallRuleValue]; } elseif ($mapping.Type.ToString() -eq 'System.String[]') { $firewallRule[$mapping.Name] = $firewallRuleValue.Split(','); } else { $firewallRule[$mapping.Name] = $firewallRuleValue -as $mapping.Type; } } } # end foreach mapping } } #end foreach string } #end end } #end function Get-FirewallRule
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Lib/ConvertTo-CIDR.ps1
ConvertTo-CIDR.ps1
function ConvertTo-CIDR { [CmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory, ValueFromPipeline)] [System.String] $SubnetMask ) $SubnetMask -split '\.' | ForEach-Object { $subnet = $subnet * 256 + [System.Convert]::ToInt64($_); } return [System.Convert]::ToString($subnet, 2).IndexOf('0'); } #end function ConvertTo-CIDR
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Lib/Remove-DuplicateMembers.ps1
Remove-DuplicateMembers.ps1
<# The MIT License (MIT) Copyright (c) 2015 Microsoft Corporation. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #> function Remove-DuplicateMembers { [CmdletBinding()] [OutputType([System.String[]])] param ( [System.String[]] $Members ) process { Set-StrictMode -Version Latest $destIndex = 0; for([int] $sourceIndex = 0 ; $sourceIndex -lt $Members.Count; $sourceIndex++) { $matchFound = $false; for([int] $matchIndex = 0; $matchIndex -lt $destIndex; $matchIndex++) { if($Members[$sourceIndex] -eq $Members[$matchIndex]) { # A duplicate is found. Discard the duplicate. Write-Verbose -Message ($localized.RemovingDuplicateMember -f $Members[$sourceIndex]); $matchFound = $true; continue; } } if(!$matchFound) { $Members[$destIndex++] = $Members[$sourceIndex].ToLowerInvariant(); } } # Create the output array. $destination = New-Object -TypeName System.String[] -ArgumentList $destIndex; # Copy only distinct elements from the original array to the destination array. [System.Array]::Copy($Members, $destination, $destIndex); return $destination; } #end process } #end function RemoveDuplicateMembers
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Lib/Resolve-ProfileParameter.ps1
Resolve-ProfileParameter.ps1
function Resolve-ProfileParameter { [CmdletBinding()] [OutputType([System.String[]])] param ( [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Public','Private','Domain','Any')] [System.String[]] $Profile ) process { $dedupedProfiles = Remove-DuplicateMembers -Members $Profile; if ($dedupedProfiles -contains 'Any') { ## If we have any specified, expand and return this return @('Domain','Private','Public'); } else { ## Otherwise return the deduped profiles return $dedupedProfiles; } } #end process } #end function Resolve-ProfileParameter
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Lib/Test-Members.ps1
Test-Members.ps1
<# The MIT License (MIT) Copyright (c) 2015 Microsoft Corporation. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #> function Test-Members { [CmdletBinding()] [OutputType([System.Boolean])] param ( ## Existing array members [AllowNull()] [System.String[]] $ExistingMembers, ## Explicit array members [AllowNull()] [System.String[]] $Members ) process { Write-Verbose -Message ($localized.CheckingArrayMembers -f $ExistingMembers.Count); if ($PSBoundParameters.ContainsKey('Members')) { if ($null -eq $Members) { $Members = @(); } $Members = [System.String[]] @(Remove-DuplicateMembers -Members $Members); if ($ExistingMembers.Count -ne $Members.Count) { Write-Verbose -Message ($localized.MembershipCountMismatch -f $Members.Count, $ExistingMembers.Count); Write-Verbose -Message ("1: $($members.Count) $($ExistingMembers.Count)") return $false; } foreach ($member in $Members) { if ($member -notin $ExistingMembers) { Write-Verbose -Message ($localized.MemberNotInDesiredState -f $member);; Write-Verbose -Message ("2: $member") return $false; } } } #end if $Members Write-Verbose -Message $localized.MembershipInDesiredState; return $true; } #end process } #end function Test-Membership
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Lib/Get-NetshFirewallRule.ps1
Get-NetshFirewallRule.ps1
function Get-NetshFirewallRule { [CmdletBinding()] [OutputType([System.String[]])] param ( [Parameter(ValueFromPipeline)] [ValidateNotNullOrEmpty()] [System.String] $DisplayName, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('Public','Private','Domain')] [System.String[]] $Profile, [Parameter(ValueFromRemainingArguments)] [System.Object[]] $Arguments ) process { if ($PSBoundParameters.ContainsKey('DisplayName') -and $PSBoundParameters.ContainsKey('Profile')) { $profileString = ([System.String[]] @(Remove-DuplicateMembers -Members $Profile)) -join ','; $netshMessage = 'advfirewall firewall show rule name="{0}" profile="{1}" verbose' -f $DisplayName, $profileString; Write-Verbose -Message ($localized.ExecutingNetsh -f $netshMessage); $netshOutput = & netsh advfirewall firewall show rule name="$DisplayName" profile="$profileString" verbose; } elseif ($PSBoundParameters.ContainsKey('DisplayName')) { $netshMessage = 'advfirewall firewall show rule name="{0}" verbose' -f $DisplayName; Write-Verbose -Message ($localized.ExecutingNetsh -f $netshMessage); $netshOutput = & netsh advfirewall firewall show rule name="$DisplayName" verbose; } elseif ($PSBoundParameters.ContainsKey('Profile')) { $profileString = ([System.String[]] @(Remove-DuplicateMembers -Members $Profile)) -join ','; $netshMessage = 'advfirewall firewall show rule name=all profile="{0}" verbose' -f $profileString; Write-Verbose -Message ($localized.ExecutingNetsh -f $netshMessage); $netshOutput = & netsh advfirewall firewall show rule name=all profile="$profileString" verbose; } else { $netshMessage = 'advfirewall firewall show rule name=all verbose'; Write-Verbose -Message ($localized.ExecutingNetsh -f $netshMessage); $netshOutput = & netsh advfirewall firewall show rule name=all verbose; } return ($netshOutput -split "`r`n"); } #end process } #end function Get-NetshFirewallRule
PowerShellCorpus/PowerShellGallery/LegacyNetworking/1.0.1/Lib/ConvertFrom-CIDR.ps1
ConvertFrom-CIDR.ps1
function ConvertFrom-CIDR { [CmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory, ValueFromPipeline)] [Uint32] $CIDR ) ## Convert CIDR to netmask $int64 = ([System.Convert]::ToInt64(('1'*$CIDR + '0'*(32-$CIDR)), 2)); return '{0}.{1}.{2}.{3}' -f ([System.Math]::Truncate($int64 / 16777216)).ToString(), ([System.Math]::Truncate(($int64 % 16777216) / 65536)).ToString(), ([System.Math]::Truncate(($int64 % 65536) / 256)).ToString(), ([System.Math]::Truncate($int64 % 256)).ToString(); } #end function ConvertFrom-CIDR
PowerShellCorpus/PowerShellGallery/Disposable/1.4.0.3/New-DisposableObject.ps1
New-DisposableObject.ps1
<# .SYNOPSIS Dispose disposable variables, the equivalent of C# using for PowerShell. .DESCRIPTION Objects which own unmanaged resources (such as network connections and SQL Server database connections) should have their Dispose method called in order to free up those connections and so the object's memory can later be released in a timely manner. New-DisposableObject provides a simple way of managing this using a simple syntax usually consisting of the instantiation of the object followed by a scriptblock in which it will be used, before being disposed of behind the scenes. .PARAMETER DisposableObject An object which implements System.IDisposable. This is most likely an expression; see the example. .PARAMETER ScriptBlock A script block during which the above object will be used, and after which the object should be disposed of. .EXAMPLE New-DisposableObject ($dataSet = New-Object System.Data.DataSet) { } Disposes of $dataSet. .EXAMPLE # Try 1 $var = "ABC" "Before: Var is $var" New-DisposableObject ($dataSet = New-Object System.Data.DataSet) { $var = "BCD" "During: Var is $var" } "After: Var is $var" # Try 2 "Before: Var is $var" New-DisposableObject ($dataSet = New-Object System.Data.DataSet) { $script:var = "BCD" "During: Var is $var" } "After: Var is $var" Showing the effects of variables within the scriptblock. .NOTES Care must be taken not to modify variables within the scriptblock which exist in the outer scope. If you must do so, those variables must use a $script: prefix, otherwise your change may be lost as shown in the second example. This function is based largely on work done by Adam Weigert @ http://weblogs.asp.net/adweigert/powershell-adding-the-using-statement #> function New-DisposableObject { param ( [System.IDisposable] $DisposableObject, [ScriptBlock] $ScriptBlock ) if ($DisposableObject) { try { &$ScriptBlock } finally { if ($null -ne $DisposableObject) { if ($null -eq $DisposableObject.psbase) { $DisposableObject.Dispose() } else { $DisposableObject.psbase.Dispose() } } } } }
PowerShellCorpus/PowerShellGallery/Timezone/1.2.2/Timezone.Tests.ps1
Timezone.Tests.ps1
#Requires -Module Pester if ((Get-Module).Name -contains 'Timezone') { Remove-Module -Name Timezone } Import-Module "$PSScriptRoot\Timezone.psm1" InModuleScope Timezone { Describe 'Get-Timezone' { Context 'UTC' { It 'Returns the current Timezone object' { $timezone = Get-Timezone $timezone.Timezone | Should Not Be $null $timezone.UTCOffset | Should Not Be $null $timezone.ExampleLocation | Should Not Be $null } } Context 'Ahead of GMT timezone' { It 'Returns a Singapore (UTC+08:00) Timezone object' { $timezone = (Get-Timezone -Timezone 'Singapore Standard Time') $timezone.Timezone | Should Be 'Singapore Standard Time' $timezone.UTCOffset | Should Be '+08:00' $timezone.ExampleLocation | Should Be '(UTC+08:00) Kuala Lumpur, Singapore' } } Context 'Behind GMT timezone' { It 'Returns a Central America (UTC-06:00) Timezone object' { $timezone = (Get-Timezone -Timezone 'Central America Standard Time') $timezone.Timezone | Should Be 'Central America Standard Time' $timezone.UTCOffset | Should Be '-06:00' $timezone.ExampleLocation | Should Be '(UTC-06:00) Central America' } } Context 'UTCOffset' { It 'Checks the UTCOffset parameter implicit positive returns data' { Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '00:00') -DifferenceObject (Get-Timezone -UTCOffset '+00:00') | Should Be $null Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '00:00') -DifferenceObject (Get-Timezone -UTCOffset '-00:00') | Should Be $null Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '01:00') -DifferenceObject (Get-Timezone -UTCOffset '+01:00') | Should Be $null Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '10:00') -DifferenceObject (Get-Timezone -UTCOffset '+10:00') | Should Be $null Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '05:45') -DifferenceObject (Get-Timezone -UTCOffset '+05:45') | Should Be $null Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '09:30') -DifferenceObject (Get-Timezone -UTCOffset '+09:30') | Should Be $null } } Context 'Multiple Offset' { It 'Checks multiple offsets are handled' { Compare-Object -ReferenceObject (Get-Timezone -UTCOffset ((Get-Timezone -All).UTCOffset | Select-Object -Unique)) -DifferenceObject (Get-Timezone -All) | Should Be $null Compare-Object -ReferenceObject (Get-Timezone -UTCOffset '02:00', '03:00') -DifferenceObject (Get-Timezone -All | Where-Object UTCOffset -Match "\+0[2-3]\:00") | Should Be $null } } Context 'Match Parametersets' { It 'Checks timezones returned via -UTCOffset can be matched to timezone objects' { $timezones = Get-Timezone -All $timezones | Select-Object -Unique -Property UTCOffset | ForEach-Object { { Get-Timezone -UTCOffset $_ -eq Get-Timezone -All | Where-Object UTCOffset -eq $_ } | Should Be $True } } } Context 'All' { It 'Checks all timezones for consistency with individual data return' { $timezone = Get-Timezone -All Get-Timezone -All | Get-Timezone | ForEach-Object { $timezone.Timezone -contains $_.Timezone | Should Be $true $timezone.UTCOffset -contains $_.UTCOffset | Should Be $true $timezone.ExampleLocation -contains $_.ExampleLocation | Should Be $true } } } Context 'Multiple' { It 'Returns multiple individual timezones' { { Get-Timezone -Timezone 'Eastern Standard Time', 'SA Pacific Standard Time' } | Should Not Throw } } Context 'PipelineInput' { It 'Returns a timezone from pipeline data by value' { 'UTC' | Get-Timezone | Should Not Be $null 'utc' | Get-Timezone | Should Not Be $null } It 'Returns a timezone from pipeline data by property name' { Get-Timezone -Timezone 'Pacific Standard Time' | Get-Timezone | Should Not Be $null } } Context 'Validation' { It 'Tries to get an invalid timezone' { { Get-Timezone -Timezone 'My First Timezone' } | Should Throw { Get-Timezone -Timezone 0 } | Should Throw { Get-Timezone -Timezone 19:00 } | Should Throw { Get-Timezone -UTCOffset 'Another Timezone' } | Should Throw } } } Describe 'Set-Timezone-UTC' { Context 'Standard' { It 'Sets the timezone to UTC' { Set-Timezone -Timezone 'UTC' -WhatIf | Should Be $null } } Context 'PipelineInput' { It 'Sets the timezone from pipeline data' { 'Dateline Standard Time' | Set-Timezone -WhatIf | Should Be $null } It 'Returns a timezone from pipeline data by property name' { Get-Timezone -Timezone 'Hawaiian Standard Time' | Set-Timezone -WhatIf | Should Be $null } } Context 'Validation' { It 'Tries to set an invalid timezone' { { Set-Timezone -Timezone 'My First Timezone' } | Should Throw } } } } Remove-Module -Name Timezone
PowerShellCorpus/PowerShellGallery/Timezone/1.2.2/Timezone.Help.Tests.ps1
Timezone.Help.Tests.ps1
<# .NOTES =========================================================================== Created with: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.119 Created on: 4/12/2016 1:11 PM Created by: June Blender Organization: SAPIEN Technologies, Inc Filename: *.Help.Tests.ps1 =========================================================================== .DESCRIPTION To test help for the commands in a module, place this file in the module folder. To test any module from any path, use https://github.com/juneb/PesterTDD/Module.Help.Tests.ps1 #> #Requires -Module Pester $ModuleBase = Split-Path -Parent $MyInvocation.MyCommand.Path # Handles modules in version directories $leaf = Split-Path $ModuleBase -Leaf $parent = Split-Path $ModuleBase -Parent $parsedVersion = $null if ([System.Version]::TryParse($leaf, [ref]$parsedVersion)) { $ModuleName = Split-Path $parent -Leaf } else { $ModuleName = $leaf } # Removes all versions of the module from the session before importing Get-Module $ModuleName | Remove-Module # Because ModuleBase includes version number, this imports the required version # of the module $Module = Import-Module $ModuleBase\$ModuleName.psm1 -PassThru -ErrorAction Stop $commands = Get-Command -Module $module ## When testing help, remember that help is cached at the beginning of each session. ## To test, restart session. foreach ($command in $commands) { $commandName = $command.Name Describe "Test help for $commandName" { # If help is not found, synopsis in auto-generated help is the syntax diagram It "should not be auto-generated" { (Get-Help $command -ErrorAction SilentlyContinue).Synopsis | Should Not BeLike '*`[`<CommonParameters`>`]*' } # Should be a description for every function It "gets description for $commandName" { (Get-Help $command -ErrorAction SilentlyContinue).Description | Should Not BeNullOrEmpty } # Should be at least one example It "gets example code from $commandName" { ((Get-Help $command -ErrorAction SilentlyContinue).Examples.Example | Select-Object -First 1).Code | Should Not BeNullOrEmpty } # Should be at least one example description It "gets example help from $commandName" { ((Get-Help $command -Full -ErrorAction SilentlyContinue).Examples.Example.Remarks | Select-Object -First 1).Text | Should Not BeNullOrEmpty } Context "Test parameter help for $commandName" { $Common = 'Debug', 'ErrorAction', 'ErrorVariable', 'InformationAction', 'InformationVariable', 'OutBuffer', 'OutVariable', 'PipelineVariable', 'Verbose', 'WarningAction', 'WarningVariable' $parameterNames = (Get-Command $command).ParameterSets.Parameters.Name | Sort-Object -Unique | Where-Object { $_ -notin $common } foreach ($parameterName in $parameterNames) { # Should be a description for every parameter It "gets help for parameter: $parameterName" { (Get-Help $command -Parameter $parameterName -ErrorAction SilentlyContinue).Description.Text | Should Not BeNullOrEmpty } } } } }
PowerShellCorpus/PowerShellGallery/AutoPatchDSC/1.4.2/Write-AutoPatchLog.ps1
Write-AutoPatchLog.ps1
#write log with verbose option Function Write-AutoPatchLog { [CmdletBinding()] param ( [Parameter(Mandatory=$True, Position=1)] [ValidateNotNullOrEmpty()] [string] $message, [string] $logFile = $Global:AutoPatchDSCLogFile, [switch] $writeError, [switch] $writeWarning, [switch] $writeInformation, [switch] $writeDebug ) (Get-PSCallStack)[1].command #Default if non specified if ($logfile -eq '') {$logFile = 'C:\Windows\AutoPatchLog.txt'} #make sure log directory exists $logDir = (Split-path $logFile) if (-not (test-path -PathType Container -Path $logDir)) {New-Item -ItemType Directory -Path $logDir} #Write to the log file and verbose stream $output = "[$((Get-PSCallStack)[2].command):$((Get-PSCallStack)[1].command)] $(Get-Date): $message" try { $output | Out-File -FilePath $logFile -Append } catch { Write-Error $_.Exception } if ($writeError) {Write-Error $output} elseif ($writeWarning) {Write-Warning $output} elseif ($writeDebug) {Write-Debug $output} elseif ($writeInformation) {Write-Information $output} else {Write-Verbose $output} }
PowerShellCorpus/PowerShellGallery/testing/0.1.1/src/Import-ModuleFromPath.ps1
Import-ModuleFromPath.ps1
#Requires -Version 3.0 <# .Synopsis Re-Imports a module from the given path. .DESCRIPTION The function can be used in a Pester test script to load a module from the developer path by removing all already loaded modules with the same name. .EXAMPLE Import-ModuleFromPath . Reloads the module from the current location .EXAMPLE Import-ModuleFromPath ..\anymodule Reloads the module from the relative path .EXAMPLE Import-ModuleFromPath C:\path\to\module Reloads the module from the absolute path .EXAMPLE Import-ModuleFromPath -Parent Reloads the module by analyzing the PSCallStack. The module folder must be located in the parent folder. The Parent switch can be used when the tests folder is located inside the module folder. c:\path\to\module |-- module.psm1 (or module.psd1) |-- tests |-- some.tests.ps1 If the function "Import-ModuleFromPath -Parent" is being used inside the "some.tests.ps1"" Pester test, the import function resolves the module path "c:\path\to\module" #> function Import-ModuleFromPath{ [CmdletBinding(DefaultParameterSetName='ByPath')] Param ( # The path to the module folder. [Parameter( ParameterSetName='ByPath', Mandatory, Position=0 )] [string] $Path, # Indicates that the module should be loaded from the parent folder of the current # invocation scope. [Parameter( ParameterSetName='ByParentSwitch', Mandatory )] [switch] $Parent ) if ($PsCmdlet.ParameterSetName -eq 'ByParentSwitch') { $Path = GetPathFromCallStack $Name = Split-Path -Path $Path -Leaf Write-Verbose "Identified module path from call stack: $Path" } else { # Only the path has been specified. Resolve module name from path $Name = (Get-Item $Path -ErrorAction Stop).Name } $absolutePath = (Get-Item $Path).FullName Write-Verbose -Message "Path to module: $Path" Get-Module -Name $Name -All | Remove-Module -Force Import-Module $absolutePath -Global -Force -ErrorAction Stop } function GetPathFromCallStack { $scriptRoot = (Get-PSCallStack)[2].GetFrameVariables().PSScriptRoot.Value Split-Path -Parent -Path $scriptRoot }
PowerShellCorpus/PowerShellGallery/testing/0.1.1/tests/TestHelper.ps1
TestHelper.ps1
function New-TestModule { Param([string] $Name) # The actual module folder $moduleFolder = New-Item -Path "${TestDrive}\${Name}" -ItemType Directory # The corresponding module.psm1 file New-Item -Path "${moduleFolder}\${Name}.psm1" -ItemType File | Out-Null Write-Output $moduleFolder } function New-TestScript { Param([string] $Path, [string] $Content) $scriptPath = New-Item -Path $Path -ItemType File -Force Set-Content -Path $scriptPath -Value $Content Write-Output $scriptPath }
PowerShellCorpus/PowerShellGallery/testing/0.1.1/tests/TestHelper.Meta.Tests.ps1
TestHelper.Meta.Tests.ps1
#Requires -Modules Pester $sut = 'TestHelper' . "${PSScriptRoot}\${sut}.ps1" Describe "'New-TestModule' tests" { $path = New-TestModule 'mymodule' AfterAll { Get-Module 'mymodule' -All | Remove-Module -Force } It "should exist the module folder" { $path | Should exist } It "should contain the module name in the path" { Split-Path -Path $path -Leaf | Should be 'mymodule' } It "should be possible to import the test module" { { Import-Module $path } | Should not throw } } Describe "'New-TestScript' tests" { $sampleText = 'Hello World' $path = New-TestScript -Path "${TestDrive}\mytest.ps1" -Content @" Write-Output "${sampleText}!" "@ It "should exist the module folder" { $path | Should exist } It "should contain the specified content" { Get-Content -Path $path | Should be "Write-Output `"Hello World!`"" } It "should be evaluated correctly when calling the script" { & $path | Should be "Hello World!" } }
PowerShellCorpus/PowerShellGallery/testing/0.1.1/tests/DummyModule.Tests.ps1
DummyModule.Tests.ps1
#Requires -Modules Pester $testingModule = Get-Item -Path "${PSScriptRoot}\..\..\testing" Get-Module -Name testing -All | Remove-Module -Force Import-Module $testingModule -Force -ErrorAction Stop Import-ModuleFromPath -Path "${PSScriptRoot}\DummyModule" Describe "Calling method from DummyModule when imported via Path parameter" { It "Should return Hello World" { Invoke-MyDummyFunctionForTheTest | Should be 'Hello World!' } }
PowerShellCorpus/PowerShellGallery/testing/0.1.1/tests/Import-ModuleFromPath.Tests.ps1
Import-ModuleFromPath.Tests.ps1
#Requires -Modules Pester . $PSScriptRoot\TestHelper.ps1 $module = 'testing' $sut = 'Import-ModuleFromPath' $path = Split-Path -Path $PSScriptRoot -Parent Get-Module -Name $module -All | Remove-Module -Force Import-Module $path -Force -ErrorAction Stop Describe "'$sut' tests with valid module folder" { $modulePath = New-TestModule 'mymodule' Mock -CommandName Remove-Module -ModuleName $module -MockWith { } Mock -CommandName Import-Module -ModuleName $module -MockWith { } It "should not throw error" { { & $sut -Path $modulePath } | Should Not Throw } Context "With loaded module" { # Simulate module has already been loaded Mock -CommandName Get-Module -ModuleName $module -MockWith { New-Object -TypeName PSModuleInfo -ArgumentList $false } & $sut -Path $modulePath It "Remove-Module should be called" { Assert-MockCalled -CommandName Remove-Module -Exactly 1 -ModuleName $module -Scope Context } It "Import-Module should be called" { Assert-MockCalled -CommandName Import-Module -Exactly 1 -ModuleName $module -Scope Context } } Context "With module not loaded" { # Simulate no module has been loaded Mock -CommandName Get-Module -ModuleName $module -MockWith { } & $sut -Path $modulePath It "Remove-Module should not be called" { Assert-MockCalled -CommandName Remove-Module -Exactly 0 -ModuleName $module -Scope Context } It "Import-Module should be called" { Assert-MockCalled -CommandName Import-Module -Exactly 1 -ModuleName $module -Scope Context } } } Describe "'$sut' tests with no corresponding psm1 file" { # Only create folder without module file $modulePath = New-Item -Path "${TestDrive}\module" -ItemType Directory Mock -CommandName Remove-Module -ModuleName $module -MockWith { } Mock -CommandName Get-Module -ModuleName $module -MockWith { } It "should throw error" { { & $sut -Path $modulePath } | Should Throw } } Describe "'$sut' tests with invalid path" { $modulePath = "C:\path\does\not\exist" It "Should not exist the module" { $modulePath | Should not exist } It "should throw error" { { & $sut -Path $modulePath } | Should Throw } } <# Idea of the following tests: When the SUT gets invoked without a Path parameter using the Parent switch, the Path gets determinded by analyzing the PSCallStack. To get a valid CallStack the invocation of the SUT gets written into a *.ps1 file on the $TestDrive. The created *.ps1 file will be used to call the SUT. #> Describe "'$sut' with Parent switch" { $modulePath = New-TestModule 'mymodule' # Create the file as it would be a pester tests file and write the file content into it $scriptPath = New-TestScript ` -Path "${modulePath}\tests\Invoke-SutWithoutPath.Tests.ps1" ` -Content "$sut -Parent" Mock -CommandName Remove-Module -ModuleName $module -MockWith { } Mock -CommandName Import-Module -ModuleName $module -MockWith { } Mock -CommandName Get-Module -ModuleName $module -MockWith { } It "Should exist the test script" { $scriptPath | Should exist } It "should identify the path when location is set" { # invoke the command from the created script & $scriptPath Assert-MockCalled -CommandName Import-Module -Exactly 1 ` -ModuleName $module -Scope It -ParameterFilter { $Name -eq $modulePath} } } Describe "'$sut' with real module structure" { $modulePath = New-TestModule 'mymodule' AfterEach { Get-Module 'mymodule' -All | Remove-Module } Context "Calling $sut from tests script using absolute path" { $scriptPath = New-TestScript -Path "${modulePath}\Some.Tests.ps1" ` -Content "$sut $modulePath" It "should load module" { & $scriptPath Get-Module 'mymodule' -All | Should not BeNullOrEmpty } } Context "Calling $sut using relative path" { $currentLocation = Get-Location It "should load module when at correct location" { Set-Location -Path $modulePath & $sut ..\mymodule Get-Module 'mymodule' -All | Should not BeNullOrEmpty } It "should throw when at wrong location" { Set-Location -Path (Split-Path $modulePath -Parent) { & $sut ..\mymodule } | Should throw } Set-Location $currentLocation } Context "Calling $sut using '.' for Path parameter" { $currentLocation = Get-Location It "should load module" { Set-Location -Path $modulePath & $sut . Get-Module 'mymodule' -All | Should not BeNullOrEmpty } Set-Location $currentLocation } }
PowerShellCorpus/PowerShellGallery/testing/0.1.1/tests/DummyModule/test/DummyModule.Tests.ps1
DummyModule.Tests.ps1
#Requires -Modules Pester $testingModule = Get-Item -Path "${PSScriptRoot}\..\..\..\..\testing" Get-Module -Name testing -All | Remove-Module -Force Import-Module $testingModule -Force -ErrorAction Stop Import-ModuleFromPath -Parent Describe "Calling method from DummyModule when imported via Parent parameter" { It "Should return Hello World" { Invoke-MyDummyFunctionForTheTest | Should be 'Hello World!' } }
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/TestSampleUsingAzure.ps1
TestSampleUsingAzure.ps1
# To Run this test create a Windows Server 2012 or 2012 R2 VM in Azure # and run this script. It will prompt you to choose a VM, choose the VM. # wait a while, RDP into the machine and manually verify that the DHCP Server # is configured as specified in .\samples\SampleConfiguration.ps1 Write-Verbose -Message 'Publishing configuration ...' -Verbose Publish-AzureVMDscConfiguration -ConfigurationPath .\Samples\SampleConfiguration.ps1 -Verbose -force Write-Verbose -Message 'Choosing VM ...' -Verbose $vm = get-azurevm | Out-GridView -Title 'choose vm to test with' -OutputMode Single if($vm) { Write-Verbose -Message 'Setting Extension ...' -Verbose Set-AzureVMDscExtension -ConfigurationArchive SampleConfiguration.ps1.zip -ConfigurationName Sample_xDhcpsServerScope_NewScope -VM $vm -Verbose Write-Verbose -Message 'Updating Vm ...' -Verbose $vm | Update-AzureVM } Write-Verbose -Message 'Done' -Verbose
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Misc/New-DhcpServerOptionResource.ps1
New-DhcpServerOptionResource.ps1
$Properties = @{ DnsServer = New-xDscResourceProperty -Name DnsServerIPAddress -Type String[] -Attribute Required ` -Description 'IP address of DNS Servers' Router = New-xDscResourceProperty -Name Router -Type String[] -Attribute Required ` -Description 'IP address of the router/default gateway.' DnsDomain = New-xDscResourceProperty -Name DnsDomain -Type String -Attribute Write ` -Description 'Domain name of DNS Server' AddressFamily = New-xDscResourceProperty -Name AddressFamily -Type String -Attribute Write ` -ValidateSet 'IPv4' -Description 'Address family type' ScopeID = New-xDscResourceProperty -Name ScopeID -Type String -Attribute Key ` -Description 'ScopeId for which options are set' Ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write ` -ValidateSet 'Present','Absent' ` -Description 'Whether option should be set or removed' } New-xDscResource -Name MSFT_xDhcpServerOption -Property $Properties.Values -ModuleName xDhcpServer -FriendlyName xDhcpServerOption
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Misc/New-DhcpServerScopeResource.ps1
New-DhcpServerScopeResource.ps1
$Properties = @{ ScopeID = New-xDscResourceProperty -Name ScopeID -Type String -Attribute Read ` -Description 'ScopeId for which properties are set' Name = New-xDscResourceProperty -Name Name -Type String -Attribute Required ` -Description 'Name of DHCP Scope' AddressFamily = New-xDscResourceProperty -Name AddressFamily -Type String -Attribute Write ` -ValidateSet 'IPv4' -Description 'Address family type' IPStartRange = New-xDscResourceProperty -Name IPStartRange -Type String -Attribute Key ` -Description 'Starting address to set for this scope' IPEndRange = New-xDscResourceProperty -Name IPEndRange -Type String -Attribute Key ` -Description 'Ending address to set for this scope' SubnetMask = New-xDscResourceProperty -Name SubnetMask -Type String -Attribute Write ` -Description 'Subnet mask for the scope specified in IP address format' LeaseDuration = New-xDscResourceProperty -Name LeaseDuration -Type String -Attribute Write ` -Description 'Time interval for which an IP address should be leased' State = New-xDscResourceProperty -Name State -Type String -Attribute Write ` -ValidateSet 'Active','Inactive' ` -Description 'Whether scope should be active or inactive' Ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write ` -ValidateSet 'Present','Absent' ` -Description 'Whether scope should be set or removed' } New-xDscResource -Name MSFT_xDhcpServerScope -Property $Properties.Values -ModuleName xDhcpServer -FriendlyName xDhcpServerScope
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Misc/New-DhcpServerReservationResource.ps1
New-DhcpServerReservationResource.ps1
$Properties = @{ ScopeID = New-xDscResourceProperty -Name ScopeID -Type String -Attribute Key ` -Description 'ScopeId for which reservations are set' IPAddress = New-xDscResourceProperty -Name IPAddress -Type String -Attribute Required ` -Description 'IP address of the reservation for which the properties are modified' ClientMACAddress = New-xDscResourceProperty -Name ClientMACAddress -Type String -Attribute Required ` -Description 'Client ID to set on the reservation For Windows clients it is the MAC address' Name = New-xDscResourceProperty -Name Name -Type String -Attribute Write ` -Description 'Reservation name' AddressFamily = New-xDscResourceProperty -Name AddressFamily -Type String -Attribute Write ` -ValidateSet 'IPv4' -Description 'Address family type' Ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write ` -ValidateSet 'Present','Absent' ` -Description 'Whether option should be set or removed' } New-xDscResource -Name MSFT_xDhcpServerReservation -Property $Properties.Values -ModuleName xDhcpServer -FriendlyName xDhcpServerReservation
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Samples/SampleConfiguration.ps1
SampleConfiguration.ps1
configuration Sample_xDhcpsServerScope_NewScope { Import-DscResource -module xDHCpServer WindowsFeature DHCP { Name = 'DHCP' Ensure = 'Present' } xDhcpServerScope Scope { Ensure = 'Present' IPStartRange = '192.168.1.1' IPEndRange = '192.168.1.254' Name = 'ContosoScope' SubnetMask = '255.255.255.0' LeaseDuration = '00:08:00' State = 'Active' AddressFamily = 'IPv4' DependsOn = @('[WindowsFeature]DHCP') } xDhcpServerReservation PullServerIP { Ensure = 'Present' ScopeID = '192.168.1.0' ClientMACAddress = '00155D8A54A1' IPAddress = '192.168.1.2' Name = 'DSCPullServer' AddressFamily = 'IPv4' DependsOn = @('[WindowsFeature]DHCP') } xDhcpServerOption Option { Ensure = 'Present' ScopeID = '192.168.1.0' DnsDomain = 'contoso.com' DnsServerIPAddress = '192.168.1.22','192.168.1.1' AddressFamily = 'IPv4' Router = '192.168.1.1' DependsOn = @('[WindowsFeature]DHCP') } }
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Tests/Unit/MSFT_xDhcpServerAuthorization.Tests.ps1
MSFT_xDhcpServerAuthorization.Tests.ps1
$Global:DSCModuleName = 'xDhcpServer' $Global:DSCResourceName = 'MSFT_xDhcpServerAuthorization' #region HEADER [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } else { & git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull') } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Unit #endregion # TODO: Other Optional Init Code Goes Here... # Begin Testing try { #region Pester Tests # The InModuleScope command allows you to perform white-box unit testing on the internal # (non-exported) code of a Script Module. InModuleScope $Global:DSCResourceName { #region Pester Test Initialization ## Mock missing functions function Get-DhcpServerInDc { } function Add-DhcpServerInDc { } ## http://virtualengine.co.uk/2015/mocking-missing-cmdlet-pipelines-with-pester/ function Remove-DhcpServerInDc { [CmdletBinding()] param ( [Parameter(ValueFromPipeline)] $someValue ) } ## Test TargetResource parameters with Ensure = 'Present' $testPresentParams = @{ Ensure = 'Present'; DnsName = 'test1.contoso.com'; IPAddress = '192.168.1.1'; } ## Test TargetResource parameters with Ensure = 'Absent' $testAbsentParams = @{ Ensure = 'Absent'; DnsName = 'test1.contoso.com'; IPAddress = '192.168.1.1'; } ## Authorised server list with test1.contoso.com authorised $fakeDhcpServersPresent = @( @{ IPAddress = '192.168.1.1'; DnsName = 'test1.contoso.com'; }, @{ IPAddress = '192.168.1.2'; DnsName = 'test2.contoso.com'; }, @{ IPAddress = '192.168.1.3'; DnsName = 'test3.contoso.com'; } ) ## Authorised server list with test1.contoso.com not authorised $fakeDhcpServersAbsent = @( @{ IPAddress = '192.168.1.2'; DnsName = 'test2.contoso.com'; }, @{ IPAddress = '192.168.1.3'; DnsName = 'test3.contoso.com'; } ) ## Authorised server list with mismathed DnsName, but matched IPAddress $fakeDhcpServersMismatchDnsName = @( @{ IPAddress = '192.168.1.1'; DnsName = 'test11.contoso.com'; }, @{ IPAddress = '192.168.1.2'; DnsName = 'test2.contoso.com'; }, @{ IPAddress = '192.168.1.3'; DnsName = 'test3.contoso.com'; } ) ## Authorised server list with mismathed IPAddress, but matched DnsName $fakeDhcpServersMismatchIPAddress = @( @{ IPAddress = '192.168.1.11'; DnsName = 'test1.contoso.com'; }, @{ IPAddress = '192.168.1.2'; DnsName = 'test2.contoso.com'; }, @{ IPAddress = '192.168.1.3'; DnsName = 'test3.contoso.com'; } ) #endregion #region Function Get-TargetResource Describe "$($Global:DSCResourceName)\Get-TargetResource" { Mock Assert-Module { }; It 'Returns a [System.Collection.Hashtable] type' { Mock Get-DhcpServerInDC { return $fakeDhcpServersPresent; } $result = Get-TargetResource @testPresentParams; $result -is [System.Collections.Hashtable] | Should Be $true; } It 'Returns Ensure is Present when DHCP server authorization exists' { Mock Get-DhcpServerInDC { return $fakeDhcpServersPresent; } $result = Get-TargetResource @testPresentParams $result.Ensure | Should Be 'Present'; } It 'Returns Ensure is Absent when DHCP server authorization does not exist' { Mock Get-DhcpServerInDC { } $result = Get-TargetResource @testPresentParams; $result.Ensure | Should Be 'Absent'; } } #endregion Function Get-TargetResource #region Function Test-TargetResource Describe "$($Global:DSCResourceName)\Test-TargetResource" { Mock Assert-Module { }; It 'Returns a [System.Boolean] type' { Mock Get-DhcpServerInDC { return $fakeDhcpServersPresent; } $result = Test-TargetResource @testPresentParams; $result -is [System.Boolean] | Should Be $true; } It 'Fails when DHCP Server authorization does not exist and Ensure is Present' { Mock Get-DhcpServerInDC { return $fakeDhcpServersAbsent; } Test-TargetResource @testPresentParams | Should Be $false; } It 'Fails when DHCP Server authorization does exist and Ensure is Absent' { Mock Get-DhcpServerInDC { return $fakeDhcpServersPresent; } Test-TargetResource @testAbsentParams | Should Be $false; } It 'Fails when DHCP Server authorization does exist, Ensure is Present but DnsName is wrong' { Mock Get-DhcpServerInDC { return $fakeDhcpServersMismatchDnsName; } Test-TargetResource @testPresentParams | Should Be $false; } It 'Fails when DHCP Server authorization does exist, Ensure is Present but IPAddress is wrong' { Mock Get-DhcpServerInDC { return $fakeDhcpServersMismatchIPAddress; } Test-TargetResource @testPresentParams | Should Be $false; } It 'Passes when DHCP Server authorization does exist and Ensure is Present' { Mock Get-DhcpServerInDC { return $fakeDhcpServersPresent; } $result = Test-TargetResource @testPresentParams $result -is [System.Boolean] | Should Be $true; } It 'Passes when DHCP Server authorization does not exist and Ensure is Absent' { Mock Get-DhcpServerInDC { return $fakeDhcpServersAbsent; } $result = Test-TargetResource @testAbsentParams $result -is [System.Boolean] | Should Be $true; } } #endregion Function Test-TargetResource #region Function Set-TargetResource Describe "$($Global:DSCResourceName)\Set-TargetResource" { Mock Assert-Module { }; It 'Calls Add-DhcpServerInDc when Ensure is Present' { Mock Add-DhcpServerInDC { } Set-TargetResource @testPresentParams; Assert-MockCalled Add-DhcpServerInDC -Scope It; } It 'Calls Remove-DhcpServerInDc when Ensure is Present' { Mock Get-DhcpServerInDC { return $fakeDhcpServersPresent; } Mock Remove-DhcpServerInDC { } Set-TargetResource @testAbsentParams; Assert-MockCalled Remove-DhcpServerInDC -Scope It; } } #endregion Function Set-TargetResource #region Function Get-IPv4Address Describe "$($Global:DSCResourceName)\Get-IPv4Address" { It 'Returns a IPv4 address' { $result = Get-IPv4Address; $result -match '\d+\.\d+\.\d+\.\d+' | Should Be $true; } } #endregion Function Get-IPv4Address #region Function Get-Hostname Describe "$($Global:DSCResourceName)\Get-Hostname" { It 'Returns at least the current NetBIOS name' { $hostname = [System.Net.Dns]::GetHostname(); $result = Get-Hostname; $result -match $hostname | Should Be $true; } } #endregion Function Get-Hostname } #end InModuleScope } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Tests/Unit/MSFT_xDhcpServerScope.Tests.ps1
MSFT_xDhcpServerScope.Tests.ps1
$Global:DSCModuleName = 'xDhcpServer' $Global:DSCResourceName = 'MSFT_xDhcpServerScope' #region HEADER [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } else { & git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull') } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Unit #endregion # Begin Testing try { #region Pester Tests # The InModuleScope command allows you to perform white-box unit testing on the internal # (non-exported) code of a Script Module. InModuleScope $Global:DSCResourceName { #region Pester Test Initialization # TODO: Optopnal Load Mock for use in Pester tests here... #endregion $testScopeName = 'Test Scope'; $testScopeID = '192.168.1.0'; $testIPStartRange = '192.168.1.10'; $testIPEndRange = '192.168.1.99'; $testSubnetMask = '255.255.255.0'; $testState = 'Active'; $testLeaseDuration = New-TimeSpan -Days 8; $testParams = @{ Name = $testScopeName; IPStartRange = $testIPStartRange; IPEndRange = $testIPEndRange; SubnetMask = $testSubnetMask; } $fakeDhcpServerv4Scope = [PSCustomObject] @{ ScopeID = $testScopeID; Name = $testScopeName; StartRange = $testIPStartRange; EndRange = $testIPEndRange; SubnetMask = $testSubnetMask; LeaseDuration = $testLeaseDuration; State = $testState; AddressFamily = 'IPv4'; } #region Function Get-TargetResource Describe "$($Global:DSCResourceName)\Get-TargetResource" { Mock Assert-Module -ParameterFilter { $ModuleName -eq 'DHCPServer' } { } It 'Calls "Assert-Module" to ensure "DHCPServer" module is available' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Get-TargetResource @testParams; Assert-MockCalled Assert-Module -ParameterFilter { $ModuleName -eq 'DHCPServer' } -Scope It; } It 'Returns a "System.Collections.Hashtable" object type' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Get-TargetResource @testParams; $result -is [System.Collections.Hashtable] | Should Be $true; } } #endregion Function Get-TargetResource #region Function Test-TargetResource Describe "$($Global:DSCResourceName)\Test-TargetResource" { Mock Assert-Module -ParameterFilter { $ModuleName -eq 'DHCPServer' } { } It 'Returns a "System.Boolean" object type' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams; $result -is [System.Boolean] | Should Be $true; } It 'Passes when all parameters are correct' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams; $result | Should Be $true; } It 'Passes when optional "LeaseDuration" parameter is correct' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams -LeaseDuration $testLeaseDuration.ToString(); $result | Should Be $true; } It 'Passes when optional "State" parameter is correct' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams -State 'Active'; $result | Should Be $true; } It 'Passes when "Ensure" = "Absent" and scope does not exist' { Mock Get-DhcpServerv4Scope { } $result = Test-TargetResource @testParams -Ensure 'Absent'; $result | Should Be $true; } It 'Fails when "Name" parameter is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $testNameParams = $testParams.Clone(); $testNameParams['Name'] = 'IncorrectName'; $result = Test-TargetResource @testNameParams; $result | Should Be $false; } It 'Fails when "IPStartRange" parameter is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $testIPStartRangeParams = $testParams.Clone(); $testIPStartRangeParams['IPStartRange'] = '192.168.1.1'; $result = Test-TargetResource @testIPStartRangeParams; $result | Should Be $false; } It 'Fails when "IPEndRange" parameter is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $testIPEndRangeParams = $testParams.Clone(); $testIPEndRangeParams['IPEndRange'] = '192.168.1.254'; $result = Test-TargetResource @testIPEndRangeParams; $result | Should Be $false; } It 'Fails when "SubnetMask" parameter is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $testSubnetMaskParams = $testParams.Clone(); $testSubnetMaskParams['SubnetMask'] = '255.255.240.0'; $result = Test-TargetResource @testSubnetMaskParams; $result | Should Be $false; } It 'Fails when optional "LeaseDuration" parameter is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams -LeaseDuration '08:00:00'; $result | Should Be $false; } It 'Fails when optional "State" parameter is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams -State 'Inactive'; $result | Should Be $false; } It 'Fails when "Ensure" = "Absent" and scope does exist' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } $result = Test-TargetResource @testParams -Ensure 'Absent'; $result | Should Be $false; } } #endregion #region Function Set-TargetResource Describe "$($Global:DSCResourceName)\Set-TargetResource" { Mock Assert-Module -ParameterFilter { $ModuleName -eq 'DHCPServer' } { } It 'Calls "Add-DhcpServerv4Scope" when "Ensure" = "Present" and scope does not exist' { Mock Get-DhcpServerv4Scope { } Mock Add-DhcpServerv4Scope { } Set-TargetResource @testParams; Assert-MockCalled Add-DhcpServerv4Scope -Scope It; } It 'Calls "Remove-DhcpServerv4Scope" when "Ensure" = "Absent" and scope does exist' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } Mock Remove-DhcpServerv4Scope { } Set-TargetResource @testParams -Ensure 'Absent'; Assert-MockCalled Remove-DhcpServerv4Scope -Scope It; } It 'Calls "Set-DhcpServerv4Scope" when "Ensure" = "Present" and scope does exist' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } Mock Set-DhcpServerv4Scope { } Set-TargetResource @testParams -LeaseDuration '08:00:00'; Assert-MockCalled Set-DhcpServerv4Scope -Scope It; } It 'Calls "Remove-DhcpServerv4Scope" when "Ensure" = "Present", scope does exist but "SubnetMask" is incorrect' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } Mock Remove-DhcpServerv4Scope { } Mock Set-DhcpServerv4Scope { } $testSubnetMaskParams = $testParams.Clone(); $testSubnetMaskParams['SubnetMask'] = '255.255.240.0'; Set-TargetResource @testSubnetMaskParams; Assert-MockCalled Remove-DhcpServerv4Scope -Scope It; } } #endregion #region Function Set-TargetResource Describe "$($Global:DSCResourceName)\Validate-ResourceProperties" { # TODO: Complete Tests... } #endregion } #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion # TODO: Other Optional Cleanup Code Goes Here... }
PowerShellCorpus/PowerShellGallery/xDhcpServer/1.5.0.0/Tests/Unit/MSFT_xDhcpServerOption.tests.ps1
MSFT_xDhcpServerOption.tests.ps1
$Global:DSCModuleName = 'xDhcpServer' # Example xNetworking $Global:DSCResourceName = 'MSFT_xDhcpServerOption' # Example MSFT_xFirewall #region HEADER [String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\')) } else { & git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull') } Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force $TestEnvironment = Initialize-TestEnvironment ` -DSCModuleName $Global:DSCModuleName ` -DSCResourceName $Global:DSCResourceName ` -TestType Unit #endregion # Begin Testing try { InModuleScope $Global:DSCResourceName { #region Pester Test Initialization # TODO: Optopnal Load Mock for use in Pester tests here... #endregion $testScopeID = '192.168.1.0'; $testDnsServerIPAddress = '192.168.1.10'; $testDnsDomain = 'contoso.com'; $testRouter = '192.168.1.1'; $testParams = @{ ScopeID = $testScopeID; DnsServerIPAddress = $testDnsServerIPAddress; } $fakeDhcpServerv4Option = [PSCustomObject] @{ ScopeID = $testScopeID; DnsDomain = $testDnsDomain; AddressFamily = 'IPv4'; DnsServerIPAddress = $testDnsServerIPAddress; Router = $testRouter; } $fakeDhcpServerv4Scope = [PSCustomObject] @{ ScopeID = $testScopeID; } #region Function Get-TargetResource Describe "$($Global:DSCResourceName)\Get-TargetResource" { It 'Returns all properties' { Mock Get-DhcpServerv4Scope { return $fakeDhcpServerv4Scope; } Mock Get-DhcpServerv4OptionValue { return $fakeDhcpServerv4Option } $result = Get-TargetResource @testParams; $missingCount = ( $fakeDhcpServerv4Option.psobject.properties.ForEach{ $result.ContainsKey($_.Name) } | Where-Object { -not $_ } | Measure-Object ).Count $missingCount | Should Be 0; } } #endregion Function Get-TargetResource #region Function ValidateResourceProperties Describe "$($Global:DSCResourceName)\ValidateResourceProperties" { $dnsDomainName = 'contoso.com' $dnsIpAddress = @('2.1.1.2','2.1.1.3') $routeripAddress = '1.1.1.2' Mock -CommandName Set-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { } # Absent removes the whole option, so this is not new to this issue. # So not currently testing Absent and Apply = $true foreach($params in @(@{Ensure='Present';Apply=$false},@{Ensure='Absent';Apply=$false},@{Ensure='Present';Apply=$true})) { It "Return true when DNS Server scalar match, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=6;Value=$dnsIpAddress[1]}) } $expectedReturn = $true if($params.Ensure -eq 'Absent') { $expectedReturn = $false } if($params.Apply) { $expectedReturn = $null } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -DnsServerIPAddress $dnsIpAddress[1] -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue -Exactly 0 -Scope It } It "Return true when DNS Server array match, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=6;Value=$dnsIpAddress}) } $expectedReturn = $true if($params.Ensure -eq 'Absent') { $expectedReturn = $false } if($params.Apply) { $expectedReturn = $null } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -DnsServerIPAddress $dnsIpAddress -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue -Exactly 0 -Scope It } It "Return false when DNS Server mismatch, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=6;Value=$dnsIpAddress}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -DnsServerIPAddress '1.2.2.1' -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } It "Return false when DNS Server empty, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=15;Value=$dnsDomainName}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -DnsServerIPAddress '1.2.2.1' -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } It "Return true when DNS domain name match, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=15;Value=$dnsDomainName}) } $expectedReturn = $true if($params.Ensure -eq 'Absent') { $expectedReturn = $false } if($params.Apply) { $expectedReturn = $null } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -DnsDomain $dnsDomainName -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue -Exactly 0 -Scope It } It "Return false when DNS domain name mismatch, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=15;Value=$dnsDomainName}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -DnsDomain 'wrong.com' -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } It "Return true when Router scalar match, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=3;Value=$routeripAddress}) } $expectedReturn = $true if($params.Ensure -eq 'Absent') { $expectedReturn = $false } if($params.Apply) { $expectedReturn = $null } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -Router $routeripAddress -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue -Exactly 0 -Scope It } It "Return true when Router array match, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=3;Value=$routeripAddress}) } $expectedReturn = $true if($params.Ensure -eq 'Absent') { $expectedReturn = $false } if($params.Apply) { $expectedReturn = $null } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -Router $routeripAddress -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue -Exactly 0 -Scope It } It "Return false when Router scalar mismatch, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=3;Value=$routeripAddress}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -Router '1.1.1.3' -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } It "Return false when Router array mismatch, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=3;Value=$routeripAddress}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -Router @('1.1.1.2','1.1.1.4') -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } It "Return false when Router array extra element, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=3;Value=$routeripAddress}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0'-Router @('1.1.1.2','1.1.1.3', '1.1.1.4') -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } It "Return false when Router array missing element, apply: $($params.Apply), Ensure: $($params.Ensure)" { Mock -CommandName Get-DhcpServerv4OptionValue -ModuleName MSFT_xDhcpServerOption -MockWith { return @(new-object psobject -property @{OptionId=3;Value=$routeripAddress}) } $expectedReturn = $false $setMockCalledParams = @{} if($params.Apply) { $expectedReturn = $null } else { $setMockCalledParams.Add('Exactly',$true) $setMockCalledParams.Add('Times',0) } $result = ValidateResourceProperties @params -scopeId '1.1.1.0' -Router @('1.1.1.2','1.1.1.3') -Verbose $result | should be $expectedReturn Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName Get-DhcpServerv4OptionValue -Scope It Assert-MockCalled -ModuleName MSFT_xDhcpServerOption -commandName set-DhcpServerv4OptionValue @setMockCalledParams -Scope It } } #endregion } #endregion InModuleScope } #endregion } finally { #region FOOTER Restore-TestEnvironment -TestEnvironment $TestEnvironment #endregion }
PowerShellCorpus/PowerShellGallery/DockerDsc/0.0.0.1/Examples/Example-DockerService.ps1
Example-DockerService.ps1
configuration docker { param ( [ValidateNotNullOrEmpty()] [String] $Path = 'C:\Program Files\Docker' ) Import-DscResource -ModuleName DockerDsc Import-DscResource -ModuleName xPSDesiredStateConfiguration node localhost { WindowsFeature containers { Name = 'Containers' Ensure = 'Present' } #download latest beta xRemoteFile DockerD { DestinationPath = ('{0}\dockerd.exe' -f $Path) Uri = 'https://master.dockerproject.org/windows/amd64/dockerd.exe' } #download latest beta xRemoteFile DockerClient { DestinationPath = ('{0}\docker.exe' -f $Path) Uri = 'https://master.dockerproject.org/windows/amd64/docker.exe' } Environment DockerEnv { Path = $true Name = 'Path' Value = ('{0}\' -f $Path) } DockerService DockerD { Ensure = 'Present' Path = $Path DependsOn = '[WindowsFeature]containers','[xRemoteFile]DockerD' } service DockerD { Name = 'Docker' State = 'Running' StartupType = 'Automatic' DependsOn = '[DockerService]DockerD' } } }
PowerShellCorpus/PowerShellGallery/cSecurityOptions/3.1.2/DSCResources/Tests/Unit/UserRightsAssignment.Tests.ps1
UserRightsAssignment.Tests.ps1
$DSCResourceName = 'UserRightsAssignment' $DSCModuleName = 'cSecurityOptions' $Splat = @{ Path = $PSScriptRoot ChildPath = "..\..\DSCResources\$DSCResourceName\$DSCResourceName.psm1" Resolve = $true ErrorAction = 'Stop' } $DSCResourceModuleFile = Get-Item -Path (Join-Path @Splat) $moduleRoot = "${env:ProgramFiles}\WindowsPowerShell\Modules\$DSCModuleName" if(-not (Test-Path -Path $moduleRoot)) { $null = New-Item -Path $moduleRoot -ItemType Directory } else { # Copy the existing folder out to the temp directory to hold until the end of the run # Delete the folder to remove the old files. $tempLocation = Join-Path -Path $env:Temp -ChildPath $DSCModuleName Copy-Item -Path $moduleRoot -Destination $tempLocation -Recurse -Force Remove-Item -Path $moduleRoot -Recurse -Force $null = New-Item -Path $moduleRoot -ItemType Directory } Copy-Item -Path $PSScriptRoot\..\..\* -Destination $moduleRoot -Recurse -Force -Exclude '.git' if (Get-Module -Name $DSCResourceName) { Remove-Module -Name $DSCResourceName } Import-Module -Name $DSCResourceModuleFile.FullName -Force InModuleScope UserRightsAssignment { ####################################################################################### Describe 'Get-TargetResource' { Context 'ServerCore' { #region Mocks Mock TestServerCore { $true } #endregion $NonServerCoreConformantAssignments = @( 'SeChangeNotifyPrivilege', 'SeIncreaseWorkingSetPrivilege' ) foreach ($nonServerCoreConformantAssignment in $nonServerCoreConformantAssignments) { It "$nonServerCoreConformantAssignment Privilege should return return Absent" { (get-targetresource -Privilege $nonServerCoreConformantAssignment).Ensure | should be 'Absent' } } } Context '0 Users' { Mock 'GetAccountsWithUserRight' { @{ 'Account' = '' } } It 'should return ensure Absent' { (get-targetresource -Privilege 'SeIncreaseQuotaPrivilege').Ensure | should be 'Absent' } } Context '1 Users' { Mock 'GetAccountsWithUserRight' { @{ 'Account' = 'a' } } It 'should return ensure Present' { (get-targetresource -Privilege 'SeIncreaseQuotaPrivilege').Ensure | should be 'Present' } It 'should return proper account' { (get-targetresource -Privilege 'SeIncreaseQuotaPrivilege').Identity | should be 'a' } } Context 'Many Users' { Mock 'GetAccountsWithUserRight' { @{ 'Account' = 'b', 'c', 'd' } } It 'should return ensure Present' { (get-targetresource -Privilege 'SeIncreaseQuotaPrivilege').Ensure | should be 'Present' } It 'should return proper account' { (get-targetresource -Privilege 'SeIncreaseQuotaPrivilege').Identity | should be 'b', 'c', 'd' } } } Describe 'Test-TargetResource' { Mock GetUserRightsAssignment { @{ 'Privilege' = $Privilege 'Identity' = '' 'Ensure' = 'Absent' } } -ParameterFilter { $Privilege -eq 'SeNetworkLogonRight' } Mock GetUserRightsAssignment { @{ 'Privilege' = $Privilege 'Identity' = 'a' 'Ensure' = 'Present' } } -ParameterFilter { $Privilege -eq 'SeTcbPrivilege' } Mock FilterIdentity { $Identity } Context 'ServerCore' { #region Mocks Mock TestServerCore { $true } #endregion $NonServerCoreConformantAssignments = @( 'SeChangeNotifyPrivilege', 'SeIncreaseWorkingSetPrivilege' ) foreach ($nonServerCoreConformantAssignment in $nonServerCoreConformantAssignments) { $Parameters = @{ 'Privilege' = $NonServerCoreConformantAssignment 'Identity' = 'a' 'Ensure' = 'Present' } It "$nonServerCoreConformantAssignment test for Ensure should be false" { test-targetresource @Parameters | should be $false } } It 'Should return true if Privilege Exists' { $Parameters = @{ 'Privilege' = 'SeTcbPrivilege' 'Identity' = 'a' 'Ensure' = 'Present' } test-targetresource @Parameters | should be $True } It 'Should return false if Privilege Does not Exists' { $Parameters = @{ 'Privilege' = 'SeNetworkLogonRight' 'Identity' = 'a' 'Ensure' = 'Present' } test-targetresource @Parameters | should be $False } It 'Should return false if input identity does not match current identity list (more account than specified)' { $Parameters = @{ 'Privilege' = 'SeTcbPrivilege' 'Identity' = 'a','b' 'Ensure' = 'Present' } test-targetresource @Parameters | should be $False } It 'Should return false if input identity does not match current identity list (no accounts specified)' { $Parameters = @{ 'Privilege' = 'SeTcbPrivilege' 'Identity' = '' 'Ensure' = 'Present' } test-targetresource @Parameters | should be $False } } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Add-GacAssembly.ps1
Add-GacAssembly.ps1
<# .SYNOPSIS Adds the assembly to the GAC .DESCRIPTION Adds the assembly to the GAC. An assembly is only added to the GAC if the assembly is not already added to the GAC or if the file version is higher than the assembly already in the GAC. Can only be called from an elevated prompt. It must be a strong named/signed assembly (PublicKeyToken must be set). .PARAMETER Path Specifies the path to the assembly. Wildcards are permitted. .PARAMETER LiteralPath Specifies the path to the assembly. Unlike Path, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcards. .PARAMETER InstallReference Specifies the InstallReference to add the assembly to the GAC .PARAMETER Force Force the addition to the GAC even if the file version of the assembly already in the GAC is higher .PARAMETER PassThru The AssemblyName added is returned as output .INPUTS [string] .EXAMPLE C:\PS> Add-GacAssembly .\SomeAssembly.dll This example adds the SomeAssembly.dll assembly to the GAC. .LINK http://powershellgac.codeplex.com #> function Add-GacAssembly { [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'PathSet')] [OutputType('System.Reflection.AssemblyName')] param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'PathSet')] [ValidateNotNullOrEmpty()] [string[]] $Path, [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'LiteralPathSet')] [ValidateNotNullOrEmpty()] [Alias('PSPath')] [string[]] $LiteralPath, [Parameter(Position = 1)] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-GacAssemblyInstallReferenceCanBeUsed $_ } )] [PowerShellGac.InstallReference] $InstallReference, [Switch] $Force, [Switch] $PassThru ) process { if ($PsCmdlet.ParameterSetName -eq 'PathSet') { $paths = @() foreach ($p in $Path) { $paths += (Resolve-Path $p).ProviderPath } } else { $paths = (Resolve-Path -LiteralPath $LiteralPath).ProviderPath } foreach ($p in $paths) { if (!$PSCmdLet.ShouldProcess($p)) { continue } [PowerShellGac.GlobalAssemblyCache]::InstallAssembly($p, $InstallReference, $Force) Write-Verbose "Installed $p into the GAC" if ($PassThru) { [System.Reflection.AssemblyName]::GetAssemblyName($p) } } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Get-GacAssemblyInstallReference.ps1
Get-GacAssemblyInstallReference.ps1
<# .SYNOPSIS Gets the InstallReference of assemblies in the GAC .DESCRIPTION Gets the InstallRefernence of assemblies in the GAC. InstallRefernence shows if an assembly is referenced by an installer. .PARAMETER AssemblyName Specifies the assembly name. Must be fully qualified. See Test-AssemblyNameFullyQualified. .INPUTS [System.Reflection.AssemblyName[]] .EXAMPLE C:\PS> Get-GacAssembly -Name System | Get-GacAssemblyInstallReference Type Identifier Description ---- ---------- ----------- Opaque {71F8EFBF-09AF-418D-91F1-52707CDFA274} .NET Framework Redist Setup Opaque {71F8EFBF-09AF-418D-91F1-52707CDFA274} .NET Framework Redist Setup This example returns the InstallReferences from the System assemblies in the GAC. .LINK Test-AssemblyNameFullyQualified .LINK http://powershellgac.codeplex.com #> function Get-GacAssemblyInstallReference { [CmdletBinding()] [OutputType('PowerShellGac.InstallReference')] param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-AssemblyNameFullyQualified $_ } )] [System.Reflection.AssemblyName[]] $AssemblyName ) process { foreach ($assmName in $AssemblyName) { [PowerShellGac.GlobalAssemblyCache]::GetInstallReferences($assmName) } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Remove-GacAssembly.ps1
Remove-GacAssembly.ps1
<# .SYNOPSIS Removes the assembly from the GAC .DESCRIPTION Removes the assembly from the GAC. Can only be called from an elevated prompt. .PARAMETER AssemblyName Specifies the assembly name. Must be fully qualified. See Test-AssemblyNameFullyQualified. .PARAMETER InstallReference Specifies the InstallReference used to remove the assembly from the GAC. .PARAMETER PassThru The AssemblyName removed is returned as output .INPUTS [System.Reflection.AssemblyName[]] .EXAMPLE C:\PS> Get-GacAssembly -Name SomeAssembly | Remove-GacAssembly This example removes all assemblies with the name SomeAssembly from the GAC. .LINK Test-AssemblyNameFullyQualified .LINK http://powershellgac.codeplex.com #> function Remove-GacAssembly { [CmdletBinding(SupportsShouldProcess = $true)] [OutputType('System.Reflection.AssemblyName')] param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-AssemblyNameFullyQualified $_ } )] [System.Reflection.AssemblyName[]] $AssemblyName, [Parameter(Position = 1)] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-GacAssemblyInstallReferenceCanBeUsed $_ } )] [PowerShellGac.InstallReference] $InstallReference, [Switch] $PassThru ) process { foreach ($assmName in $AssemblyName) { $fullyQualifiedAssemblyName = $assmName.FullyQualifiedName if (!$PSCmdLet.ShouldProcess($fullyQualifiedAssemblyName)) { continue } $disp = [PowerShellGac.GlobalAssemblyCache]::UninstallAssembly($assmName, $InstallReference) switch ($disp) { Unknown { Write-Error -Message 'Unknown Error' -Category InvalidResult -TargetObject $assmName } Uninstalled { Write-Verbose "Removed $fullyQualifiedAssemblyName from the GAC" } StillInUse { Write-Error -Message 'Still in use. An application is using the assembly.' -Category PermissionDenied -TargetObject $assmName } AlreadyUninstalled { Write-Error -Message 'Already uninstalled. The assembly does not exist in the GAC.' -Category NotInstalled -TargetObject $assmName } DeletePending { Write-Error -Message 'Delete pending' -Category ResourceBusy -TargetObject $assmName } HasInstallReference { Write-Error -Message 'Has install reference. The assembly has not been removed from the GAC because another install reference exists.' -Category PermissionDenied -TargetObject $assmName } ReferenceNotFound { Write-Error -Message 'Reference not found. The reference that is specified is not found in the GAC' -Category ObjectNotFound -TargetObject $assmName } default { Write-Error -Message "Unknown Error: $disp" -Category InvalidResult -TargetObject $assmName } } if ($PassThru) { $assmName } } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/New-GacAssemblyInstallReference.ps1
New-GacAssemblyInstallReference.ps1
<# .SYNOPSIS Creates a new install reference .DESCRIPTION Creates a new install reference to be used with Add-GacAssembly or Remove-GacAssembly .PARAMETER Type Specifies the type of the install reference to be created .PARAMETER Identifier Specifies the identifier of the install reference to be created .PARAMETER Description Specifies the description of the install reference to be created .INPUTS [PowerShellGac.InstallReference[]] .EXAMPLE C:\PS> $reference = New-GacAssemblyInstallReference Opaque ([guid]::NewGuid()) 'Sample install reference' This example shows how you can create a new install reference. .LINK Add-GacAssembly .LINK Remove-GacAssembly .LINK http://powershellgac.codeplex.com #> function New-GacAssemblyInstallReference { [CmdletBinding()] [OutputType('PowerShellGac.InstallReference')] param ( [Parameter(Position = 0, Mandatory = $true)] [ValidateNotNullOrEmpty()] [PowerShellGac.InstallReferenceType] $Type, [Parameter(Position = 1, Mandatory = $true)] [ValidateNotNullOrEmpty()] [string] $Identifier, [Parameter(Position = 2)] [ValidateNotNullOrEmpty()] [string] $Description ) process { New-Object -TypeName 'PowerShellGac.InstallReference' -ArgumentList $Type, $Identifier, $Description } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Test-AssemblyNameFullyQualified.ps1
Test-AssemblyNameFullyQualified.ps1
<# .SYNOPSIS Determines whether the assembly name is fully qualified .DESCRIPTION Determines whether the assembly name is fully qualified. An assembly name is fully qualified if it contains all the following parts: * Name * Version * Culture * PublicKeyToken * ProcessorArchitecture Note that the ProcessorArchitecture always has a valid default value of None. Test-AssemblyNameFullyQualified also returns True if only the ProcessorArchitecture is not specified. .PARAMETER AssemblyName Specifies the assembly name to be tested .INPUTS [System.Reflection.AssemblyName[]] .EXAMPLE C:\PS> Test-AssemblyNameFullyQualified 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL' True C:\PS> Test-AssemblyNameFullyQualified 'System, Version=2.0.0.0' False This example shows how you can determine if the assembly name is fully qualified. .LINK http://powershellgac.codeplex.com #> function Test-AssemblyNameFullyQualified { [CmdletBinding()] [OutputType('System.Boolean')] param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullOrEmpty()] [System.Reflection.AssemblyName[]] $AssemblyName ) process { foreach ($assmName in $AssemblyName) { [PowerShellGac.GlobalAssemblyCache]::IsFullyQualifiedAssemblyName($assmName) } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Get-GacAssemblyFile.ps1
Get-GacAssemblyFile.ps1
<# .SYNOPSIS Gets the FileInfo of assemblies in the GAC .DESCRIPTION Gets the FileInfo of assemblies in the GAC. FileInfo can be used as input for Copy-Item to extract an assembly from the GAC or to get the VersionInfo from the assembly. .PARAMETER AssemblyName Specifies the assembly name. Must be fully qualified. See Test-AssemblyNameFullyQualified. .INPUTS [System.Reflection.AssemblyName[]] .EXAMPLE C:\PS> Get-GacAssembly -Name System -Version 4.0.0.0 | Get-GacAssemblyFile | Copy-Item -Destination C:\Temp This example extracts the System assembly with version 4.0.0.0 from the GAC to the C:\Temp path. .EXAMPLE C:\PS> (Get-GacAssembly -Name System | Get-GacAssemblyFile).VersionInfo ProductVersion FileVersion FileName -------------- ----------- -------- 2.0.50727.6401 2.0.50727.640... C:\Windows\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll 4.0.30319.18033 4.0.30319.180... C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\S... This example returns the VersionInfo all System assemblies in the GAC. .LINK Test-AssemblyNameFullyQualified .LINK http://powershellgac.codeplex.com #> function Get-GacAssemblyFile { [CmdletBinding()] [OutputType('System.IO.FileInfo')] param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-AssemblyNameFullyQualified $_ } )] [System.Reflection.AssemblyName[]] $AssemblyName ) process { foreach ($assmName in $AssemblyName) { $path = [PowerShellGac.GlobalAssemblyCache]::GetAssemblyPath($assmName) [System.IO.FileInfo] $path } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Test-GacAssemblyInstallReferenceCanBeUsed.ps1
Test-GacAssemblyInstallReferenceCanBeUsed.ps1
<# .SYNOPSIS Determines whether the install reference can be used .DESCRIPTION Determines whether the install reference can be used with Add-GacAssembly and Remove-GacAssembly. Only types Installer, FilePath en Opaque can be used. WindowsInstaller and OsInstall not. .PARAMETER InstallReference Specifies the install reference to be tested .INPUTS [PowerShellGac.InstallReference[]] .EXAMPLE C:\PS> Test-GacAssemblyInstallReferenceCanBeUsed (New-GacAssemblyInstallReference Opaque ([guid]::NewGuid())) True C:\PS> Test-GacAssemblyInstallReferenceCanBeUsed (New-GacAssemblyInstallReference WindowsInstaller 'MSI') False This example shows how you can determine if the install reference can be used. .LINK Add-GacAssembly .LINK Remove-GacAssembly .LINK http://powershellgac.codeplex.com #> function Test-GacAssemblyInstallReferenceCanBeUsed { [CmdletBinding()] [OutputType('System.Boolean')] param ( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [ValidateNotNullOrEmpty()] [PowerShellGac.InstallReference[]] $InstallReference ) process { foreach ($reference in $InstallReference) { $reference.CanBeUsed() } } }
PowerShellCorpus/PowerShellGallery/Gac/1.0.1/Get-GacAssembly.ps1
Get-GacAssembly.ps1
<# .SYNOPSIS Gets the assemblies in the GAC .DESCRIPTION Gets the assemblies in the GAC. Assemblies can be filterd by Name, Version, Culture, PublicKeyToken or ProcessArchitecture. .PARAMETER Name Filter on the Name part. Supports wildcards. .PARAMETER Version Filter on the Version part. Supports wildcards. .PARAMETER Culture Filter on the Culture part. 'neutral' or '' can be used to filter on assemblies without cultures. Supports wildcards. .PARAMETER PublicKeyToken Filter on the PublicKeyToken part. Supports wildcards. .PARAMETER ProcessorArchitecture Filter on the ProcessorArchitecture part. Supports wildcards. .PARAMETER AssemblyName Filter on AssemblyName. Must be fully qualified. See Test-AssemblyNameFullyQualified. .INPUTS [System.Reflection.AssemblyName[]] .EXAMPLE C:\PS> Get-GacAssembly This example returns all assemblies in the GAC. .EXAMPLE C:\PS> Get-GacAssembly -Name System* -Version 2.0.0.0 This example returns all assemblies in the GAC with a name starting with System and version 2.0.0.0. .LINK Test-AssemblyNameFullyQualified .LINK http://powershellgac.codeplex.com #> function Get-GacAssembly { [CmdletBinding(DefaultParameterSetName = 'PartsSet')] [OutputType('System.Reflection.AssemblyName')] param ( [Parameter(Position = 0, ParameterSetName = 'PartsSet')] [ValidateNotNullOrEmpty()] [string[]] $Name, [Parameter(Position = 1, ParameterSetName = 'PartsSet')] [ValidateNotNullOrEmpty()] [string[]] $Version, [Parameter(Position = 2, ParameterSetName = 'PartsSet')] [ValidateNotNullOrEmpty()] [string[]] $Culture, [Parameter(Position = 3, ParameterSetName = 'PartsSet')] [ValidateNotNullOrEmpty()] [string[]] $PublicKeyToken, [Parameter(Position = 4, ParameterSetName = 'PartsSet')] [ValidateNotNullOrEmpty()] [System.Reflection.ProcessorArchitecture[]] $ProcessorArchitecture, [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'AssemblyNameSet')] [ValidateNotNullOrEmpty()] [ValidateScript( { Test-AssemblyNameFullyQualified $_ } )] [System.Reflection.AssemblyName[]] $AssemblyName ) process { if ($PsCmdlet.ParameterSetName -eq 'AssemblyNameSet') { $fullNames = @() foreach ($assmName in $AssemblyName) { $fullNames += $assmName.FullyQualifiedName } foreach ($assembly in [PowerShellGac.GlobalAssemblyCache]::GetAssemblies()) { $fullyQualifiedAssemblyName = $assembly.FullyQualifiedName foreach ($fullName in $fullNames) { if ($fullyQualifiedAssemblyName -eq $fullName) { $assembly break } } } } else { foreach ($assembly in [PowerShellGac.GlobalAssemblyCache]::GetAssemblies()) { $hit = $false foreach ($n in $Name) { if ($assembly.Name -like $n) { $hit = $true break } } if ($Name -and -not $hit) { continue } $hit = $false foreach ($v in $Version) { if ($assembly.Version -like $v) { $hit = $true break } } if ($Version -and -not $hit) { continue } $hit = $false foreach ($c in $Culture) { if ($c -eq 'neutral' -and $assembly.CultureInfo.Equals([System.Globalization.CultureInfo]::InvariantCulture)) { $hit = $true break } if ($c -ne 'neutral' -and $assembly.CultureInfo -like $c) { $hit = $true break } } if ($Culture -and -not $hit) { continue } $hit = $false foreach ($p in $PublicKeyToken) { if ($assembly.PublicKeyToken -like $p) { $hit = $true break } } if ($PublicKeyToken -and -not $hit) { continue } $hit = $false foreach ($p in $ProcessorArchitecture) { if ($assembly.ProcessorArchitecture -eq $p) { $hit = $true break } } if ($ProcessorArchitecture -and -not $hit) { continue } $assembly } } } }
PowerShellCorpus/PowerShellGallery/LINQ/4.0/Add-SourceFiles.ps1
Add-SourceFiles.ps1
$ErrorActionPreference = 'Stop' function Add-SourceFile([String[]]$Path) { $CompilationUnit = New-Object System.Text.StringBuilder $AddTypeArgs = @{} if ($PSVersionTable.PSVersion.Major -ge 3) { $AddTypeArgs.Language = 'CSharp' $AddTypeArgs.ReferencedAssemblies = @('System.Core', 'System.Data', 'System.Xml') } else { $AddTypeArgs.Language = 'CSharpVersion3' $AddTypeArgs.ReferencedAssemblies = @('System.Data', 'System.Xml') } foreach ($SourcePath in $Path) { if ($SourcePath -notlike '*.cs') { throw 'Add-SourceFile only supports the C# language.' } [Void]$CompilationUnit.AppendLine([IO.File]::ReadAllText("$PSScriptRoot\Source\$SourcePath")) [Void]$CompilationUnit.AppendLine() } $AddTypeArgs.TypeDefinition = $CompilationUnit.ToString() Add-Type @AddTypeArgs } Add-SourceFile @( 'PSEnumerable.cs' 'PSObjectComparer.cs' 'PSObjectFactory.cs' )
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Examples/Sample_xVirtualMemory.ps1
Sample_xVirtualMemory.ps1
<# .SYNOPSIS Example to set the paging file .DESCRIPTION Example script that sets the paging file to reside on drive C with the custom size 2048MB #> configuration Sample_xVirtualMemory { param ( [Parameter()] [String[]] $NodeName = 'localhost' ) Import-DSCResource -ModuleName xComputerManagement node $NodeName { xVirtualMemory pagingSettings { Type = "CustomSize" Drive = "C" InitialSize = "2048" MaximumSize = "2048" } } } Sample_xVirtualMemory Start-DscConfiguration -Path Sample_xVirtualMemory -Wait -verbose -Force
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Examples/Sample_xScheduledTask.ps1
Sample_xScheduledTask.ps1
configuration Sample_xScheduledTask { param ( [string[]]$NodeName = 'localhost' ) Import-DSCResource -ModuleName xComputerManagement Node $NodeName { xScheduledTask MaintenanceScriptExample { TaskName = "Custom maintenance tasks" ActionExecutable = "C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe" ActionArguments = "-File `"C:\scripts\my custom script.ps1`"" ScheduleType = "Minutes" RepeatInterval = 15 } } } Sample_xScheduledTask Start-DscConfiguration -Path Sample_xScheduledTask -Wait -Verbose -Force
PowerShellCorpus/PowerShellGallery/xComputerManagement/1.10.0.0/Examples/Sample_xPowerPlan.ps1
Sample_xPowerPlan.ps1
<# .SYNOPSIS Example to set a power plan. .DESCRIPTION This examples sets the active power plan to the 'High performance' plan. #> Configuration Sample_xPowerPlan { param ( [Parameter()] [String[]] $NodeName = 'localhost' ) Import-DSCResource -ModuleName xComputerManagement Node $NodeName { xPowerPlan SetPlanHighPerformance { IsSingleInstance = 'Yes' Name = 'High performance' } } } Sample_xPowerPlan Start-DscConfiguration -Path Sample_xPowerPlan -Wait -Verbose -Force