full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/e9e42994-6ca4-4473-bf6b-148b56a46132.ps1
e9e42994-6ca4-4473-bf6b-148b56a46132.ps1
Coresponding to the Scripting Guy blog "How Can I Both Save Information in a File and Display It on the Screen?" (http://blogs.technet.com/heyscriptingguy/archive/2009/07/07/hey-scripting-guy-how-can-i-both-save-information-in-a-file-and-display-it-on-the-screen.aspx): My comment is: All of the above is cool but can't work if you want your Write-Host or Write-Debug to be redirected to file as well as printing to console. Maybe the Scripting Guy can explain why (AFAIK these cmdlets are already redirecting their output). so these examples don't work!: Write-Debug "blablabla" > File.txt Write-Debug "blablabla" | Out-File -filepath C:\\File.txt Write-Debug "blablabla" | Tee -filepath C:\\File.txt Here's the function I finally use: Function WriteToDebug ([string]$DebugMessage) { $ScriptOut = ((Get-Date -format G ) + "`t$DebugMessage" ) Out-File -FilePath $LogFileDebug -Append -InputObject $ScriptOut Write-Debug "$ScriptOut" } Where i replaced every Write-Debug in the script to WriteToDebug.
PowerShellCorpus/PoshCode/CTP3_ Watch Folder.ps1
CTP3_ Watch Folder.ps1
#requires -version 2.0 # Example # # ps> . .\\watch-folder.ps1 # ps> watch-folder c:\\temp # ps> "foo" > c:\\temp\\test.txt # ps> $table # ps> (shows changes) function watch-folder { param([string]$folder) $fsw = new-object System.IO.FileSystemWatcher $fsw.Path = $folder # stores changes to $folder $global:table = new-object system.data.datatable [void] $table.Columns.Add("FullPath", [string]) [void] $table.Columns.Add("ChangeType", [string]) $action = { [console]::beep(440,10) [void] $table.Rows.Add($eventArgs.FullPath, $eventArgs.ChangeType) } [void] Register-ObjectEvent -InputObject $fsw -EventName Created -Action $action [void] Register-ObjectEvent -InputObject $fsw -EventName Changed -Action $action [void] Register-ObjectEvent -InputObject $fsw -EventName Deleted -Action $action }
PowerShellCorpus/PoshCode/VMware Host Network Info_1.ps1
VMware Host Network Info_1.ps1
# Set the VI Server and Filename before running Connect-VIServer MYVISERVER $filename = "C:\\DetailedNetworkInfo.csv" Write "Gathering VMHost objects" $vmhosts = Get-VMHost | Sort Name | Where-Object {$_.State -eq "Connected"} | Get-View $MyCol = @() foreach ($vmhost in $vmhosts){ $ESXHost = $vmhost.Name Write "Collating information for $ESXHost" $networkSystem = Get-view $vmhost.ConfigManager.NetworkSystem foreach($pnic in $networkSystem.NetworkConfig.Pnic){ $pnicInfo = $networkSystem.QueryNetworkHint($pnic.Device) foreach($Hint in $pnicInfo){ $NetworkInfo = "" | select-Object Host, vSwitch, PNic, Speed, MAC, DeviceID, PortID, Observed, VLAN $NetworkInfo.Host = $vmhost.Name $NetworkInfo.vSwitch = Get-Virtualswitch -VMHost (Get-VMHost ($vmhost.Name)) | where {$_.Nic -eq ($Hint.Device)} $NetworkInfo.PNic = $Hint.Device $NetworkInfo.DeviceID = $Hint.connectedSwitchPort.DevId $NetworkInfo.PortID = $Hint.connectedSwitchPort.PortId $record = 0 Do{ If ($Hint.Device -eq $vmhost.Config.Network.Pnic[$record].Device){ $NetworkInfo.Speed = $vmhost.Config.Network.Pnic[$record].LinkSpeed.SpeedMb $NetworkInfo.MAC = $vmhost.Config.Network.Pnic[$record].Mac } $record ++ } Until ($record -eq ($vmhost.Config.Network.Pnic.Length)) foreach ($obs in $Hint.Subnet){ $NetworkInfo.Observed += $obs.IpSubnet + " " Foreach ($VLAN in $obs.VlanId){ If ($VLAN -eq $null){ } Else{ $strVLAN = $VLAN.ToString() $NetworkInfo.VLAN += $strVLAN + " " } } } $MyCol += $NetworkInfo } } } $Mycol | Sort Host, PNic | Export-Csv $filename -NoTypeInformation
PowerShellCorpus/PoshCode/Set-Encoding_1.ps1
Set-Encoding_1.ps1
function Set-Encoding{ <# .Synopsis Takes a Script file or any other text file into memory and Re-Encodes it in the format specified. .Parameter Source The path to the file to be re-encoded. .Parameter Destination The path to write the corrected file to .Parameter Encoding The encoding to convert to Note: Default Uses the encoding of the system's current ANSI code page. OEM Uses the current original equipment manufacturer code page identifier for the operating system. .Example ls *.ps1 | Set-Encoding ASCII .Example ls *.ps1 | Set-Encoding UTF8 -Destination { [System.IO.Path]::ChangeExtension($_.FullName, ".utf8.ps1") } .Description Provides an easy way to change the text encoding on a lot of scripts at once. .Notes Don't use on non-text files! The script just calls Out-File with the -Encoding parameter and the -Force switch, but it's very useful for making sure all your script files are correctly UTF8 or ASCII encoded so they can be signed. #> [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateSet("Unicode","UTF7","UTF8","UTF32","ASCII", "BigEndianUnicode","Default", "OEM")] [string]$Encoding , [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [Alias("Fullname","Path","File")] [string]$Source , [Parameter(Position=2, Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [string]$Destination = $Source , [Switch]$Passthru ) PROCESS{ Write-Verbose "Encoding content from '$Source' into '$Destination' with $Encoding encoding." (Get-Content $Source) | Out-File -FilePath $Destination -Encoding $Encoding -Force if($Passthru){ Get-Item $Destination } } }
PowerShellCorpus/PoshCode/Split-TextToLines Demo.ps1
Split-TextToLines Demo.ps1
function Show-LineArrayStructure ($lines) { $len = $lines.length "Type is: $($lines.gettype().Name)" "Number of lines: $len" for ($i = 0; $i -lt $len; $i++) { "$($i + 1). Line: length $($lines[$i].length) >$($lines[$i])<" } '' } $text = "abc`r`nefg`r`n" # $text # $text.length $lines = $text.Split("`n") Show-LineArrayStructure $lines $lines2 = $text.Split("`r`n") Show-LineArrayStructure $lines2 $lines3 = $([Regex]::Split($text,"`r`n" )) Show-LineArrayStructure $lines3 $lines4 = $text -split "`n" Show-LineArrayStructure $lines4 # best method $lines5 = $text -split "`r`n" Show-LineArrayStructure $lines5
PowerShellCorpus/PoshCode/wget 1.0.ps1
wget 1.0.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Joel "Jaykul" Bennett ### </Author> ### <Description> ### Downloads a file from the web to the specified file path. ### </Description> ### <Usage> ### Get-URL http://huddledmasses.org/downloads/RunOnlyOne.exe RunOnlyOne.exe ### Get-URL http://huddledmasses.org/downloads/RunOnlyOne.exe C:\\Users\\Joel\\Documents\\WindowsPowershell\\RunOnlyOne.exe ### </Usage> ### </Script> # --------------------------------------------------------------------------- param([string]$url, [string]$path) if(!(Split-Path -parent $path) -or !(Test-Path -pathType Container (Split-Path -parent $path))) { $path = Join-Path $pwd (Split-Path -leaf $path) } "Downloading [$url]`nSaving at [$path]" $client = new-object System.Net.WebClient $client.DownloadFile( $url, $path ) $path
PowerShellCorpus/PoshCode/Set-RDPSetting.ps1
Set-RDPSetting.ps1
######################################################################################################################## # NAME # Set-RDPSetting # # SYNOPSIS # Adds or updates a named property to an existing RDP file. # # SYNTAX # Edit-RDP [-Path] <string> [-Name] <string> [[-Value] <object>] [-PassThru] # # DETAILED DESCRIPTION # The Edit-RDP cmdlet can be used to add or update properties in an existing RDP file. This cmdlet can properly # translate boolean values or strings containing boolean or integer values for properties that are integers. # # PARAMETERS # -Path <string> # Specifies the path to the RDP file. # # Required? true # Position? 1 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Name <string> # Specifies the name of the property to set. # # Required? false # Position? 2 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -Value <Object> # Specifies the value to set the property to. # # Required? false # Position? 3 # Default value # Accept pipeline input? false # Accept wildcard characters? false # # -PassThru <SwitchParameter> # Passes thru an object that represents the RDP file to the pipeline. By default, this cmdlet does # not pass any objects through the pipeline. # # Required? false # Position? named # Default value false # Accept pipeline input? false # Accept wildcard characters? false # # INPUT TYPE # # # RETURN TYPE # System.IO.FileInfo # # NOTES # # -------------------------- EXAMPLE 1 -------------------------- # # C:\\PS>Set-RDPSetting -Path C:\\myserver.rdp -Name "full address" -Value "myotherserver" # # # This command changes the name of the server to connect to. # # # -------------------------- EXAMPLE 2 -------------------------- # # C:\\PS>Set-RDPSetting -Path C:\\myserver.rdp -Name "redirectclipboard" -Value $true # # # This command turns on redirection of the clipboard from the remote computer. # # # -------------------------- EXAMPLE 3 -------------------------- # # C:\\PS>Get-RDPSetting -Path C:\\template.rdp | Set-RDPSetting -Path C:\\myserver.rdp | Start-RDP # # # This command updates all the settings in "myserver.rdp" with the corresponding values from "template.rdp", # and then opens a connection with the resulting file. # # #Function global:Set-RDPSetting { param( [string]$Path = $(throw "A path to a RDP file is required."), [string]$Name = "", [Object]$Value = "", [switch]$Passthru ) begin { if (Test-Path $path) { $content = Get-Content -Path $path } else { throw "Path does not exist." } $datatypes = @{ 'allow desktop composition' = 'i'; 'allow font smoothing' = 'i'; 'alternate shell' = 's'; 'audiomode' = 'i'; 'authentication level' = 'i'; 'auto connect' = 'i'; 'autoreconnection enabled' = 'i'; 'bitmapcachepersistenable' = 'i'; 'compression' = 'i'; 'connect to console' = 'i'; 'desktopheight' = 'i'; 'desktopwidth' = 'i'; 'disable cursor setting' = 'i'; 'disable full window drag' = 'i'; 'disable menu anims' = 'i'; 'disable themes' = 'i'; 'disable wallpaper' = 'i'; 'displayconnectionbar' = 'i'; 'domain' = 's'; 'drivestoredirect' = 's'; 'full address' = 's'; 'gatewaycredentialssource' = 'i'; 'gatewayhostname' = 's'; 'gatewayprofileusagemethod' = 'i'; 'gatewayusagemethod' = 'i'; 'keyboardhook' = 'i'; 'maximizeshell' = 'i'; 'negotiate security layer' = 'i'; 'password 51' = 'b'; 'prompt for credentials' = 'i'; 'promptcredentialonce' = 'i'; 'port' = 'i'; 'redirectclipboard' = 'i'; 'redirectcomports' = 'i'; 'redirectdrives' = 'i'; 'redirectposdevices' = 'i'; 'redirectprinters' = 'i'; 'redirectsmartcards' = 'i'; 'remoteapplicationmode' = 'i'; 'screen mode id' = 'i'; 'server port' = 'i'; 'session bpp' = 'i'; 'shell working directory' = 's'; 'smart sizing' = 'i'; 'username' = 's'; 'winposstr' = 's' } } process { if ($_.Name) { $tempname = $_.Name $tempvalue = $_.Value # Convert value if ($datatypes[$tempname] -eq 'i') { if (($tempvalue -eq $true) -or ($tempvalue -imatch '^true$')) { $tempvalue = 1 } elseif (($tempvalue -eq $false) -or ($tempvalue -imatch '^false$') -or ($tempvalue -eq '')) { $tempvalue = 0 } elseif ($tempvalue -match '^[0-9]+$') { $tempvalue = [int]$tempvalue } } else { $tempvalue = [string]$tempvalue } # Set or update property $found = $false $content = $content | ForEach-Object { if ($_ -match "^$tempname") { "${tempname}:$($datatypes[$tempname]):$tempvalue" $found = $true } else {$_} } if (!$found) { $content += @("${tempname}:$($datatypes[$tempname]):$tempvalue") } } } end { if ($name) { # Convert value if ($datatypes[$name] -eq 'i') { if (($value -eq $true) -or ($value -imatch '^true$')) { [int]$value = 1 } elseif (($value -eq $false) -or ($value -imatch '^false$') -or ($value -eq '')) { [int]$value = 0 } elseif ($value -match '^[0-9]+$') { [int]$value = $value } } else { [string]$value = $value } # Set or update property $found = $false $content = $content | ForEach-Object { if ($_ -match "^$name") { "${name}:$($datatypes[$name]):$value" $found = $true } else {$_} } if (!$found) { $content += @("${name}:$($datatypes[$name]):$value") } } $content | Set-Content -Path $path if ($passthru) { Get-ChildItem -Path $path } } #}
PowerShellCorpus/PoshCode/Invoke-BPAModeling.ps1
Invoke-BPAModeling.ps1
<# NAME: Invoke-BPAModeling.ps1 AUTHOR: Jan Egil Ring EMAIL: jer@powershell.no COMMENT: Script to invoke Best Practices Analyzer on remote computers. Requires Windows Server 2008 R2 on target computers, and Windows PowerShell 2.0 on the computer running the script from. For more details, see the following blog-post: http://blog.powershell.no/2010/08/17/invoke-best-practices-analyzer-on-remote-servers-using-powershell You have a royalty-free right to use, modify, reproduce, and distribute this script file in any way you find useful, provided that you agree that the creator, owner above has no warranty, obligations, or liability for such use. VERSION HISTORY: 1.0 16.08.2010 - Initial release #> #requires -version 2 #Import Active Directory module Import-Module ActiveDirectory #Initial variables, these must be customized $servers = Get-ADComputer -LDAPFilter "(operatingsystem=*Windows Server 2008 R2*)" | select name,dnshostname $SMTPServer = "smtp.domain.local" $CSVReport = $true $CSVReportPath = "\\\\server\\share\\BPAReports\\" $HTMLReport = $true $HTMLReportPath = "\\\\server\\share\\BPAReports\\" $EMailReport = $true $EMailReportTo = "it-operations@domain.local" $EMailReportFrom = "bpa@domain.local" $ReportAllSevereties = $false $TotalComputers = ($servers | Measure-Object).Count $CurrentComputer = 1 foreach ($server in $servers) { $servername = $server.name #Display progress Write-Progress -Activity "Invoking BPA-model $BestPracticesModelId..." -Status "Current server: $servername" -Id 1 -PercentComplete (($CurrentComputer/$TotalComputers) * 100) try { Invoke-Command -Computer $server.dnshostname -ArgumentList $servername,$SMTPServer,$CSVReport,$CSVReportPath,$HTMLReport,$HTMLReportPath,$EMailReport,$EMailReportTo,$EMailReportFrom,$ReportAllSevereties -ScriptBlock { param ( $servername, $SMTPServer, $CSVReport, $CSVReportPath, $HTMLReport, $HTMLReportPath, $EMailReport, $EMailReportTo, $EMailReportFrom, $ReportAllSevereties) #Import Server Manager module Import-Module ServerManager $ModelsToRun = @() if ((Get-WindowsFeature Application-Server).Installed) { $ModelsToRun += "Microsoft/Windows/ApplicationServer" } if ((Get-WindowsFeature AD-Certificate).Installed) { $ModelsToRun += "Microsoft/Windows/CertificateServices" } if ((Get-WindowsFeature DHCP).Installed) { $ModelsToRun += "Microsoft/Windows/DHCP" } if ((Get-WindowsFeature AD-Domain-Services).Installed) { $ModelsToRun += "Microsoft/Windows/DirectoryServices" } if ((Get-WindowsFeature DNS).Installed) { $ModelsToRun += "Microsoft/Windows/DNSServer" } if ((Get-WindowsFeature File-Services).Installed) { $ModelsToRun += "Microsoft/Windows/FileServices" } if ((Get-WindowsFeature Hyper-V).Installed) { $ModelsToRun += "Microsoft/Windows/Hyper-V" } if ((Get-WindowsFeature NPAS).Installed) { $ModelsToRun += "Microsoft/Windows/NPAS" } if ((Get-WindowsFeature Remote-Desktop-Services).Installed) { $ModelsToRun += "Microsoft/Windows/TerminalServices" } if ((Get-WindowsFeature Web-Server).Installed) { $ModelsToRun += "Microsoft/Windows/WebServer" } if ((Get-WindowsFeature OOB-WSUS).Installed) { $ModelsToRun += "Microsoft/Windows/WSUS" } foreach ($BestPracticesModelId in $ModelsToRun) { #Path-variables $date = Get-Date -Format "dd-MM-yy_HH-mm" $BPAName = $BestPracticesModelId.Replace("Microsoft/Windows/","") $CSVPath = $CSVReportPath+$servername+"-"+$BPAName+"-"+$date+".csv" $HTMLPath = $HTMLReportPath+$servername+"-"+$BPAName+"-"+$date+".html" #HTML-header $Head = " <title>BPA Report for $BestPracticesModelId on $servername</title> <style type='text/css'> table { border-collapse: collapse; width: 700px } body { font-family: Arial } td, th { border-width: 2px; border-style: solid; text-align: left; padding: 2px 4px; border-color: black } th { background-color: grey } td.Red { color: Red } </style>" #Import Best Practices module Import-Module BestPractices #Invoke BPA Model Invoke-BpaModel -BestPracticesModelId $BestPracticesModelId | Out-Null #Include all severeties in BPA Report if enabled. If not, only errors and warnings are reported. if ($ReportAllSevereties) { $BPAResults = Get-BpaResult -BestPracticesModelId $BestPracticesModelId } else { $BPAResults = Get-BpaResult -BestPracticesModelId $BestPracticesModelId | Where-Object {$_.Severity -eq "Error" -or $_.Severity -eq “Warning” } } #Send BPA Results to CSV-file if enabled if ($BPAResults -and $CSVReport) { $BPAResults | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath $CSVPath } #Send BPA Results to HTML-file if enabled if ($BPAResults -and $HTMLReport) { $BPAResults | ConvertTo-Html -Property Severity,Category,Title,Problem,Impact,Resolution,Help -Title "BPA Report for $BestPracticesModelId on $servername" -Body "BPA Report for $BestPracticesModelId on server $servername <HR>" -Head $head | Out-File -FilePath $HTMLPath } #Send BPA Results to e-mail if enabled if ($BPAResults -and $EMailReport) { $CSVReportAttachment = $env:temp+"\\"+$servername+"-"+$BPAName+"-"+$date+".csv" $HTMLReportAttachment = $env:temp+"\\"+$servername+"-"+$BPAName+"-"+$date+".html" $BPAResults | ConvertTo-Csv -NoTypeInformation | Out-File -FilePath $CSVReportAttachment $BPAResults | ConvertTo-Html -Property Severity,Category,Title,Problem,Impact,Resolution,Help -Title "BPA Report for $BestPracticesModelId on $servername" -Body "BPA Report for $BestPracticesModelId on server $servername <HR>" -Head $head | Out-File -FilePath $HTMLReportAttachment Send-MailMessage -From $EMailReportFrom -SmtpServer $SMTPServer -To $EMailReportTo -Subject "BPA Results for $servername" -Body "The BPA Result for $BestPracticesModelId on $servername are attached to this message" -Attachment $CSVReportAttachment,$HTMLReportAttachment Remove-Item $CSVReportAttachment Remove-Item $HTMLReportAttachment } } } } #Catch PS Remoting transport errors catch [PSRemotingTransportException]{ Write-Host "Unable to connect to $servername. The following error occured:" -ForegroundColor red -BackgroundColor black Write-Host ($error[0]).errordetails.message -ForegroundColor red -BackgroundColor black } #Catch other errors (errors from remote scriptblock commands won`t be captured here, they will be returned like default) catch { Write-Host "An error occured when connecting to $servername. The following error occured:" -ForegroundColor red -BackgroundColor black Write-Host ($error[0]).errordetails.message -ForegroundColor red -BackgroundColor black } #Increase current computer variable for Write-Progress $CurrentComputer ++ }
PowerShellCorpus/PoshCode/List AD Attributes_1.ps1
List AD Attributes_1.ps1
$forest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $Schema = $forest.schema $Properties = $Schema.FindAllProperties() foreach($property in $Properties) { "#################################" "Name: {0}" -f $property.Name "Link: {0}" -f $property.link "LinkID: {0}" -f $property.linkid if(!$?) { "Error: {0}" -f $error[0].message } "#################################" }
PowerShellCorpus/PoshCode/MailChimp .ps1
MailChimp .ps1
#Author: Ant B 2012 #Purpose: Batch feed recipients to MailChimp # Check for ActiveDirectory Module and load if it isn't already. if ( (Get-Module -Name ActiveDirectory -ErrorAction SilentlyContinue) -eq $null ) { Import-Module ActiveDirectory } $ie = new-object -com "InternetExplorer.Application" # Vars for building the URL @@$apikey = "<Your API Key>" @@$listid = "<Your list ID>" $URL = "https://us4.api.mailchimp.com/1.3/?output=xml&method=listBatchSubscribe&apikey=$apikey" $URLOpts = "&id=$($listid)&double_optin=False&Update_existing=True" $Header = "surname","givenanme","mail" # Get members of the group @@$DGMembers = Get-AdGroupMember -Identity "<Full path to AD Group>" | ForEach {Get-ADUser $_.samaccountname -Properties mail} | Select GivenName, Surname, mail # Copy the array contents to a CSV for comparison on the next run, we'll use it to look for removals if (test-path "submitted.csv") {Clear-Content submitted.csv} $DGMembers | select mail | export-csv submitted.csv # Check for the CSV created above and dump it to an array for comparison if (test-path "submitted.csv") {$list = Import-CSV -delimiter "," -Path submitted.csv -Header $Header} $Removals = compare-object $DGMembers $list | Where {$_.SideIndicator -eq "=>"} # Loop through the array of group members and submit to the MailChimp API ForEach ($ObjItem in $DGMembers) { $batch = "&batch[0][EMAIL]=$($ObjItem.mail)&batch[0][FNAME]=$($ObjItem.givenname)&batch[0][LNAME]=$($ObjItem.surname)" $MailOpts = "&batch[0][EMAIL_TYPE]html" $FURL = $URL + $batch + $MailOpts + $URLOpts Write-Host $FURL $ie.navigate($FURL) Start-Sleep -MilliSeconds 300 }
PowerShellCorpus/PoshCode/Reflection Module _1.5.ps1
Reflection Module _1.5.ps1
#requires -version 2.0 # ALSO REQUIRES Autoload for some functionality (Latest version: http://poshcode.org/3173) # You should create a Reflection.psd1 with the contents: # @{ ModuleToProcess="Reflection.psm1"; RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="4.5.0.0" } #History: # 1.0 - First public release (March 19, 2010) # 2.0 - Private Build # - Included the Accelerator function inline # - Added a few default aliases # 3.0 - September 3, 2010 # - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!) # - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312 # 3.5 - January 28, 2011 # - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature # - Fixed alias exporting so aliases will show up now # - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies # 3.6 - January 28, 2011 # - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin # 3.7 - February 1, 2001 - NOT RELEASED # - Added [TransformAttribute] type # 3.8 - May 4, 2011 - NOT RELEASED # - Huge rewrite of Invoke-Generic (also published separately: http://poshcode.org/2649) # 3.9 - May 25, 2011 - NOT RELEASED # - Added "Interface" parameter to Get-Type # 4.0 - Sept 27, 2011 # - Fix conflicts with PowerShell 3 # 4.1 - Oct 27, 2011 # - Fix PowerShell 3 changes so they don't break PowerShell 2 (huy!) # 4.2 - Added Add-Enum and Add-Struct -- even though they're really more CodeGen than reflection # # 4.5 - March 2, 2013 # - Added Test-AssignableToGeneric and Get-ExtensionMethod # - Updated Read-Choice from the standalone script I use. Add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class TransformAttribute : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public override string ToString() { return string.Format("[Transform(Script='{{{0}}}')]", Script); } public override Object Transform( EngineIntrinsics engine, Object inputData) { try { Collection<PSObject> output = engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData ); if(output.Count > 1) { Object[] transformed = new Object[output.Count]; for(int i =0; i < output.Count;i++) { transformed[i] = output[i].BaseObject; } return transformed; } else if(output.Count == 1) { return output[0].BaseObject; } else { throw new ArgumentTransformationMetadataException(NoOutputMessage); } } catch (ArgumentTransformationMetadataException) { throw; } catch (Exception e) { throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e); } } public TransformAttribute() { this.Script = ScriptBlock.Create("{`$args}"); } public TransformAttribute( ScriptBlock Script ) { this.Script = Script; } public ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ function Get-Type { <# .Synopsis Gets the types that are currenty loaded in .NET, or gets information about a specific type .Description Gets information about one or more loaded types, or gets the possible values for an enumerated type or value. .Example Get-Type Gets all loaded types (takes a VERY long time to print out) .Example Get-Type -Assembly ([PSObject].Assembly) Gets types from System.Management.Automation .Example [Threading.Thread]::CurrentThread.ApartmentState | Get-Type Gets all of the possible values for the ApartmentState property .Example [Threading.ApartmentState] | Get-Type Gets all of the possible values for an apartmentstate #> [CmdletBinding(DefaultParameterSetName="Assembly")] param( # The Assemblies to search for types. # Can be an actual Assembly object or a regex to pass to Get-Assembly. [Parameter(ValueFromPipeline=$true)] [PsObject[]]$Assembly, # The type name(s) to search for (wildcard patterns allowed). [Parameter(Mandatory=$false,Position=0)] [SupportsWildCards()] [String[]]$TypeName, # A namespace to restrict where we selsect types from (wildcard patterns allowed). [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Namespace, # A Base type they should derive from (wildcard patterns allowed). [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$BaseType, # An interface they should implement (wildcard patterns allowed). [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Interface, # An Custom Attribute which should decorate the class [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Attribute, # The enumerated value to get all of the possible values of [Parameter(ParameterSetName="Enum")] [PSObject]$Enum, # Causes Private types to be included [Parameter()][Alias("Private","ShowPrivate")] [Switch]$Force ) process { if($psCmdlet.ParameterSetName -eq 'Enum') { if($Enum -is [Enum]) { [Enum]::GetValues($enum.GetType()) } elseif($Enum -is [Type] -and $Enum.IsEnum) { [Enum]::GetValues($enum) } else { throw "Specified Enum is neither an enum value nor an enumerable type" } } else { if($Assembly -as [Reflection.Assembly[]]) { ## This is what we expected, move along } elseif($Assembly -as [String[]]) { $Assembly = Get-Assembly $Assembly } elseif(!$Assembly) { $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() } :asm foreach ($asm in $assembly) { Write-Verbose "Testing Types from Assembly: $($asm.Location)" if ($asm) { trap { if( $_.Exception.LoaderExceptions -and $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) { $PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail") continue asm } Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail" Write-Debug $( $_.Exception.LoaderExceptions | Out-String ) continue asm } $asm.GetTypes() | Where { ( $Force -or $_.IsPublic ) -AND ( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND ( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND ( !$Attribute -or $( foreach($n in $Attribute) { $_.CustomAttributes | ForEach { $_.AttributeType.Name -like $n -or $_.AttributeType.FullName -like $n } } ) -contains $True ) -AND ( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) -AND ( !$Interface -or @( foreach($n in $Interface) { $_.GetInterfaces() -like $n } ).Count -gt 0 ) } } } } } } function Add-Assembly { #.Synopsis # Load assemblies #.Description # Load assemblies from a folder #.Parameter Path # Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). #.Parameter Passthru # Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output. # Aliased to -Types #.Parameter Recurse # Gets the items in the specified locations and in all child items of the locations. # # Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("PSPath")] [string[]]$Path = ".", [Alias("Types")] [Switch]$Passthru, [Switch]$Recurse ) process { foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) { Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic } } } } function Get-Assembly { <# .Synopsis Get a list of assemblies available in the runspace .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly. #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true, Position=0)] [string[]]$Name = '' ) process { [appdomain]::CurrentDomain.GetAssemblies() | Where { $Assembly = $_ if($Name){ $( foreach($n in $Name){ if(Resolve-Path $n -ErrorAction 0) { $n = [Regex]::Escape( (Resolve-Path $n).Path ) } $Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n) } ) -contains $True } else { $true } } } } function Update-PSBoundParameters { #.Synopsis # Ensure a parameter value is set #.Description # Update-PSBoundParameters takes the name of a parameter, a default value, and optionally a min and max value, and ensures that PSBoundParameters has a value for it. #.Parameter Name # The name (key) of the parameter you want to set in PSBoundParameters #.Parameter Default # A Default value for the parameter, in case it's not already set #.Parameter Min # The Minimum allowed value for the parameter #.Parameter Max # The Maximum allowed value for the parameter #.Parameter PSBoundParameters # The PSBoundParameters you want to affect (this picks the local PSBoundParameters object, so you shouldn't have to set it) Param( [Parameter(Mandatory=$true, Position=0)] [String]$Name, [Parameter(Mandatory=$false, Position=1)] $Default, [Parameter()] $Min, [Parameter()] $Max, [Parameter(Mandatory=$true, Position=99)] $PSBoundParameters=$PSBoundParameters ) end { $outBuffer = $null ## If it's not set, and you passed a default, we set it to the default if($Default) { if (!$PSBoundParameters.TryGetValue($Name, [ref]$outBuffer)) { $PSBoundParameters[$Name] = $Default } } ## If you passed a $max, and it's set greater than $max, we set it to $max if($Max) { if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -gt $Max) { $PSBoundParameters[$Name] = $Max } } ## If you passed a $min, and it's set less than $min, we set it to $min if($Min) { if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -lt $Min) { $PSBoundParameters[$Name] = $Min } } $PSBoundParameters } } function Get-Constructor { <# .Synopsis Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type. .Description Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor. .Parameter Type The type to get the constructor for .Parameter Force Force inclusion of Private and Static constructors which are hidden by default. .Parameter NoWarn Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors. .Example Get-Constructor System.IO.FileInfo Description ----------- Gets all the information about the single constructor for a FileInfo object. .Example Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax Description ----------- Displays the constructor syntax for all of the *Info objects in the System.IO namespace. Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors. .Example $path = $pwd $driveName = $pwd.Drive $fileName = "$Profile" Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax } Description ----------- Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo. Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical. #> [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("ParameterType")] [Type]$Type, [Switch]$Force, [Switch]$NoWarn ) process { $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" } } } function Get-ExtensionMethod { <# .Synopsis Finds Extension Methods which target the specified type .Example Get-ExtensionMethod String Finds all extension methods which target strings #> [CmdletBinding()] param( # The type name to find Extension Methods for [Parameter(Mandatory=$false,Position=0)] [SupportsWildCards()] [String[]]$TargetTypeName, # A filter for the Extension Method name [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Name = "*", # The type to search for Extension Methods (defaults to search all types) [Parameter(Mandatory=$false,Position=99)] [SupportsWildCards()] [String[]]$TypeName = "*" ) process { Get-Type -TypeName $TypeName -Attribute ExtensionAttribute | Get-Method -Name $Name -BindingFlags "Static,Public,NonPublic" -Attribute ExtensionAttribute | ForEach-Object { $Method = $_ $ParameterType = $_.GetParameters()[0].ParameterType ForEach($T in $TargetTypeName) { Write-Verbose "Is '$T' a '$ParameterType'?" if($ParameterType.Name -like $T -or $ParameterType.FullName -like $T) { Write-Verbose "The name '$T' matches '$ParameterType'" Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -ParamBlock) -Force Write-Output $Method continue } if($ParameterType.IsGenericType) { $interface = $null if(Test-AssignableToGeneric $T $ParameterType -interface ([ref]$interface)) { # if([GenericHelper]::IsAssignableToGenericType( $T, $ParameterType )) { Write-Verbose "'$T' is a generic that's assignable to '$ParameterType'" Add-Member -Input $Method -Type NoteProperty -Name Extends -Value $interface.Value -Force Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -GenericArguments $interface.GetGenericArguments() -ParamBlock) -Force Write-Output $Method continue } } else { if($ParameterType.IsAssignableFrom($T)) { Write-Verbose "'$ParameterType' is assignable from '$T'" Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -ParamBlock) -Force Write-Output $Method continue } } } } } } function Test-AssignableToGeneric { <# .Synopsis Determine if a specific type can be cast to the given generic type #> param( # The concrete type you want to test generics against [Parameter(Position=0, Mandatory = $true)] [Type]$type, # A Generic Type to test [Parameter(ValueFromPipeline=$true, Position=1, Mandatory = $true)] [Type]$genericType, # Check the GenericTypeDefinition of the GenericType (in case it's typed) [Switch]$force, # If the type is assignable because of an interface, return that interface here [Parameter(Position=2)] [ref]$interface = [ref]$null ) process { $interfaces = $type.GetInterfaces() if($type.IsGenericType -and ($type.GetGenericTypeDefinition().equals($genericType))) { return $true } foreach($i in $interfaces) { if($i.IsGenericType -and $i.GetGenericTypeDefinition().Equals($genericType)) { $interface.Value = $i return $true } if($i.IsGenericType -and $i.GetGenericTypeDefinition().Equals($genericType.GetGenericTypeDefinition())) { $genericTypeArgs = @($genericType.GetGenericArguments())[0] if(($genericTypeArgs.IsGenericParameter -and $genericTypeArgs.BaseType.IsAssignableFrom( @($i.GetGenericArguments())[0] ) ) -or $genericTypeArgs.IsAssignableFrom( @($i.GetGenericArguments())[0] )) { $interface.Value = $i return $true } } } if($force -and $genericType -ne $genericType.GetGenericTypeDefinition()) { if(Test-AssignableToGeneric $type $genericType.GetGenericTypeDefinition()) { return $true } } $base = $type.BaseType if(!$base) { return $false } Test-AssignableToGeneric $base $genericType } } function Get-Method { <# .Synopsis Returns MethodInfo for the (public) methods of the specified Type. .Description Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method. .Parameter Type .Parameter Name .Parameter Force #> [CmdletBinding(DefaultParameterSetName="Type")] param( # The type to get methods from [Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Type]$Type, # The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns) [Parameter(Mandatory=$false, Position=1)] [SupportsWildCards()] [PSDefaultValue(Help='*')] [String[]]$Name ="*", # Force inclusion of Private methods and property accessors which are hidden by default. [Switch]$Force, # The Binding Flags filter the output. defaults to returning all methods, static or instance [PSDefaultValue(Help='Instance,Static,Public')] [System.Reflection.BindingFlags]$BindingFlags = $(if($Force){"Instance,Static,Public,NonPublic"} else {"Instance,Static,Public"}), # An Custom Attribute which should decorate the class [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Attribute ) process { Write-Verbose "[$($type.FullName)].GetMethods(`"$BindingFlags`")" Write-Verbose "[$($type.FullName)].GetConstructors(`"$BindingFlags`")" Write-Verbose "Filter by Name -like '$Name'" $Type.GetMethods($BindingFlags) + $type.GetConstructors($BindingFlags) | Where-Object { # Hide the Property accessor methods ($Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_") -AND # And Filter by Name, if necessary ($Name -eq "*" -or ($( foreach($n in $Name) { $_.Name -like $n } ) -contains $True)) -AND (!$Attribute -or $( foreach($n in $Attribute) { $_.CustomAttributes | ForEach { $_.AttributeType.Name -like $n -or $_.AttributeType.FullName -like $n } } ) -contains $True ) } } } if(!($RMI = Get-TypeData System.Reflection.RuntimeMethodInfo) -or !$RMI.Members.ContainsKey("TypeName")) { Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "TypeName" -MemberType ScriptProperty -Value { $this.ReflectedType.FullName } Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "Definition" -MemberType ScriptProperty -Value { Get-MemberSignature $this -Simple } Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "Syntax" -MemberType AliasProperty -Value "Definition" Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "SafeSyntax" -MemberType ScriptProperty -Value { Get-MemberSignature $this } } function Get-MemberSignature { <# .Synopsis Get the powershell signature for calling a member. #> [CmdletBinding(DefaultParameterSetName="CallSignature")] param( # The Method we're getting the signature for [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=0)] [System.Reflection.MethodBase]$MethodBase, [Parameter(Mandatory=$false, Position=1)] [Type[]]$GenericArguments, # Return the simplified markup [Parameter(ParameterSetName="CallSignature")] [Switch]$Simple, # Return a param block [Parameter(ParameterSetName="ParamBlock")] [Switch]$ParamBlock ) process { if($PSCmdlet.ParameterSetName -eq "ParamBlock") { $Simple = $true } $parameters = $( foreach($param in $MethodBase.GetParameters()) { # Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan # Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)" $paramType = $param.ParameterType Write-Verbose "$(if($paramType.IsGenericType){'Generic: '})$($GenericArguments)" if($paramType.IsGenericType -and $GenericArguments) { try { $paramType = $paramType.GetGenericTypeDefinition().MakeGenericType( $GenericArguments ) } catch { continue } } if($paramType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' } if($paramType.IsArray) { $array = ',' } else { $array = '' } if($ParamBlock) { '[Parameter(Mandatory=$true)]{0}[{1}]${2}' -f $ref, $paramType.ToString().TrimEnd('&'), $param.Name } elseif($Simple) { '[{0}] {2}' -f $paramType.ToString().TrimEnd('&'), $param.Name } else { '{0}({1}[{2}]${3})' -f $ref, $array, $paramType.ToString().TrimEnd('&'), $param.Name } } ) if($PSCmdlet.ParameterSetName -eq "ParamBlock") { $parameters -join ', ' } elseif($MethodBase.IsConstructor) { "New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')" } elseif($Simple) { "$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))" } elseif($MethodBase.IsStatic) { "[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))" } else { "[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))" } } } function Read-Choice { [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [hashtable[]]$Choices, [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!", [Parameter(Mandatory=$False)] [string]$Message = "Choose one of the following options:", [Parameter(Mandatory=$False)] [int[]]$Default = 0, [Switch]$MultipleChoice, [Switch]$Passthru ) begin { [System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value } ) ) if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Read-Choice { <# .Synopsis Prompt the user for a choice, and return the (0-based) index of the selected item .Parameter Message This is the prompt that will be presented to the user. Basically, the question you're asking. .Parameter Choices An array of strings representing the choices (or menu items), with optional ampersands (&) in them to mark (unique) characters which can be used to select each item. .Parameter ChoicesWithHelp A Hashtable where the keys represent the choices (or menu items), with optional ampersands (&) in them to mark (unique) characters which can be used to select each item, and the values represent help text to be displayed to the user when they ask for help making their decision. .Parameter Default The (0-based) index of the menu item to select by default (defaults to zero). .Parameter MultipleChoice Prompt the user to select more than one option. This changes the prompt display for the default PowerShell.exe host to show the options in a column and allows them to choose multiple times. Note: when you specify MultipleChoice you may also specify multiple options as the default! .Parameter Caption An additional caption that can be displayed (usually above the Message) as part of the prompt .Parameter Passthru Causes the Choices objects to be output instead of just the indexes .Example Read-Choice "WEBPAGE BUILDER MENU" "&Create Webpage","&View HTML code","&Publish Webpage","&Remove Webpage","E&xit" .Example [bool](Read-Choice "Do you really want to do this?" "&No","&Yes" -Default 1) This example takes advantage of the 0-based index to convert No (0) to False, and Yes (1) to True. It also specifies YES as the default, since that's the norm in PowerShell. .Example Read-Choice "Do you really want to delete them all?" @{"&No"="Do not delete all files. You will be prompted to delete each file individually."; "&Yes"="Confirm that you want to delete all of the files"} Note that with hashtables, order is not guaranteed, so "Yes" will probably be the first item in the prompt, and thus will output as index 0. Because of thise, when a hashtable is passed in, we default to Passthru output. #> [CmdletBinding(DefaultParameterSetName="HashtableWithHelp")] param( [Parameter(Mandatory=$true, Position = 10, ParameterSetName="HashtableWithHelp")] [Hashtable]$ChoicesWithHelp , [Parameter(Mandatory=$true, Position = 10, ParameterSetName="StringArray")] [String[]]$Choices , [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!" , [Parameter(Mandatory=$False, Position=0)] [string]$Message = "Choose one of the following options:" , [Parameter(Mandatory=$False)] [int[]]$Default = 0 , [Switch]$MultipleChoice , [Switch]$Passthru ) begin { if($ChoicesWithHelp) { [System.Collections.DictionaryEntry[]]$choices = $ChoicesWithHelp.GetEnumerator() | %{$_} } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( if($choices -is [String[]]) { foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice } } else { foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key, $choice.Value } } ) ) # Passing an array as the $Default triggers multiple choice prompting. if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru -or !($choices -is [String[]])) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Get-Argument { param( [Type]$Target, [ref]$Method, [Array]$Arguments ) end { trap { write-error $_ break } $flags = [System.Reflection.BindingFlags]"public,ignorecase,invokemethod,instance" [Type[]]$Types = @( foreach($arg in $Arguments) { if($arg -is [type]) { $arg } else { $arg.GetType() } } ) try { Write-Verbose "[$($Target.FullName)].GetMethod('$($Method.Value)', [$($Flags.GetType())]'$flags', `$null, ([Type[]]($(@($Types|%{$_.Name}) -join ','))), `$null)" $MethodBase = $Target.GetMethod($($Method.Value), $flags, $null, $types, $null) $Arguments if($MethodBase) { $Method.Value = $MethodBase.Name } } catch { } if(!$MethodBase) { Write-Verbose "Try again to get $($Method.Value) Method on $($Target.FullName):" $MethodBase = Get-Method $target $($Method.Value) if(@($MethodBase).Count -gt 1) { $i = 0 $i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:" [System.Reflection.MethodBase]$MethodBase = $MethodBase[$i] } ForEach($parameter in $MethodBase.GetParameters()) { $found = $false For($a =0;$a -lt $Arguments.Count;$a++) { if($argument[$a] -as $parameter.ParameterType) { Write-Output $argument[$a] if($a -gt 0 -and $a -lt $Arguments.Count) { $Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a) } elseif($a -eq 0) { $Arguments = $Arguments | Select -Last ($Arguments.Count - 1) } else { # a -eq count $Arguments = $Arguments | Select -First ($Arguments.Count - 1) } $found = $true break } } if(!$Found) { $userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)" if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) { Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType) } else { Write-Output ($userInput -as $parameter.ParameterType) } } } } } } function Invoke-Member { [CmdletBinding()] param( [parameter(position=10, valuefrompipeline=$true, mandatory=$true)] [allowemptystring()] $InputObject, [parameter(position=0, mandatory=$true)] [validatenotnullorempty()] $Member, [parameter(position=1, valuefromremainingarguments=$true)] [allowemptycollection()] $Arguments, [parameter()] [switch]$Static ) # begin { # if(!(get-member SafeSyntax -input $Member -type Property)){ # if(get-member Name -inpup $Member -Type Property) { # $Member = Get-Method $InputObject $Member.Name # } else { # $Member = Get-Method $InputObject $Member # } # } # $SafeSyntax = [ScriptBlock]::Create( $Member.SafeSyntax ) # } process { # if ($InputObject) # { # if ($InputObject | Get-Member $Member -static:$static) # { if ($InputObject -is [type]) { $target = $InputObject } else { $target = $InputObject.GetType() } if(Get-Member $Member -InputObject $InputObject -Type Properties) { $_.$Member } elseif($Member -match "ctor|constructor") { $Member = ".ctor" [System.Reflection.BindingFlags]$flags = "CreateInstance" $InputObject = $Null } else { [System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod" if($Static) { $flags = "$Flags,Static" } else { $flags = "$Flags,Instance" } } [ref]$Member = $Member [Object[]]$Parameters = Get-Argument $Target $Member $Arguments [string]$Member = $Member.Value Write-Verbose $(($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ }) -Join ", ") try { Write-Verbose "Invoking $Member on [$target]$InputObject with [$($Flags.GetType())]'$flags' and [$($Parameters.GetType())]($($Parameters -join ','))" Write-Verbose "[$($target.FullName)].InvokeMember('$Member', [System.Reflection.BindingFlags]'$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))" $target.InvokeMember($Member, [System.Reflection.BindingFlags]"$flags", $null, $InputObject, $Parameters) } catch { Write-Warning $_.Exception if ($_.Exception.Innerexception -is [MissingMethodException]) { write-warning "Method argument count (or type) mismatch." } } # } else { # write-warning "Method $Member not found." # } # } } } function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On')] $InputObject, [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName, [Parameter(Position=2)] [Alias("Types")] [Type[]]$ParameterTypes, [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs, [Switch]$Static ) begin { if($Static) { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static" } else { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance" } } process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($WithArgs -and -not $ParameterTypes) { $ParameterTypes = $withArgs | % { $_.GetType() } } elseif(!$ParameterTypes) { $ParameterTypes = [Type]::EmptyTypes } trap { continue } $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags) if(!$MemberInfo) { $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null) } if(!$MemberInfo) { $MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object { $MI = $_ [bool]$Accept = $MI.Name -eq $MethodName if($Accept){ Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)" [Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name) [Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value { $GenericTypes -Contains $this.ParameterType } -Passthru) $Accept = $ParameterTypes.Count -eq $Parameters.Count Write-Verbose " $Accept = $($Parameters.Count) Arguments" if($Accept) { for($i=0;$i -lt $Parameters.Count;$i++) { $Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType)) Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)" } } } return $Accept } | Sort { @($_.GetGenericArguments()).Count } | Select -First 1 } Write-Verbose "Time to make generic methods." Write-Verbose $MemberInfo [Type[]]$GenericParameters = @() [Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType) for($i=0;$i -lt $ParameterTypes.Count;$i++){ Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])" if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) { $GenericParameters += $ParameterTypes[$i] } $ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru } $ParameterTypes | Where-Object { $_.IsGeneric } Write-Verbose "$($GenericParameters -join ', ') generic parameters" $MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters ) Write-Verbose $MemberInfo if($WithArgs) { [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')" $MemberInfo.Invoke( $InputObject, $Arguments ) } else { $MemberInfo.Invoke( $InputObject ) } } } # get a reference to the Type $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") function Import-Namespace { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string]$Namespace, [Switch]$Force ) end { Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator } } function Add-Accelerator { <# .Synopsis Add a type accelerator to the current session .Description The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]). .Example Add-Accelerator list System.Collections.Generic.List``1 $list = New-Object list[string] Creates an accelerator for the generic List[T] collection type, and then creates a list of strings. .Example Add-Accelerator "List T", "GList" System.Collections.Generic.List``1 $list = New-Object "list t[string]" Creates two accelerators for the Generic List[T] collection type. .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate (without square brackets) .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64]) Also see the help for Get-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding()] param( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator, [Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type]$Type ) process { # add a user-defined accelerator foreach($a in $Accelerator) { if($xlr8r::AddReplace) { $xlr8r::AddReplace( $a, $Type) } else { $null = $xlr8r::Remove( $a ) $xlr8r::Add( $a, $Type) } trap [System.Management.Automation.MethodInvocationException] { if($xlr8r::get.keys -contains $a) { if($xlr8r::get[$a] -ne $Type) { Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]" } Continue; } throw } } } } function Get-Accelerator { <# .Synopsis Get one or more type accelerator definitions .Description The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type .Example Get-Accelerator System.String Returns the KeyValue pair for the [System.String] accelerator(s) .Example Get-Accelerator ps*,wmi* Returns the KeyValue pairs for the matching accelerator definition(s) .Parameter Accelerator One or more short form accelerators to search for (Accept wildcard characters). .Parameter Type One or more types to search for. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". Also see the help for Add-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(DefaultParameterSetName="ByType")] param( [Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator, [Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type[]]$Type ) process { # add a user-defined accelerator switch($PSCmdlet.ParameterSetName) { "ByAccelerator" { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { $_ } } } break } "ByType" { if($Type -and $Type.Count) { $xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value } } else { $xlr8r::get.GetEnumerator() | %{ $_ } } break } } } } function Remove-Accelerator { <# .Synopsis Remove a type accelerator from the current session .Description The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators. .Example Remove-Accelerator int Add-Accelerator int Int64 Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works: So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64" .Example Get-Accelerator System.Single | Remove-Accelerator Removes both of the default accelerators for System.Single: [float] and [single] .Example Get-Accelerator System.Single | Remove-Accelerator -WhatIf Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print: What if: Removes the alias [float] for type [System.Single] What if: Removes the alias [single] for type [System.Single] .Parameter Accelerator The short form accelerator that you want to remove (Accept wildcard characters). .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Get-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","FullName")] [string[]]$Accelerator ) process { foreach($a in $Accelerator) { foreach($key in $xlr8r::Get.Keys -like $a) { if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]", "Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?", "Removing Type Accelerator" )) { # remove a user-defined accelerator $xlr8r::remove($key) } } } } } ############################################################################### ##### Imported from PowerBoots $Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree' $DependencyProperties = @{} if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) { #$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) ) $DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml } function Get-ReflectionModule { $executioncontext.sessionstate.module } function Set-ObjectProperties { [CmdletBinding()] param( $Parameters, [ref]$DObject ) if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() } if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White } foreach ($param in $Parameters) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" } ## INGORE DEPENDENCY PROPERTIES FOR NOW :) if($param.Key -eq "DependencyProps") { ## HANDLE EVENTS .... } elseif ($param.Key.StartsWith("On_")) { $EventName = $param.Key.SubString(3) if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" } $sb = $param.Value -as [ScriptBlock] if(!$sb) { $sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock } $Dobject.Value."Add_$EventName".Invoke( $sb ); # $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) ); # $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) ); } ## HANDLE PROPERTIES .... else { try { ## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here. if($DebugPreference -ne "SilentlyContinue") { Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray } if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) { $Values = @() foreach($sb in $param.Value) { $Values += & (Get-ReflectionModule) $sb } } else { $Values = $param.Value } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green } Set-Property $Dobject $Param.Key $Values if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta } if($DebugPreference -ne "SilentlyContinue") { if( $Dobject.Value.$($param.Key) -ne $null ) { Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green } } } catch [Exception] { Write-Host "COUGHT AN EXCEPTION" -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } while($DependencyProps) { $name, $value, $DependencyProps = $DependencyProps $name = ([string]@($name)[0]).Trim("-") if($name -and $value) { Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value } } } if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host } if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() } } function Set-Property { PARAM([ref]$TheObject, $Name, $Values) $DObject = $TheObject.Value if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta } $PropertyType = $DObject.GetType().GetProperty($Name).PropertyType if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green} # [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject ) # [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) ) # In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class. [Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject ) [Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) ) $Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null $TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() ) } elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) { $Binding = @($Values)[0]; if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan} if(!$Binding.Source -and !$Binding.ElementName) { $Binding.Source = $DObject.DataContext } if($DependencyProperties.ContainsKey($Name)) { $field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType) if($field) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue } if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue} $DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null } else { throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )" } } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan } try { $DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow } } catch { Write-Host "Nope, was not able to set it." -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } } elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) { if($Values -is [System.Collections.IEnumerable]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan } $DObject.$($Name) = $Values } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan } $DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]" $DObject.$($Name).Add($Values) } } elseif($DObject.$($Name) -is [System.Collections.IList]) { foreach ($value in @($Values)) { try { $null = $DObject.$($Name).Add($value) } catch { # Write-Host "CAUGHT array problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) ) } else { Write-Error $_.Exception throw } } } } else { ## If they pass an array of 1 when we only want one, we just use the first value if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White} try { $DObject.$($Name) = $Values[0] } catch [Exception] { # Write-Host "CAUGHT collection value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $Values[0]) ) }else { throw } } } else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan} try { $DObject.$($Name) = $Values } catch [Exception] { # Write-Host "CAUGHT value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $values) ) }else { throw } } } } } function Set-DependencyProperty { [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true)] $Property, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Element, [Parameter()] [Switch]$Passthru ) DYNAMICPARAM { $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary $Param1 = new-object System.Management.Automation.RuntimeDefinedParameter $Param1.Name = "Value" # $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) ) $Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) ) if( $Property ) { if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))) { $Param1.ParameterType = $Property.PropertyType } elseif($Property -is [string] -and $Property.Contains(".")) { $Class,$Property = $Property.Split(".") if($DependencyProperties.ContainsKey($Property)){ $type = $DependencyProperties.$Property.Keys -like "*$Class" if($type) { $Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType } } } elseif($DependencyProperties.ContainsKey($Property)){ if($Element) { if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) { $Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType } } else { $Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType } } else { $Param1.ParameterType = [PSObject] } } else { $Param1.ParameterType = [PSObject] } $paramDictionary.Add("Value", $Param1) return $paramDictionary } PROCESS { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red continue } if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])) ){ trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red continue } $Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType)) } else { if("$Property".Contains(".")) { $Class,$Property = "$Property".Split(".") } if( $DependencyProperties.ContainsKey("$Property" ) ) { $fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } ) if($fields.Count -eq 0 ) { $fields = @($DependencyProperties.$Property.Keys -like "*$Class" ) } if($fields.Count) { $success = $false foreach($field in $fields) { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red continue } $Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType))) if($?) { $success = $true; break } } if(!$success) { throw "food" } } else { Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red } } else { Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red } } if( $Passthru ) { $Element } } } function Add-Struct { #.Synopsis # Creates Struct types from a list of types and properties #.Description # Add-Struct is a wrapper for Add-Type to create struct types. #.Example # New-Struct Song { # [string]$Artist # [string]$Album # [string]$Name # [TimeSpan]$Length # } -CreateConstructorFunction # # Description # ----------- # Creates a "Song" type with strongly typed Artist, Album, Name, and Length properties, with a simple constructor and a constructor function #.Example # New-Struct @{ # >> Product = { [string]$Name; [double]$Price; } # >> Order = { [Guid]$Id; [Product]$Product; [int]$Quantity } # >> Customer = { # >> [string]$FirstName # >> [string]$LastName # >> [int]$Age # >> [Order[]]$OrderHistory # >> } # >> } # >> # # Description # ----------- # To create a series of related struct types (where one type is a property of another type), you need to use the -Types hashtable parameter set. That way, all of the types will compiled together at once, so the compiler will be able to find them all. # [CmdletBinding(DefaultParameterSetName="Multiple")] param( # The name of the TYPE you are creating. Must be unique per PowerShell session. [ValidateScript({ if($_ -notmatch '^[a-z][a-z1-9_]*$') { throw "'$_' is invalid. A valid name identifier must start with a letter, and contain only alpha-numeric or the underscore (_)." } return $true })] [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")] [string]$Name, # A Scriptblock full of "[Type]$Name" definitions to show what properties you want on your Struct type [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")] [ScriptBlock]$Property,
PowerShellCorpus/PoshCode/Search-CertificateStore..ps1
Search-CertificateStore..ps1
##############################################################################\n##\n## Search-CertificateStore\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nSearch the certificate provider for certificates that match the specified\nEnhanced Key Usage (EKU.)\n\n.EXAMPLE\n\nSearch-CertificateStore "Encrypting File System"\n\n#>\n\nparam(\n ## The friendly name of an Enhanced Key Usage\n ## (such as 'Code Signing')\n [Parameter(Mandatory = $true)]\n $EkuName\n)\n\nSet-StrictMode -Off\n\n## Go through every certificate in the current user's "My" store\nforeach($cert in Get-ChildItem cert:\\CurrentUser\\My)\n{\n ## For each of those, go through its extensions\n foreach($extension in $cert.Extensions)\n {\n ## For each extension, go through its Enhanced Key Usages\n foreach($certEku in $extension.EnhancedKeyUsages)\n {\n ## If the friendly name matches, output that certificate\n if($certEku.FriendlyName -eq $ekuName)\n {\n $cert\n }\n }\n }\n}
PowerShellCorpus/PoshCode/Save-Credentials_4.ps1
Save-Credentials_4.ps1
<# .SYNOPSIS The script saves a username and password, encrypted with a custom key to to a file. .DESCRIPTION The script saves a username and password, encrypted with a custom key to to a file. The key is coded into the script but should be changed before use. The key allows the password to be decrypted by any user who has the key, on any machine. if the key parameter is omitted from ConvertFrom-SecureString, only the user who generated the file on the computer that generated the file can decrypt the password. see http://bsonposh.com/archives/254 for more info. To retrieve the password: $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 $VCCred = Import-Csv 'C:\\PATH\\FILE.TXT' $VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key) $VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password) .NOTES File Name : SaveCredentials.ps1 Author : Samuel Mulhearn Version History: Version 1.0 28 Jun 2012. Release .LINK http://poshcode.org/3491 .EXAMPLE Call the script with .\\Save-Credentials.ps1 no arguments or parameters are required #> $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 Write-Host "Key length is:" $key.length "The key length is acceptable if 16 or 32" $ScriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition $Outfile = "$ScriptPath\\Credentials.txt" Write-Host "This script will a username and encrpyted password into $outfile" $null | Out-File -FilePath $Outfile $credential = Get-Credential $obj = New-Object -typename System.Object $obj | Add-Member -MemberType noteProperty -name Username -value $credential.UserName $obj | Add-Member -MemberType noteProperty -name Password -value ($credential.Password | ConvertFrom-SecureString -key $key) $obj | Export-Csv -Path $OutFile write-host "Username and password have been saved to $outfile"
PowerShellCorpus/PowerShellGallery/ServerOpsMenu/0.1.1/Private/New-Menu.ps1
New-Menu.ps1
$title = 'Server Operations Tasks' $path = 'ServerOpsMenu.xml' $hash = [ordered]@{ 'Get Services' = {Get-CimInstance Win32_Service | Select-Object 'DisplayName','Name','StartMode','State','Status' | Format-Table -AutoSize} 'Restart Service' = {Get-Service (Read-Host 'Service Name') | Restart-Service -Confirm -Force -Verbose} 'Get Top 5 Processes by CPU' = {Get-Process | Sort-Object -Descending -Property CPU | Select-Object -First 5 | Format-Table -AutoSize} 'Get Top 5 Processes by Memory' = {Get-Process | Sort-Object -Descending -Property WS | Select-Object -First 5 | Format-Table -AutoSize} 'Stop Process' = {Get-Process (Read-Host 'Process Name') | Stop-Process -Confirm -Force -Verbose} 'Get Volumes' = {Get-CimInstance Win32_LogicalDisk | Where-Object DriveType -eq 3 | foreach {[pscustomobject]@{ID = $_.DeviceID;VolumeName = $_.VolumeName;'Disk Space' = '{0}GB/{1}GB Used' -f (([math]::round($_.Size/1GB)-[math]::round($_.FreeSpace/1GB))),([math]::round($_.Size/1GB))}}} 'Get Recent System Eventlog' = {Get-Eventlog -LogName System -Newest 50 | Select-Object Index, TimeGenerated, InstanceID, EntryType, Message | Format-Table -AutoSize} 'Restart Server' = {Restart-Computer -Confirm -Force} } #create item objects $items = $hash.GetEnumerator() | foreach -Begin { $i=0 } -Process { $i++ [pscustomobject]@{ ItemNumber = $i MenuItem = $_.Name Action = $_.Value } } -end {} $MyMenu = [pscustomObject]@{ Title = $Title Items = $items } $MyMenu | Export-Clixml -Path $path
PowerShellCorpus/PowerShellGallery/ServerOpsMenu/0.1.1/Private/Get-MOTD.ps1
Get-MOTD.ps1
Function Get-MOTD { <# .NAME Get-MOTD .SYNOPSIS Displays system information to a host. .DESCRIPTION The Get-MOTD cmdlet is a system information tool written in PowerShell. .EXAMPLE .VERSION 0.1.0 #> [CmdletBinding()] Param ( [Parameter( Mandatory=$false, Position=0)] [ValidateNotNullOrEmpty()] [string[]] $ComputerName, [Parameter()] [PsCredential] [System.Management.Automation.CredentialAttribute()] $Credential ) $ScriptBlock = { $Operating_System = Get-CimInstance -ClassName Win32_OperatingSystem $Logical_Disk = Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object -Property DeviceID -eq $Operating_System.SystemDrive [pscustomobject]@{ Operating_System = $Operating_System Processor = Get-CimInstance -ClassName Win32_Processor Process_Count = (Get-Process).Count Shell_Info = "{0}.{1}" -f $PSVersionTable.PSVersion.Major,$PSVersionTable.PSVersion.Minor Logical_Disk = $Logical_Disk } } if ($ComputerName) { # Build Hash to be used for passing parameters to New-PSSession commandlet $PSSessionParams = @{ ComputerName = $ComputerName ErrorAction = 'Stop' } # Add optional parameters to hash if ($Credential) { $PSSessionParams.Add('Credential', $Credential) } # Create remote powershell session try { $RemoteSession = New-PSSession @PSSessionParams } catch { $Message = (Get-Date -Format HH:mm:ss).ToString()+" : Unable to initiate remote session with client ComputerName ; $_" Write-Verbose $Message break } } # Build Hash to be used for passing parameters to Invoke-Command commandlet $CommandParams = @{ ScriptBlock = $ScriptBlock ErrorAction = 'Stop' } # Add optional parameters to hash if ($RemoteSession) { $CommandParams.Add('Session', $RemoteSession) } # Run ScriptBlock try { $ReturnedValues = Invoke-Command @CommandParams } catch { $Message = (Get-Date -Format HH:mm:ss).ToString()+" : Data collection failed on $ComputerName ; $_" Write-Verbose $Message break } # Assign variables $Date = Get-Date $OS_Name = $ReturnedValues.Operating_System.Caption $Computer_Name = $ReturnedValues.Operating_System.CSName $Kernel_Info = $ReturnedValues.Operating_System.Version $Process_Count = $ReturnedValues.Process_Count $Uptime = "$(($Uptime = $Date - $($ReturnedValues.Operating_System.LastBootUpTime)).Days) days, $($Uptime.Hours) hours, $($Uptime.Minutes) minutes" $Shell_Info = $ReturnedValues.Shell_Info $CPU_Info = $ReturnedValues.Processor.Name -replace '\(C\)', '' -replace '\(R\)', '' -replace '\(TM\)', '' -replace 'CPU', '' -replace '\s+', ' ' $Current_Load = $ReturnedValues.Processor.LoadPercentage $Memory_Size = "{0}mb/{1}mb Used" -f (([math]::round($ReturnedValues.Operating_System.TotalVisibleMemorySize/1KB))- ([math]::round($ReturnedValues.Operating_System.FreePhysicalMemory/1KB))),([math]::round($ReturnedValues.Operating_System.TotalVisibleMemorySize/1KB)) $Disk_Size = "{0}gb/{1}gb Used" -f (([math]::round($ReturnedValues.Logical_Disk.Size/1GB)- [math]::round($ReturnedValues.Logical_Disk.FreeSpace/1GB))),([math]::round($ReturnedValues.Logical_Disk.Size/1GB)) # Write to the Console Write-Host -Object ("") Write-Host -Object ("") Write-Host -Object (" ,.=:^!^!t3Z3z., ") -ForegroundColor Red Write-Host -Object (" :tt:::tt333EE3 ") -ForegroundColor Red Write-Host -Object (" Et:::ztt33EEE ") -NoNewline -ForegroundColor Red Write-Host -Object (" @Ee., .., $Date") -ForegroundColor Green Write-Host -Object (" ;tt:::tt333EE7") -NoNewline -ForegroundColor Red Write-Host -Object (" ;EEEEEEttttt33# ") -ForegroundColor Green Write-Host -Object (" :Et:::zt333EEQ.") -NoNewline -ForegroundColor Red Write-Host -Object (" SEEEEEttttt33QL ") -NoNewline -ForegroundColor Green Write-Host -Object ("User: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$env:UserName") -ForegroundColor Cyan Write-Host -Object (" it::::tt333EEF") -NoNewline -ForegroundColor Red Write-Host -Object (" @EEEEEEttttt33F ") -NoNewline -ForeGroundColor Green Write-Host -Object ("Hostname: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$Computer_Name") -ForegroundColor Cyan Write-Host -Object (" ;3=*^``````'*4EEV") -NoNewline -ForegroundColor Red Write-Host -Object (" :EEEEEEttttt33@. ") -NoNewline -ForegroundColor Green Write-Host -Object ("OS: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$OS_Name") -ForegroundColor Cyan Write-Host -Object (" ,.=::::it=., ") -NoNewline -ForegroundColor Cyan Write-Host -Object ("``") -NoNewline -ForegroundColor Red Write-Host -Object (" @EEEEEEtttz33QF ") -NoNewline -ForegroundColor Green Write-Host -Object ("Kernel: ") -NoNewline -ForegroundColor Red Write-Host -Object ("NT ") -NoNewline -ForegroundColor Cyan Write-Host -Object ("$Kernel_Info") -ForegroundColor Cyan Write-Host -Object (" ;::::::::zt33) ") -NoNewline -ForegroundColor Cyan Write-Host -Object (" '4EEEtttji3P* ") -NoNewline -ForegroundColor Green Write-Host -Object ("Uptime: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$Uptime") -ForegroundColor Cyan Write-Host -Object (" :t::::::::tt33.") -NoNewline -ForegroundColor Cyan Write-Host -Object (":Z3z.. ") -NoNewline -ForegroundColor Yellow Write-Host -Object (" ````") -NoNewline -ForegroundColor Green Write-Host -Object (" ,..g. ") -NoNewline -ForegroundColor Yellow Write-Host -Object ("Shell: ") -NoNewline -ForegroundColor Red Write-Host -Object ("Powershell $Shell_Info") -ForegroundColor Cyan Write-Host -Object (" i::::::::zt33F") -NoNewline -ForegroundColor Cyan Write-Host -Object (" AEEEtttt::::ztF ") -NoNewline -ForegroundColor Yellow Write-Host -Object ("CPU: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$CPU_Info") -ForegroundColor Cyan Write-Host -Object (" ;:::::::::t33V") -NoNewline -ForegroundColor Cyan Write-Host -Object (" ;EEEttttt::::t3 ") -NoNewline -ForegroundColor Yellow Write-Host -Object ("Processes: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$Process_Count") -ForegroundColor Cyan Write-Host -Object (" E::::::::zt33L") -NoNewline -ForegroundColor Cyan Write-Host -Object (" @EEEtttt::::z3F ") -NoNewline -ForegroundColor Yellow Write-Host -Object ("Current Load: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$Current_Load") -NoNewline -ForegroundColor Cyan Write-Host -Object ("%") -ForegroundColor Cyan Write-Host -Object (" {3=*^``````'*4E3)") -NoNewline -ForegroundColor Cyan Write-Host -Object (" ;EEEtttt:::::tZ`` ") -NoNewline -ForegroundColor Yellow Write-Host -Object ("Memory: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$Memory_Size") -ForegroundColor Cyan Write-Host -Object (" ``") -NoNewline -ForegroundColor Cyan Write-Host -Object (" :EEEEtttt::::z7 ") -NoNewline -ForegroundColor Yellow Write-Host -Object ("System Volume: ") -NoNewline -ForegroundColor Red Write-Host -Object ("$Disk_Size") -ForegroundColor Cyan Write-Host -Object (" 'VEzjt:;;z>*`` ") -ForegroundColor Yellow Write-Host -Object (" ```` ") -ForegroundColor Yellow Write-Host -Object ("") }
PowerShellCorpus/PowerShellGallery/ServerOpsMenu/0.1.1/Public/Invoke-Menu.ps1
Invoke-Menu.ps1
Function Invoke-Menu { <# .SYNOPSIS .DESCRIPTION .PARAMETER Name .EXAMPLE .EXAMPLE .VERSION 0.1.0 #> [cmdletbinding()] Param ( [Parameter( Mandatory=$false, Position=0)] [string[]] $ComputerName, [Parameter( Mandatory=$false, Position=1)] [PsCredential] [System.Management.Automation.CredentialAttribute()] $Credential, [Parameter( Mandatory=$false, Position=2)] [ValidateScript({ if (Test-Path $_) {$True} else {Throw "Cannot validate path $_"} })] [string] $Path = 'ServerOpsMenu.xml' ) Begin { if ($ComputerName) { # Build Hash to be used for passing parameters to New-PSSession commandlet $PSSessionParams = @{ ComputerName = $ComputerName ErrorAction = 'Stop' } # Add optional parameters to hash if ($Credential) { $PSSessionParams.Add('Credential', $Credential) } # Create remote powershell session try { $RemoteSession = New-PSSession @PSSessionParams } catch { $Message = (Get-Date -Format HH:mm:ss).ToString()+" : Unable to initiate remote session with client ComputerName ; $_" Write-Verbose $Message break } Get-MOTD @PSSessionParams } else { Get-MOTD } $ImportedMenu = Import-Clixml -Path $Path #verify there are title and item properties if ($ImportedMenu.Title -AND $ImportedMenu.Items) { $HereMenu = @" $($ImportedMenu.title) "@ } } Process { foreach ($Item in $ImportedMenu.Items) { $HereMenu+= "{0} - {1}`n" -f $Item.ItemNumber,$Item.MenuItem } $HereMenu += "Enter a menu number or Q to quit" #Keep looping and running the menu until the user selects Q (or q). $Running = $True Do { #cls $Selection = Read-Host $HereMenu if ($Selection -match "^q" -OR $Selection.length -eq 0) { #quit the menu $Running = $False Write-Host "Exiting the menu. Have a nice day" -ForegroundColor green #bail out Return } elseif (-Not ([int]$Selection -ge 1 -AND [int]$Selection -le $($ImportedMenu.Items.count)) ) { Write-Warning "Enter a menu choice between 1 and $($ImportedMenu.Items.count) or Q to quit" } else { #create a scriptblock $ScriptBlock = [scriptblock]::Create($ImportedMenu.Items[$Selection -1].action) # Build Hash to be used for passing parameters to Invoke-Command commandlet $CommandParams = @{ ScriptBlock = $ScriptBlock ErrorAction = 'Stop' } # Add optional parameters to hash if ($RemoteSession) { $CommandParams.Add('Session', $RemoteSession) } Invoke-Command @CommandParams | Out-Host #pause #$Nothing = Read-Host "Press any key to continue" } } While ($Running) else { Write-Warning "$Path does not appear to have menu information" } } End {} }
PowerShellCorpus/PowerShellGallery/ServerOpsMenu/0.1.1/Tests/IHGServerOps.Tests.ps1
IHGServerOps.Tests.ps1
̀
PowerShellCorpus/PowerShellGallery/OpenWeatherMap/2.1.0/Run-Tests.ps1
Run-Tests.ps1
$PesterVersion = '3.4.2' # Save-module locally Save-Module -Name Pester -Path '.modules\' -RequiredVersion $PesterVersion # Copy custom assertions Copy-Item -Path '.\Assertions\*.ps1' -Destination ".\.modules\Pester\$PesterVersion\Functions\Assertions" # Import local Pester module so we can extend built-in assertions Import-Module ".\.modules\Pester\$PesterVersion\Pester.psd1" # Run tests Invoke-Pester -Script ".\OpenWeatherMap.Tests.ps1"
PowerShellCorpus/PowerShellGallery/OpenWeatherMap/2.1.0/OpenWeatherMap.Tests.ps1
OpenWeatherMap.Tests.ps1
Import-Module OpenWeatherMap -Force ######## Test Values ########## $TestUnixTimestamp = 1471017423 # TODO Replace with raw JSON from file $RawWeatherMain = @{ temp = 60; temp_min = 50; temp_max = 70 } $RawWeatherConditions = @(@{ id = 500; description = 'light rain'; }) $RawWeather = @{ main = $RawWeatherMain weather = $RawWeatherConditions } $RawForecast = @{ dt = $TestUnixTimestamp; main = $RawWeatherMain; weather = $RawWeatherConditions } ################################### Describe 'Get-WeatherForecastItem' { It 'should return a hashtable with a forecast' { $Unit = Get-WeatherUnitMeasurement -Units imperial $Symbol = Get-WeatherSymbol -Code 500 $Result = Get-WeatherForecastItem $RawForecast -Units imperial $Result.Time | Should BeDate '8/12/2016 10:57:03' $Result.Temperature | Should Be "60$Unit" $Result.Weather | Should Be 'light rain' $Result.WeatherCode | Should Be 500 $Result.WeatherSymbol | Should Be $Symbol } } Describe 'Get-WeatherCityTemperature' { Context 'with units' { $Unit = Get-WeatherUnitMeasurement -Units imperial It 'should support current temperature by default' { Get-WeatherCityTemperature $RawWeather -Units imperial | Should Be "60$Unit" } It 'should support current temperature' { Get-WeatherCityTemperature $RawWeather -Type Current -Units imperial | Should Be "60$Unit" } It 'should support min temperature' { Get-WeatherCityTemperature $RawWeather -Type Min -Units imperial | Should Be "50$Unit" } It 'should support max temperature' { Get-WeatherCityTemperature $RawWeather -Type Max -Units imperial | Should Be "70$Unit" } } Context 'without units' { It 'should support current temperature by default' { Get-WeatherCityTemperature $RawWeather -Units none | Should Be 60 } It 'should support current temperature' { Get-WeatherCityTemperature $RawWeather -Type Current -Units none | Should Be 60 } It 'should support min temperature' { Get-WeatherCityTemperature $RawWeather -Type Min -Units none | Should Be 50 } It 'should support max temperature' { Get-WeatherCityTemperature $RawWeather -Type Max -Units none | Should Be 70 } } } Describe 'Get-WeatherCityStatus' { It 'should return weather condition' { $Result = Get-WeatherCityStatus -WeatherCity $RawWeather $Result | Should Be 'light rain' } It 'should return weather condition symbol' { $Result = Get-WeatherCityStatus -WeatherCity $RawWeather -Symbol $Result | Should Be '🌧' } } Describe 'Get-DateTimeUtcFromUnix' { It 'supports UTC Unix timestamp' { $Result = Get-DateTimeUtcFromUnix $TestUnixTimestamp $Result | Should BeDate '8/12/2016 10:57:03' } } Describe 'Get-WeatherUnitMeasurement' { It 'returns °F by default' { Get-WeatherUnitMeasurement | Should Be '°F' } It 'returns °F for imperial units' { Get-WeatherUnitMeasurement -Units imperial | Should Be '°F' } It 'returns °C for metric units' { Get-WeatherUnitMeasurement -Units metric | Should Be '°C' } It 'returns K for kelvin units' { Get-WeatherUnitMeasurement -Units kelvin | Should Be 'K' } } Describe 'Get-WeatherForecastSummaryForDay' { It 'should return forecast time closest to 12pm' { $Times = @( @{ Time = (Get-Date -Hour 8) }, @{ Time = (Get-Date -Hour 10) }, @{ Time = (Get-Date -Hour 13) } ) (Get-WeatherForecastSummaryForDay -Times $Times).Time.Hour | Should Be 13 } } Describe 'Get-WeatherSymbol' { It 'should return symbol for Tornado' { Get-WeatherSymbol 900 | Should Be '🌪' } It 'should return symbol for Tropical storm' { Get-WeatherSymbol 901 | Should Be '🌩' } It 'should return symbol for Hurricane' { Get-WeatherSymbol 902 | Should Be '🌀' } It 'should return symbol for Cold' { Get-WeatherSymbol 903 | Should Be '❄' } It 'should return symbol for Hot' { Get-WeatherSymbol 904 | Should Be '🔥' } It 'should return symbol for Windy' { Get-WeatherSymbol 905 | Should Be '🎐' } It 'should return symbol for Extreme' { Get-WeatherSymbol 906 | Should Be '☠' Get-WeatherSymbol 999 | Should Be '☠' } It 'should return symbol for Clear' { Get-WeatherSymbol 800 | Should Be '☀' } It 'should return symbol for Cloudy' { Get-WeatherSymbol 801 | Should Be '☁' } It 'should return symbol for Atmosphere' { Get-WeatherSymbol 700 | Should Be '🌫' } It 'should return symbol for Snow' { Get-WeatherSymbol 600 | Should Be '☃' } It 'should return symbol for Rain' { Get-WeatherSymbol 500 | Should Be '🌧' Get-WeatherSymbol 400 | Should Be '🌧' } It 'should return symbol for Drizzle' { Get-WeatherSymbol 300 | Should Be '☂' } It 'should return symbol for Thunderstorm' { Get-WeatherSymbol 200 | Should Be '🌩' } It 'should fallback to empty string when not matched' { Get-WeatherSymbol 100 | Should Be '' } }
PowerShellCorpus/PowerShellGallery/OpenWeatherMap/2.1.0/profile.example.ps1
profile.example.ps1
# Import module from current folder Import-Module .\OpenWeatherMap # Import weather from global module path ($env:PSModulePath) # Import-Module OpenWeatherMap Function Write-LocalWeatherCurrent([switch]$Inline) { # Replace city and API key Write-WeatherCurrent -City Minneapolis -ApiKey xxx -Units imperial -Inline:$Inline } Function Write-LocalWeatherForecast($Days = 1) { # Replace city and API key Write-WeatherForecast -City Minneapolis -ApiKey xxx -Units imperial -Days $Days } # EXAMPLE: Write at startup Write-Host "Weather: " -NoNewline -ForegroundColor Yellow Write-LocalWeatherCurrent # Type `weather` in the prompt to see current weather Set-Alias weather Write-LocalWeatherCurrent # Type `forecast` or `forecast -d 2` to get the current forecast Set-Alias forecast Write-LocalWeatherForecast # EXAMPLE: Override prompt and include inline weather Function Prompt() { # Write current dir Write-Host ($PWD) -NoNewline -ForegroundColor Red # Write inline weather Write-LocalWeatherCurrent -Inline Write-Host "›" -NoNewline -ForegroundColor Gray return ' ' }
PowerShellCorpus/PowerShellGallery/OpenWeatherMap/2.1.0/Assertions/BeDate.ps1
BeDate.ps1
Function PesterBeDate($Value, $Expected) { $Expected = [System.DateTime]::Parse($Expected) $Value.Year | Should Be $Expected.Year $Value.Month | Should Be $Expected.Month $Value.Day | Should Be $Expected.Day $Value.Hour | Should Be $Expected.Hour $Value.Minute | Should Be $Expected.Minute $Value.Second | Should Be $Expected.Second } Function PesterBeDateFailureMessage($Value, $Expected) { if (-not (($expected -is [string]) -and ($value -is [System.DateTime]))) { return "Expected: {$expected}`nBut was: {$value}" } return "Expected: $Expected\nBut was: $($Value.ToString('MM/dd/YYYY h:mm:ss'))" } Function NotPesterBeDateFailureMessage($Value, $Expected) { return PesterBeDateFailureMessage -Value $Value -Expected $Expected }
PowerShellCorpus/PowerShellGallery/posh-vpn/0.1.3/Get-VPNProfile.ps1
Get-VPNProfile.ps1
function Get-AnyConnectProfile() # {{{ { [CmdletBinding()] [OutputType([string[]])] Param( ) Write-Verbose "Starting the AnyConnect cli" $vpncli = New-Object System.Diagnostics.Process $vpncli.StartInfo = New-Object System.Diagnostics.ProcessStartInfo(Get-AnyConnect) $vpncli.StartInfo.Arguments = "hosts" $vpncli.StartInfo.CreateNoWindow = $false $vpncli.StartInfo.UseShellExecute = $false $vpncli.StartInfo.RedirectStandardOutput = $true $vpncli.StartInfo.RedirectStandardError = $true $vpncli.Start() | Out-Null $profiles = @() Write-Verbose "Reading its output" for ($output = $vpncli.StandardOutput.ReadLine(); $output -ne $null; $output = $vpncli.StandardOutput.ReadLine()) { Write-Debug $output if ($output -match ' >> note: (.*)') { Write-Warning $matches[1] $status = 'Note' } elseif ($output -match '.*\[hosts\]') { Write-Verbose "Found VPN profiles:" } elseif ($output -match '.*> (.*)') { Write-Verbose " Adding $($matches[1])" $profiles += $matches[1] } } for ($output = $vpncli.StandardError.ReadLine(); $output -ne $null; $output = $vpncli.StandardError.ReadLine()) { Write-Warning $output } return $profiles } #}}} <# .SYNOPSIS Displays all profiles/Computers that can be used with a given Provider .DESCRIPTION Displays all profiles/Computers that can be used with a given Provider .NOTES Only Cisco AnyConnect VPNs are supported as of now. .PARAMETER Provider The VPN Provider to use. One of: AnyConnect .OUTPUTS System.String[] The list of profiles, servers that can be connected to from the local computer. .LINK https://github.com/gildas/posh-vpn .EXAMPLE $session = Get-VPNProfile -Provider AnyConnect vpn.acme.com Description ----------- Gives the list of servers the user can connect to #> function Get-VPNProfile() # {{{ { [CmdletBinding()] [OutputType([string[]])] Param( [Parameter(Position=1, Mandatory=$true)] [ValidateSet('AnyConnect')] [string] $Provider ) $PSBoundParameters.Remove('Provider') | Out-Null switch($Provider) { 'AnyConnect' { Get-AnyConnectProfile @PSBoundParameters } default { Throw "Unsupported VPN Provider: $Provider" } } } # }}}
PowerShellCorpus/PowerShellGallery/posh-vpn/0.1.3/Install.ps1
Install.ps1
[CmdletBinding()] Param( [Parameter(Position=1, Mandatory=$false)] $Path ) $ModuleName = 'Posh-VPN' $ModuleVersion = '0.1.3' $GithubRoot = "https://raw.githubusercontent.com/gildas/posh-vpn/$ModuleVersion" if ([string]::IsNullOrEmpty($Path)) { $my_modules = Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'WindowsPowerShell\Modules' $module_paths = @($env:PSModulePath -split ';') if (! (Test-Path $my_modules)) { Write-Verbose "Creating Personal Powershell Module folder" New-Item -ItemType Directory -Path $my_modules -ErrorAction Stop | Out-Null } if ($module_paths -notcontains $my_modules) { Write-Verbose "Adding Personal Powershell Module folder to Module Search list" $env:PSModulePath = $my_modules + ';' + $env:PSModulePath [Environment]::SetEnvironmentVariable('PSModulePath', $env:PSModulePath, 'User') } $Path = Join-Path $my_modules $ModuleName } if (! (Test-Path $Path)) { Write-Verbose "Creating $ModuleName Module folder" New-Item -ItemType Directory -Path $Path -ErrorAction Stop | Out-Null } @( 'Get-AnyConnect.ps1', 'Get-VPNProfile.ps1', 'Get-VPNStatus.ps1', 'Disconnect-VPN.ps1', 'Connect-VPN.ps1', 'LICENSE', 'VERSION', 'README.md', 'Posh-VPN.psd1', 'Posh-VPN.psm1' ) | ForEach-Object { Start-BitsTransfer -DisplayName "$ModuleName Installation" -Description "Installing $_" -Source "$GithubRoot/$_" -Destination $Path -ErrorAction Stop }
PowerShellCorpus/PowerShellGallery/posh-vpn/0.1.3/Get-AnyConnect.ps1
Get-AnyConnect.ps1
function Get-AnyConnect() # {{{ { [CmdletBinding()] Param( [Parameter(Mandatory=$false)] [Alias('ui', 'graphics')] [switch] $gui ) $AnyConnectPath = Join-Path ${env:ProgramFiles(x86)} (Join-Path 'Cisco' 'Cisco AnyConnect Secure Mobility Client') if (Test-Path $AnyConnectPath) { if ($gui) { $application = 'vpnui.exe' } else { $application = 'vpncli.exe' } return (Join-Path $AnyConnectPath $application) } Throw [System.IO.FileNotFoundException] "AnyConnect is not installed" } # }}}
PowerShellCorpus/PowerShellGallery/posh-vpn/0.1.3/Get-VPNStatus.ps1
Get-VPNStatus.ps1
function Get-AnyConnectStatus() # {{{ { [CmdletBinding()] [OutputType([string])] Param( [Parameter(Mandatory=$false)] [PSCustomObject] $VPNSession ) Write-Verbose "Starting the AnyConnect cli" $vpncli = New-Object System.Diagnostics.Process $vpncli.StartInfo = New-Object System.Diagnostics.ProcessStartInfo(Get-AnyConnect) $vpncli.StartInfo.Arguments = "state" $vpncli.StartInfo.CreateNoWindow = $false $vpncli.StartInfo.UseShellExecute = $false $vpncli.StartInfo.RedirectStandardOutput = $true $vpncli.StartInfo.RedirectStandardError = $true $vpncli.Start() | Out-Null $status = 'Unknown' Write-Verbose "Reading its output" for ($output = $vpncli.StandardOutput.ReadLine(); $output -ne $null; $output = $vpncli.StandardOutput.ReadLine()) { Write-Debug $output if ($output -match ' >> note: (.*)') { Write-Warning $matches[1] $status = 'Note' } if ($output -match ' >> state: (.*)') { $status = $matches[1] Write-Verbose $status } } for ($output = $vpncli.StandardError.ReadLine(); $output -ne $null; $output = $vpncli.StandardError.ReadLine()) { Write-Warning $output } return $status } #}}} <# .SYNOPSIS Gets the current status of a VPN Session or a Provider. .DESCRIPTION Gets the current status of a VPN Session or a Provider. .NOTES Only Cisco AnyConnect VPNs are supported as of now. .PARAMETER Provider The VPN Provider to use. One of: AnyConnect .PARAMETER VPNSession The VPN session object returned by Connect-VPN. .OUTPUTS System.String The current status of the VPN Session of the Provider. With AnyConnect, the values are typically: Connected, Disconnected, Unknown. .LINK https://github.com/gildas/posh-vpn .EXAMPLE $session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -Credentials (Get-Credential ACME\gildas) Get-VPNStatus $session Connected Description ----------- Gets the connection of a session .EXAMPLE Get-VPNStatus -Provider AnyConnect Disconnected Description ----------- Gets the status of Cisco AnyConnect VPN #> function Get-VPNStatus() # {{{ { [CmdletBinding(DefaultParameterSetName='Session')] [OutputType([string])] Param( [Parameter(Position=1, ParameterSetName='Session', Mandatory=$true)] [PSCustomObject] $VPNSession, [Parameter(Position=1, ParameterSetName='Provider', Mandatory=$true)] [ValidateSet('AnyConnect')] [string] $Provider ) switch($PSCmdlet.ParameterSetName) { 'Session' { switch($VPNSession.Provider) { 'AnyConnect' { Get-AnyConnectStatus @PSBoundParameters } $null { Throw [System.ArgumentException] "VPNSession misses a Provider"; } default { Throw "Unsupported VPN Provider: $VPNSession.Provider" } } } 'Provider' { $PSBoundParameters.Remove('Provider') | Out-Null switch($Provider) { 'AnyConnect' { Get-AnyConnectStatus @PSBoundParameters } default { Throw "Unsupported VPN Provider: $VPNSession.Provider" } } } } } # }}}
PowerShellCorpus/PowerShellGallery/posh-vpn/0.1.3/Disconnect-VPN.ps1
Disconnect-VPN.ps1
function Disconnect-AnyConnect() # {{{ { [CmdletBinding()] Param( [Parameter(Mandatory=$false)] [PSCustomObject] $VPNSession ) Write-Verbose "Starting the VPN cli" $vpncli = New-Object System.Diagnostics.Process $vpncli.StartInfo = New-Object System.Diagnostics.ProcessStartInfo(Get-AnyConnect) $vpncli.StartInfo.Arguments = "disconnect" $vpncli.StartInfo.CreateNoWindow = $false $vpncli.StartInfo.UseShellExecute = $false $vpncli.StartInfo.RedirectStandardOutput = $true $vpncli.StartInfo.RedirectStandardError = $true $vpncli.Start() | Out-Null Write-Verbose "Reading its output" for ($output = $vpncli.StandardOutput.ReadLine(); $output -ne $null; $output = $vpncli.StandardOutput.ReadLine()) { Write-Debug $output if ($output -match ' >> note: (.*)') { Write-Warning $matches[1] } elseif ($output -match ' >> state: (.*)') { Write-Verbose $matches[1] } } for ($output = $vpncli.StandardError.ReadLine(); $output -ne $null; $output = $vpncli.StandardError.ReadLine()) { Write-Warning $output } } #}}} <# .SYNOPSIS Disconnect from a VPN Session or Provider. .DESCRIPTION Disconnect this computer from a given VPN Session or Provider. .NOTES Only Cisco AnyConnect VPNs are supported as of now. .PARAMETER Provider The VPN Provider to use. One of: AnyConnect .PARAMETER VPNSession The VPN session object returned by Connect-VPN. .LINK https://github.com/gildas/posh-vpn .EXAMPLE $session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -Credentials (Get-Credential ACME\gildas) Disconnect-VPN $session Description ----------- Disconnects from a Cisco AnyConnect VPN session .EXAMPLE Disconnect-VPN -Provider AnyConnect Description ----------- Disconnects from any Cisco AnyConnect VPN #> function Disconnect-VPN() # {{{ { [CmdletBinding(DefaultParameterSetName='Session')] Param( [Parameter(Position=1, ParameterSetName='Session', Mandatory=$true)] [PSCustomObject] $VPNSession, [Parameter(Position=1, ParameterSetName='Provider', Mandatory=$true)] [ValidateSet('AnyConnect')] [string] $Provider ) switch($PSCmdlet.ParameterSetName) { 'Session' { switch($VPNSession.Provider) { 'AnyConnect' { Disconnect-AnyConnect @PSBoundParameters } $null { Throw [System.ArgumentException] "VPNSession misses a Provider"; } default { Throw "Unsupported VPN Provider: $VPNSession.Provider" } } } 'Provider' { $PSBoundParameters.Remove('Provider') | Out-Null switch($Provider) { 'AnyConnect' { Disconnect-AnyConnect @PSBoundParameters } default { Throw "Unsupported VPN Provider: $VPNSession.Provider" } } } } } # }}}
PowerShellCorpus/PowerShellGallery/posh-vpn/0.1.3/Connect-VPN.ps1
Connect-VPN.ps1
function Connect-AnyConnect() # {{{ { [CmdletBinding(DefaultParameterSetName='Credential')] [OutputType([PSCustomObject])] Param( [Parameter(Position=1, Mandatory=$true)] [Alias("Server")] [string] $ComputerName, [Parameter(Position=2, ParameterSetName='Credential', Mandatory=$true)] [System.Management.Automation.PSCredential] $Credential, [Parameter(Position=2, ParameterSetName='Plain', Mandatory=$true)] [Alias("Username")] [string] $User, [Parameter(Position=3, ParameterSetName='Plain', Mandatory=$true)] [string] $Password ) if ($PSCmdlet.ParameterSetName -eq 'Credential') { Write-Verbose "Loading PSCredentials" $User = $Credential.UserName $Password = $Credential.GetNetworkCredential().password } else { $secret = ConvertTo-SecureString $Password -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($User, $secret) $secret = $null } # Disconnect as needed $temp_session = [PSCustomObject] @{ Provider='AnyConnect'; ComputerName=$ComputerName; Credential=$Credential; } if ((Get-AnyConnectStatus -VPNSession $temp_session -Verbose:$false) -ne 'Disconnected') { Disconnect-AnyConnect -VPNSession $temp_session -Verbose:$Verbose } # First Stop any VPN cli and ui # There must be only one "client" running when connecting Get-Process | Where ProcessName -match 'vpn(ui|cli)' | ForEach { if (! $_.HasExited) { Write-Verbose "Stopping process $($_.Name) (pid: $($_.Id))" Stop-Process $_.Id } else { Write-Verbose "Process $($_.Name) is exiting (pid: $($_.Id))" } } Write-Debug "Starting AnyConnect to $ComputerName as $User (Password: $Password)" Write-Verbose "Starting the AnyConnect cli" $vpncli = New-Object System.Diagnostics.Process $vpncli.StartInfo = New-Object System.Diagnostics.ProcessStartInfo(Get-AnyConnect) $vpncli.StartInfo.Arguments = "-s" $vpncli.StartInfo.CreateNoWindow = $true $vpncli.StartInfo.UseShellExecute = $false $vpncli.StartInfo.RedirectStandardInput = $true $vpncli.StartInfo.RedirectStandardOutput = $true #$vpncli.StartInfo.RedirectStandardError = $true if (! $vpncli.Start()) { Throw "Cannot start AnyConnect Client, error: $LASTEXITCODE" } Write-Verbose "Waiting for process to be ready" Start-Sleep 2 Write-Verbose "Sending connect" $vpncli.StandardInput.WriteLine('connect ' + $ComputerName) Write-Verbose "Sending user" $vpncli.StandardInput.WriteLine($User) Write-Verbose "Sending password" $vpncli.StandardInput.WriteLine($Password) Write-Verbose "Reading its output stream" $found = $false for ($output = $vpncli.StandardOutput.ReadLine(); $output -ne $null; $output = $vpncli.StandardOutput.ReadLine()) { Write-Debug $output if ($output -eq ' >> Login failed.') { Throw [System.Security.Authentication.InvalidCredentialException] } elseif ($output -match ' >> note: (.*)') { Write-Warning $matches[1] } elseif ($output -match ' >> state: (.*)') { $state = $matches[1] Write-Verbose $state if ($state -eq 'Connected') { break } } } Start-Process -FilePath (Get-Anyconnect -gui) return [PSCustomObject] @{ Provider='AnyConnect'; ComputerName=$ComputerName; Credential=$Credential; } } #}}} <# .SYNOPSIS Connects to a VPN Provider. .DESCRIPTION Connects this computer to a given VPN Provider. .NOTES Only Cisco AnyConnect VPNs are supported as of now. .PARAMETER Provider The VPN Provider to use. One of: AnyConnect .PARAMETER ComputerName The ComputerName or VPN profile to use. The TAB completion will provide the list of possible values depending on the chosen Provider. .PARAMETER Credential The PSCredential to use. .PARAMETER User If no PSCredential is provided, a User and a (plain text) Password must be provided. .PARAMETER Password If no PSCredential is provided, a User and a (plain text) Password must be provided. .INPUTS The ComputerName can be piped in. .OUTPUTS System.Management.Automation.PSObject Represents the VPN connection (its Provider, the ComputerName, and the Credential). .LINK https://github.com/gildas/posh-vpn .EXAMPLE $session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -Credentials (Get-Credential ACME\gildas) Description ----------- Connects to a Cisco AnyConnect VPN at vpn.acme.com with the PSCredential entered via Get-Credential .EXAMPLE $session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -User ACME\gildas -Password s3cr3t Description ----------- Connects to a Cisco AnyConnect VPN at vpn.acme.com with the clear text user and password #> function Connect-VPN # {{{ { [CmdletBinding(DefaultParameterSetName='Credential')] [OutputType([PSCustomObject])] Param( [Parameter(Position=1, Mandatory=$true)] [ValidateSet('AnyConnect')] [string] $Provider, #[Parameter(Position=2, Mandatory=$true)] #[Alias("Server")] #[string] $ComputerName, [Parameter(Position=3, ParameterSetName='Credential', Mandatory=$true)] [System.Management.Automation.PSCredential] $Credential, [Parameter(Position=3, ParameterSetName='Plain', Mandatory=$true)] [Alias("Username")] [string] $User, [Parameter(Position=4, ParameterSetName='Plain', Mandatory=$true)] [string] $Password ) DynamicParam { $parameters = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary #[Parameter(Position=2, Mandatory=$true)] $attributes = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $parameter_attribute = New-Object -Type System.Management.Automation.ParameterAttribute $parameter_attribute.Position = 2 $parameter_attribute.Mandatory = $true $parameter_attribute.ValueFromPipeline = $true #$parameter_attribute.ParameterSetName = @('Credential', 'Plain') $attributes.Add($parameter_attribute) if ($Provider -eq 'AnyConnect') { #[ValidateSet(Get-VPNProfiles -Provider AnyConnect)] $validateset = New-Object -Type System.Management.Automation.ValidateSetAttribute(Get-VPNProfile -Provider AnyConnect) $attributes.Add($validateset) } #[Alias("Server")] $aliases = New-Object -Type System.Management.Automation.AliasAttribute(@('Server')) $attributes.Add($aliases) #[string] $ComputerName, $parameter = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ComputerName", [string], $attributes) $parameters.Add('ComputerName', $parameter) return $parameters } process { $PSBoundParameters.Remove('Provider') | Out-Null switch($Provider) { 'AnyConnect' { Connect-AnyConnect @PSBoundParameters } default { Throw "Unsupported VPN Provider: $Provider" } } } } # }}}
PowerShellCorpus/PowerShellGallery/Mdbc/4.8.9/Scripts/Update-MongoFiles.ps1
Update-MongoFiles.ps1
<# .Synopsis Updates the file system snapshot database. .Description Server: local, database: test, collections: files, files_log Module: Mdbc <https://github.com/nightroman/Mdbc> The script scans the specified directory tree, updates file and directory documents, and then removes orphan documents which have not been updated. Changes are optionally logged in another collection. Collection "files" * _id : full item path * Attributes : file system flags * Length : file length * LastWriteTime : last write time * CreationTime : creation time * Name : item name * Extension : file extension * Updated : last update time Collection "files_log" * _id : full item path * Updated : last update time * Log : array of item snapshots * Op : 0: created, 1: changed, 2: removed .Parameter Path Specifies one or more literal directory paths to be processed. .Parameter CollectionName Specifies the collection name. Default: files (implies files_log). .Parameter Log Tells to log created, changed, and removed items to files_log. .Parameter Split Tells to perform parallel data processing using Split-Pipeline. Module: SplitPipeline <https://github.com/nightroman/SplitPipeline> .Inputs None. Use the parameters to specify input. .Outputs The result object with statistics * Path : the input path * Created : count of created * Changed : count of changed * Removed : count of removed * Elapsed : elapsed time span .Link Get-MongoFile.ps1 #> param ( [Parameter(Position=0)][string[]]$Path = '.', [string]$CollectionName = 'files', [switch]$Log, [switch]$Split ) $ErrorActionPreference = 'Stop' Set-StrictMode -Version 2 $Now = [DateTime]::Now # Resolves exact case paths. function Resolve($Path) { $directory = [IO.DirectoryInfo]$Path if ($directory.Parent) { Join-Path (Resolve $directory.Parent.FullName) $directory.Parent.GetFileSystemInfos($directory.Name)[0].Name } else { $directory.Name.ToUpper() } } $Path = foreach($_ in $Path) { Resolve ($PSCmdlet.GetUnresolvedProviderPathFromPSPath($_)) } Write-Host "Updating data for $Path ..." # Connects collections and initializes data. function Connect { Import-Module Mdbc Connect-Mdbc . test $CollectionName $CollectionLog = $Database.GetCollection(($CollectionName + '_log')) $info = 1 | Select-Object Path, Created, Changed, Removed, Elapsed $info.Created = $info.Changed = $info.Removed = 0 $Update = New-MdbcUpdate -Set @{Updated = $Now} } # Gets input items from the path. function Input { $ea = if ($PSVersionTable.PSVersion.Major -ge 3) {'Ignore'} else { 0 } Get-ChildItem -LiteralPath $Path -Force -Recurse -ErrorAction $ea } # Updates documents from input items. function Update {process{ $file = !$_.PSIsContainer # main data $data = New-MdbcData $data._id = $_.FullName $data.Attributes = [int]$_.Attributes if ($file) { $data.Length = $_.Length $data.LastWriteTime = $_.LastWriteTime } # query by main data and update Updated $r = Update-MdbcData $Update $data -Result # updated means not changed, done if ($r.DocumentsAffected) {return} # more data if (!$file) { $data.LastWriteTime = $_.LastWriteTime } $data.CreationTime = $_.CreationTime $data.Name = $_.Name if ($file) { $data.Extension = $_.Extension } $data.Updated = $Now # add or update data $r = Add-MdbcData $data -Update -Result $op = [int]$r.UpdatedExisting if ($op) { ++$info.Changed } else { ++$info.Created } if (!$Log) {return} # log created or changed $data.Remove('_id') $data.Remove('Name') $data.Remove('Extension') $data.Op = $op Update-MdbcData -Collection $CollectionLog -Add -Query $_.FullName -Update ( New-MdbcUpdate -Set @{Updated = $Now; Op = $op} -Push @{Log = $data} ) }} ### Update existing . Connect $info.Path = $Path $time = [Diagnostics.Stopwatch]::StartNew() if ($Split) { Import-Module SplitPipeline Input | Split-Pipeline -Verbose -Count 2, 4 -Load 500, 5000 -Function Connect, Update -Variable CollectionName, Log, Now ` -Begin { . Connect } -Script { $input | Update } -End { $info } | .{process{ $info.Created += $_.Created $info.Changed += $_.Changed }} } else { Input | Update } ### Remove missing $in = foreach($_ in $Path) { if (!$_.EndsWith('\')) {$_ += '\'} [regex]('^' + [regex]::Escape($_)) } $queryUnknown = New-MdbcQuery -Not (New-MdbcQuery Updated -Type 9) $queryMissing = New-MdbcQuery -And (New-MdbcQuery _id -In $in), (New-MdbcQuery Updated -LT $Now) foreach($data in Get-MdbcData (New-MdbcQuery -Or $queryUnknown, $queryMissing)) { ++$info.Removed # remove data $id = $data._id Remove-MdbcData $id # log removed if ($Log) { $data.Remove('_id') $data.Remove('Name') $data.Remove('Extension') $data.Op = 2 Update-MdbcData -Collection $CollectionLog -Add -Query $id -Update ( New-MdbcUpdate -Set @{Updated = $Now; Op = 2} -Push @{Log = $data} ) } } # output info $info.Elapsed = $time.Elapsed $info
PowerShellCorpus/PowerShellGallery/Mdbc/4.8.9/Scripts/Mdbc.ps1
Mdbc.ps1
<# .Synopsis Mdbc module helpers. .Description NOTE: This script is a profile for interactive use, it reflects personal preferences, features may not be suitable for all scenarios and they may change. Consider this as the base for your own interactive profile. The script imports the module, sets aliases, functions, and variables for interactive use and optionally connects to a specified server and database. Aliases: amd - Add-MdbcData emd - Export-MdbcData gmd - Get-MdbcData gmh - Get-MdbcHelp imc - Invoke-MdbcCommand imd - Import-MdbcData nmd - New-MdbcData nmq - New-MdbcQuery nmu - New-MdbcUpdate omf - Open-MdbcFile rmd - Remove-MdbcData smf - Save-MdbcFile umd - Update-MdbcData Functions: Get-MdbcHelp Variables: $Server - connected server $Database - default database $Collection - default collection $m<name> - collection <name> (for each collection) $<operator> - read only operator shortcuts for JSON-like expressions With a large number of collections their names are not displayed. Command Get-Variable m*..* is useful for finding a collection by its name pattern. .Parameter ConnectionString Connection string, see Connect-Mdbc. The default is empty, the script does not connect. .Parameter DatabaseName Database name or wildcard pattern. If it is not resolved to an existing database name then the script prints all database names and exits. The default name is 'test'. .Parameter CollectionName Name of the default collection which instance is referenced by $Collection. The default is 'test', not necessarily existing. #> param ( [Parameter()] $ConnectionString, $DatabaseName = 'test', $CollectionName = 'test' ) Import-Module Mdbc <# .Synopsis Gets help information for MongoDB command(s). .Description Command format: {Name} {L}{S}{A} {Help}. L - lockType R:read-lock W:write-lock S - slaveOk S:slave-ok A - adminOnly A:admin-only .Parameter Name Command name or wildcard pattern. The default is '*' (all commands). .Parameter Database Target database. The default is $Database. .Parameter All Tells to get all commands including internal. .Link Invoke-MdbcCommand #> function global:Get-MdbcHelp([Parameter()]$Name='*', $Database=$Database, [switch]$All) { $commands = (Invoke-MdbcCommand listCommands -Database $Database).commands foreach($cmd in $commands.Keys | .{process{if ($_ -like $Name) {$_}}}) { $c = $commands[$cmd] $help = $c.help.Trim() if (!$All -and ($cmd[0] -eq '_' -or $help -match '^Internal')) {continue} $lock = switch($c.lockType) {-1 {'R'} 1 {'W'} 0 {'-'}} $slave = if ($c.slaveOk) {'S'} else {'-'} $admin = if($c.adminOnly) {'A'} else {'-'} @" $('-'*($cmd.Length)) $cmd $lock$slave$admin $help "@ } } ### Aliases Set-Alias -Scope global -Name amd -Value Add-MdbcData Set-Alias -Scope global -Name emd -Value Export-MdbcData Set-Alias -Scope global -Name gmd -Value Get-MdbcData Set-Alias -Scope global -Name gmh -Value Get-MdbcHelp Set-Alias -Scope global -Name imc -Value Invoke-MdbcCommand Set-Alias -Scope global -Name imd -Value Import-MdbcData Set-Alias -Scope global -Name nmd -Value New-MdbcData Set-Alias -Scope global -Name nmq -Value New-MdbcQuery Set-Alias -Scope global -Name nmu -Value New-MdbcUpdate Set-Alias -Scope global -Name omf -Value Open-MdbcFile Set-Alias -Scope global -Name rmd -Value Remove-MdbcData Set-Alias -Scope global -Name smf -Value Save-MdbcFile Set-Alias -Scope global -Name umd -Value Update-MdbcData ### Operators @( 'addToSet' 'all' 'and' 'bit' 'each' 'elemMatch' 'exists' 'gt' 'gte' 'in' 'inc' 'lt' 'lte' 'mod' 'ne' 'nin' 'nor' 'not' 'options' 'or' 'pop' 'pull' 'pullAll' 'push' 'pushAll' 'regex' 'rename' 'set' 'setOnInsert' 'size' 'slice' 'sort' 'type' 'unset' 'where' ) | .{process{ New-Variable -Name $_ -Value "`$$_" -Scope global -Option ReadOnly -Force }} # Not connected if (!$ConnectionString) {return} # Server variable Connect-Mdbc $ConnectionString $global:Server = $Server Write-Host "Server `$Server $($Server.Settings.Server)" # Database variable $name = @($Server.GetDatabaseNames() -like $DatabaseName) if ($name.Count -ne 1) { Write-Host "Server databases: $($Server.GetDatabaseNames())" return } Write-Host "Database `$Database $name" $global:Database = $Server.GetDatabase($name) # Collection variables $global:Collection = $Database.GetCollection($CollectionName) $collections = @($Database.GetCollectionNames()) Write-Host "$($collections.Count) collections" $global:MaximumVariableCount = 32kb foreach($name in $collections) { if (!$name.StartsWith('system.')) { if ($collections.Count -lt 50) { Write-Host "Collection `$m$name" } New-Variable -Scope global -Name "m$name" -Value $Database.GetCollection($name) -ErrorAction Continue -Force } }
PowerShellCorpus/PowerShellGallery/Mdbc/4.8.9/Scripts/Mdbc.ArgumentCompleters.ps1
Mdbc.ArgumentCompleters.ps1
<# .Synopsis Argument completers for Mdbc commands. .Description The script registers Mdbc completers for command parameters: Connect-Mdbc -DatabaseName .. -CollectionName .. Add-MdbcData New-MdbcData Export-MdbcData -Property .., .. Completers can be used with: * PowerShell v5 native Register-ArgumentCompleter Simply invoke Mdbc.ArgumentCompleters.ps1, e.g. in a profile. * TabExpansionPlusPlus https://github.com/lzybkr/TabExpansionPlusPlus Put Mdbc.ArgumentCompleters.ps1 to TabExpansionPlusPlus module directory in order to be loaded automatically. Or invoke it after importing the module, e.g. in a profile. * TabExpansion2.ps1 https://www.powershellgallery.com/packages/TabExpansion2 Put Mdbc.ArgumentCompleters.ps1 to the path in order to be loaded on the first completion. Or invoke after TabExpansion2.ps1, e.g. in a profile. #> Register-ArgumentCompleter -CommandName Connect-Mdbc -ParameterName DatabaseName -ScriptBlock { param($commandName, $parameterName, $wordToComplete, $commandAst, $boundParameters) if (!($ConnectionString = $boundParameters['ConnectionString'])) { $ConnectionString = '.' } @(Connect-Mdbc $ConnectionString *) -like "$wordToComplete*" | .{process{ New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', $_ }} } Register-ArgumentCompleter -CommandName Connect-Mdbc -ParameterName CollectionName -ScriptBlock { param($commandName, $parameterName, $wordToComplete, $commandAst, $boundParameters) if (!($ConnectionString = $boundParameters['ConnectionString'])) { $ConnectionString = '.' } if (!($DatabaseName = $boundParameters['DatabaseName'])) { $DatabaseName = 'test' } @(Connect-Mdbc $ConnectionString $DatabaseName * | ForEach-Object Name) -like "$wordToComplete*" | .{process{ New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', $_ }} } Register-ArgumentCompleter -CommandName Add-MdbcData, New-MdbcData, Export-MdbcData -ParameterName Property -ScriptBlock { $private:commandName, $private:parameterName, $private:wordToComplete, $private:commandAst, $private:boundParameters = $args $private:data = $boundParameters['InputObject'] if (!$data) { $private:ast = $commandAst.Parent if ($ast -isnot [System.Management.Automation.Language.PipelineAst] -or $ast.PipelineElements.Count -ne 2) { return } try { $data = & ([scriptblock]::Create($ast.PipelineElements[0])) } catch { return } } $keys = [System.Collections.Generic.HashSet[object]]@() $pattern = "$wordToComplete*" foreach($_ in $data) { if ($_ -is [System.Collections.IDictionary]) { foreach($_ in $_.Keys -like $pattern) { $null = $keys.Add($_) } } elseif ($_) { foreach($_ in $_.PSObject.Properties.Match($pattern)) { $null = $keys.Add($_.Name) } } } $keys | Sort-Object -CaseSensitive | .{process{ New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', $_ }} }
PowerShellCorpus/PowerShellGallery/Mdbc/4.8.9/Scripts/Get-MongoFile.ps1
Get-MongoFile.ps1
<# .Synopsis Gets file paths from the file system snapshot database. .Description Requires: Mdbc module Server: local Database: test Collection: files (default) The script searches for file paths by a regular expression pattern or a name. It works with data created by Update-MongoFiles.ps1. .Parameter Pattern Regular expression pattern or literal file name. .Parameter CollectionName Specifies the collection name. Default: files. .Parameter Name Tells that the Pattern is a literal name. .Example > Get-MongoFile readme Get files which names contain "readme". .Example > Get-MongoFile readme.txt -Name Get files named "readme.txt" .Link Update-MongoFiles.ps1 #> param ( [Parameter(Position=0, Mandatory=$true)][string]$Pattern, $CollectionName = 'files', [switch]$Name ) Import-Module Mdbc Connect-Mdbc . test $CollectionName if ($Name) { $query = New-MdbcQuery Name -IEQ $Pattern } else { $query = New-MdbcQuery Name -Matches $Pattern, i } foreach($_ in Get-MdbcData $query -Property @()) { $_._id }
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/build.ps1
build.ps1
param ( [string]$path = ".\", [string]$type = "Debug" ) #Registry Key path for .net framework 4.x.x [string]$keyPath = "HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full" #Release number for .net framework 4.6.x on windows 10 systems. [string]$requiredVersion = "393295" #Release numbers for .net framework 4.6.x on all other OS are greater than the number above. [string]$clean = "/t:Clean" [string]$build = "/t:Build" [string]$options = "/v:m" [string]$config = "/p:Configuration=" + $type [string]$output = "/p:OutputPath=$(Join-Path $PSScriptRoot \bin)" #Change pwd to $PSScriptRoot #checks for solution file in path Function Check-Path() { $fullPath = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot $path)) Write-Verbose "Solution Path - $fullPath" $solution = Get-ChildItem $path *.sln -Recurse If(-not $solution) { Write-Error "Solution File Not Found" } Else { $solution = $solution.FullName Write-Verbose "Solution File Found - $solution" } return $solution } #Tests the registry key for matching or newer version of .Net Framework for building solution #Idea for following function from #http://blog.smoothfriction.nl/archive/2011/01/18/powershell-detecting-installed-net-versions.aspx Function Test-Key ([string]$key) { if(!(Test-Path $keyPath)) { return $false } [int]$versionNumber = [int](Get-ItemProperty $keyPath).$key Write-Verbose "Version Release Number - $versionNumber" if ($versionNumber -ge [int]$requiredVersion) { return $true } Write-Verbose "Required Version - $requiredVersion" return $false } Function Check-Version() { If(Test-Key("Release")) { return $true } return $false } Function Build-Solution([string]$solutionName) { If($hasVersion -eq $false) { Write-Error "Unable to build - Incorrection version" return } If(-not $solutionName) { Write-Error "Unable to build - No Solution Found" return } Write-Host "Building solution - $solutionName" & $msbuild $solutionName $options $clean $config $output & $msbuild $solutionName $options $build $config $output } $msbuild = "${env:ProgramFiles(x86)}\MSBuild\14.0\Bin\MSBuild.exe" $solutionName = Check-Path $hasVersion = Check-Version Build-Solution($solutionName)
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew.Tests/PSDropbin.Tests.ps1
PSDropbin.Tests.ps1
if(!(Test-Path variable:PsDropbinTesting)) { try { $sessionName = "$PSCommandPath Session" $testSession = New-PSSession -Name $sessionName -SessionOption (New-PSSessionOption -NoMachineProfile) -EnableNetworkAccess Context "Invoking a new session" { Invoke-Command -Session $testSession -ArgumentList $PSCommandPath -ScriptBlock { param($PSCommandPath) New-Variable PSDropbinTesting -Scope Global -Value $True -Visibility Public Import-Module Pester Invoke-Pester $PSCommandPath; }; } } finally { if(Test-Path variable:testSession) { remove-PSSession $testSession; } } return; } else { $sut = $PSCommandPath.Replace(".Tests", "").Replace(".ps1", ".psd1"); #Write-Output "`$PSCommandPath = '$PSCommandPath'" #Write-Output "`$sut = '$sut'" Try { $dropbinModule = Import-Module $sut -Verbose -PassThru $originalLocation = Get-Location Describe "PSDropbin" { It "Does the PSDropbin module load successfully" { $dropboxProvider = (Get-PSProvider Dropbox) Write-Debug $dropboxProvider if($dropboxProvider -eq $null) { throw "Not yet loaded" }; Get-PSDrive Drpbx | Should Be "Drpbx" } It "Try Test-Path and Set-Location on the default drive's Public folder" { #$dropbox = New-PSDrive -PSProvider Dropbox -Name Drpbx -Root "/" -ErrorAction Stop Test-Path "Drpbx:\Public" | Should Be $true Set-Location "Drpbx:\Public" $pwd | should be "Drpbx:\Public" } It "Try Test-Path and Set-Location on the default drives root folder" { Test-Path "Drpbx:\" | Should Be $true Set-Location "Drpbx:\" $pwd | should be "Drpbx:\" } It "Verify Set-Location works on the root of a Dropbin drive." { Try { $dropbox = New-PSDrive -PSProvider Dropbox -Name DrpbxTemp -Root "/" $currentPath = $pwd; Set-Location DrpbxTemp:\ | should not throw $pwd | should be "DrpbxTemp:\" } Finally { if($dropbox) { Set-Location $currentPath; Remove-PSDrive $dropbox; } } } It "Verify test-path returns false for non-existen path." { $doesExist = Test-Path "drpbx:\ThisPathDoesNotExist" $doesExist | Should Be $false } It "Verify test-path returns true for existing path." { $doesExist = Test-Path "drpbx:\Public" $doesExist | Should Be $true } } } Finally { If($dropbinModule) { Set-Location $originalLocation Remove-Module $dropbinModule } } }
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew.Tests/CopyFileItem.Tests.ps1
CopyFileItem.Tests.ps1
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew/Move-Item.ps1
Move-Item.ps1
None
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew/SetupProvider.ps1
SetupProvider.ps1
Import-Module "$psscriptroot\PSDropbin.psd1" Set-DropboxCredential Remove-Module PSDropbin Import-Module "$psscriptroot\PSDropbin.psd1"
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew/Copy-Item.ps1
Copy-Item.ps1
None
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew/pushRelease.ps1
pushRelease.ps1
param( [string]$version = "v1.0", #[string]$prerelease = "false", #[string]$draft= "false", [string]$info = "" ) #Paths & FileNames [string]$choco = "Chocolatey\" [string]$tools = "tools\" [string]$installFile = "ChocolateyInstall.ps1" [string]$uninstallFile = "ChocolateyUninstall.ps1" [string]$nuspecFile = "project.nuspec" #Git Command Strings [string]$addCommand = "git add bin\Release -f" [string]$tagCommand = "git tag" [string]$pushCommand = "git push origin master --follow-tags" #Chocolatey related Strings & Command Strings [string]$packageName = "`$packageName = 'PSDropBin'" [string]$url = "`$url = 'https://github.com/IntelliTect/PSDropbin/PSDropNew/archives/" [string]$unzipLocation = "`$unzipLocation = '`${env:ProgramFiles}\PSDropBin'" [string]$installCommand = "Install-ChocolateyZipPackage `$packageName `$url `$unzipLocation" [string]$postInstallMessage = "Write-Host 'Run setup.ps1 located at `$unzipLocation to finish setup.' -foregroundcolor White -backgroundcolor Red" [string]$uninstallCommand = "Uninstall-ChocolateyZipPackage `$packageName '" Function Build-Chocolatey() { If (-not (Test-Path ($choco + $tools))) { md ($choco + $tools) | Out-Null } Build-Install Build-Uninstall #Build-NuSpec } Function Build-Install() { $fullPath = $choco + $tools + $installFile $packageName > $fullPath $urlFull = $url + $version + ".zip'" $urlFull >> $fullPath $unzipLocation >> $fullPath $installCommand >> $fullPath $postInstallMessage >> $fullPath } Function Build-Uninstall() { $fullPath = $choco + $tools + $uninstallFile $packageName > $fullPath $uninstallCommandFull = $uninstallCommand + $version + ".zip'" $uninstallCommandFull >> $fullPath } Function Build-NuSpec() { } #Build-Chocolatey Invoke-Expression $addCommand If(-not $info) { $tagLightWeight = $version + "-lw" $tagCommandFull = $tagCommand + " " + $tagLightWeight } Else { $tag = " -a " + $version $tagAnnotation = " -m " + $info $tagCommandFull = $tagCommand + $tag + $tagAnnotation } Invoke-Expression $tagCommandFull Invoke-Expression $pushCommand <# Build Full Release [string]$uri = "https://api.github.com/repos/IntelliTect/PSDropbin/releases?access_token=:" [string]$personalAccessCode = "f2b803e867daf53349fed934452ff1920f8262c0" $body = @{ tag_name = $version target_commitish = "master" name = $version body = "Description" draft = $draft prerelease = $prerelease } Invoke-RestMethod -Method Post -Uri ($uri + $personalAccessCode) -Body $body #>
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew/New-DropboxDrive.ps1
New-DropboxDrive.ps1
None
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/PSDropNew/packages/Newtonsoft.Json.6.0.6/tools/install.ps1
install.ps1
param($installPath, $toolsPath, $package, $project) # open json.net splash page on package install # don't open if json.net is installed as a dependency try { $url = "http://james.newtonking.com/json" $dte2 = Get-Interface $dte ([EnvDTE80.DTE2]) if ($dte2.ActiveWindow.Caption -eq "Package Manager Console") { # user is installing from VS NuGet console # get reference to the window, the console host and the input history # show webpage if "install-package newtonsoft.json" was last input $consoleWindow = $(Get-VSComponentModel).GetService([NuGetConsole.IPowerConsoleWindow]) $props = $consoleWindow.GetType().GetProperties([System.Reflection.BindingFlags]::Instance -bor ` [System.Reflection.BindingFlags]::NonPublic) $prop = $props | ? { $_.Name -eq "ActiveHostInfo" } | select -first 1 if ($prop -eq $null) { return } $hostInfo = $prop.GetValue($consoleWindow) if ($hostInfo -eq $null) { return } $history = $hostInfo.WpfConsole.InputHistory.History $lastCommand = $history | select -last 1 if ($lastCommand) { $lastCommand = $lastCommand.Trim().ToLower() if ($lastCommand.StartsWith("install-package") -and $lastCommand.Contains("newtonsoft.json")) { $dte2.ItemOperations.Navigate($url) | Out-Null } } } else { # user is installing from VS NuGet dialog # get reference to the window, then smart output console provider # show webpage if messages in buffered console contains "installing...newtonsoft.json" in last operation $instanceField = [NuGet.Dialog.PackageManagerWindow].GetField("CurrentInstance", [System.Reflection.BindingFlags]::Static -bor ` [System.Reflection.BindingFlags]::NonPublic) $consoleField = [NuGet.Dialog.PackageManagerWindow].GetField("_smartOutputConsoleProvider", [System.Reflection.BindingFlags]::Instance -bor ` [System.Reflection.BindingFlags]::NonPublic) if ($instanceField -eq $null -or $consoleField -eq $null) { return } $instance = $instanceField.GetValue($null) if ($instance -eq $null) { return } $consoleProvider = $consoleField.GetValue($instance) if ($consoleProvider -eq $null) { return } $console = $consoleProvider.CreateOutputConsole($false) $messagesField = $console.GetType().GetField("_messages", [System.Reflection.BindingFlags]::Instance -bor ` [System.Reflection.BindingFlags]::NonPublic) if ($messagesField -eq $null) { return } $messages = $messagesField.GetValue($console) if ($messages -eq $null) { return } $operations = $messages -split "==============================" $lastOperation = $operations | select -last 1 if ($lastOperation) { $lastOperation = $lastOperation.ToLower() $lines = $lastOperation -split "`r`n" $installMatch = $lines | ? { $_.StartsWith("------- installing...newtonsoft.json ") } | select -first 1 if ($installMatch) { $dte2.ItemOperations.Navigate($url) | Out-Null } } } } catch { # stop potential errors from bubbling up # worst case the splash page won't open } # yolo
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/bin/Move-Item.ps1
Move-Item.ps1
None
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/bin/PSDropbin.Tests.ps1
PSDropbin.Tests.ps1
if(!(Test-Path variable:PsDropbinTesting)) { try { $sessionName = "$PSCommandPath Session" $testSession = New-PSSession -Name $sessionName -SessionOption (New-PSSessionOption -NoMachineProfile) -EnableNetworkAccess Context "Invoking a new session" { Invoke-Command -Session $testSession -ArgumentList $PSCommandPath -ScriptBlock { param($PSCommandPath) New-Variable PSDropbinTesting -Scope Global -Value $True -Visibility Public Import-Module Pester Invoke-Pester $PSCommandPath; }; } } finally { if(Test-Path variable:testSession) { remove-PSSession $testSession; } } return; } else { $sut = $PSCommandPath.Replace(".Tests", "").Replace(".ps1", ".psd1"); #Write-Output "`$PSCommandPath = '$PSCommandPath'" #Write-Output "`$sut = '$sut'" Try { $dropbinModule = Import-Module $sut -Verbose -PassThru $originalLocation = Get-Location Describe "PSDropbin" { It "Does the PSDropbin module load successfully" { $dropboxProvider = (Get-PSProvider Dropbox) Write-Debug $dropboxProvider if($dropboxProvider -eq $null) { throw "Not yet loaded" }; Get-PSDrive Drpbx | Should Be "Drpbx" } It "Try Test-Path and Set-Location on the default drive's Public folder" { #$dropbox = New-PSDrive -PSProvider Dropbox -Name Drpbx -Root "/" -ErrorAction Stop Test-Path "Drpbx:\Public" | Should Be $true Set-Location "Drpbx:\Public" $pwd | should be "Drpbx:\Public" } It "Try Test-Path and Set-Location on the default drives root folder" { Test-Path "Drpbx:\" | Should Be $true Set-Location "Drpbx:\" $pwd | should be "Drpbx:\" } It "Verify Set-Location works on the root of a Dropbin drive." { Try { $dropbox = New-PSDrive -PSProvider Dropbox -Name DrpbxTemp -Root "/" $currentPath = $pwd; Set-Location DrpbxTemp:\ | should not throw $pwd | should be "DrpbxTemp:\" } Finally { if($dropbox) { Set-Location $currentPath; Remove-PSDrive $dropbox; } } } It "Verify test-path returns false for non-existen path." { $doesExist = Test-Path "drpbx:\ThisPathDoesNotExist" $doesExist | Should Be $false } It "Verify test-path returns true for existing path." { $doesExist = Test-Path "drpbx:\Public" $doesExist | Should Be $true } } } Finally { If($dropbinModule) { Set-Location $originalLocation Remove-Module $dropbinModule } } }
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/bin/CopyFileItem.Tests.ps1
CopyFileItem.Tests.ps1
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/bin/SetupProvider.ps1
SetupProvider.ps1
Import-Module "$psscriptroot\PSDropbin.psd1" Set-DropboxCredential Remove-Module PSDropbin Import-Module "$psscriptroot\PSDropbin.psd1"
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/bin/Copy-Item.ps1
Copy-Item.ps1
None
PowerShellCorpus/PowerShellGallery/IntelliTect.PSDropbin/0.7.1.0/bin/New-DropboxDrive.ps1
New-DropboxDrive.ps1
None
PowerShellCorpus/PowerShellGallery/EnvironmentCheckToolkit/2.0/PackageInvoke-Sample.ps1
PackageInvoke-Sample.ps1
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force Write-Output "Nuget Installation done" if(Test-Path "$PSScriptRoot\EnvironmentCheckToolkit\") { Remove-Item "$PSScriptRoot\EnvironmentCheckToolkit\*" -Recurse -Force } Save-Module -Name EnvironmentCheckToolkit -Path $PSScriptRoot foreach ($i in Get-ChildItem -Recurse "$PSScriptRoot\EnvironmentCheckToolkit\") { if ($i.Name -eq "CheckEnvironment.ps1") { & ($i.DirectoryName+"\"+$i.Name) "<Json FilePath>" break; } }
PowerShellCorpus/PowerShellGallery/EnvironmentCheckToolkit/2.0/CheckEnvironment.ps1
CheckEnvironment.ps1
param( [Parameter(Mandatory = $false)] [String] $FilePath, [Parameter(Mandatory = $false)] $ParamTable ) function DbObjectValidation{ param ( [Parameter(Mandatory = $true)] $DbConnection, [Parameter(Mandatory = $true)] [String] $TypeDescription, [Parameter(Mandatory = $true)] [String] $ObjectName ) try { $sqlQuery = "SELECT * FROM Sys.Objects WHERE name = '"+$ObjectName+"'and type_desc ='"+$TypeDescription+"'" $command = New-object system.data.sqlclient.SqlCommand $command.connection = $DbConnection $command.CommandText = $sqlQuery $scalar = $command.ExecuteScalar() if($scalar) { Write-Host "DbOject: $ObjectName Exists" -foregroundcolor Black -backgroundcolor Green $command.Dispose() return 0 } else { Write-Host "DbOject: $ObjectName does not exist" -foregroundcolor White -backgroundcolor Red return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in DBObject Validation" -foregroundcolor White -backgroundcolor Red return 1 } } function DbDataValidation{ param ( [Parameter(Mandatory = $true)] $DbConnection, [Parameter(Mandatory = $true)] [String] $Script, [Parameter(Mandatory = $true)] [String] $ExpectedOutput ) try { $command = New-object system.data.sqlclient.SqlCommand $command.connection = $DbConnection $command.CommandText = $Script $scalar = $command.ExecuteScalar() if($scalar -eq $ExpectedOutput) { Write-Host "Script: '"$Script "' returned the expected output." -foregroundcolor Black -backgroundcolor Green $command.Dispose() return 0 } else { Write-Host "Script: '"$Script "' did not return the expected output. Expected Value - $ExpectedOutput, Actual Value - $scalar" -foregroundcolor White -backgroundcolor Red return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in DBData Validation" -foregroundcolor White -backgroundcolor Red return 1 } } function LogicAppCheck{ param ( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $LogicAppName ) try { $logicapp=Get-AzureRmLogicApp -ResourceGroupName $ResourceGroupName -Name $LogicAppName -ErrorVariable logicapperr if($logicapperr.Count.Equals(0) -and ($logicapp.State -eq ("Enabled"))) { Write-Host "LogicApp: $LogicAppName Exists and is enabled" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "LogicApp: $LogicAppName does not exist or is disabled" -foregroundcolor White -backgroundcolor Red return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Logic App check" -foregroundcolor White -backgroundcolor Red return 1 } } function TopicCheck{ param ( [Parameter(Mandatory = $true)] [String] $ServiceBusNamespace, [Parameter(Mandatory = $true)] [String] $TopicName, [Parameter(Mandatory = $false)] [String] $TopicSize ) try { $currentNamespace=Get-AzureSBNamespace -Name $ServiceBusNamespace $namespaceManager = [Microsoft.ServiceBus.NamespaceManager]::CreateFromConnectionString($currentNamespace.ConnectionString); if($TopicSize) { $topicDetails = $namespaceManager.GetTopic($TopicName) if(($namespaceManager.TopicExists($TopicName)) -and ($topicDetails.MaxSizeInMegabytes -eq $TopicSize)) { Write-Host "Topic: $TopicName Exists and is of the specified size" -foregroundcolor Black -backgroundcolor Green return 0 } elseif ($namespaceManager.TopicExists($TopicName)) { Write-Host "Topic: $TopicName exist but is not of the specified size" -foregroundcolor White -backgroundcolor Red return 1 } else { Write-Host "Topic: $TopicName does not exist " -foregroundcolor White -backgroundcolor Red return 1 } } else { if($namespaceManager.TopicExists($TopicName)) { Write-Host "Topic: $TopicName Exists" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Topic: $TopicName does not exist" -foregroundcolor White -backgroundcolor Red return 1 } } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in topic check" -foregroundcolor White -backgroundcolor Red return 1 } } function SubscriptionCheck{ param ( [Parameter(Mandatory = $true)] [String] $ServiceBusNamespace, [Parameter(Mandatory = $true)] [String] $TopicName, [Parameter(Mandatory = $true)] [String] $SubscriptionName ) try { $currentNamespace=Get-AzureSBNamespace -Name $ServiceBusNamespace $namespaceManager = [Microsoft.ServiceBus.NamespaceManager]::CreateFromConnectionString($currentNamespace.ConnectionString) if($namespaceManager.SubscriptionExists($TopicName,$SubscriptionName)) { Write-Host "Subscription: $SubscriptionName Exists in Topic: $TopicName" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Subscription: $SubscriptionName does not exists in Topic: $TopicName" -foregroundcolor White -backgroundcolor Red return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in subscription check" -foregroundcolor White -backgroundcolor Red return 1 } } function WebJobCheck{ param ( [Parameter(Mandatory = $true)] [String] $WebJob, [Parameter(Mandatory = $true)] [String] $WebAppName, [Parameter(Mandatory = $true)] [String] $WebJobType ) #WebJobs Check try { $webJobStatus = Get-AzureWebsiteJob -Name $WebAppname -JobName $Webjob -JobType $WebJobType -ErrorVariable webJobErr if($WebJobType -eq "Continuous") { if($webJobErr.Count.Equals(0) -and ($webJobStatus.Status -eq ("Running"))) { Write-Host "Web Job: $Webjob is successfully created" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Web Job: $Webjob is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } elseif($WebJobType -eq "Triggered") { if($webJobErr.Count.Equals(0) -and ($webJobStatus.JobType -eq ("Triggered"))) { Write-Host "Web Job: $Webjob is successfully created" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Web Job: $Webjob is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in WebJob check" -foregroundcolor White -backgroundcolor Red return 1 } } function ResourceGroupCheck{ param ( [Parameter(Mandatory = $true)] [String] $ResourceGroup, [Parameter(Mandatory = $false)] [String] $Location ) try { $resourceGrp = Get-AzureRmResourceGroup -Name $ResourceGroup -ErrorVariable resourceGrpErr if($Location) { if($resourceGrpErr.Count.Equals(0) -and ($resourceGrp.ProvisioningState -eq ("Succeeded")) -and ($resourceGrp.Location.ToLower() -eq $Location.ToLower())) { Write-Host "Resource group: $ResourceGroup is properly created in the specified location" -foregroundcolor Black -backgroundcolor Green return 0 } elseif ($resourceGrpErr.Count.Equals(0) -and ($resourceGrp.ProvisioningState -eq ("Succeeded"))) { Write-Host "Resource group: $ResourceGroup is properly created but not in the specified location" -foregroundcolor White -backgroundcolor Red return 1 } else { Write-Host "Resource group: $ResourceGroup is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } else { if($resourceGrpErr.Count.Equals(0) -and ($resourceGrp.ProvisioningState -eq ("Succeeded"))) { Write-Host "Resource group: $ResourceGroup is successfully created" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Resource group: $ResourceGroup is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Resource Group check" -foregroundcolor White -backgroundcolor Red return 1 } } function WebAppCheck{ param ( [Parameter(Mandatory = $true)] [String] $WebAppName, [Parameter(Mandatory = $true)] [String] $ResourceGroup, [Parameter(Mandatory = $false)] $ConnectionString, [Parameter(Mandatory = $false)] $WebAppSettings, [Parameter(Mandatory = $false)] $WebAppCertificates, [Parameter(Mandatory = $false)] [string] $AlwaysOn, [Parameter(Mandatory = $true)] [String] $ScriptRoot, [Parameter(Mandatory = $false)] [String] $EncryptionKey, [Parameter(Mandatory = $false)] [String] $ClientID, [Parameter(Mandatory = $false)] [String] $ClientSecret ) try { $webAppChkErr = 0 $webAppChk = Get-AzureRmWebApp -ResourceGroupName $resourcegroup -Name $webappname -ErrorVariable webAppErr if($webAppErr.Count.Equals(0) -and ($webAppChk.State -eq ("Running"))) { if($AlwaysOn) { if($webAppChk.SiteConfig.AlwaysOn.ToString().ToLower() -eq $AlwaysOn.ToLower()) { Write-Host "Web App: $WebAppname - Always On setting check passed" -foregroundcolor Black -backgroundcolor Green } else { Write-Host "Web App: $WebAppname - Always On setting check failed. Expected Value:$AlwaysOn, Actual Value:"$webAppChk.SiteConfig.AlwaysOn -foregroundcolor White -backgroundcolor Red $webAppChkErr = 1 } } if($ConnectionString) { foreach($connection in $ConnectionString) { $key = $value = "" $key = GetValue -ScriptRoot $ScriptRoot -OriginalValue $connection.key -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret $value = GetValue -ScriptRoot $ScriptRoot -OriginalValue $connection.Value -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret foreach($connectionconfig in $webAppChk.SiteConfig.ConnectionStrings) { if($connectionconfig.Name -eq $key) { if($connectionconfig.ConnectionString -eq $value) { Write-Host "Web App: $WebAppname - Connection String check passed for Connection-" $connection.key -foregroundcolor Black -backgroundcolor Green break; } else { Write-Host "Web App: $WebAppname - Connection String check failed for Connection-" $connection.key". Expected Value:"$connection.Value ", Actual Value:"$connectionconfig.ConnectionString -foregroundcolor White -backgroundcolor Red $webAppChkErr = 1 } } } } } if($WebAppSettings) { foreach($appsetting in $WebAppSettings) { $key = $value = "" $key = GetValue -ScriptRoot $ScriptRoot -OriginalValue $appsetting.key -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret $value = GetValue -ScriptRoot $ScriptRoot -OriginalValue $appsetting.Value -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret foreach($appconfig in $webAppChk.SiteConfig.AppSettings) { if($appconfig.Name -eq $key) { if($appconfig.Value -eq $value) { Write-Host "Web App: $WebAppname - App Setting check passed for Setting-" $appsetting.key -foregroundcolor Black -backgroundcolor Green break; } else { Write-Host "Web App: $WebAppname - App Setting check failed for Setting-" $appsetting.key". Expected Value:" $appsetting.Value", Actual Value:"$appconfig.Value -foregroundcolor White -backgroundcolor Red $webAppChkErr = 1 } } } } } if($WebAppCertificates) { foreach($certificate in $WebAppCertificates) { $name = $thumbprint = "" $name = GetValue -ScriptRoot $ScriptRoot -OriginalValue $certificate.Subject -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret $thumbprint = GetValue -ScriptRoot $ScriptRoot -OriginalValue $certificate.Thumbprint -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret $certDetails= Get-AzureRmWebAppCertificate -ResourceGroupName $resourcegroup -Thumbprint $thumbprint -ErrorVariable certErr if($certDetails -and $certErr.Count.Equals(0)) { if($certDetails.SubjectName -eq $name) { Write-Host "Web App: $WebAppname - $name Certificate is installed " -foregroundcolor Black -backgroundcolor Green break; } else { Write-Host "Web App: $WebAppname - $thumbprint Certificate is installed but has a different name" -foregroundcolor White -backgroundcolor Red $webAppChkErr = 1 } } else { Write-Host "Web App: $WebAppname - $name Certificate is not installed" -foregroundcolor White -backgroundcolor Red $webAppChkErr = 1 } } } } else { $webAppChkErr = 1 } if($webAppChkErr -eq 0) { Write-Host "Web App: $WebAppname is successfully deployed" -foregroundcolor Black -backgroundcolor Green return $webAppChkErr } else { Write-Host "Web App: $WebAppname is not deployed properly" -foregroundcolor White -backgroundcolor Red return $webAppChkErr } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in WebApp check" -foregroundcolor White -backgroundcolor Red return 1 } } function RedisCacheCheck{ param ( [Parameter(Mandatory = $true)] [String] $RedisCacheInstance , [Parameter(Mandatory = $true)] [String] $Key, [Parameter(Mandatory = $true)] [String] $Value, [Parameter(Mandatory = $false)] [String] $EncryptionKey, [Parameter(Mandatory = $false)] [String] $ClientID, [Parameter(Mandatory = $false)] [String] $ClientSecret ) try { Import-Module "$PSScriptRoot\RedisPopulate.dll" $cacheValue=RetrieveRedis -Rediscacheinstance $RedisCacheInstance -Keystring $Key -PortNumber "6380" if(!$cacheValue) { Write-Host "Value for Cache variable $Key could not be retrieved" -foregroundcolor White -backgroundcolor Red return 1 } if($cacheValue.GetType().Name -eq "String" -and $cacheValue.StartsWith("[KeyVault")) { $cacheValue = GetValue -ScriptRoot $PSScriptRoot -OriginalValue $cacheValue -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret } if($Value -eq $cacheValue) { Write-Host "Cache variable $Key is populated properly" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Cache variable $Key is not populated properly: Expected - $Value, Actual - $cacheValue" -foregroundcolor White -backgroundcolor Red return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Redis Cache check" -foregroundcolor White -backgroundcolor Red return 1 } } function HttpEndPointCheck{ param ( [Parameter(Mandatory = $true)] [String] $Uri, [Parameter(Mandatory = $false)] [String] $Body, [Parameter(Mandatory = $false)] [AllowNull()] [hashtable] $Header, [Parameter(Mandatory = $false)] [AllowEmptyString()] [AllowNull()] [string] $ContentType, [Parameter(Mandatory = $false)] [AllowNull()] [string] $BodyType, [Parameter(Mandatory = $false)] [AllowNull()] [string] $Method ) try { if(!$Method) { $Method = "Get" } if($BodyType.ToLower().Equals("xml")) { $body = [xml]$Body } if($BodyType.ToLower().Equals("json")) { $body = CovertTo-Json $Body } $epErr = $null; if($Header.Count -eq 0) { if(!$ContentType) { if(!$Body) { $post = Invoke-WebRequest -Uri $Uri -Method $Method -ErrorVariable epErr -UseBasicParsing } else { $post = Invoke-WebRequest -Uri $Uri -Method $Method -Body $body -ErrorVariable epErr -UseBasicParsing } } else { if(!$Body) { $post = Invoke-WebRequest -Uri $Uri -Method $Method -ContentType $ContentType -ErrorVariable epErr -UseBasicParsing } else { $post = Invoke-WebRequest -Uri $Uri -Method $Method -Body $body -ContentType $ContentType -ErrorVariable epErr -UseBasicParsing } } } else { if(!$ContentType) { if(!$Body) { $post = Invoke-WebRequest -Uri $Uri -Headers $Header -Method $Method -ErrorVariable epErr -UseBasicParsing } else { $post = Invoke-WebRequest -Uri $Uri -Headers $Header -Method $Method -Body $body -ErrorVariable epErr -UseBasicParsing } } else { if(!$Body) { $post = Invoke-WebRequest -Uri $Uri -Headers $Header -Method $Method -ContentType $ContentType -ErrorVariable epErr -UseBasicParsing } else { $post = Invoke-WebRequest -Uri $Uri -Headers $Header -Method $Method -Body $body -ContentType $ContentType -ErrorVariable epErr -UseBasicParsing } } } if ($epErr.Count.Equals(0)) { Write-Host "End Point Check Successful for Uri: $Uri" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "End Point Check UnSuccessful for Uri $Uri" -foregroundcolor White -backgroundcolor Red return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Http Endpoint check for URI $Uri" -foregroundcolor White -backgroundcolor Red return 1 } } function CDNCheck{ param ( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $EndPointName, [Parameter(Mandatory = $true)] [String] $ProfileName, [Parameter(Mandatory = $true)] [String] $OriginHostHeader, [Parameter(Mandatory = $false)] [String] $OriginPath ) try { $cdnDetails = Get-AzureRmCdnEndpoint -EndpointName $EndPointName -ProfileName $ProfileName -ResourceGroupName $ResourceGroupName -ErrorVariable cdnErr if($OriginPath) { if($cdnErr.Count.Equals(0) -and ($cdnDetails.ResourceState -eq ("Running")) -and ($cdnDetails.OriginHostHeader.ToLower() -eq $OriginHostHeader.ToLower()) -and ($cdnDetails.OriginPath.ToLower() -eq $OriginPath.ToLower())) { Write-Host "CDN Check : $EndPointName is properly created in the specified resource group" -foregroundcolor Black -backgroundcolor Green return 0 } elseif ($cdnErr.Count.Equals(0) -and ($cdnDetails.ResourceState -eq ("Running")) -and ($cdnDetails.OriginHostHeader.ToLower() -eq $OriginHostHeader.ToLower())) { Write-Host "CDN Check: Origin Path property is not set correctly.Expected Value: $OriginPath, Actual Value:" $cdnDetails.OriginPath -foregroundcolor White -backgroundcolor Red return 1 } elseif ($cdnErr.Count.Equals(0) -and ($cdnDetails.ResourceState -eq ("Running")) -and ($cdnDetails.OriginPath.ToLower() -eq $OriginPath.ToLower())) { Write-Host "CDN Check: Origin Host Header property is not set correctly.Expected Value: $OriginHostHeader, Actual Value:" $cdnDetails.OriginHostHeader -foregroundcolor White -backgroundcolor Red return 1 } else { Write-Host "CDN Check: $EndPointName is not created properly in the specified resource group" -foregroundcolor White -backgroundcolor Red return 1 } } else { if($cdnErr.Count.Equals(0) -and ($cdnDetails.ResourceState -eq ("Running")) -and ($cdnDetails.OriginHostHeader.ToLower() -eq $OriginHostHeader.ToLower())) { Write-Host "CDN Check : $EndPointName is properly created in the specified resource group" -foregroundcolor Black -backgroundcolor Green return 0 } elseif ($cdnErr.Count.Equals(0) -and ($cdnDetails.ResourceState -eq ("Running"))) { Write-Host "CDN Check: Origin Host Header property is not set correctly.Expected Value: $OriginHostHeader, Actual Value:" $cdnDetails.OriginHostHeader -foregroundcolor White -backgroundcolor Red return 1 } else { Write-Host "CDN Check: $EndPointName is not created properly in the specified resource group" -foregroundcolor White -backgroundcolor Red return 1 } } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Resource Group check" -foregroundcolor White -backgroundcolor Red return 1 } } function StorageCheck{ param ( [Parameter(Mandatory = $true)] [String] $ResourceGroupName, [Parameter(Mandatory = $true)] [String] $StorageName, [Parameter(Mandatory = $false)] [String] $Location, [Parameter(Mandatory = $false)] [Boolean] $IsClassic ) try { if($IsClassic){ $storageDetails = Get-AzureStorageAccount -StorageAccountName $StorageName -ErrorVariable storageErr if($Location) { if($storageErr.Count.Equals(0) -and ($storageDetails.StorageAccountStatus -eq ("Created")) -and ($storageDetails.Location.ToLower() -eq $Location.ToLower())) { Write-Host "Azure Storage: $StorageName is properly created in the specified location and resource group" -foregroundcolor Black -backgroundcolor Green return 0 } elseif ($storageErr.Count.Equals(0) -and ($storageErr.StorageAccountStatus -eq ("Created"))) { Write-Host "Azure Storage: $StorageName is properly created in the resource group but not in the specified location" -foregroundcolor White -backgroundcolor Red return 1 } else { Write-Host "Azure Storage: $StorageName is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } else { if($storageErr.Count.Equals(0) -and ($storageDetails.StorageAccountStatus -eq ("Created"))) { Write-Host "Azure Storage: $StorageName is successfully created in the specified resource group" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Azure Storage: $StorageName is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } } else{ $storageDetails = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageName -ErrorVariable storageErr if($Location) { if($storageErr.Count.Equals(0) -and ($storageDetails.ProvisioningState -eq ("Succeeded")) -and ($storageDetails.Location.ToLower() -eq $Location.ToLower())) { Write-Host "Azure Storage: $StorageName is properly created in the specified location and resource group" -foregroundcolor Black -backgroundcolor Green return 0 } elseif ($storageErr.Count.Equals(0) -and ($storageDetails.ProvisioningState -eq ("Succeeded"))) { Write-Host "Azure Storage: $StorageName is properly created in the resource group but not in the specified location" -foregroundcolor White -backgroundcolor Red return 1 } else { Write-Host "Azure Storage: $StorageName is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } else { if($storageErr.Count.Equals(0) -and ($storageDetails.ProvisioningState -eq ("Succeeded"))) { Write-Host "Azure Storage: $StorageName is successfully created in the specified resource group" -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "Azure Storage: $StorageName is not created properly" -foregroundcolor White -backgroundcolor Red return 1 } } } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Storage check" -foregroundcolor White -backgroundcolor Red return 1 } } function StorageContainerCheck{ param ( [Parameter(Mandatory = $true)] [String] $StorageAccountName, [Parameter(Mandatory = $true)] [String] $ResourceGroupname, [Parameter(Mandatory = $true)] [String] $ContainerName, [Parameter(Mandatory = $false)] [Boolean] $IsClassic ) try { if($IsClassic) { $storageKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName $StorageAccountKey = $storageKey.Primary $storageAccountContext= New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey $containerdetails=Get-AzureStorageContainer -Name $ContainerName -Context $storageAccountContext -ErrorVariable containerErr if($containerErr.Count.Equals(0)) { Write-Host "StorageContainer: $ContainerName Exists in" $StorageAccountName "Storage Account." -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "StorageContainer: $ContainerName does not exist in" $StorageAccountName "Storage Account." -foregroundcolor White -backgroundcolor Red return 1 } } else { $storageKey = Get-AzureRmStorageAccountKey -ResourceGroupName $ResourceGroupname -Name $StorageAccountName $StorageAccountKey = $storageKey.Value[0] $storageAccountContext= New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey $containerdetails=Get-AzureStorageContainer -Name $ContainerName -Context $storageAccountContext -ErrorVariable containerErr if($containerErr.Count.Equals(0)) { Write-Host "StorageContainer: $ContainerName Exists in" $StorageAccountName "Storage Account." -foregroundcolor Black -backgroundcolor Green return 0 } else { Write-Host "StorageContainer: $ContainerName does not exist in" $StorageAccountName "Storage Account." -foregroundcolor White -backgroundcolor Red return 1 } } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Storage Container check" -foregroundcolor White -backgroundcolor Red return 1 } } function ApiConnectionCheck{ param ( [Parameter(Mandatory = $true)] [String] $ApiConnectionName, [Parameter(Mandatory = $false)] [String] $ResourceGroupname, [Parameter(Mandatory = $false)] [String] $Location ) try { $found = $false $namefound= $false $regrp = $true $loc = $true $resources = Find-AzureRmResource -ResourceType microsoft.web/connections foreach($res in $resources) { $regrp = $true $loc = $true if($res.Name -eq $ApiConnectionName) { $namefound = $true if($ResourceGroupname -and ($res.ResourceGroupName -ne $ResourceGroupname)) { $regrp = $false } if($Location -and ($res.Location -ne $Location)) { $loc = $false } if($regrp -and $loc) { Write-Host "Api Connection $ApiConnectionName is created properly" -foregroundcolor Black -backgroundcolor Green return 0 } } } if($found -eq $false) { if($namefound) { Write-Host "$ApiConnectionName is created but not in proper ResourceGroup or Location" -foregroundcolor White -backgroundcolor Red } else { Write-Host "Could Not Find the Api Connection $ApiConnectionName" -foregroundcolor White -backgroundcolor Red } return 1 } } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in Storage Container check" -foregroundcolor White -backgroundcolor Red return 1 } } function GetValue{ param ( [Parameter(Mandatory = $true)] $OriginalValue, [Parameter(Mandatory = $true)] [String] $ScriptRoot, [Parameter(Mandatory = $false)] [String] $EncryptionKey, [Parameter(Mandatory = $false)] [String] $ClientID, [Parameter(Mandatory = $false)] [String] $ClientSecret ) Import-module "$ScriptRoot\RedisPopulate.dll" $value=$OriginalValue try { if($value.GetType().Name -eq "String" -and $value.StartsWith("@")) { $value=$value.Remove(0,1) $value=$ParamTable.Get_Item($value) } if($value.GetType().Name -eq "String" -and $value.StartsWith("[KeyVault")) { if($EncryptionKey -and $ClientID -and $ClientSecret) { $value=DecryptVariable -Keystring $value -EncryptionKey $EncryptionKey -ClientID $ClientID -ClientSecret $ClientSecret } else { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in retrieving value for Variable - " $OriginalValue -foregroundcolor White -backgroundcolor Red Write-Host "Encrytion details missing" -foregroundcolor White -backgroundcolor Red exit 1 } } return $value } catch { Write-Host $_.Exception.Message -foregroundcolor White -backgroundcolor Red Write-Host "Exception occured in retrieving value for Variable - " $OriginalValue -foregroundcolor White -backgroundcolor Red exit 1 } } if($FilePath) { Write-Host "Reading EVT tasks from $FilePath" $ScriptRoot = (Split-Path -parent $MyInvocation.MyCommand.Definition) $json = (Get-Content $FilePath -Raw) | ConvertFrom-Json } else { Write-Host "Please provide a valid Environment Configuration json file path as parameter" -foregroundcolor White -backgroundcolor Red $exitcode=1 exit $exitcode } if($json) { $IsEVTError = 0 $FailedTasks=@() #Encryption Config $encrytionKey = GetValue -ScriptRoot $ScriptRoot -OriginalValue $json.KeyVaultEncryption.encrytionKey $clientId = GetValue -ScriptRoot $ScriptRoot -OriginalValue $json.KeyVaultEncryption.clientId $clientSecret = GetValue -ScriptRoot $ScriptRoot -OriginalValue $json.KeyVaultEncryption.clientSecret #Authorization $username = GetValue -ScriptRoot $ScriptRoot -OriginalValue $json.Authorize.username -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $password = GetValue -ScriptRoot $ScriptRoot -OriginalValue $json.Authorize.password -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $subscription = GetValue -ScriptRoot $ScriptRoot -OriginalValue $json.Authorize.subscriptionname -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $secpasswd = ConvertTo-SecureString $password -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential ($userName, $secpasswd) -ErrorVariable credentialerr #RM Login for Azure RM Commandlet auth Login-AzureRmAccount -Credential $credential -ErrorVariable rmAutherr Select-AzureRmSubscription -SubscriptionName $subscription #Azure Classic Login for Classic Commandlet auth Add-AzureAccount -Credential $credential -ErrorVariable autherr Select-AzureSubscription -SubscriptionName $subscription if($autherr -or $credentialerr -or $rmAutherr) { Write-Host "Please provide valid username and password" -foregroundcolor White -backgroundcolor Red $exitcode=1 exit $exitcode } Write-Host "Authorization Successful for User: $username to Subscription: $subscription" #Loop through the tasks foreach($task in $json.tasks) { #DatabaseObject Validation if($task.type.ToLower().Equals("dbobjectvalidation")) { Write-Host "Starting" $task.name $dbobjerror = 0 $dbconnection= $dbobjects =$sqlConnect ="" $dbconnection= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.DBConnectionString -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $dbobjects = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.DBObjects -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $sqlConnect = new-object system.data.sqlclient.sqlconnection($dbconnection) $sqlConnect.Open(); Foreach($object in $dbobjects) { $typedesc = "" $namelist="" $typedesc = GetValue -ScriptRoot $ScriptRoot -OriginalValue $object.TypeDescription -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $namelist = GetValue -ScriptRoot $ScriptRoot -OriginalValue $object.Name -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($name in $namelist) { $iserror=1 $iserror= DbObjectValidation -DbConnection $sqlConnect -TypeDescription $typedesc -ObjectName $name if($iserror -eq 1) { $dbobjerror=1 $IsEVTError=1 } } } $sqlConnect.Dispose() if($dbobjerror -eq 1) { $FailedTasks += $task.name; } continue; } #DatabaseData Validation if($task.type.ToLower().Equals("dbdatavalidation")) { Write-Host "Starting" $task.name $dbdataerror = 0 $dbconnection=$dbscripts =$sqlConnect ="" $dbconnection= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.DBConnectionString -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $dbscripts = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.DBScript -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $sqlConnect = new-object system.data.sqlclient.sqlconnection($dbconnection) $sqlConnect.Open(); Foreach($dbscript in $dbscripts) { $script=$output="" $script = GetValue -ScriptRoot $ScriptRoot -OriginalValue $dbscript.Script -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $output = GetValue -ScriptRoot $ScriptRoot -OriginalValue $dbscript.ExpectedOutput -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror=1 $iserror= DbDataValidation -DbConnection $sqlConnect -Script $script -ExpectedOutput $output if($iserror -eq 1) { $dbdataerror=1 $IsEVTError=1 } } $sqlConnect.Dispose() if($dbdataerror -eq 1) { $FailedTasks += $task.name; } continue; } #LogicApp Checking if($task.type.ToLower().Equals("logicappcheck")) { Write-Host "Starting" $task.name $logicapperror = 0 $logicappsettings ="" $logicappsettings = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.LogicAppSettings -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($setting in $logicappsettings) { $resourcegroup="" $applist="" $resourcegroup = GetValue -ScriptRoot $ScriptRoot -OriginalValue $setting.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $applist = GetValue -ScriptRoot $ScriptRoot -OriginalValue $setting.LogicAppName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($app in $applist) { $iserror=1 $app = GetValue -ScriptRoot $ScriptRoot -OriginalValue $app -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror= LogicAppCheck -ResourceGroupName $resourcegroup -LogicAppName $app if($iserror -eq 1) { $logicapperror=1 $IsEVTError=1 } } } if($logicapperror -eq 1) { $FailedTasks += $task.name; } continue; } #StorageContainer Checking if($task.type.ToLower().Equals("storagecontainercheck")) { Write-Host "Starting" $task.name $storagecontainererror = 0 $containersettings ="" $containersettings = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.StorageContainerSettings -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($setting in $containersettings) { $storagename="" $storageResourceGrp="" $containerlist="" if($setting.IsClassic) { $isclassic =[System.Convert]::ToBoolean(( GetValue -ScriptRoot $ScriptRoot -OriginalValue $setting.IsClassic -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret)) } else{ $isclassic =$false } $storagename = GetValue -ScriptRoot $ScriptRoot -OriginalValue $setting.StorageName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $storageResourceGrp = GetValue -ScriptRoot $ScriptRoot -OriginalValue $setting.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $containerlist = GetValue -ScriptRoot $ScriptRoot -OriginalValue $setting.ContainerNames -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($container in $containerlist) { $iserror=1 $container = GetValue -ScriptRoot $ScriptRoot -OriginalValue $container -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror= StorageContainerCheck -StorageAccountName $storagename -ResourceGroupname $storageResourceGrp -ContainerName $container -IsClassic $isclassic if($iserror -eq 1) { $storagecontainererror=1 $IsEVTError=1 } } } if($storagecontainererror -eq 1) { $FailedTasks += $task.name; } continue; } #Topic Checking if($task.type.ToLower().Equals("topiccheck")) { Write-Host "Starting" $task.name $topicerror = 0 $servicebusnamespace=$topiclist="" $servicebusnamespace= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.ServiceBusNamespace -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret; $topiclist= $task.properties.Topic Foreach($topic in $topiclist) { $iserror=1 $name =$size = "" $name = GetValue -ScriptRoot $ScriptRoot -OriginalValue $topic.TopicName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret if($topic.Size) { $size = GetValue -ScriptRoot $ScriptRoot -OriginalValue $topic.Size -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret } $iserror= TopicCheck -ServiceBusNamespace $servicebusnamespace -TopicName $name -TopicSize $size if($iserror -eq 1) { $topicerror=1 $IsEVTError=1 } } if($topicerror -eq 1) { $FailedTasks += $task.name; } continue; } #Subscription Checking if($task.type.ToLower().Equals("subscriptioncheck")) { Write-Host "Starting" $task.name $topicerror = 0 $servicebusnamespace=$topic=$subscriptionlist="" $servicebusnamespace= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.ServiceBusNamespace -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret; $topic= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.Topic -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $subscriptionlist= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.Subscription -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($subscription in $subscriptionlist) { $iserror=1 $iserror= SubscriptionCheck -ServiceBusNamespace $servicebusnamespace -TopicName $topic -SubscriptionName $subscription if($iserror -eq 1) { $topicerror=1 $IsEVTError=1 } } if($topicerror -eq 1) { $FailedTasks += $task.name; } continue; } #WebJob Checking if($task.type.ToLower().Equals("webjobcheck")) { Write-Host "Starting" $task.name $webjoberror = 0 $WebJobsDeployed=$webapp=$jobType="" $WebJobsDeployed= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.WebJobList -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret; $webapp=GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.WebAppName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $jobType=GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.WebJobType -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($Webjob in $WebJobsDeployed) { $iserror=1 $Webjob = GetValue -ScriptRoot $ScriptRoot -OriginalValue $Webjob -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror= WebJobCheck -WebJob $Webjob -WebAppName $webapp -WebJobType $jobType if($iserror -eq 1) { $webjoberror=1 $IsEVTError=1 } } if($webjoberror -eq 1) { $FailedTasks += $task.name; } continue; } #Resource group Checking if($task.type.ToLower().Equals("resourcegroupcheck")) { Write-Host "Starting" $task.name $resourcegrperror = 0 $resourcegrouplist="" $resourcegrouplist= $task.properties.ResourceGroupList Foreach($resourcegrp in $resourcegrouplist) { $iserror=1 $name = "" $location = "" $name = GetValue -ScriptRoot $ScriptRoot -OriginalValue $resourcegrp.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret if($resourcegrp.Location) { $location = GetValue -ScriptRoot $ScriptRoot -OriginalValue $resourcegrp.Location -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret } $iserror= ResourceGroupCheck -ResourceGroup $name -Location $location if($iserror -eq 1) { $resourcegrperror=1 $IsEVTError=1 } } if($resourcegrperror -eq 1) { $FailedTasks += $task.name; } continue; } #Storage Checking if($task.type.ToLower().Equals("storagecheck")) { Write-Host "Starting" $task.name $storageerror = 0 $storagelist="" $storagelist= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.StorageList -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($storage in $storagelist) { $iserror=1 $storagename = "" $resourcegrpname = "" $location = "" $resourcegrpname = GetValue -ScriptRoot $ScriptRoot -OriginalValue $storage.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $storagename = GetValue -ScriptRoot $ScriptRoot -OriginalValue $storage.StorageName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret if($storage.IsClassic) { $isclassic =[System.Convert]::ToBoolean(( GetValue -ScriptRoot $ScriptRoot -OriginalValue $storage.IsClassic -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret)) } else{ $isclassic =$false } if($storage.Location) { $location = GetValue -ScriptRoot $ScriptRoot -OriginalValue $storage.Location -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret } $iserror= StorageCheck -ResourceGroupName $resourcegrpname -StorageName $storagename -Location $location -IsClassic $isclassic if($iserror -eq 1) { $storageerror=1 $IsEVTError=1 } } if($storageerror -eq 1) { $FailedTasks += $task.name; } continue; } #WebApp Checking if($task.type.ToLower().Equals("webappcheck")) { Write-Host "Starting" $task.name $iserror=1 $resourcegrp=$webapp=$webappconnectionstrings=$appsettings =$alwayson =$webappcertificates="" $resourcegrp=GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $webapp= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.WebAppname -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $webappconnectionstrings= $task.properties.WebAppConnectionStrings $appsettings = $task.properties.WebAppSettings $webappcertificates=$task.properties.WebAppCertificates $alwayson = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.AlwaysOn -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror= WebAppCheck -WebAppName $webapp -ResourceGroup $resourcegrp -ConnectionString $webappconnectionstrings -AlwaysOn $alwayson -WebAppSettings $appsettings -WebAppCertificates $webappcertificates -ScriptRoot $ScriptRoot -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret if($iserror -eq 1) { $FailedTasks += $task.name; $IsEVTError=1 } continue; } #CDN Checking if($task.type.ToLower().Equals("cdncheck")) { Write-Host "Starting" $task.name $cdnerror = 0 $cdnlist="" $cdnlist= $task.properties.CDNList Foreach($cdn in $cdnlist) { $iserror=1 $endpointname = "" $profilename = "" $resourcegrpname = "" $hostheader = "" $path="" $endpointname = GetValue -ScriptRoot $ScriptRoot -OriginalValue $cdn.EndPointName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $profilename = GetValue -ScriptRoot $ScriptRoot -OriginalValue $cdn.ProfileName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $resourcegrpname = GetValue -ScriptRoot $ScriptRoot -OriginalValue $cdn.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $hostheader = GetValue -ScriptRoot $ScriptRoot -OriginalValue $cdn.OriginHostHeader -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret if($cdn.OriginPath) { $path = GetValue -ScriptRoot $ScriptRoot -OriginalValue $cdn.Originpath -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret } $iserror= CDNCheck -ResourceGroupName $resourcegrpname -EndPointName $endpointname -ProfileName $profilename -OriginHostHeader $hostheader -OriginPath $path if($iserror -eq 1) { $cdnerror=1 $IsEVTError=1 } } if($cdnerror -eq 1) { $FailedTasks += $task.name; } continue; } #Redis cache variable Checking if($task.type.ToLower().Equals("rediscachecheck")) { Write-Host "Starting" $task.name $rediscacheerror = 0 $cacheVariables=$cacheInstance="" $cacheVariables= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.CacheVariables -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $cacheInstance= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.CacheInstance -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($variable in $cacheVariables) { $iserror=1 $key =$value ="" $key = GetValue -ScriptRoot $ScriptRoot -OriginalValue $variable.Key -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $value = GetValue -ScriptRoot $ScriptRoot -OriginalValue $variable.Value -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror= RedisCacheCheck -RedisCacheInstance "$cacheInstance" -Key $key -Value $value -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret if($iserror -eq 1) { $rediscacheerror=1 $IsEVTError=1 } } if($rediscacheerror -eq 1) { $FailedTasks += $task.name; } continue; } if($task.type.ToLower().Equals("apiconnectioncheck")) { Write-Host "Starting" $task.name $apiconnectionerror = 0 $apiconnectionsettings ="" $apiconnectionsettings = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.ApiConnectionSettings -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret Foreach($apiconnection in $apiconnectionsettings) { $apiconnectionname="" $ResourceGrp="" $location="" $apiconnectionname = GetValue -ScriptRoot $ScriptRoot -OriginalValue $apiconnection.ApiConnectionName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $ResourceGrp = GetValue -ScriptRoot $ScriptRoot -OriginalValue $apiconnection.ResourceGroupName -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $location = GetValue -ScriptRoot $ScriptRoot -OriginalValue $apiconnection.Location -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $iserror=1 $iserror= ApiConnectionCheck -ApiConnectionName $apiconnectionname -ResourceGroupname $ResourceGrp -Location $location if($iserror -eq 1) { $apiconnectionerror=1 $IsEVTError=1 } } if($apiconnectionerror -eq 1) { $FailedTasks += $task.name; } continue; } #End point ping if($task.type.ToLower().Equals("httpendpointcheck")) { Write-Host "Starting" $task.name $autherror = 0 $UrlList=$header=$aadtoken=$authtoken="" $UrlList= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.Url -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $header= $task.properties.Headers $aadtoken= $task.properties.AADTokenGenerator $authtoken= $task.properties.AuthTokenGenerator $hashheader = @{} if($aadtoken) { $clientId=$clientsecret=$aadtenant=$resource=$clientCred =$authString =$authenticationContext =$token ="" $clientId= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.AADTokenGenerator.ClientId -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $clientsecret= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.AADTokenGenerator.ClientSecret -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $aadtenant= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.AADTokenGenerator.AADTenant -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $resource= GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.AADTokenGenerator.Resource -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $clientCred = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential $ClientId, $ClientSecret $authString = "https://login.microsoftonline.com/$AADTenant”; $authenticationContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext $authString $token = $authenticationContext.AcquireToken($Resource, $clientCred) $hashheader = @{'Authorization'=$token.CreateAuthorizationHeader()} } elseif($authtoken) { $authurl = $tokenobject = "" $authurl = GetValue -ScriptRoot $ScriptRoot -OriginalValue $task.properties.AuthTokenGenerator.AuthUrl -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret $tokenobject = Invoke-WebRequest -Uri $authurl -ErrorVariable tokenerror -UseBasicParsing if ($tokenobject) { $token = $tokenobject.Content | ConvertFrom-Json $tokentype = $token.token_type $accesstoken =$token.access_token $hashheader = @{'Authorization'= "$tokentype $accesstoken"} } } elseif($header) { $header.psobject.properties | Foreach { $hashheader[$_.Name] = (GetValue -ScriptRoot $ScriptRoot -OriginalValue $_.Value -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret)} } Foreach($Url in $UrlList) { $baseurllist = $relurllist = "" $baseurllist = (GetValue -ScriptRoot $ScriptRoot -OriginalValue $Url.Base -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret) $relurllist = (GetValue -ScriptRoot $ScriptRoot -OriginalValue $Url.Relative -EncryptionKey $encrytionKey -ClientID $clientId -ClientSecret $clientSecret) Foreach($baseurl in $baseurllist) { Foreach($relurl in $relurllist) { $iserror=1 $iserror= HttpEndPointCheck -Uri $baseurl$relurl -Header $hashheader if($iserror -eq 1) { $autherror=1 $IsEVTError=1 } } } } if($autherror -eq 1) { $FailedTasks += $task.name; } continue; } } if($IsEVTError -eq 1) { Write-Host "EVTs failed for following tasks: $FailedTasks" -foregroundcolor White -backgroundcolor Red $exitcode=1 exit $exitcode } else { Write-Host "All EVTs were successful" -foregroundcolor Black -backgroundcolor Green } } else { Write-Host "No data found in the input Json" -foregroundcolor White -backgroundcolor Red $exitcode=1 exit $exitcode }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/valentia.ps1
valentia.ps1
#Requires -Version 3.0 <# .SYNOPSIS Get ACL from selected source path. .DESCRIPTION You can get ACL information from selected source path. This is same logic as gACLResource. .NOTES Author: guitarrapc Created: 3/Sep/2014 .EXAMPLE Get-ValentiaACL -Path c:\Deployment -Account Users -------------------------------------------- Get ACL Information from c:\Deployment for user "Users", means no Computer/Domain user name checking. .EXAMPLE Get-ValentiaACL -Path c:\Deployment -Account contoso\John -------------------------------------------- Get ACL Information from c:\Deployment for user "contoso\John", means strict user name checking. .ExternalHelp "https://github.com/guitarrapc/DSCResources/tree/master/Custom/gACLResource" #> function Get-ValentiaACL { [CmdletBinding()] [OutputType([Hashtable])] param ( [Parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false, position = 3)] [ValidateSet("Present", "Absent")] [ValidateNotNullOrEmpty()] [String]$Ensure = "Present", [Parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [ValidateSet("Allow", "Deny")] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false, position = 5)] [Bool]$Inherit = $false, [Parameter(mandatory = $false, position = 6)] [Bool]$Recurse = $false, [Parameter(mandatory = $false, position = 7)] [Bool]$Strict = $false ) $desiredRule = GetDesiredRule -Path $Path -Account $Account -Rights $Rights -Access $Access -Inherit $Inherit -Recurse $Recurse $currentACL = (Get-Item $Path).GetAccessControl("Access") $currentRules = $currentACL.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $match = IsDesiredRuleAndCurrentRuleSame -DesiredRule $desiredRule -CurrentRules $currentRules -Strict $Strict $presence = if ($true -eq $match) { "Present" } else { "Absent" } return @{ Ensure = $presence Path = $Path Account = $Account Rights = $Rights Access = $Access Inherit = $Inherit Recurse = $Recurse } } # file loaded from path : \functions\Helper\ACL\Get-ValentiaACL.ps1 #Requires -Version 3.0 <# .SYNOPSIS Set ACL from selected source path. .DESCRIPTION You can Set ACL information to selected source path. This is same logic as gACLResource. .NOTES Author: guitarrapc Created: 3/Sep/2014 .EXAMPLE Set-ValentiaACL -Path c:\Deployment -Account Users -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- Add FullControl to the c:\Deployment for user "Users", means no Computer/Domain user name checking. .EXAMPLE Set-ValentiaACL -Path c:\Deployment -Account contoso\John -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- Add FullControl to the c:\Deployment for user "BuiltIn\Users", means strict user name checking. .ExternalHelp "https://github.com/guitarrapc/DSCResources/tree/master/Custom/gACLResource" #> function Set-ValentiaACL { [CmdletBinding()] param ( [Parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false, position = 3)] [ValidateSet("Present", "Absent")] [ValidateNotNullOrEmpty()] [String]$Ensure = "Present", [Parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [ValidateSet("Allow", "Deny")] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false, position = 5)] [Bool]$Inherit = $false, [Parameter(mandatory = $false, position = 6)] [Bool]$Recurse = $false, [Parameter(mandatory = $false, position = 7)] [Bool]$Strict = $false ) $desiredRule = GetDesiredRule -Path $Path -Account $Account -Rights $Rights -Access $Access -Inherit $Inherit -Recurse $Recurse $currentACL = (Get-Item $Path).GetAccessControl("Access") $currentRules = $currentACL.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $match = IsDesiredRuleAndCurrentRuleSame -DesiredRule $desiredRule -CurrentRules $currentRules -Strict $Strict if ($Ensure -eq "Present") { $CurrentACL.AddAccessRule($DesiredRule) $CurrentACL | Set-Acl -Path $Path } elseif ($Ensure -eq "Absent") { $CurrentACL.RemoveAccessRule($DesiredRule) > $null $CurrentACL | Set-Acl -Path $Path } } # file loaded from path : \functions\Helper\ACL\Set-ValentiaACL.ps1 #Requires -Version 3.0 <# .SYNOPSIS Test ACL from selected source path. .DESCRIPTION You can Test ACL information to selected source path. This is same logic as gACLResource. .NOTES Author: guitarrapc Created: 3/Sep/2014 .EXAMPLE Test-ValentiaACL -Path c:\Deployment -Account Users -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- TestACL to the c:\Deployment for user "Users", means no Computer/Domain user name checking. .EXAMPLE Test-ValentiaACL -Path c:\Deployment -Account contoso\John -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- TestACL to the c:\Deployment for user "contoso\John", means strict user name checking. .ExternalHelp "https://github.com/guitarrapc/DSCResources/tree/master/Custom/gACLResource" #> function Test-ValentiaACL { [CmdletBinding()] [OutputType([Boolean])] param ( [Parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false, position = 3)] [ValidateSet("Present", "Absent")] [ValidateNotNullOrEmpty()] [String]$Ensure = "Present", [Parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [ValidateSet("Allow", "Deny")] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false, position = 5)] [Bool]$Inherit = $false, [Parameter(mandatory = $false, position = 6)] [Bool]$Recurse = $false, [Parameter(mandatory = $false, position = 7)] [Bool]$Strict = $false ) $desiredRule = GetDesiredRule -Path $Path -Account $Account -Rights $Rights -Access $Access -Inherit $Inherit -Recurse $Recurse $currentACL = (Get-Item $Path).GetAccessControl("Access") $currentRules = $currentACL.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $match = IsDesiredRuleAndCurrentRuleSame -DesiredRule $desiredRule -CurrentRules $currentRules -Strict $Strict $presence = if ($true -eq $match) { "Present" } else { "Absent" } return $presence -eq $Ensure } # file loaded from path : \functions\Helper\ACL\Test-ValentiaACL.ps1 #Requires -Version 3.0 function GetDesiredRule { [OutputType([System.Security.AccessControl.FileSystemAccessRule])] [CmdletBinding()] param ( [Parameter(mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false)] [Bool]$Inherit = $false, [Parameter(mandatory = $false)] [Bool]$Recurse = $false ) $InheritFlag = if ($Inherit) { "{0}, {1}" -f [System.Security.AccessControl.InheritanceFlags]::ContainerInherit, [System.Security.AccessControl.InheritanceFlags]::ObjectInherit } elseif ($Recurse) { "{0}, {1}" -f [System.Security.AccessControl.InheritanceFlags]::ContainerInherit, [System.Security.AccessControl.InheritanceFlags]::ObjectInherit } else { [System.Security.AccessControl.InheritanceFlags]::None } $desiredRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Account, $Rights, $InheritFlag, "None", $Access) return $desiredRule } # file loaded from path : \functions\Helper\ACL\Private\GetDesiredRule.ps1 #Requires -Version 3.0 function IsDesiredRuleAndCurrentRuleSame { [OutputType([Bool])] [CmdletBinding()] param ( [System.Security.AccessControl.FileSystemAccessRule]$DesiredRule, [System.Security.AccessControl.AuthorizationRuleCollection]$CurrentRules, [bool]$Strict ) $match = if ($Strict) { Write-Verbose "Using strict name checking. It does not split AccountName with \''." $currentRules ` | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} ` | where FileSystemRights -eq $DesiredRule.FileSystemRights ` | where AccessControlType -eq $DesiredRule.AccessControlType ` | where Inherit -eq $_.InheritanceFlags ` | measure } else { Write-Verbose "Using non-strict name checking. It split AccountName with \''." $currentRules ` | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} ` | where FileSystemRights -eq $DesiredRule.FileSystemRights ` | where AccessControlType -eq $DesiredRule.AccessControlType ` | where Inherit -eq $_.InheritanceFlags ` | measure } if ($match.Count -eq 0) { Write-Verbose "Current ACL result." Write-Verbose ($CurrentRules | Format-List | Out-String) Write-Verbose "Desired ACL result." Write-Verbose ($DesiredRule | Format-List | Out-String) Write-Verbose "Result does not match as desired. Showing Desired v.s. Current Status." [PSCustomObject]@{ DesiredRuleIdentity = $DesiredRule.IdentityReference.Value CurrentRuleIdentity = $currentRules.IdentityReference.Value StrictCurrentRuleIdentity = $currentRules.IdentityReference.Value.Split("\")[1] StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose [PSCustomObject]@{ DesiredFileSystemRights = $DesiredRule.FileSystemRights CurrentFileSystemRights = $currentRules.FileSystemRights StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose [PSCustomObject]@{ DesiredAccessControlType = $DesiredRule.AccessControlType CurrentAccessControlType = $currentRules.AccessControlType StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose [PSCustomObject]@{ DesiredInherit = $DesiredRule.Inherit CurrentInherit = $currentRules.Inherit StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | where Inherit -eq $DesiredRule.Inherit | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | where Inherit -eq $DesiredRule.Inherit | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose } return $match.Count -ge 1 } # file loaded from path : \functions\Helper\ACL\Private\IsDesiredRuleAndCurrentRuleSame.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Convert-ValentiaDecryptPassword { param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$EncryptedKey, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$thumbprint = $valentia.certificate.Encrypt.ThumbPrint, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$certPath = $valentia.certificate.Encrypt.CertPath ) process { $EnvelopedCms = New-Object Security.Cryptography.Pkcs.EnvelopedCms $EnvelopedCms.Decode([convert]::FromBase64String($EncryptedKey)) $EnvelopedCms.Decrypt($Cert) [Text.Encoding]::UTF8.GetString($EnvelopedCms.ContentInfo.Content) } begin { try { Add-type –AssemblyName System.Security } catch { } $Path = Join-Path $certPath $thumbprint if (Test-Path $Path) { $Cert = Get-Item $Path } else { Write-Warning ("Certification not found exception!! Cert: '{0}'" -f $Path) } } } # file loaded from path : \functions\Helper\Certificate\Convert-ValentiaDecryptPassword .ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Convert-ValentiaEncryptPassword { param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [pscredential[]]$Credential, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$thumbprint = $valentia.certificate.Encrypt.ThumbPrint, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$certPath = $valentia.certificate.Encrypt.CertPath ) process { foreach ($cred in $Credential) { $passwordByte = [Text.Encoding]::UTF8.GetBytes($Cred.GetNetworkCredential().Password) $contentInfo = New-Object Security.Cryptography.Pkcs.ContentInfo @(,$passwordByte) $EnvelopedCms = New-Object Security.Cryptography.Pkcs.EnvelopedCms $contentInfo $EnvelopedCms.Encrypt((New-Object System.Security.Cryptography.Pkcs.CmsRecipient($Cert))) [Convert]::ToBase64String($EnvelopedCms.Encode()) } } begin { try { Add-type –AssemblyName System.Security } catch { } $Path = Join-Path $certPath $thumbprint if (Test-Path $Path) { $Cert = Get-Item $Path } else { Write-Warning ("Certification not found exception!! Cert: '{0}'" -f $Path) } } } # file loaded from path : \functions\Helper\Certificate\Convert-ValentiaEncryptPassword .ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Export-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509Certificate2]$cert, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [string]$exportFilePath = $valentia.certificate.FilePath.Cert, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509ContentType]$certType = $valentia.certificate.export.CertType ) process { "Export cert '{0}' to '{1}'." -f $cert.ThumbPrint ,$FilePath | Write-ValentiaVerboseDebug $certToExportInBytes = $cert.Export($certType) [System.IO.File]::WriteAllBytes($FilePath, $certToExportInBytes) } begin { "Export Path setup." | Write-ValentiaVerboseDebug $FilePath = $exportFilePath -f $CN $dir = Split-Path $FilePath -Parent if (-not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force } elseif (Test-Path $FilePath) { Remove-Item -Path $FilePath -Confirm -Force } if (Test-Path $FilePath) { throw "Certificate already exist in '{0}'. Make sure you have delete exist cert before export." -f $FilePath } } end { Get-Item $FilePath } } # file loaded from path : \functions\Helper\Certificate\Export-ValentiaCertificate.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Export-ValentiaCertificatePFX { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509Certificate2]$pfx, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [string]$exportFilePath = $valentia.certificate.FilePath.PFX, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509ContentType]$PFXType = $valentia.certificate.export.PFXType, [parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [PSCredential]$Credential = $null ) process { "Export pfx '{0}' as object." -f $cert.ThumbPrint | Write-ValentiaVerboseDebug $pfxToExportInBytes = $pfx.Export($PFXType, $credential.GetNetworkCredential().Password) [System.IO.File]::WriteAllBytes($FilePath, $pfxToExportInBytes) } begin { "Export Path setup." | Write-ValentiaVerboseDebug $FilePath = $exportFilePath -f $CN $dir = Split-Path $FilePath -Parent if (-not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force } elseif (Test-Path $FilePath) { Remove-Item -Path $FilePath -Confirm -Force } "Get pfx password to export." | Write-ValentiaVerboseDebug if ($null -eq $Credential) { $credential = Get-Credential -Credential "INPUT Password FOR PFX export." } if (Test-Path $FilePath) { throw "Certificate already exist in '{0}'. Make sure you have delete exist cert before export." -f $FilePath } } } # file loaded from path : \functions\Helper\Certificate\Export-ValentiaCertificatePFX.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Get-ValentiaCertificateFromCert { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocation = $valentia.certificate.export.CertStoreLocation, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreName = $valentia.certificate.export.CertStoreName ) "Obtain Cert from CertStoreLocation." | Write-ValentiaVerboseDebug $certStoreLocationPath = Join-Path "cert:" $certStoreLocation -Resolve $certStoreFullPath = Join-Path $certStoreLocationPath $certStoreName -Resolve $cert = (Get-ChildItem $certStoreFullPath | where Subject -eq "CN=$cn") | select -First 1 if ($null -eq $cert) { throw "Certificate for CN '{0}' not found." -f $CN } return [System.Security.Cryptography.X509Certificates.X509Certificate2]$cert } # file loaded from path : \functions\Helper\Certificate\Get-ValentiaCertificateFromCert.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Import-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocation = $valentia.certificate.import.CertStoreLocation, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreName = $valentia.certificate.import.CertStoreName, [parameter(mandatory = $false, position = 3, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$importFilePath = $valentia.certificate.FilePath.Cert ) process { try { "Import certificate '{0}' to CertStore '{1}'" -f $FilePath, (Get-Item ("cert:{0}\{1}" -f $certStore.Location, $certStore.Name)).PSPath | Write-ValentiaVerboseDebug $CertStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::MaxAllowed) $CertStore.Add($CertToImport) } finally { $CertStore.Close() } } begin { "obtain cert." | Write-ValentiaVerboseDebug $FilePath = ($importFilePath -f $CN) if (-not (Test-Path $FilePath)) { throw "Certificate not found in '{0}'. Make sure you have been already exported." -f $FilePath } if ($certStoreLocation -eq [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine) { if(-not(Test-ValentiaPowerShellElevated)) { throw "Your PowerShell Console is not elevated! Must start PowerShell as an elevated to run this function because of UAC." } else { "Current session is already elevated, continue setup environment." | Write-ValentiaVerboseDebug } } "Cert identification." | Write-ValentiaVerboseDebug $flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet $CertToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $FilePath, "", $flags $CertStore = New-Object System.Security.Cryptography.X509Certificates.X509Store $CertStoreName, $CertStoreLocation } } # file loaded from path : \functions\Helper\Certificate\Import-ValentiaCertificate.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Import-ValentiaCertificatePFX { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocation = $valentia.certificate.import.CertStoreLocation, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreName = $valentia.certificate.import.CertStoreName, [parameter(mandatory = $false, position = 3, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$importFilePath = $valentia.certificate.FilePath.PFX, [parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [PSCredential]$Credential = $null ) process { try { "Import certificate PFX '{0}' to CertStore '{1}'" -f $FilePath, (Get-Item ("cert:{0}\{1}" -f $certStore.Location, $certStore.Name)).PSPath | Write-ValentiaVerboseDebug $PFXStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::MaxAllowed) $PFXStore.Add($PFXToImport) } finally { $PFXStore.Close() } } begin { "obtain pfx." | Write-ValentiaVerboseDebug $FilePath = ($importFilePath -f $CN) if (-not (Test-Path $FilePath)) { throw "Certificate not found in '{0}'. Make sure you have been already exported." -f $FilePath } if ($certStoreLocation -eq [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine) { if(-not(Test-ValentiaPowerShellElevated)) { throw "Your PowerShell Console is not elevated! Must start PowerShell as an elevated to run this function because of UAC." } else { "Current session is already elevated, continue setup environment." | Write-ValentiaVerboseDebug } } "Get pfx password to export." | Write-ValentiaVerboseDebug if ($null -eq $Credential) { $credential = Get-Credential -Credential "INPUT Password FOR PFX export." } "PFX identification." | Write-ValentiaVerboseDebug $flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet $PFXToImport = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $FilePath, $credential.GetNetworkCredential().Password, $flags $PFXStore = New-Object System.Security.Cryptography.X509Certificates.X509Store $CertStoreName, $CertStoreLocation } } # file loaded from path : \functions\Helper\Certificate\Import-ValentiaCertificatePFX.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Remove-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$CertFilePath = $valentia.certificate.FilePath.Cert, [parameter(mandatory = $false, position = 2)] [switch]$force = $false ) $param = @{ Path = $CertFilePath -f $CN Confirm = (-not $force) Force = $force } if (Test-Path $param.Path) { Remove-Item @param } } # file loaded from path : \functions\Helper\Certificate\Remove-ValentiaCertificate.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Remove-ValentiaCertificatePFX { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$PFXFilePath = $valentia.certificate.FilePath.PFX, [parameter(mandatory = $false, position = 2)] [switch]$force = $false ) $param = @{ Path = $PFXFilePath -f $CN Confirm = (-not $force) Force = $force } if (Test-Path $param.Path) { Remove-Item @param } } # file loaded from path : \functions\Helper\Certificate\Remove-ValentiaCertificatePFX.ps1 #Requires -Version 3.0 #-- Helper for certificate --# function Show-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false,position = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocationExport = $valentia.certificate.export.CertStoreLocation, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreNameExport = $valentia.certificate.export.CertStoreName, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocationImport = $valentia.certificate.import.CertStoreLocation, [parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreNameImport = $valentia.certificate.import.CertStoreName, [parameter(mandatory = $false, position = 5)] [ValidateNotNullOrEmpty()] [string]$CertFilePath = $valentia.certificate.FilePath.Cert, [parameter(mandatory = $false, position = 6)] [ValidateNotNullOrEmpty()] [string]$PFXFilePath = $valentia.certificate.FilePath.PFX ) "Obtain CERT from export CertStoreLocation." | Write-ValentiaVerboseDebug $certExport = Get-ValentiaCertificateFromCert if ($null -eq $certExport) { Write-Warning ("Certificate for CN '{0}' not found." -f $CN) } "Obtain CERT from Import CertStoreLocation." | Write-ValentiaVerboseDebug $certStoreLocationPathImport= Join-Path "cert:" $certStoreLocationImport -Resolve $certStoreFullPathImport = Join-Path $certStoreLocationPathImport $certStoreNameImport -Resolve $certImport = (Get-ChildItem $certStoreFullPathImport | where Subject -eq "CN=$cn") | select -First 1 if ($null -eq $certImport) { Write-Warning ("Certificate for CN '{0}' not found." -f $CN) } "Obtain Cer file." | Write-ValentiaVerboseDebug $certPath = $CertFilePath -f $CN if (Test-Path $certPath) { $certFile = Get-Item $certPath } else { Write-Warning ("Certificate file not found '{0}'." -f $certPath) } "Obtain PFX file." | Write-ValentiaVerboseDebug $pfxPath = $PFXFilePath -f $CN if (Test-Path $pfxPath) { $pfxFile = Get-Item $pfxPath } else { Write-Warning ("PFX file not found '{0}'." -f $pfxPath) } return [PSCustomObject]@{ ExportCert = $certExport ImportCert = $certImport CertFile = $certFile PFXFile = $pfxFile } } # file loaded from path : \functions\Helper\Certificate\Show-ValentiaCertificate.ps1 #Requires -Version 3.0 #-- Helper for valentia --# # clean <# .SYNOPSIS Clean up valentia task variables. .DESCRIPTION Clear valentia variables for each task, and remove then. valentia only keep default variables after this cmdlet has been run. .NOTES Author: guitarrapc Created: 13/Jul/2013 .EXAMPLE Invoke-ValentiaClean -------------------------------------------- Clean up valentia variables stacked in the $valentia variables. #> function Invoke-ValentiaClean { [CmdletBinding()] param ( ) if ($valentia.context.Count -gt 0) { $currentContext = $valentia.context.Peek() $env:path = $currentContext.originalEnvPath Set-Location $currentContext.originalDirectory $global:ErrorActionPreference = $currentContext.originalErrorActionPreference # Erase Context [void] $valentia.context.Clear() } } # file loaded from path : \functions\Helper\CleanupVariables\Invoke-ValentiaClean.ps1 #Requires -Version 3.0 #-- Helper for valentia --# # cleanResult <# .SYNOPSIS Clean up valentia task previous result. .DESCRIPTION Clear valentia last result. .NOTES Author: guitarrapc Created: 13/Jul/2013 .EXAMPLE Invoke-ValentiaCleanResult #> function Invoke-ValentiaCleanResult { [CmdletBinding()] param ( ) $valentia.Result = [ordered]@{ SuccessStatus = @() TimeStart = [datetime]::Now.DateTime ScriptToRun = "" DeployMembers = @() Result = New-Object 'System.Collections.Generic.List[PSCustomObject]' ErrorMessageDetail = @() } } # file loaded from path : \functions\Helper\CleanupVariables\Invoke-ValentiaCleanResult.ps1 #Requires -Version 3.0 function Get-ValentiaComputerName { [CmdletBinding(DefaultParameterSetName = 'Registry')] param ( [parameter(mandatory = $false, Position = 0, ParameterSetName = "Registry")] [switch]$Registry, [parameter(mandatory = $false, Position = 0, ParameterSetName = "DotNet")] [switch]$DotNet ) end { if ($DotNet) { Write-Verbose "Objain Host Names from Syste.Net.DSC." $hostByName = [System.Net.DNS]::GetHostByName('') [PSCustomObject]@{ HostaName = $hostByName.HostName IPAddress = $hostByName.AddressList } } else { $RegistryParam.GetEnumerator() | %{CheckItemProperty -BasePath $_.BasePath -name $_.Name} } } begin { Set-StrictMode -Version Latest # HostName from Refistry Write-Verbose "Obtain Host Names from Registry Keys." $HKLMComputerName = "registry::HKLM\SYSTEM\CurrentControlSet\Control\Computername" $HKLMTcpip = "registry::HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" $HKLMWinLogon = "registry::HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" $HKUWMSDK = "registry::HKU\.Default\Software\Microsoft\Windows Media\WMSDK\General" $RegistryParam = ( @{ BasePath = "$HKLMComputerName\Computername" name ="Computername" }, @{ BasePath = "$HKLMComputerName\ActiveComputername" name ="Computername" }, @{ BasePath = $HKLMTcpip name = "Hostname" }, @{ BasePath = $HKLMTcpip name = "NV Hostname" }, @{ BasePath = $HKLMWinLogon name = "AltDefaultDomainName" }, @{ BasePath = $HKLMWinLogon name = "DefaultDomainName" }, @{ BasePath = $HKUWMSDK name = "Computername" } ) function CheckItemProperty ([string]$BasePath, [string]$Name) { $result = $null if (Test-Path $BasePath) { $base = Get-ItemProperty $BasePath $keyExist = ($base | Get-Member -MemberType NoteProperty).Name -contains $Name if (($null -ne $base) -and $keyExist) { Write-Verbose ("Found. Path '{0}' and Name '{1}' found. Show result." -f $BasePath, $Name) $result = [ordered]@{ path = $BasePath Property = $name value = ($base | where $Name | %{Get-ItemProperty -path $BasePath -name $Name}).$Name } } else { Write-Verbose ("Skip. Path '{0}' found but Name '{1}' not found." -f $BasePath, $Name) } } else { Write-Verbose ("Skip. Path '{0}' not found." -f $BasePath) } if ($null -eq $result) { Write-Verbose ("Skip. Item Property '{0}' not found from path '{1}'." -f $name, $BasePath) } else { return [PSCustomObject]$result } } } } # file loaded from path : \functions\Helper\ComputerName\Get-ValentiaComputerName.ps1 #Requires -Version 3.0 #-- Helper for valentia --# function Rename-ValentiaComputerName { [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [validateLength(1,15)] [string]$NewComputerName, [parameter(mandatory = $false, Position = 1)] [switch]$Force, [parameter(mandatory = $false, Position = 2)] [switch]$PassThru = $false ) end { # InvalidCharactorCheck if ($detect = GetContainsInvalidCharactor -ComputerName $NewComputerName) { throw ("NewComputerName '{0}' conrains invalid charactor : {1} . Make sure not to include following fault charactors. : {2}" -f $NewComputerName, (($detect | sort -Unique) -join ""), '`~!@#$%^&*()=+_[]{}\|;:.''",<>/?') } # Execute Change $RegistryParam.GetEnumerator() ` | %{CheckItemProperty -BasePath $_.BasePath -name $_.Name} ` | where {$force -or $PSCmdlet.ShouldProcess($_.path, ("Change ComputerName on Registry PropertyName : '{1}', CurrentValue : '{2}', NewName : '{3}'" -f $_.path, $_.Property, $_.Value, $NewComputerName))} ` | %{ if ($_.Path -eq $HKLMTcpip) { Write-Verbose ("Removing existing Registry before set new ComputerName. Registry : '{0}'" -f $_.path) Remove-ItemProperty -Path $_.path -Name $_.Property } Write-Verbose ("Setting New ComputerName on Registry : '{0}'" -f $_.path) Set-ItemProperty -Path $_.path -Name $_.Property -Value $NewComputerName -PassThru:$passThru } } begin { Set-StrictMode -Version Latest $PSBoundParameters.Remove('Force') > $null $list = New-Object 'System.Collections.Generic.List[PSCustomObject]' # HostName from Refistry Write-Verbose "Obtain Host Names from Registry Keys." $HKLMComputerName = "registry::HKLM\SYSTEM\CurrentControlSet\Control\Computername" $HKLMTcpip = "registry::HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters" $HKLMWinLogon = "registry::HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" $HKUWMSDK = "registry::HKU\.Default\Software\Microsoft\Windows Media\WMSDK\General" $RegistryParam = ( @{ BasePath = "$HKLMComputerName\Computername" name ="Computername" }, @{ BasePath = "$HKLMComputerName\ActiveComputername" name ="Computername" }, @{ BasePath = $HKLMTcpip name = "Hostname" }, @{ BasePath = $HKLMTcpip name = "NV Hostname" }, @{ BasePath = $HKLMWinLogon name = "AltDefaultDomainName" }, @{ BasePath = $HKLMWinLogon name = "DefaultDomainName" }, @{ BasePath = $HKUWMSDK name = "Computername" } ) function GetContainsInvalidCharactor ([string]$ComputerName) { $detectedChar = "" # Invalid Charactor list described by MS : http://support.microsoft.com/kb/228275 $invalidCharactor = [System.Linq.Enumerable]::ToArray('`~!@#$%^&*()=+_[]{}\|;:.''",<>/?') $detectedChar = [System.Linq.Enumerable]::ToArray($ComputerName) | where {$_ -in $invalidCharactor} return $detectedChar } function CheckItemProperty ([string]$BasePath, [string]$Name) { $result = $null if (Test-Path $BasePath) { $base = Get-ItemProperty $BasePath $keyExist = ($base | Get-Member -MemberType NoteProperty).Name -contains $Name if (($null -ne $base) -and $keyExist) { Write-Verbose ("Found. Path '{0}' and Name '{1}' found. Show result." -f $BasePath, $Name) $result = [ordered]@{ path = $BasePath Property = $name value = ($base | where $Name | %{Get-ItemProperty -path $BasePath -name $Name}).$Name } } else { Write-Verbose ("Skip. Path '{0}' found but Name '{1}' not found." -f $BasePath, $Name) } } else { Write-Verbose ("Skip. Path '{0}' not found." -f $BasePath) } if ($null -eq $result) { Write-Verbose ("Skip. Item Property '{0}' not found from path '{1}'." -f $name, $BasePath) } else { return [PSCustomObject]$result } } } } # file loaded from path : \functions\Helper\ComputerName\Rename-ValentiaComputerName.ps1 #requires -Version 3.0 function Backup-ValentiaConfig { <# .Synopsis Backup CurrentConfiguration with timestamp. .DESCRIPTION Backup configuration in $Valentia.appdataconfig.root .EXAMPLE Backup-ValentiaConfig #> [OutputType([void])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $Valentia.fileEncode ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) $rootPath = $valentia.originalconfig.root $fileName = $valentia.originalconfig.file } } if (Test-Path $configPath) { $private:datePrefix = ([System.DateTime]::Now).ToString($valentia.log.dateformat) $private:backupConfigName = $datePrefix + "_" + $fileName $private:backupConfigPath = Join-Path $rootPath $backupConfigName Write-Verbose ("Backing up config file '{0}' => '{1}'." -f $configPath, $backupConfigPath) Get-Content -Path $configPath -Encoding $encoding -Raw | Out-File -FilePath $backupConfigPath -Encoding $encoding -Force } else { Write-Verbose ("Could not found configuration file '{0}'." -f $configPath) } } # file loaded from path : \functions\Helper\Config\Backup-valentiaConfig.ps1 #Requires -Version 3.0 <# .Synopsis Edit Valentia Config in Console .DESCRIPTION Read config and edit in the console .EXAMPLE Edit-ValentiaConfig #> function Edit-ValentiaConfig { [OutputType([void])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [switch]$NoProfile ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) } } if (Test-Path $configPath) { if ($NoProfile) { PowerShell_ise.exe -File $configPath -NoProfile } else { PowerShell_ise.exe -File $configPath } } else { ("Could not found configuration file '{0}'." -f $configPath) | Write-ValentiaVerboseDebug } } # file loaded from path : \functions\Helper\Config\Edit-ValentiaConfig.ps1 #Requires -Version 3.0 <# .Synopsis Edit Valentia Config in Console .DESCRIPTION Read config and edit in the console .EXAMPLE Edit-ValentiaConfig #> function Reset-ValentiaConfig { [OutputType([void])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $Valentia.fileEncode ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) } } if (Test-Path $configPath) { . $configPath } else { ("Could not found configuration file '{0}'." -f $configPath) | Write-ValentiaVerboseDebug } } # file loaded from path : \functions\Helper\Config\Reset-ValentiaConfig.ps1 #Requires -Version 3.0 <# .Synopsis Show Valentia Config in Console .DESCRIPTION Read config and show in the console .EXAMPLE Show-ValentiaConfig #> function Show-ValentiaConfig { [OutputType([string[]])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $Valentia.fileEncode ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) } } if (Test-Path $configPath) { Get-Content -Path $configPath -Encoding $encoding } else { ("Could not found configuration file '{0}'." -f $configPath) | Write-ValentiaVerboseDebug } } # file loaded from path : \functions\Helper\Config\Show-ValentiaConfig.ps1 #Requires -Version 3.0 function Get-ValentiaCredential { [OutputType([PSCredential])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [string]$AsUserName = "" ) return [Valentia.CS.CredentialManager]::Read($TargetName, $Type, $AsUserName); } # file loaded from path : \functions\Helper\Credential\Get-ValentiaCredential.ps1 #Requires -Version 3.0 function Remove-ValentiaCredential { [OutputType([void])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic ) [Valentia.CS.CredentialManager]::Remove($TargetName, $Type); } # file loaded from path : \functions\Helper\Credential\Remove-ValentiaCredential.ps1 #Requires -Version 3.0 function Set-ValentiaCredential { [OutputType([void])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential]$Credential = (Get-Credential -User $valentia.Users.DeployUser -Message "Input password to be save."), [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic ) [Valentia.CS.CredentialManager]::Write($TargetName, $Credential, $Type) } # file loaded from path : \functions\Helper\Credential\Set-ValentiaCredential.ps1 #Requires -Version 3.0 function Test-ValentiaCredential { [OutputType([bool])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic ) [Valentia.CS.CredentialManager]::Exists($TargetName, $Type); } # file loaded from path : \functions\Helper\Credential\Test-ValentiaCredential.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Add-ValentiaCredSSPDelegateReg { [CmdletBinding()] param ( [Parameter(Position = 1, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $param = @{ Path = (Split-Path $keys -Parent) Name = (Split-Path $keys -Leaf) Value = 1 Force = $true } $result = Get-ValentiaCredSSPDelegateReg -Keys $Keys if ($result.Value -ne 1) { Set-ItemProperty @param -PassThru } elseif ($null -eq $result) { New-ItemProperty @param } } # file loaded from path : \functions\Helper\CredSSP\Private\Add-ValentiaCredSSPDelegateReg.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Add-ValentiaCredSSPDelegateRegKey { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $param = @{ Path = (Split-Path $keys -Parent) Name = (Split-Path $keys -Leaf) Force = $true } $result = Get-ValentiaCredSSPDelegateRegKey -Keys $Keys if ($result -eq $false) { New-Item @param } } # file loaded from path : \functions\Helper\CredSSP\Private\Add-ValentiaCredSSPDelegateRegKey.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Add-ValentiaCredSSPDelegateRegKeyProperty { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key, [Parameter(Position = 1, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$regValue = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Value ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $param = @{ Path = $keys Value = $regValue Force = $true } $result = Get-ValentiaCredSSPDelegateRegKeyProperty -Keys $Keys if ($result.Value -notcontains $regValue) { $max = ($result.Key | measure -Maximum).Maximum $max++ New-ItemProperty @param -Name $max } elseif ($null -eq $result.Key) { New-ItemProperty @param -Name 1 } } # file loaded from path : \functions\Helper\CredSSP\Private\Add-ValentiaCredSSPDelegateRegKeyProperty.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Enable-ValentiaCredSSP { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$TrustedHosts = $valentia.wsman.TrustedHosts ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest try { Enable-WSManCredSSP -Role Server -Force Enable-WSManCredSSP -Role Client -DelegateComputer $TrustedHosts -Force } catch { # Unfortunately you need to repeat cpmmand again to enable Client Role. Enable-WSManCredSSP -Role Client -DelegateComputer $TrustedHosts -Force } finally { Get-WSManCredSSP } } # file loaded from path : \functions\Helper\CredSSP\Private\Enable-ValentiaCredSSP.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Get-ValentiaCredSSPDelegateReg { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $path = (Split-Path $keys -Parent) $name = (Split-Path $keys -Leaf) Get-ItemProperty -Path $path ` | %{ $hashtable = @{ Name = $name Path = $path } if ($_ | Get-Member | where MemberType -eq NoteProperty | where Name -eq $name) { $hashtable.Add("Value", $_.$name) } else { $hashtable.Add("Value", $null) } [PSCustomObject]$hashtable } } # file loaded from path : \functions\Helper\CredSSP\Private\Get-ValentiaCredSSPDelegateReg.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Get-ValentiaCredSSPDelegateRegKey { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $path = (Split-Path $keys -Parent) $name = (Split-Path $keys -Leaf) Get-ChildItem -Path $path ` | %{ $hashtable = @{ Name = $name PSPath = $path } if ($_ | where name -eq $name) { $true } else { $false } } } # file loaded from path : \functions\Helper\CredSSP\Private\Get-ValentiaCredSSPDelegateRegKey.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Get-ValentiaCredSSPDelegateRegKeyProperty { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $regProperty = Get-ItemProperty -Path $keys if ($regProperty) { $regProperty ` | Get-Member -MemberType NoteProperty ` | where Name -Match "\d+" ` | %{ $name = $_.Name [PSCustomObject]@{ Key = $name Value = $regProperty.$name path = $keys } } } else { [PSCustomObject]@{ Key = "" Value = "" path = $Keys } } } # file loaded from path : \functions\Helper\CredSSP\Private\Get-ValentiaCredSSPDelegateRegKeyProperty.ps1 #Requires -Version 3.0 #-- Public Functions for CredSSP Configuration --# function Remove-ValentiaCredSSPDelegateRegKey { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$TrustedHosts = $valentia.wsman.TrustedHosts, [Parameter(Position = 1, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Keys = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Key, [Parameter(Position = 2, mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$regValue = $valentia.credssp.AllowFreshCredentialsWhenNTLMOnly.Value ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $result = Get-ValentiaCredSSPDelegateRegKey -TrustedHosts $TrustedHosts -Keys $Keys if ($result.Value -contains $regValue) { $result | %{Remove-ItemProperty -Path $_.pspath -Name $_.Key -Force} } } # file loaded from path : \functions\Helper\CredSSP\Private\Remove-ValentiaCredSSPDelegateRegKey.ps1 #Requires -Version 3.0 #-- helper for DNS Entry --# <# .Synopsis Get HostName to IPAddress Entry / IPAddress to HostName Entry .DESCRIPTION using Dns.GetHostEntryAsync Method. You can skip Exception for none exist HostNameOrAddress result by adding -SkipException $true .EXAMPLE Get-HostEntryAsync -HostNameOrAddress "google.com", "173.194.38.100", "neue.cc" # Test Success .EXAMPLE "google.com", "173.194.38.100", "neue.cc" | Get-HostEntryAsync # Pipeline Input .EXAMPLE Get-HostEntryAsync -HostNameOrAddress "google.com", "173.194.38.100", "hogemopge.fugapiyo" # Error will stop execution .EXAMPLE Get-HostEntryAsync -HostNameOrAddress "google.com", "173.194.38.100", "hogemopge.fugapiyo" -SkipException $true # Skip Error result .LINK http://msdn.microsoft.com/en-US/library/system.net.dns.gethostentryasync(v=vs.110).aspx #> function Get-ValentiaHostEntryAsync { [CmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [string[]]$HostNameOrAddress, [parameter(mandatory = $false, Position = 1, ValueFromPipelineByPropertyName = 1)] [bool]$SkipException = $false ) process { foreach ($name in $HostNameOrAddress) { $x = [System.Net.DNS]::GetHostEntryAsync($name) $x.ConfigureAwait($false) > $null $task = [PSCustomObject]@{ HostNameOrAddress = $name Task = $x } $tasks.Add($task) } } end { try { [System.Threading.Tasks.Task]::WaitAll($tasks.Task) } catch { $stackStrace = $_ $throw = $Tasks ` | where {$_.Task.Exception} ` | %{ $stackStrace [System.Environment]::NewLine "Error HostNameOrAddress : {0}" -f $_.HostNameOrAddress [System.Environment]::NewLine $_.Task.Exception } if (-not $SkipException) { throw $throw } else { Write-Verbose ("-SkipException was {0}. Skipping Error : '{1}'." -f $SkipException, "$(($Tasks | where {$_.Task.Exception}).HostNameOrAddress -join ', ')") } } finally { foreach ($task in $tasks.Task) { [System.Net.IPHostEntry]$IPHostEntry = $task.Result $IPHostEntry } } } begin { $tasks = New-Object 'System.Collections.Generic.List[PSCustomObject]' } } # file loaded from path : \functions\Helper\DNS\Get-ValentiaHostEntryAsync.ps1 #Requires -Version 3.0 #-- function helper for Dynamic Param --# <# .SYNOPSIS This cmdlet will return Dynamic param dictionary .DESCRIPTION You can use this cmdlet to define Dynamic Param .NOTES Author: guitrrapc Created: 02/03/2014 .EXAMPLE function Show-ValentiaDynamicParamMulti { [CmdletBinding()] param( [parameter(position = 6)] $nyao ) dynamicParam { $dynamicParams = ( @{Mandatory = $true name = "hoge" Options = "hoge","piyo" position = 0 Type = "System.String[]" validateSet = $true valueFromPipelineByPropertyName = $true}, @{Mandatory = $true name = "foo" Options = 1,2,3,4,5 position = 1 Type = "System.Int32[]" validateSet = $true}, @{DefaultValue = (4,2,5) Mandatory = $false name = "bar" Options = 1,2,3,4,5 position = 2 Type = "System.Int32[]" validateSet = $false} ) $dynamic = New-ValentiaDynamicParamMulti -dynamicParams $dynamicParams return $dynamic } begin { } process { $PSBoundParameters.hoge $PSBoundParameters.foo if ($PSBoundParameters.ContainsKey('bar')) { $PSBoundParameters.bar $PSBoundParameters.bar.GetType().FullName } else { $bar = $dynamic.bar.Value $bar $bar.GetType().FullName } } } "Test 1 ---------------------" Show-ValentiaDynamicParamMulti -hoge hoge -foo 1,2,3,4 "Test 2 ---------------------" Show-ValentiaDynamicParamMulti -hoge piyo -foo 2 -bar 2 #> function New-ValentiaDynamicParamMulti { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0, valueFromPipeline = 1, valueFromPipelineByPropertyName = 1)] [hashtable[]]$dynamicParams ) begin { $dynamicParamLists = New-ValentiaDynamicParamList -dynamicParams $dynamicParams $dictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary } process { foreach ($dynamicParamList in $dynamicParamLists) { # create attributes $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "__AllParameterSets" ( "helpMessage", "mandatory", "parameterSetName", "position", "valueFromPipeline", "valueFromPipelineByPropertyName", "valueFromRemainingArguments" ) ` | %{ if($dynamicParamList.$_) { $attributes.$_ = $dynamicParamList.$_ } } # create attributes Collection $attributesCollection = New-Object 'Collections.ObjectModel.Collection[System.Attribute]' $attributesCollection.Add($attributes) # create validation set if ($dynamicParamList.validateSet) { $validateSetAttributes = New-Object System.Management.Automation.ValidateSetAttribute $dynamicParamList.options $attributesCollection.Add($validateSetAttributes) } # Set default type or get from dynamicparam # Priority # 1. Type KV # 2. Type of DefaultValue # 3. System.Object[] if ($dynamicParamList.type) { $type = [Type]::GetType($dynamicParamList.Type) } else { if ($dynamicParamList.defaultValue) { $DefaultValueType = $dynamicParamList.defaultValue.GetType().FullName $type = [Type]::GetType($DefaultValueType) } else { $type = [Type]::GetType("System.Object[]") } } if ($null -eq $type) { throw "type not defined or Null exception! Make sure you have set fullname for the type : '{0}'" -f $dynamicParamList.type } # create RuntimeDefinedParameter $runtimeDefinedParameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter @($dynamicParamList.name, $type, $attributesCollection) # Set Default Value if passed if ($dynamicParamList.defaultValue) { if ($dynamicParamList.defaultValue -is $type) { $runtimeDefinedParameter.Value = $dynamicParamList.defaultValue } elseif ($dynamicParamList.defaultValue -as $type) { Write-Verbose ("Convert Type for ParameterName '{0}'. DefaultValue '{1}' convert from '{2}' to '{3}'" ` -f $dynamicParamList.name, $dynamicParamLists.defaultValue, $dynamicParamList.defaultValue.GetType().FullName, $type) $runtimeDefinedParameter.Value = $dynamicParamList.defaultValue -as $type } else { throw "Cannot convert Type for ParameterName '{0}'. DefaultValue '{1}' could not convert from '{2}' to '{3}'" ` -f $dynamicParamList.name, $dynamicParamLists.defaultValue, $dynamicParamList.defaultValue.GetType().FullName, $type } } # create Dictionary $dictionary.Add($dynamicParamList.name, $runtimeDefinedParameter) } } end { # return result return $dictionary } } <# .SYNOPSIS This cmdlet will return Dynamic param list item for dictionary .DESCRIPTION You can pass this list to DynamicPramMulti to create Dynamic Param #> function New-ValentiaDynamicParamList { [CmdletBinding()] param ( [parameter( mandatory = $true, position = 0, valueFromPipeline = 1, valueFromPipelineByPropertyName = 1)] [hashtable[]] $dynamicParams ) begin { # create generic list $list = New-Object System.Collections.Generic.List[HashTable] # create key check array [string[]]$keyCheckInputItems = "helpMessage", "mandatory", "name", "parameterSetName", "options", "position", "valueFromPipeline", "valueFromPipelineByPropertyName", "valueFromRemainingArguments", "validateSet", "Type", "DefaultValue" $keyCheckList = New-Object System.Collections.Generic.List[String] $keyCheckList.AddRange($keyCheckInputItems) # sort dynamicParams hashtable by position $newDynamicParams = Sort-ValentiaDynamicParamHashTable -dynamicParams $dynamicParams } process { foreach ($dynamicParam in $newDynamicParams) { $invalidParamter = $dynamicParam.Keys | where {$_ -notin $keyCheckList} if ($($invalidParamter).count -ne 0) { throw ("Invalid parameter '{0}' found. Please use parameter from '{1}'" -f $invalidParamter, ("$keyCheckInputItems" -replace " "," ,")) } else { if (-not $dynamicParam.Keys.contains("name")) { throw ("You must specify mandatory parameter '{0}' to hashtable key." -f "name") } elseif (-not $dynamicParam.Keys.contains("options")) { throw ("You must specify mandatory parameter '{0}' to hashtable key." -f "options") } else { $list.Add($dynamicParam) } } } } end { return $list } } function Sort-ValentiaDynamicParamHashTable { [CmdletBinding()] param ( [parameter( mandatory = $true, position = 0, valueFromPipeline = 1, valueFromPipelineByPropertyName = 1)] [hashtable[]] $dynamicParams ) begin { # get max number of position for null position item $max = ($dynamicParams.position | measure -Maximum).Maximum } process { # output PSCustomObject[Name<SortedPosition>,Value<DynamicParamHashTable>]. posision is now sorted. $h = $dynamicParams ` | %{ $history = New-Object System.Collections.Generic.List[int] $hash = @{} # temp posision for null item. This set as (max + number of collection items) $num = $max + $parameters.Length }{ Write-Verbose ("position is '{0}'." -f $position) $position = $_.position #region null check if ($null -eq $position) { Write-Verbose ("position is '{0}'. set current max index '{1}'" -f $position, $num) $position = $num $num++ } #endregion #region dupricate check if ($position -notin $history) { Write-Verbose ("position '{0}' not found in '{1}'. Add to history." -f $position, ($history -join ", ")) $history.Add($position) } else { $changed = $false while ($position -in $history) { Write-Verbose ("position '{0}' found in '{1}'. Start increment." -f $position, ($history -join ", ")) $position++ $changed = $true } Write-Verbose (" incremented position '{0}' not found in '{1}'. Add to history." -f $position, ($history -join ", ")) if ($changed){$history.Add($position)} } #endregion #region set temp hash Write-Verbose ("Set position '{0}' as name of temp hash." -f $position) $hash."$position" = $_ #endregion }{[PSCustomObject]$hash} } end { # get index for each object $index = [int[]](($h | Get-Member -MemberType NoteProperty).Name) | sort # return sorted hash order by index return $index | %{$h.$_} } } # file loaded from path : \functions\Helper\DynamicParam\New-ValentiaDynamicParamMulti.ps1 #Requires -Version 3.0 #-- Helper Functions --# <# .SYNOPSIS Get encoding from the file your tried to read. .DESCRIPTION You can specify what is the encoding used in the file you want to check. Will return encoding name used in PowerShell, it means you can pass returned value to Get-Content or other. .NOTES Author: guitarrapc Created: 19/Nov/2013 .EXAMPLE Get-ValentiaFileEncoding -Path hogehoge.ps1 -------------------------------------------- Get encoding of hogehoge.ps1 #> function Get-ValentiaFileEncoding { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0)] [string]$path ) if (Test-Path $path) { $bytes = [byte[]](Get-Content $Path -Encoding byte -ReadCount 4 -TotalCount 4) if(-not $bytes) { return 'utf8' } switch -regex ('{0:x2}{1:x2}{2:x2}{3:x2}' -f $bytes[0],$bytes[1],$bytes[2],$bytes[3]) { '^efbbbf' {return 'utf8'} '^2b2f76' {return 'utf7'} '^fffe' {return 'unicode'} '^feff' {return 'bigendianunicode'} '^0000feff' {return 'utf32'} default {return 'ascii'} } } else { throw ("path '{0}' not exist excemption." -f $path) } } # file loaded from path : \functions\Helper\Encoding\Get-ValentiaFileEncoding.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Create New Firewall Rule for PowerShell Remoting .DESCRIPTION Will allow PowerShell Remoting port for firewall .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Enable-PSRemotingFirewallRule -------------------------------------------- Add PowerShellRemoting-In accessible rule to Firewall. #> function New-ValentiaPSRemotingFirewallRule { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Input PowerShellRemoting-In port. default is 5985")] [int]$PSRemotePort = 5985, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Input Name of Firewall rule for PowerShellRemoting-In.")] [string]$Name = "Windows Remote Management (HTTP-In)", [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input Decription of Firewall rule for PowerShellRemoting-In.")] [string]$Description = "Windows PowerShell Remoting required to open for public connection. not for private network.", [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input Group of Firewall rule for PowerShellRemoting-In.")] [string]$Group = "Windows Remote Management" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if (-not((Get-NetFirewallRule | where Name -eq $Name) -and (Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq $PSRemotePort))) { Write-Verbose ("Windows PowerShell Remoting port TCP $PSRemotePort was not opend. Set new rule '{1}'" -f $PSRemotePort, $Name) New-NetFirewallRule ` -Name $Name ` -DisplayName $Name ` -Description $Description ` -Group $Group ` -Enabled True ` -Profile Any ` -Direction Inbound ` -Action Allow ` -EdgeTraversalPolicy Block ` -LooseSourceMapping $False ` -LocalOnlyMapping $False ` -OverrideBlockRules $False ` -Program Any ` -LocalAddress Any ` -RemoteAddress Any ` -Protocol TCP ` -LocalPort $PSRemotePort ` -RemotePort Any ` -LocalUser Any ` -RemoteUser Any } else { "Windows PowerShell Remoting port TCP 5985 was alredy opened. Get Firewall Rule." | Write-ValentiaVerboseDebug Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq 5985 } if ((Get-WinSystemLocale).Name -eq "ja-JP") { $japanesePSRemoteingEnableRule = "Windows リモート管理 (HTTP 受信)" if (-not((Get-NetFirewallRule | where DisplayName -eq $japanesePSRemoteingEnableRule | where Profile -eq "Any") -and (Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq $PSRemotePort))) { ("日本語OSと検知しました。'{0}' という名称で TCP '{1}' をファイアウォールに許可します。" -f $japanesePSRemoteingEnableRule, 5985) | Write-ValentiaVerboseDebug New-NetFirewallRule ` -Name $japanesePSRemoteingEnableRule ` -DisplayName $japanesePSRemoteingEnableRule ` -Description $Description ` -Group $Group ` -Enabled True ` -Profile Any ` -Direction Inbound ` -Action Allow ` -EdgeTraversalPolicy Block ` -LooseSourceMapping $False ` -LocalOnlyMapping $False ` -OverrideBlockRules $False ` -Program Any ` -LocalAddress Any ` -RemoteAddress Any ` -Protocol TCP ` -LocalPort $PSRemotePort ` -RemotePort Any ` -LocalUser Any ` -RemoteUser Any } } } # file loaded from path : \functions\Helper\FireWall\Firewall\New-ValentiaPSRemotingFirewallRule.ps1 #Requires -Version 3.0 #-- Prerequisite Deploy Setting Module Functions --# <# .SYNOPSIS Configure Deployment Path .DESCRIPTION This cmdlet will create valentis deploy folders for each Branch path. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE New-valentiaFolder -------------------------------------------- create as default #> function New-ValentiaFolder { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Root Folder path.")] [ValidateNotNullOrEmpty()] [string]$RootPath = $valentia.RootPath, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Branch Path path.")] [ValidateNotNullOrEmpty()] [ValentiaBranchPath[]]$BranchPath = [Enum]::GetNames([ValentiaBranchPath]), [Parameter(Position = 2, mandatory = $false, HelpMessage = "Log Folder path.")] [ValidateNotNullOrEmpty()]$LogFolder = $valentia.Log.path, [Parameter(Position = 3, mandatory = $false, HelpMessage = "Suppress output directory create info.")] [switch]$Quiet ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # Create Fullpath String if (($BranchPath).count -ne 0) { $DeployFolders = $BranchPath | %{Join-Path $RootPath $_} } $directories = New-Object System.Collections.Generic.List[System.IO.DirectoryInfo] } process { # Check each Fupllpath and create if not exist. foreach ($Deployfolder in $DeployFolders) { if(-not (Test-Path $DeployFolder)) { ("'{0}' not exist, creating." -f $DeployFolder) | Write-ValentiaVerboseDebug $output = New-Item -Path $DeployFolder -ItemType directory -Force $directories.Add($output) } else { ("'{0}' already exist, skip." -f $DeployFolder) | Write-ValentiaVerboseDebug $output = Get-Item -Path $DeployFolder $directories.Add($output) } } # Check Log Folder and create if not exist if(-not (Test-Path $LogFolder)) { ("'{0}' not exist, creating." -f $LogFolder) | Write-ValentiaVerboseDebug $output = New-Item -Path $LogFolder -ItemType directory -Force $directories.Add($output) } else { ("'{0}' already exist, skip." -f $LogFolder) | Write-ValentiaVerboseDebug $output = Get-Item -Path $LogFolder $directories.Add($output) } } end { if (-not $Quiet) { ($directories).FullName } # Cleanup valentia Environment Invoke-ValentiaClean } } # file loaded from path : \functions\Helper\Folder\New-ValentiaFolder.ps1 #Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# # target <# .SYNOPSIS Get ipaddress or NetBIOS from DeployGroup File specified .DESCRIPTION This cmdlet will read Deploy Group path and set them into array of Deploygroups. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE target production-hoge.ps1 -------------------------------------------- read production-hoge.ps1 from deploy group branch path. .EXAMPLE target production-hoge.ps1 c:\test -------------------------------------------- read production-hoge.ps1 from c:\test. #> function Get-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string[]]$DeployGroups, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Input DeployGroup Folder path if changed from default.")] [ValidateNotNullOrEmpty()] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)) ) process { foreach ($DeployGroup in $DeployGroups) { # Get valentia.deployextension information ('Set DeployGroupFile Extension as "$valentia.deployextension" : {0}' -f $valentia.deployextension) | Write-ValentiaVerboseDebug $DeployExtension = $valentia.deployextension 'Read DeployGroup and return $DeployMemebers' | Write-ValentiaVerboseDebug Read-ValentiaGroup -DeployGroup $DeployGroup } } begin { # Get valentiaGroup function Read-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, Mandatory)] [string] $DeployGroup ) if ($DeployGroup.EndsWith($DeployExtension)) # if DeployGroup last letter = Extension is same as $DeployExtension { $DeployGroupPath = Join-Path $DeployFolder $DeployGroup -Resolve ("Read DeployGroupPath {0} where letter not contain # inline." -f $DeployGroupPath) | Write-ValentiaVerboseDebug return (Select-String -path $DeployGroupPath -Pattern ".*#.*" -notmatch -Encoding $valentia.fileEncode | Select-String -Pattern "\w" -Encoding $valentia.fileEncode).line } else { return $DeployGroup } } } } # file loaded from path : \functions\Helper\Group\Get-ValentiaGroup.ps1 #Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# # ipremark <# .SYNOPSIS Remark Deploy ip from deploygroup file .DESCRIPTION This cmdlet remark deploygroup ipaddresses from $valentia.root\$valentia.branch.deploygroup not to refer the ipaddress .NOTES Author: guitarrapc Created: 04/Oct/2013 .EXAMPLE Invoke-valentiaDeployGroupRemark -remarkIPAddresses 10.0.0.10,10.0.0.11 -overWrite -Verbose -------------------------------------------- replace 10.0.0.10 and 10.0.0.11 with #10.0.0.10 and #10.0.0.11 then replace file. (like sed -f "s/^10.0.0.10$/#10.0.0.10" -i) Invoke-valentiaDeployGroupRemark -remarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -------------------------------------------- replace 10.0.0.10 and 10.0.0.11 with #10.0.0.10 and #10.0.0.11 (like sed -f "s/^10.0.0.10$/#10.0.0.10") Invoke-valentiaDeployGroupRemark -remarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -Recurse $false -Path d:\hoge -------------------------------------------- Check d:\hoge folder without recursive. This means it only check path you desired. #> function Invoke-ValentiaDeployGroupRemark { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [Alias("IPAddress", "HostName")] [string[]]$remarkIPAddresses, [parameter(position = 1, mandatory = $false,ValueFromPipelineByPropertyName = 1)] [string]$Path = (Join-Path $valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [parameter(position = 2, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [bool]$Recurse = $true, [parameter(position = 3, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [switch]$overWrite, [parameter(position = 4, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode ) begin { if (-not (Test-Path $Path)){ throw New-Object System.IO.FileNotFoundException ("Path $Path not found Exception!!", "$Path")} } end { Get-ChildItem -Path $Path -Recurse:$Recurse -File ` | %{ foreach ($remarkIPAddress in $remarkIPAddresses) { if ($overWrite) { Invoke-ValentiaSed -path $_.FullName -searchPattern "^$remarkIPAddress$" -replaceWith "#$remarkIPAddress" -encoding $encoding -overWrite } else { Invoke-ValentiaSed -path $_.FullName -searchPattern "^$remarkIPAddress$" -replaceWith "#$remarkIPAddress" -encoding $encoding } } } } } # file loaded from path : \functions\Helper\Group\Invoke-ValentiaDeployGroupRemark.ps1 #Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# # ipunremark <# .SYNOPSIS Unremark Deploy ip from deploygroup file .DESCRIPTION This cmdlet unremark deploygroup ipaddresses from $valentia.root\$valentia.branch.deploygroup to refer the ipaddress. .NOTES Author: guitarrapc Created: 04/Oct/2013 .EXAMPLE Invoke-valentiaDeployGroupUnremark -unremarkIPAddresses 10.0.0.10,10.0.0.11 -overWrite -Verbose -------------------------------------------- replace #10.0.0.10 and #10.0.0.11 with 10.0.0.10 and 10.0.0.11 then replace file (like sed -f "s/^#10.0.0.10$/10.0.0.10" -i) Invoke-valentiaDeployGroupUnremark -unremarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -------------------------------------------- replace #10.0.0.10 and #10.0.0.11 with 10.0.0.10 and 10.0.0.11 (like sed -f "s/^#10.0.0.10$/10.0.0.10") Invoke-valentiaDeployGroupUnremark -remarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -Recurse $false -Path d:\hoge -------------------------------------------- Check d:\hoge folder without recursive. This means it only check path you desired. #> function Invoke-ValentiaDeployGroupUnremark { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [Alias("IPAddress", "HostName")] [string[]]$unremarkIPAddresses, [parameter(position = 1, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [string]$Path = (Join-Path $valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [parameter(position = 2, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [bool]$Recurse = $true, [parameter(position = 3, mandatory = $false)] [switch]$overWrite, [parameter(position = 4, mandatory = $false)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $encoding = $valentia.fileEncode ) begin { if (-not (Test-Path $Path)){ throw New-Object System.IO.FileNotFoundException ("Path $Path not found Exception!!", "$Path")} } end { Get-ChildItem -Path $Path -Recurse:$Recurse -File ` | %{ foreach ($unremarkIPAddress in $unremarkIPAddresses) { if ($overWrite) { Invoke-ValentiaSed -path $_.FullName -searchPattern "^#$unremarkIPAddress$" -replaceWith "$unremarkIPAddress" -encoding $encoding -overWrite } else { Invoke-ValentiaSed -path $_.FullName -searchPattern "^#$unremarkIPAddress$" -replaceWith "$unremarkIPAddress" -encoding $encoding } } } } } # file loaded from path : \functions\Helper\Group\Invoke-ValentiaDeployGroupUnremark.ps1 #Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# <# .SYNOPSIS Create new DeployGroup File written "target PC IP/hostname" for PS-RemoteSession .DESCRIPTION This cmdlet will create valentis deploy group file to specify deploy targets. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE New-valentiaGroup -DeployClients "10.0.4.100","10.0.4.101" -FileName new.ps1 -------------------------------------------- write 10.0.4.100 and 10.0.4.101 to create deploy group file as "new.ps1". #> function New-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Specify IpAddress or NetBIOS name for deploy target clients.")] [string[]]$DeployClients, [Parameter(Position = 1, mandatory = $true, HelpMessage = "Input filename to output DeployClients")] [string]$FileName, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Specify folder path to deploy group. defailt is Deploygroup branchpath")] [string]$DeployGroupsFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 3, mandatory = $false, HelpMessage = "If you want to add item to exist file.")] [switch]$Add, [Parameter(Position = 4, mandatory = $false, HelpMessage = "If you want to popup confirm message when file created.")] [switch]$Confirm, [Parameter(Position = 5, mandatory = $false, HelpMessage = "If you want to Show file information when operation executed.")] [switch]$PassThru ) process { if($PSBoundParameters.ContainsKey('Add')) { $DeployClients | Add-Content @param } else { $DeployClients | Set-Content @param } } begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # check FileName is null or empty try { if ([string]::IsNullOrEmpty($FileName)) { throw '"$FileName" was Null or Enpty, input DeployGroup FileName.' } else { $DeployPath = Join-Path $DeployGroupsFolder $FileName } } catch { throw $_ } # set splatting $param = @{ path = $DeployPath Encoding = $valentia.fileEncode Force = $true Confirm = $PSBoundParameters.ContainsKey('Confirm') PassThru = $PSBoundParameters.ContainsKey('PassThru') } } end { if (Test-Path $DeployPath) { Get-ChildItem -Path $DeployPath } else { Write-Error ("{0} not existing." -f $DeployPath) } # Cleanup valentia Environment Invoke-ValentiaClean } } # file loaded from path : \functions\Helper\Group\New-ValentiaGroup.ps1 #Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# <# .SYNOPSIS Show valentia deploygroup file (.ps1) list .DESCRIPTION This cmdlet will show files (extension = $valentia.deployextension = default is '.ps1') in [ValentiaBranchPath]::Deploygroup folder. .NOTES Author: guitarrapc Created: 29/Oct/2013 .EXAMPLE Show-ValentiaGroup -------------------------------------------- show files in $valentia.Root\([ValentiaBranchPath]::Deploygroup) folder. #> function Show-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Input branch folder to show.")] [ValentiaBranchPath[]]$Branches = ([ValentiaBranchPath]::Deploygroup), [Parameter(Position = 1, mandatory = $false, HelpMessage = "Use if you want to search directory recursibly.")] [switch]$recurse ) $DeployExtension = $valentia.deployextension foreach ($branch in $Branches) { if ($branch.Length -eq 0) { throw '"$Branch" was Null or Empty, input BranchName.' } else { ("Creating full path and resolving with '{0}' and '{1}'" -f $valentia.RootPath, ([ValentiaBranchPath]::$branch)) | Write-ValentiaVerboseDebug $BranchFolder = Join-Path $valentia.RootPath $branch -Resolve # show items $param = @{ Path = $BranchFolder Recurse = if($PSBoundParameters.recurse.IsPresent){$true}else{$false} } Get-ChildItem @param | where extension -eq $DeployExtension } } } # file loaded from path : \functions\Helper\Group\Show-ValentiaGroup.ps1 #Requires -Version 3.0 #-- helper for write verbose and debug --# <# .SYNOPSIS Pass to write-verbose / debug for input. .DESCRIPTION You can show same message for verbose and debug. .NOTES Author: guitarrapc Created: 16/Feb/2014 .EXAMPLE "hoge" | Write-ValentiaVerboseDebug -------------------------------------------- Will show both Verbose message and Debug. #> filter Write-ValentiaVerboseDebug { Write-Verbose -Message $_ Write-Debug -Message $_ } # file loaded from path : \functions\Helper\HostOutput\Write-ValentiaVerboseDebug.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Disable EnhancedIESecutiry for Internet Explorer .DESCRIPTION Change registry to disable EnhancedIESecutiry. It will only work for [Windows Server] not for Workstation, and [Windows Server 2008 R2] and higer. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Disable-ValentiaEnhancedIESecutiry -------------------------------------------- Disable IEEnhanced security. #> function Disable-ValentiaEnhancedIESecutiry { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Registry key for Admin.")] [string]$AdminKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}", [Parameter(Position = 0, mandatory = $false, HelpMessage = "Registry key for User.")] [string]$UserKey = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # get os version, Windows 7 will be "6 1 0 0" $osversion = [Environment]::OSVersion.Version # Higher than $valentia.supportWindows $minimumversion = New-Object 'Version' $valentia.supportWindows # check osversion higher than valentia support version if ($osversion -ge $minimumversion) { if (Test-Path $AdminKey) { if ((Get-ItemProperty -Path $AdminKey -Name "IsInstalled").IsInstalled -eq "1") { Set-ItemProperty -Path $AdminKey -Name "IsInstalled" -Value 0 $IsstatusChanged = $true } else { $IsstatusChanged = $false } } else { $IsstatusChanged = $false } if (Test-Path $UserKey) { if ((Get-ItemProperty -Path $UserKey -Name "IsInstalled").IsInstalled -eq "1") { Set-ItemProperty -Path $UserKey -Name "IsInstalled" -Value 0 $IsstatusChanged = $true } else { $IsstatusChanged = $false } } else { $IsstatusChanged = $false } if ($IsstatusChanged) { # Stop Internet Exploer if launch "IE Enhanced Security Configuration (ESC) has been disabled. Checking IE to stop process." | Write-ValentiaVerboseDebug Get-Process | where Name -eq "iexplore" | Stop-Process -Confirm } else { "IE Enhanced Security Configuration (ESC) had already been disabled. Nothing will do." | Write-ValentiaVerboseDebug } } else { Write-Warning -Message ("Your Operating System '{0}', Version:'{1}' was lower than valentia supported version '{2}'." -f ` (Get-CimInstance -class Win32_OperatingSystem).Caption, $osversion, $minimumversion) } } # file loaded from path : \functions\Helper\IE\Private\Disable-ValentiaEnhancedIESecutiry.ps1 #Requires -Version 3.0 #-- Running prerequisite Initialize OS Setting Module Functions --# # Initial <# .SYNOPSIS Initializing valentia PSRemoting environment for Deploy Server and client. .DESCRIPTION Make sure to Run as Admin Priviledge. This function will execute followings. 1. Set-ExecutionPolicy (Default : RemoteSigned) 2. Add PowerShell Remoting Inbound rule to Firewall 3. Network Connection Profile Setup 4. Disable PSRemoting and CredSSP for reset 5. Enable-PSRemoting 6. Add hosts to trustedHosts 7. Set WSMan MaxShellsPerUser from 25 to 100 8. Set WSMan MaxMBPerUser unlimited. 9. Set WSMan MaxProccessesPerShell unlimited. 10. Enable CredSSP for trustedHosts. 11. Restart Service WinRM 12. Disable Enhanced Security for Internet Explorer 13. Create OS user for Deploy connection. 14. Server Only : Create Deploy Folders 15. Server Only : Create/Revise Deploy user credential secure file. 16. Set HostName for the windows. 17. Get Status for Reboot Status and decide. .PARAMETER Server Select this switch to Initialize setup for Deploy Server. (Ristricted with Client) .PARAMETER Client Select this switch to Initialize setup for Deploy Client. (Ristricted with Server) .PARAMETER NoOSUser Select this switch If you don't want to initialize Deploy User. (Ristricted with Server) .PARAMETER NoPassSave Select this switch If you don't want to Save/Revise password. (Ristricted with Server) .PARAMETER HostUsage set usage for the host. (Ristricted with Server) .PARAMETER NoReboot Select this switch If you don't want to Reboot. .PARAMETER Force Select this switch If you want to Forece Restart without prompt. .PARAMETER TrustedHosts Input Trusted Hosts you want to enable. Default : "*" .PARAMETER SkipEnablePSRemoting Select this switch If you want to skip setup PSRemoting. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Initialize-valentiaEnvironment -Server -------------------------------------------- Setup Server Environment .EXAMPLE Setup Client Environment -------------------------------------------- Initialize-valentiaEnvironment -Client .EXAMPLE Initialize-valentiaEnvironment -Client -NoOSUser -------------------------------------------- Setup Client Environment and Skip Deploy OSUser creattion .EXAMPLE Setup Server Environment withour OSUser and Credential file revise -------------------------------------------- read production-hoge.ps1 from c:\test. #> function Initialize-ValentiaEnvironment { [CmdletBinding(DefaultParameterSetName = "Server")] param ( [parameter(ParameterSetName = "Server")] [switch]$Server = $true, [parameter(ParameterSetName = "Client")] [switch]$Client = $false, [string]$HostUsage = "", [PSCredential]$Credential = $null, [string]$TrustedHosts = $valentia.wsman.TrustedHosts, [switch]$Force = $false, [switch]$NoOSUser = $false, [switch]$NoPassSave = $false, [switch]$NoReboot = $true, [switch]$SkipEnablePSRemoting = $false, [switch]$CredSSP = $false ) process { if ($PSBoundParameters.ContainsKey("Verbose")) { [ordered]@{ Server = $Server Client = $Client NoOSUser = $NoOSUser NoPassSave = $NoPassSave HostUsage = $HostUsage NoReboot = $NoReboot Force = $Force TrustedHosts = $TrustedHosts SkipEnablePSRemoting = $SkipEnablePSRemoting CredSSP = $CredSSP Credential = $Credential } } ExecutionPolicy FirewallNetWorkProfile if (-not($SkipEnablePSRemoting)) { if ($CredSSP) { DisablePSRemotingCredSSP } EnablePSRemoting -SkipEnablePSRemoting $SkipEnablePSRemoting -TrustedHosts $TrustedHosts WSManConfiguration if ($CredSSP) { EnableCredSSP -TrustedHosts $TrustedHosts } } IESettings $cred = CredentialCheck -NoOSUser $NoOSUser -NoPassSave $NoPassSave -credential $credential OSUserSetup -NoOSUser $NoOSUser -credential $cred ServerSetup -server $Server -credential $cred HostnameSetup -HostUsage $HostUsage RebootCheck -NoReboot $NoReboot -Force $Force } end { # Cleanup valentia Environment Invoke-ValentiaClean } begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if(-not(Test-ValentiaPowerShellElevated)) { throw "Your PowerShell Console is not elevated! Must start PowerShell as an elevated to run this function because of UAC." } else { "Current session is already elevated, continue setup environment." | Write-ValentiaVerboseDebug } function ExecutionPolicy { Write-Host "Configuring ExecutionPolicy." -ForegroundColor Cyan "Set ExecutionPolicy to '{0}' only if execution policy is restricted." -f $valentia.ExecutionPolicy | Write-ValentiaVerboseDebug $executionPolicy = Get-ExecutionPolicy if ($executionPolicy -eq "Restricted") { Set-ExecutionPolicy $valentia.ExecutionPolicy -Force } } function FirewallNetWorkProfile { Write-Host "Configuring Firewall to accept PowerShell Remoting." -ForegroundColor Cyan if ([System.Environment]::OSVersion.Version -ge (New-Object 'Version' 6.2.0.0)) # over Win8/2012 { "Enable WindowsPowerShell Remoting Firewall Rule." | Write-ValentiaVerboseDebug New-ValentiaPSRemotingFirewallRule -PSRemotePort 5985 "Set FireWall Status from Public to Private." | Write-ValentiaVerboseDebug if ((Get-NetConnectionProfile).NetworkCategory -ne "DomainAuthenticated") { Set-NetConnectionProfile -NetworkCategory Private } } else { Write-Warning ("Your OS Version detected as '{0}', which is lower than 'Windows 8' or 'Windows Server 2012'. Skip setting Firewall rule and Network location." -f [System.Environment]::OSVersion.Version) } } function DisablePSRemotingCredSSP { Write-Host "Disabling PSRemoting and CredSSP" -ForegroundColor Cyan Start-Service winrm -PassThru winrm invoke restore winrm/config Disable-PSRemoting -Force Disable-WSManCredSSP -Role Client Disable-WSManCredSSP -Role Server Stop-Service winrm } function EnablePSRemoting ($TrustedHosts) { Write-Host "Enabling PSRemoting" -ForegroundColor Cyan "Setup PSRemoting" | Write-ValentiaVerboseDebug Start-Service winrm -PassThru Enable-PSRemoting -Force "Add $TrustedHosts hosts to trustedhosts" | Write-ValentiaVerboseDebug Enable-ValentiaWsManTrustedHosts -TrustedHosts $TrustedHosts "show winrm configuration result" | Write-ValentiaVerboseDebug winrm enumerate winrm/config/listener } function WSManConfiguration { Write-Host "Configure WSMan parameter." -ForegroundColor Cyan Set-ValetntiaWSManConfiguration } function EnableCredSSP ($TrustedHosts) { Write-Host "Enabling CredSSP" -ForegroundColor Cyan "Enable CredSSP for $TrustedHosts" | Write-ValentiaVerboseDebug Enable-ValentiaCredSSP -TrustedHosts $TrustedHosts "Enable winrm/Trustedhosts to registry AllowFreshCredentialsWhenNTLMOnly" | Write-ValentiaVerboseDebug Add-ValentiaCredSSPDelegateReg Add-ValentiaCredSSPDelegateRegKey Add-ValentiaCredSSPDelegateRegKeyProperty } function IESettings { Write-Host "Disable Enganced Security for Ineternet Explorer." -ForegroundColor Cyan "Disable Enhanced Security for Internet Explorer" | Write-ValentiaVerboseDebug Disable-ValentiaEnhancedIESecutiry } function CredentialCheck ($NoOSUser, $NoPassSave, [PSCredential]$credential = $null) { if ((-not $NoOSUser) -or (-not $NoPassSave)) { if ($null -ne $credential) { Write-Host "Credential information already passed. Skip Credential prompt." -ForegroundColor Cyan return $credential } else { Write-Host "Obtain PSCredential to set Credential information." -ForegroundColor Cyan return (Get-Credential -Credential $valentia.users.deployUser) } } } function OSUserSetup ($NoOSUser, $credential) { Write-Host "Adding Deploy User." -ForegroundColor Cyan if ($NoOSUser) { "NoOSUser switch was enabled, skipping create OSUser." | Write-ValentiaVerboseDebug } else { "Add valentia connection user" | Write-ValentiaVerboseDebug New-ValentiaOSUser -Credential $credential } } function ServerSetup ($server, $credential) { if ($Server) { Write-Host "Add valentia DeployFolder." -ForegroundColor Cyan New-ValentiaFolder "Set Valentia credential in Windows Credential Manager." | Write-ValentiaVerboseDebug # validation if ($NoPassSave){ "NoPassSave switch was enabled, skipping Create/Revise set password into Windows Credential Manager." | Write-ValentiaVerboseDebug; return; } if ($null -eq $credential){ "Credential was empty. Skipping Create/Revise set password into Windows Credential Manager." | Write-ValentiaVerboseDebug; return; } "Create Deploy user credential .pass" | Write-ValentiaVerboseDebug Set-ValentiaCredential -Credential $credential } } function HostnameSetup ($HostUsage) { Write-Host "Check HostName configuration." -ForegroundColor Cyan if ($HostUsage -eq "") { "skipping Set HostName." | Write-ValentiaVerboseDebug } else { "Update HostName." | Write-ValentiaVerboseDebug Set-ValentiaHostName -HostUsage $HostUsage } } function RebootCheck ($NoReboot, $Force) { Write-Host "Check Reboot status." -ForegroundColor Cyan if(Get-ValentiaRebootRequiredStatus) { if ($NoReboot) { Write-Host 'NoReboot switch was enabled, skipping reboot.' -ForegroundColor Cyan } elseif ($Force) { Write-Host "Start Restart Force." -ForegroundColor Cyan "Start Restart Force." | Write-ValentiaVerboseDebug Restart-Computer -Force:$Force } else { Write-Host "Start Restart with confirmation." -ForegroundColor Cyan "Start Restart with confirmation." | Write-ValentiaVerboseDebug Restart-Computer -Force:$Force -Confirm } } } } } # file loaded from path : \functions\Helper\Initialize\Initialize-ValentiaEnvironment.ps1 #Requires -Version 3.0 #-- Helper for valentia --# # go <# .SYNOPSIS Move location to valentia folder .DESCRIPTION You can specify branch path in configuration. If you changed from default, then change validation set for BranchPath for intellisence. .NOTES Author: guitarrapc Created: 13/Jul/2013 .EXAMPLE go -------------------------------------------- just move to root deployment path. .EXAMPLE go application -------------------------------------------- change location to BranchPath c:\deployment\application (in default configuration.) #> function Set-ValentiaLocation { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Select branch deploy folder to change directory.")] [ValentiaBranchPath]$BranchPath ) begin { $prevLocation = (Get-Location).Path $newlocation = Join-Path $valentia.RootPath ([ValentiaBranchPath]::$BranchPath) } process { # Move to BrachPath if exist ("moving to new location as '{0}' : '{1}'" -f $BranchPath, $newlocation) | Write-ValentiaVerboseDebug if (Test-Path $newlocation) { Set-Location -Path $newlocation } else { throw "Path not found exception! Make sure {0} is exist." -f $newlocation } } end { ("moved Location : '{0}', previous Location : '{1}'" -f (Get-Location).Path, $prevLocation) | Write-ValentiaVerboseDebug if ((Get-Location).Path -ne $prevLocation) { ("Location change to '{0}'" -f (Get-Location).Path) | Write-ValentiaVerboseDebug } else { Write-Warning "Location not changed." } } } # file loaded from path : \functions\Helper\Location\Set-ValentiaLocation.ps1 #Requires -Version 3.0 #-- Helper for valentia --# #-- Log Settings -- # <# .SYNOPSIS Setup Valentia Log Folder .DESCRIPTION Check Valentia Log folder and return log full path .NOTES Author: guitarrapc Created: 18/Sep/2013 .EXAMPLE New-ValentiaLog -LogFolder c:\logs\deployment -LogFile "hoge.log" -------------------------------------------- This is format sample. .EXAMPLE New-ValentiaLog -------------------------------------------- As New-ValentiaLog have default value in parameter, you do not required to specify log information #> function New-ValentiaLog { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Path to LogFolder.")] [string]$LogFolder = $(Join-Path $valentia.Log.path (Get-Date).ToString("yyyyMMdd")), [Parameter(Position = 1, mandatory = $false, HelpMessage = "Name of LogFile.")] [string]$LogFile = "$($valentia.Log.name)_$((Get-Date).ToString("yyyyMMdd_HHmmss"))_$([Guid]::NewGuid().ToString())$($valentia.Log.extension)" ) if (-not(Test-Path $LogFolder)) { ("LogFolder not found creating {0}" -f $LogFolder) | Write-ValentiaVerboseDebug New-Item -Path $LogFolder -ItemType Directory > $null } try { "Defining LogFile full path." | Write-ValentiaVerboseDebug $valentia.Log.fullPath = Join-Path $LogFolder $LogFile } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ $ErrorCmdletName += ($MyInvocation.MyCommand).Name throw $_ } } # file loaded from path : \functions\Helper\Log\New-ValentiaLog.ps1 #Requires -Version 3.0 #-- Helper for valentia --# #-- End Result Execution -- # function Out-ValentiaResult { [CmdletBinding()] param ( [parameter(mandatory = $true)] [System.Diagnostics.Stopwatch]$StopWatch, [parameter(mandatory = $true)] [string]$Cmdlet, [parameter(mandatory = $false)] [string]$TaskFileName = "", [parameter(mandatory = $true)] [string[]]$DeployGroups, [parameter(mandatory = $true)] [bool]$SkipException, [parameter(mandatory = $true)] [bool]$Quiet ) # obtain Result $CommandResult = [ordered]@{ Success = !($valentia.Result.SuccessStatus -contains $false) TimeStart = $valentia.Result.TimeStart TimeEnd = (Get-Date).DateTime TotalDuration = $stopwatch.Elapsed.TotalSeconds Module = "$($MyInvocation.MyCommand.Module)" Cmdlet = $Cmdlet Alias = "$((Get-Alias | where ResolvedCommandName -eq $Cmdlet).Name)" TaskFileName = $TaskFileName ScriptBlock = "{0}" -f $valentia.Result.ScriptTorun DeployGroup = "{0}" -f "$($DeployGroups -join ', ')" TargetHostCount = $($valentia.Result.DeployMembers).count TargetHosts = "{0}" -f ($valentia.Result.DeployMembers -join ', ') Result = $valentia.Result.Result SkipException = $SkipException ErrorMessage = $($valentia.Result.ErrorMessageDetail | where {$_ -ne $null} | sort -Unique) } # show result WriteValentiaResultHost -quiet $Quiet -CommandResult $CommandResult # output result Log as json OutValentiaResultLog -CommandResult $CommandResult } # file loaded from path : \functions\Helper\Log\Out-ValentiaResult.ps1 #Requires -Version 3.0 #-- Helper for valentia --# # - Out Log and Host -# filter OutValentiaModuleLogHost { [CmdletBinding(DefaultParameterSetName = "message")] param ( [parameter(mandatory = $false, position = 0, valuefromPipeline = 1, ValuefromPipelineByPropertyName = 1)] [string]$logmessage, [parameter(mandatory = $false, position = 1)] [string]$logfile = $valentia.log.fullpath, [parameter(mandatory = $false, position = 2)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode, [parameter(mandatory = $false, position = 3, ParameterSetName = "message")] [switch]$message, [parameter(mandatory = $false, position = 3, ParameterSetName = "showdata")] [switch]$showdata, [parameter(mandatory = $false, position = 3, ParameterSetName = "hidedata")] [switch]$hidedata, [parameter(mandatory = $false, position = 3, ParameterSetName = "hidedataAsString")] [switch]$hidedataAsString, [parameter(mandatory = $false, position = 3, ParameterSetName = "warning")] [switch]$warning, [parameter(mandatory = $false, position = 3, ParameterSetName = "verbosing")] [switch]$verbosing, [parameter(mandatory = $false, position = 3, ParameterSetName = "error")] [switch]$error, [parameter(mandatory = $false, position = 3, ParameterSetName = "result")] [switch]$result, [parameter(mandatory = $false, position = 3, ParameterSetName = "resultAppend")] [switch]$resultAppend ) process { if($message) { $item = "[$(Get-Date)][message][$_]" Write-Host "$item" -ForegroundColor Cyan $item | Out-File -FilePath $logfile -Encoding $encoding -Append -Force -Width 1048 } elseif($showdata) { $_ $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($hidedata) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($hideDataAsString) { $item = "[$(Get-Date)][message][$_]" $item | Out-File -FilePath $logfile -Encoding $encoding -Append -Force -Width 1048 } elseif($warning) { Write-Warning $_ $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($verbosing) { Write-Verbose $_ $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($error) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($result) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Force -Width 1048 } elseif($resultAppend) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Force -Width 1048 -Append } } } # file loaded from path : \functions\Helper\Log\Private\OutValentiaModuleLogHost.ps1 #Requires -Version 3.0 #-- Helper for valentia --# #-- Log Output Result Settings -- # function OutValentiaResultLog { [CmdletBinding()] param ( [parameter(mandatory = $true)] [System.Collections.Specialized.OrderedDictionary]$CommandResult, [parameter(mandatory = $false)] [string]$removeProperty = "Result", [bool]$Append = $false ) try { $json = $CommandResult | ConvertTo-Json } catch { $json = $CommandResult.Remove($removeProperty) | ConvertTo-Json } finally { if ($Append) { $json | OutValentiaModuleLogHost -resultAppend } else { $json | OutValentiaModuleLogHost -result } } } # file loaded from path : \functions\Helper\Log\Private\OutValentiaResultLog.ps1 #Requires -Version 3.0 #-- Helper for valentia --# #-- Log Output Result Settings -- # function WriteValentiaResultHost { [CmdletBinding()] param ( [parameter(mandatory = $true)] [bool]$quiet, [parameter(mandatory = $true)] [System.Collections.Specialized.OrderedDictionary]$CommandResult ) if (-not $quiet) { # Show Stopwatch for Total section Write-Verbose ("`t`tTotal duration Second`t: {0}" -f $CommandResult.TotalDuration) [PSCustomObject]$CommandResult } else { ([PSCustomObject]$Commandresult).Success } } # file loaded from path : \functions\Helper\Log\Private\WriteValentiaResultHost.ps1 #Requires -Version 3.0 #-- Public Module Functions to load Task --# # Task <# .SYNOPSIS Execute Task and push into CurrentContext .NOTES Author: guitarrapc Created: 31/July/2014 .EXAMPLE Push-ValentiaCurrentContextToTask -ScriptBlock $scriptBlock -TaskFileName $TaskFileName #> function Push-ValentiaCurrentContextToTask { [CmdletBinding()] param ( [parameter(mandatory = $false)] [ScriptBlock]$ScriptBlock, [parameter(mandatory = $false)] [string]$TaskFileName ) # Swtich ScriptBlock or ScriptFile was selected switch ($true) { {$ScriptBlock} { # run Task with ScriptBlock ("ScriptBlock parameter [ {0} ] was selected." -f $ScriptBlock) | Write-ValentiaVerboseDebug $taskkey = Task -name ScriptBlock -action $ScriptBlock # Read Current Context $currentContext = $valentia.context.Peek() } {$TaskFileName} { # check file exist or not if (-not(Test-Path (Join-Path (Get-Location).Path $TaskFileName))) { $TaskFileStatus = [PSCustomObject]@{ ErrorMessageDetail = "TaskFileName '{0}' not found in '{1}' exception!!" -f $TaskFileName,(Join-Path (Get-Location).Path $TaskFileName) SuccessStatus = $false } $valentia.Result.SuccessStatus += $TaskFileStatus.SuccessStatus $valentia.Result.ErrorMessageDetail += $TaskFileStatus.ErrorMessageDetail } # Read Task File and get Action to run ("TaskFileName parameter '{0}' was selected." -f $TaskFileName) | Write-ValentiaVerboseDebug # run Task $TaskFileName inside functions and obtain scriptblock written in. $taskkey = & $TaskFileName # Read Current Context $currentContext = $valentia.context.Peek() } default { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += "TaskFile or ScriptBlock parameter must not be null" throw "TaskFile or ScriptBlock parameter must not be null" } } return $currentContext.tasks.$taskKey } # file loaded from path : \functions\Helper\Prerequisites\Private\Push-ValentiaCurrentContextToTask.ps1 #Requires -Version 3.0 #-- Helper for valentia Invokation Prerequisite setup--# function Set-ValentiaInvokationPrerequisites { [CmdletBinding()] param ( [parameter(mandatory = $true)] [System.Diagnostics.Stopwatch]$StopWatch, [Parameter(Position = 0, mandatory = $true)] [string[]]$DeployGroups, [Parameter(Position = 1, mandatory = $false)] [string]$TaskFileName, [Parameter(Position = 2, mandatory = $false)] [ScriptBlock]$ScriptBlock, [Parameter(Position = 3, mandatory = $false)] [string]$DeployFolder, [Parameter(Position = 4, mandatory = $false)] [string[]]$TaskParameter ) # clear previous result Invoke-ValentiaCleanResult # Initialize Error status $valentia.Result.SuccessStatus = $valentia.Result.ErrorMessageDetail = @() # Get Start Time $valentia.Result.TimeStart = (Get-Date).DateTime # Import default Configurations $valeWarningMessages.warn_import_configuration | Write-ValentiaVerboseDebug Import-ValentiaConfiguration # Import default Modules $valeWarningMessages.warn_import_modules | Write-ValentiaVerboseDebug Import-valentiaModules # Log Setting New-ValentiaLog # Set Task and push CurrentContext $task = Push-ValentiaCurrentContextToTask -ScriptBlock $ScriptBlock -TaskFileName $TaskFileName # Set Task as CurrentContext with task key $valentia.Result.ScriptTorun = $task.Action # Obtain DeployMember IP or Hosts for deploy try { "Get host addresses to connect." | Write-ValentiaVerboseDebug $valentia.Result.DeployMembers = Get-valentiaGroup -DeployFolder $DeployFolder -DeployGroup $DeployGroups } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ Write-Error $_ } # Show Stopwatch for Begin section Write-Verbose ("{0}Duration Second for Begin Section: {1}" -f "`t`t", $Stopwatch.Elapsed.TotalSeconds) } # file loaded from path : \functions\Helper\Prerequisites\Private\Set-ValentiaInvokationPrerequisites.ps1 #Requires -Version 3.0 # -- helper function -- # <# .SYNOPSIS Show valentia Prompt For Choice description and will return item you passed. .DESCRIPTION You can show choice Description with your favored items. .NOTES Author: guitarrapc Created: 17/Nov/2013 .EXAMPLE Show-ValentiaPromptForChoice -------------------------------------------- default will use what you have written in valentia-config.ps1 .EXAMPLE Show-ValentiaPromptForChoice -questionHelps $(Show-ValentiaGroup).Name -------------------------------------------- Will check valentia deploy folder and get deploygroup files. You can see choice description for each deploygroup file, and will get which item was selected. #> function Show-ValentiaPromptForChoice { [CmdletBinding()] param ( # input prompt items with array. second index is for help message. [parameter(mandatory = $false, position = 0)] [string[]]$questions = $valentia.promptForChoice.questions, # input title message showing when prompt. [parameter(mandatory = $false, position = 1)] [string[]]$title = $valentia.promptForChoice.title, # input message showing when prompt. [parameter(mandatory = $false, position = 2)] [string]$message = $valentia.promptForChoice.message, # input additional message showing under message. [parameter(mandatory = $false, position = 3)] [string]$additionalMessage = $valentia.promptForChoice.additionalMessage, # input Index default selected when prompt. [parameter(mandatory = $false, position = 4)] [int]$defaultIndex = $valentia.promptForChoice.defaultIndex ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom try { # create caption Messages if(-not [string]::IsNullOrEmpty($additionalMessage)) { $message += ([System.Environment]::NewLine + $additionalMessage) } # create dictionary include dictionary <int, KV<string, string>> : accessing KV <string, string> with int key return from prompt $script:dictionary = New-Object 'System.Collections.Generic.Dictionary[int, System.Collections.Generic.KeyValuePair[string, string]]' foreach ($question in $questions) { if ("$questions" -eq "$($valentia.promptForChoice.questions)") { if ($private:count -eq 1) { # create key to access value $private:key = $valentia.promptForChoice.defaultChoiceNo } else { # create key to access value $private:key = $valentia.promptForChoice.defaultChoiceYes } } else { # create key to access value $private:key = [System.Text.Encoding]::ASCII.GetString($([byte[]][char[]]'a') + [int]$private:count) } # create KeyValuePair<string, string> for prompt item : accessing value with 1 letter Alphabet by converting char $script:keyValuePair = New-Object 'System.Collections.Generic.KeyValuePair[string, string]'($key, $question) # add to Dictionary $dictionary.Add($count, $keyValuePair) # increment to next char $count++ # prompt limit to max 26 items as using single Alphabet charactors. if ($count -gt 26) { throw ("Not allowed to pass more then '{0}' items for prompt" -f ($dictionary.Keys).count) } } # create choices Collection $script:collectionType = [System.Management.Automation.Host.ChoiceDescription] $script:choices = New-Object "System.Collections.ObjectModel.Collection[$CollectionType]" # create choice description from dictionary<int, KV<string, string>> foreach ($dict in $dictionary.GetEnumerator()) { foreach ($kv in $dict) { # create prompt choice item. Currently you could not use help message. $private:choice = (("{0} (&{1}){2}-" -f $kv.Value.Value, "$($kv.Value.Key)".ToUpper(), [Environment]::NewLine), ($valentia.promptForChoice.helpMessage -f $kv.Value.Key, $kv.Value.Value)) # add to choices $choices.Add((New-Object $CollectionType $choice)) } } # show choices on host $script:answer = $host.UI.PromptForChoice($title, $message, $choices, $defaultIndex) # return value from key return ($dictionary.GetEnumerator() | where Key -eq $answer).Value.Value } catch { throw $_ } } # file loaded from path : \functions\Helper\PromptForChoice\Show-ValentiaPromptForChoice.ps1 #Requires -Version 3.0 #-- Scheduler Task Functions --# <# .SYNOPSIS Extension to Disable TaskScheduler Log Status .DESCRIPTION You can change TaskScheduler Log to State => Enable Make sure Log affect to all TaskScheduler. .NOTES Author: guitarrapc Created: 19/Sep/2014 .EXAMPLE Disable-ValentiaScheduledTaskLogSetting .LINK https://github.com/guitarrapc/valentia/wiki/TaskScheduler-Automation #> function Disable-ValentiaScheduledTaskLogSetting { [CmdletBinding()] param() begin { $ErrorMessages = Data { ConvertFrom-StringData -StringData @" LogOperationNotPermitted = "Attempted to perform an unauthorized operation. You must elevate PowerShell Session to Change TaskSchedulerLog setting." "@ } } end { if (-not(Test-ValentiaPowerShellElevated)){ throw New-Object System.UnauthorizedAccessException ($ErrorMessages.LogOperationNotPermitted) } try { $logName = 'Microsoft-Windows-TaskScheduler/Operational' $log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName $log.IsEnabled = $false $log.SaveChanges() } finally { $log.Dispose() } } } # file loaded from path : \functions\Helper\ScheduledTask\Disable-ValentiaScheduledTaskLogSetting.ps1 #Requires -Version 3.0 #-- Scheduler Task Functions --# <# .SYNOPSIS Extension to Enable TaskScheduler Log Status .DESCRIPTION You can change TaskScheduler Log to State => Enable Make sure Log affect to all TaskScheduler. .NOTES Author: guitarrapc Created: 19/Sep/2014 .EXAMPLE Enable-ValentiaScheduledTaskLogSetting .LINK https://github.com/guitarrapc/valentia/wiki/TaskScheduler-Automation #> function Enable-ValentiaScheduledTaskLogSetting { [CmdletBinding()] param() begin { $ErrorMessages = Data { ConvertFrom-StringData -StringData @" LogOperationNotPermitted = "Attempted to perform an unauthorized operation. You must elevate PowerShell Session to Change TaskSchedulerLog setting." "@ } } end { if (-not(Test-ValentiaPowerShellElevated)){ throw New-Object System.UnauthorizedAccessException ($ErrorMessages.LogOperationNotPermitted) } try { $logName = 'Microsoft-Windows-TaskScheduler/Operational' $log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName $log.IsEnabled = $true $log.SaveChanges() } finally { $log.Dispose() } } } # file loaded from path : \functions\Helper\ScheduledTask\Enable-ValentiaScheduledTaskLogSetting.ps1 #Requires -Version 3.0 #-- Scheduler Task Functions --# <# .SYNOPSIS Extension to set TaskScheduler and Unregister Task you selected. .DESCRIPTION You can remove task and Empty folder if desired. .NOTES Author: guitarrapc Created: 24/Sep/2014 .EXAMPLE $param = @{ taskName = "hoge" Description = "None" taskPath = "\fuga" execute = "powershell.exe" Argument = '-Command "Get-Date | out-File c:\task01.log"' ScheduledAt = [datetime]"00:30:00" Once = $true Hidden = $true Disable = $false Force = $true Runlevel = "limited" } Set-ValentiaScheduledTask @param Remove-ValentiaScheduledTask -taskName $param.taskName -taskPath $param.taskPath # remove Task from your selected path .EXAMPLE $param = @{ taskName = "hoge" Description = "None" taskPath = "\fuga" execute = "powershell.exe" Argument = '-Command "Get-Date | out-File c:\task01.log"' ScheduledAt = [datetime]"00:30:00" Once = $true Hidden = $true Disable = $false Force = $true Runlevel = "limited" } Set-ValentiaScheduledTask @param Remove-ValentiaScheduledTask -taskName $param.taskName -taskPath $param.taskPath -RemoveEmptyFolder $true # remove Task and Empty Folder .EXAMPLE $param = @{ taskName = "hoge" Description = "None" taskPath = "\fuga" execute = "powershell.exe" Argument = '-Command "Get-Date | out-File c:\task01.log"' ScheduledAt = [datetime]"00:30:00" Once = $true Hidden = $true Disable = $false Force = $true Runlevel = "limited" } Set-ValentiaScheduledTask @param Get-ScheduledTask -TaskName hoge -TaskPath \fuga\ | Remove-ValentiaScheduledTask # Remove ScheduledTask passed as CIMInstance .LINK https://github.com/guitarrapc/valentia/wiki/TaskScheduler-Automation #> function Remove-ValentiaScheduledTask { [CmdletBinding(DefaultParameterSetName="TaskName")] param ( [parameter(mandatory = $true, Position = 0, ParameterSetName = "TaskName", ValueFrompipelineByPropertyName = 1)] [string]$taskName, [parameter(mandatory = $false, Position = 1, ParameterSetName = "TaskName", ValueFrompipelineByPropertyName = 1)] [string]$taskPath = "\", [parameter(mandatory = $false, Position = 1, ParameterSetName = "CimTask", ValueFrompipeline = 1)] [CimInstance[]]$InputObject, [parameter(mandatory = $false, Position = 2)] [bool]$RemoveEmptyFolder = $false, [parameter(mandatory = $false, Position = 3)] [bool]$Force = $false ) end { $Confirm = !$Force if ($PSBoundParameters.ContainsKey('taskName')) { # exist $existingTaskParam = @{ TaskName = $taskName TaskPath = ValidateTaskPathLastChar -taskPath $taskPath } # Unregister Task $task = GetExistingTaskScheduler @existingTaskParam if (($task | measure).count -eq 0) { Write-Verbose ($VerboseMessages.TaskNotFound -f $existingTaskParam.taskName, $existingTaskParam.taskPath) } else { Write-Verbose ($VerboseMessages.RemoveTask -f $existingTaskParam.taskName, $existingTaskParam.taskPath) $task | Unregister-ScheduledTask -PassThru -Confirm:$Confirm } } else { $InputObject | Unregister-ScheduledTask -PassThru -Confirm:$confirm } # Remove Empty task folder if ($RemoveEmptyFolder){ Remove-ValentiaScheduledTaskEmptyDirectoryPath } } begin { $VerboseMessages = Data { ConvertFrom-StringData -StringData @" RemoveTask = "Removing Task Scheduler Name '{0}', Path '{1}'" TaskNotFound = "Task not found for TaskName '{0}', TaskPath '{1}'. Skip execution." "@ } function GetExistingTaskScheduler ($TaskName, $TaskPath) { $task = Get-ScheduledTask | where TaskName -eq $taskName | where TaskPath -eq $taskPath return $task } function ValidateTaskPathLastChar ($taskPath) { $lastChar = [System.Linq.Enumerable]::ToArray($taskPath) | select -Last 1 if ($lastChar -ne "\"){ return $taskPath + "\" } return $taskPath } } } # file loaded from path : \functions\Helper\ScheduledTask\Remove-ValentiaScheduledTask.ps1 #Requires -Version 3.0 #-- Scheduler Task Functions --# <# .SYNOPSIS Extension to set TaskScheduler and Remove Task folder where Task not exist .DESCRIPTION You can remove task Empty folder. Normal Unregister Cmdlet never erase them and it may cause some issue like TaskScheduler could not name as same as child folder of TaskPath. You can not create hoge task in root (\) when there are \hoge\ folder. \ -> \hoge\ -> \Microsoft\ .NOTES Author: guitarrapc Created: 24/Sep/2014 .EXAMPLE $param = @{ taskName = "hoge" Description = "None" taskPath = "\fuga" execute = "powershell.exe" Argument = '-Command "Get-Date | out-File c:\task01.log"' ScheduledAt = [datetime]"00:30:00" Once = $true Hidden = $true Disable = $false Force = $true Runlevel = "limited" } Set-ValentiaScheduledTask @param Remove-ValentiaScheduledTask -taskName $param.taskName -taskPath $param.taskPath Remove-ValentiaScheduledTaskEmptyDirectoryPath # Remove task not exist any task or taskfolder. .LINK https://github.com/guitarrapc/valentia/wiki/TaskScheduler-Automation #> function Remove-ValentiaScheduledTaskEmptyDirectoryPath { # validate target Directory is existing $path = Join-Path $env:windir "System32\Tasks" $result = Get-ChildItem -Path $path -Directory | where Name -ne "Microsoft" if (($result | measure).count -eq 0){ return; } # validate Child is blank $result.FullName ` | where {(Get-ChildItem -Path $_) -eq $null} ` | Remove-Item -Force } # file loaded from path : \functions\Helper\ScheduledTask\Remove-ValentiaScheduledTaskEmptyDirectoryPath.ps1 #Requires -Version 3.0 #-- Scheduler Task Functions --# <# .SYNOPSIS Extension to set TaskScheduler and define them as enumerable. .DESCRIPTION You can pass several task scheduler definition at once. .NOTES Author: guitarrapc Created: 11/Aug/2014 .EXAMPLE $param = @{ taskName = "Sample Repeatable Task" Description = "None" taskPath = "\" execute = "PATH TO EXE" Argument = '' ScheduledAt = [datetime]::Now ScheduledTimeSpan = (New-TimeSpan -Minutes 5) ScheduledDuration = ([TimeSpan]::MaxValue) Hidden = $true Disable = $false Force = $true }, @{ taskName = "Sample Daily Task" Description = "None" taskPath = "\" execute = "PATH TO EXE" Argument = '' ScheduledAt = [datetime]"00:00:00" Daily = $true Hidden = $true Disable = $false Force = $true }, @{ taskName = "Sample OneTime Task" Description = "None" taskPath = "\" execute = "PATH TO EXE" Argument = '' ScheduledAt = [datetime]"00:30:00" Once = $true Hidden = $true Disable = $false Force = $true } $Credential = Get-ValentiaCredential foreach ($p in $param.GetEnumerator()) { Set-ValentiaScheduledTask @p -Credential $Credential } # Multipole task With Credential .EXAMPLE $param = @{ taskName = "Sample No Credential Task" Description = "None" taskPath = "\" execute = "PATH TO EXE" Argument = '' ScheduledAt = [datetime]::Now ScheduledTimeSpan = (New-TimeSpan -Minutes 5) ScheduledDuration = ([TimeSpan]::MaxValue) Hidden = $true Disable = $false Force = $true } Set-ValentiaScheduledTask @param # single task without credential .EXAMPLE $param = @{ taskName = "Sample High Runlevel without Credential Task" Description = "None" taskPath = "\" execute = "PATH TO EXE" Argument = '' ScheduledAt = [datetime]::Now ScheduledTimeSpan = (New-TimeSpan -Minutes 5) ScheduledDuration = ([TimeSpan]::MaxValue) Hidden = $true Disable = $false Force = $true RunLevel = "Highest" } Set-ValentiaScheduledTask @param # single task without credential and set Runlevel High .EXAMPLE $param = @{ taskName = "Sample High Runlevel with Credential Task" Description = "None" taskPath = "\" execute = "PATH TO EXE" Argument = '' ScheduledAt = [datetime]::Now ScheduledTimeSpan = (New-TimeSpan -Minutes 5) ScheduledDuration = ([TimeSpan]::MaxValue) Hidden = $true Disable = $false Force = $true RunLevel = "Highest" } $Credential = Get-ValentiaCredential Set-ValentiaScheduledTask @param -Credential $Credential # single task with credential and set Runlevel High .LINK https://github.com/guitarrapc/valentia/wiki/TaskScheduler-Automation #> function Set-ValentiaScheduledTask { [CmdletBinding(DefaultParameterSetName = "ScheduledDuration")] param ( [parameter(mandatory = $false, Position = 0)] [string]$Execute, [parameter(mandatory = $false, Position = 1)] [string]$Argument = "", [parameter(mandatory = $false, Position = 2)] [string]$WorkingDirectory = "", [parameter(mandatory = $true, Position = 3)] [string]$TaskName, [parameter(mandatory = $false, Position = 4)] [string]$TaskPath = "\", [parameter(mandatory = $false, Position = 5)] [datetime[]]$ScheduledAt, [parameter(mandatory = $false, Position = 6, parameterSetName = "ScheduledDuration")] [TimeSpan[]]$ScheduledTimeSpan = ([TimeSpan]::FromHours(1)), [parameter(mandatory = $false, Position = 7, parameterSetName = "ScheduledDuration")] [TimeSpan[]]$ScheduledDuration = [TimeSpan]::MaxValue, [parameter(mandatory = $false, Position = 8, parameterSetName = "Daily")] [bool]$Daily = $false, [parameter(mandatory = $false, Position = 9, parameterSetName = "Once")] [bool]$Once = $false, [parameter(mandatory = $false, Position = 10)] [string]$Description, [parameter(mandatory = $false, Position = 11)] [PScredential]$Credential = $null, [parameter(mandatory = $false, Position = 12)] [bool]$Disable = $true, [parameter(mandatory = $false, Position = 13)] [bool]$Hidden = $true, [parameter(mandatory = $false, Position = 14)] [TimeSpan]$ExecutionTimeLimit = ([TimeSpan]::FromDays(3)), [parameter(mandatory = $false,Position = 15)] [ValidateSet("At", "Win8", "Win7", "Vista", "V1")] [string]$Compatibility = "Win8", [parameter(mandatory = $false,Position = 16)] [ValidateSet("Highest", "Limited")] [string]$Runlevel = "Limited", [parameter(mandatory = $false, Position = 17)] [bool]$Force = $false ) end { Write-Verbose ($VerboseMessages.CreateTask -f $TaskName, $TaskPath) # exist $existingTaskParam = @{ TaskName = $TaskName TaskPath = $TaskPath } $currentTask = GetExistingTaskScheduler @existingTaskParam #region Exclude Action Change : Only Disable / Enable Task if (($Execute -eq "") -and (TestExistingTaskScheduler -Task $currentTask)) { EnableDisableScheduleTask -Disable $Disable return; } #endregion #region Include Action Change # credential if($Credential -ne $null) { # Credential $credentialParam = @{ User = $Credential.UserName Password = $Credential.GetNetworkCredential().Password } # Principal $principalParam = @{ UserId = $Credential.UserName RunLevel = $Runlevel LogOnType = "InteractiveOrPassword" } } # validation if ($Execute -eq ""){ throw New-Object System.InvalidOperationException ($ErrorMessages.ExecuteBrank) } if (Test-ValentiaPowerShellElevated) { if (TestExistingTaskSchedulerWithPath @existingTaskParam) { throw New-Object System.InvalidOperationException ($ErrorMessages.SameNameFolderFound -f $taskName) } } # Action $actionParam = @{ Argument = $Argument Execute = $Execute WorkingDirectory = $WorkingDirectory } # trigger $triggerParam = @{ ScheduledTimeSpan = $scheduledTimeSpan ScheduledDuration = $scheduledDuration ScheduledAt = $ScheduledAt Daily = $Daily Once = $Once } # Description if ($Description -eq ""){ $Description = "No Description"} # Setup Task items $action = CreateTaskSchedulerAction @actionParam $trigger = CreateTaskSchedulerTrigger @triggerParam $settings = New-ScheduledTaskSettingsSet -Disable:$Disable -Hidden:$Hidden -Compatibility $Compatibility -ExecutionTimeLimit $ExecutionTimeLimit $registerParam = if ($null -ne $Credential) { Write-Verbose $VerboseMessages.UsePrincipal $principal = New-ScheduledTaskPrincipal @principalParam $scheduledTask = New-ScheduledTask -Description $Description -Action $action -Settings $settings -Trigger $trigger -Principal $principal @{ InputObject = $scheduledTask TaskName = $TaskName TaskPath = $TaskPath Force = $Force } } else { Write-Verbose $VerboseMessages.SkipPrincipal @{ Action = $action Settings = $settings Trigger = $trigger Description = $Description TaskName = $TaskName TaskPath = $TaskPath Runlevel = $Runlevel Force = $Force } } # Register if ($force -or -not(TestExistingTaskScheduler -Task $currentTask)) { if ($null -ne $Credential) { Register-ScheduledTask @registerParam @credentialParam return; } else { Register-ScheduledTask @registerParam return; } } #endregion } begin { $ErrorMessages = Data { ConvertFrom-StringData -StringData @" InvalidTrigger = "Invalid Operation detected, you can't set same or greater timespan for RepetitionInterval '{0}' than RepetitionDuration '{1}'." ExecuteBrank = "Invalid Operation detected, Execute detected as blank. You must set executable string." SameNameFolderFound = "Already same FolderName existing as TaskPath : \\{0}\\ . Please change TaskName or Rename TaskFolder.." "@ } $VerboseMessages = Data { ConvertFrom-StringData -StringData @" CreateTask = "Creating Task Scheduler Name '{0}', Path '{1}'" UsePrincipal = "Using principal with Credential. Execution will be fail if not elevated." SkipPrincipal = "Skip Principal and Credential. Runlevel Highest requires elevated." "@ } $WarningMessages = Data { ConvertFrom-StringData -StringData @" TaskAlreadyExist = '"{0}" already exist on path "{1}". Please Set "-Force $true" to overwrite existing task.' "@ } function GetExistingTaskScheduler ($TaskName, $TaskPath) { return Get-ScheduledTask | where TaskName -eq $taskName | where TaskPath -eq $taskPath } function TestExistingTaskScheduler ($Task) { $result = ($task | Measure-Object).count -ne 0 if ($result){ Write-Verbose ($WarningMessages.TaskAlreadyExist -f $task.taskName, $task.taskPath) } return $result } function TestExistingTaskSchedulerWithPath ($TaskName, $TaskPath) { if ($TaskPath -ne "\"){ return $false } # only run when taskpath is \ $path = Join-Path $env:windir "System32\Tasks" $result = Get-ChildItem -Path $path -Directory | where Name -eq $TaskName if (($result | measure).count -ne 0) { return $true } return $false } function CreateTaskSchedulerAction ($Argument, $Execute, $WorkingDirectory) { if (($Argument -eq "") -and ($WorkingDirectory -eq "")) { return New-ScheduledTaskAction -Execute $execute } if (($Argument -ne "") -and ($WorkingDirectory -eq "")) { return New-ScheduledTaskAction -Execute $Execute -Argument $Argument } if (($Argument -ne "") -and ($WorkingDirectory -ne "")) { return New-ScheduledTaskAction -Execute $Execute -Argument $Argument -WorkingDirectory $WorkingDirectory } } function CreateTaskSchedulerTrigger ($ScheduledTimeSpan, $ScheduledDuration, $ScheduledAt, $Daily, $Once) { $trigger = if (($false -eq $Daily) -and ($false -eq $Once)) { $ScheduledTimeSpanPair = New-ValentiaZipPairs -first $ScheduledTimeSpan -Second $ScheduledDuration $ScheduledAtPair = New-ValentiaZipPairs -first $ScheduledAt -Second $ScheduledTimeSpanPair $ScheduledAtPair ` | %{ if ($_.Item2.Item1 -ge $_.Item2.Item2){ throw New-Object System.InvalidOperationException ($ErrorMessages.InvalidTrigger -f $_.Item2.Item1, $_.Item2.Item2)} New-ScheduledTaskTrigger -At $_.Item1 -RepetitionInterval $_.Item2.Item1 -RepetitionDuration $_.Item2.Item2 -Once } } elseif ($Daily) { $ScheduledAt | %{New-ScheduledTaskTrigger -At $_ -Daily} } elseif ($Once) { $ScheduledAt | %{New-ScheduledTaskTrigger -At $_ -Once} } return $trigger } function EnableDisableScheduleTask { [OutputType([Void])] [CmdletBinding()] param ( [bool]$Disable ) switch ($Disable) { $true { $currentTask | Disable-ScheduledTask return; } $false { $currentTask | Enable-ScheduledTask return; } } } } } # file loaded from path : \functions\Helper\ScheduledTask\Set-ValentiaScheduledTask.ps1 #Requires -Version 3.0 #-- Scheduler Task Functions --# <# .SYNOPSIS Test is TaskScheduler is same prameter. .DESCRIPTION You can test is scheduled task setting is desired. .NOTES Author: guitarrapc Created: 23/Feb/2015 .EXAMPLE $param = @{ Execute = "powershell.exe" TaskName = "hoge" ScheduledAt = [datetime]"2015/1/1 0:0:0" Once = $true } Set-ValentiaScheduledTask @param -Force $true Test-ValentiaScheduledTask ` -TaskName hoge ` -Execute "powershell.exe" -Verbose ` # This example is minimum testing and will return $true # None passed parameter will skip checking .EXAMPLE Test-ValentiaScheduledTask ` -TaskName hoge ` -Execute "powershell.exe" ` -ScheduledAt ([datetime]"2015/01/1 0:0:0") ` -Once $true # You can add parameter for strict parameter checking. .EXAMPLE $param = @{ Execute = "powershell.exe" Argument = "-Command ''" WorkingDirectory = "" Description = "hoge" TaskName = "hoge" TaskPath = "\hoge\" ScheduledAt = [datetime]"2015/1/1 0:0:0" #Daily = $true Once = $true Disable = $true Hidden = $true Credential = Get-ValentiaCredential } Set-ValentiaScheduledTask @param -Force $true Test-ValentiaScheduledTask ` -TaskName hoge ` -TaskPath "\hoge\" ` -Execute "powershell.exe" ` -Argument "-Command ''" ` -Description hoge ` -Credential (Get-ValentiaCredential) ` -ScheduledAt ([datetime]"2015/01/1 0:0:0") ` -Once $true # Testing scheduled task would return true .EXAMPLE Test-ValentiaScheduledTask ` -TaskName hoge ` -TaskPath "\hoge\" ` -Execute "powershell.exe" ` -Argument "-Command ''" ` -Description hoge ` -Credential (Get-ValentiaCredential) ` -ScheduledAt ([datetime]"2015/01/1 0:0:0") ` -Daily $true -Debug -Verbose # Testing scheduled task would return false as Daily is invalid. (Should check Once). # You can check progress with -Debug and -Verbose switch .LINK https://github.com/guitarrapc/valentia/wiki/TaskScheduler-Automation #> function Test-ValentiaScheduledTask { [OutputType([bool])] [CmdletBinding(DefaultParameterSetName = "ScheduledDuration")] param ( [parameter(mandatory = $true, Position = 0)] [string]$TaskName, [parameter(mandatory = $false, Position = 1)] [string]$TaskPath = "\", [parameter(mandatory = $false, Position = 2)] [string]$Execute, [parameter(mandatory = $false, Position = 3)] [string]$Argument, [parameter(mandatory = $false, Position = 4)] [string]$WorkingDirectory, [parameter(mandatory = $false, Position = 5)] [datetime[]]$ScheduledAt, [parameter(mandatory = $false, Position = 6, parameterSetName = "ScheduledDuration")] [TimeSpan[]]$ScheduledTimeSpan, [parameter(mandatory = $false, Position = 7, parameterSetName = "ScheduledDuration")] [TimeSpan[]]$ScheduledDuration, [parameter(mandatory = $false, Position = 8, parameterSetName = "Daily")] [bool]$Daily = $false, [parameter(mandatory = $false, Position = 9, parameterSetName = "Once")] [bool]$Once = $false, [parameter(mandatory = $false, Position = 10)] [string]$Description, [parameter(mandatory = $false, Position = 11)] [PScredential]$Credential, [parameter(mandatory = $false, Position = 12)] [bool]$Disable, [parameter(mandatory = $false, Position = 13)] [bool]$Hidden, [parameter(mandatory = $false, Position = 14)] [TimeSpan]$ExecutionTimeLimit = [TimeSpan]::FromDays(3), [parameter(mandatory = $false,Position = 15)] [ValidateSet("At", "Win8", "Win7", "Vista", "V1")] [string]$Compatibility, [parameter(mandatory = $false,Position = 16)] [ValidateSet("Highest", "Limited")] [string]$Runlevel ) begin { function GetScheduledTask { [OutputType([HashTable])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [Microsoft.Management.Infrastructure.CimInstance[]]$ScheduledTask, [parameter(Mandatory = $true)] [string]$Parameter, [parameter(Mandatory = $true)] [string]$Value ) Write-Debug ("Checking {0} is exists with : {1}" -f $parameter, $Value) $task = $root | where $Parameter -eq $Value $uniqueValue = $task.$Parameter | sort -Unique $result = $uniqueValue -eq $Value Write-Verbose ("{0} : {1} ({2})" -f $Parameter, $result, $uniqueValue) return @{ task = $task result = $result } } function TestScheduledTask { [OutputType([bool])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [Microsoft.Management.Infrastructure.CimInstance]$ScheduledTask, [parameter(Mandatory = $true)] [ValentiaScheduledParameterType]$Type, [parameter(Mandatory = $true)] [string]$Parameter, [parameter(Mandatory = $false)] [PSObject]$Value, [bool]$IsExist ) # skip when Parameter not use if ($IsExist -eq $false) { Write-Debug ("Skipping {0} as value not passed to function." -f $Parameter) return $true } # skip null if ($Value -eq $null) { Write-Debug ("Skipping {0} as passed value '{1}' is null." -f $Parameter, $Value) return $true } Write-Debug ("Checking {0} is match with : {1}" -f $Parameter, $Value) $target = switch ($Type) { ([ValentiaScheduledParameterType]::Root) { $ScheduledTask.$Parameter | sort -Unique } ([ValentiaScheduledParameterType]::Actions) { $ScheduledTask.Actions.$Parameter | sort -Unique } ([ValentiaScheduledParameterType]::Principal) { $ScheduledTask.Principal.$Parameter | sort -Unique } ([ValentiaScheduledParameterType]::Settings) { $ScheduledTask.Settings.$Parameter | sort -Unique } ([ValentiaScheduledParameterType]::Triggers) { $ScheduledTask.Triggers.$Parameter | sort -Unique } } if ($Value.GetType().FullName -eq "System.String") { if (($target -eq $null) -and ([string]::IsNullOrEmpty($Value))) { return $true Write-Verbose ("{0} : {1} ({2})" -f $Parameter, $result, $target) } } # value check $result = $target -eq $Value Write-Verbose ("{0} : {1} ({2})" -f $Parameter, $result, $target) return $result } function TestScheduledTaskExecutionTimeLimit { [OutputType([bool])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [Microsoft.Management.Infrastructure.CimInstance]$ScheduledTask, [parameter(Mandatory = $false)] [TimeSpan]$Value ) $private:parameter = "ExecutionTimeLimit" # skip null if ($Value -eq $null) { Write-Debug ("Skipping {0} as passed value is null" -f $Parameter) return $true } Write-Debug ("Checking {0} is match with : {1}min" -f $parameter, $Value.TotalMinutes) $executionTimeLimitTimeSpan = [System.Xml.XmlConvert]::ToTimeSpan($ScheduledTask.Settings.$parameter) $result = $Value -eq $executionTimeLimitTimeSpan Write-Verbose ("{0} : {1} ({2}min)" -f $parameter, $result, $executionTimeLimitTimeSpan.TotalMinutes) return $result } function TestScheduledTaskDisable { [OutputType([bool])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [Microsoft.Management.Infrastructure.CimInstance]$ScheduledTask, [parameter(Mandatory = $false)] [PSObject]$Value, [bool]$IsExist ) # skip when Parameter not use if ($IsExist -eq $false) { Write-Debug ("Skipping {0} as value not passed to function." -f $Parameter) return $true } # convert Enable -> Disable $target = $ScheduledTask.Settings.Enabled -eq $false # value check Write-Debug ("Checking {0} is match with : {1}" -f "Disable", $Value) $result = $target -eq $Value Write-Verbose ("{0} : {1} ({2})" -f "Disable", $result, $target) return $result } function TestScheduledTaskScheduledAt { [OutputType([bool])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [Microsoft.Management.Infrastructure.CimInstance]$ScheduledTask, [parameter(Mandatory = $false)] [DateTime[]]$Value ) $private:parameter = "StartBoundary" # skip null if ($Value -eq $null) { Write-Debug ("Skipping {0} as passed value is null" -f $Parameter) return $true } $valueCount = ($Value | measure).Count $scheduleCount = ($ScheduledTask.Triggers | measure).Count if ($valueCount -ne $scheduleCount) { throw New-Object System.ArgumentException ("Argument length not match with current ScheduledAt {0} and passed ScheduledAt {1}." -f $scheduleCount, $valueCount) } $result = @() for ($i = 0; $i -le ($ScheduledTask.Triggers.$parameter.Count -1); $i++) { Write-Debug ("Checking {0} is match with : {1}" -f $parameter, $Value[$i]) $startBoundaryDateTime = [System.Xml.XmlConvert]::ToDateTime(@($ScheduledTask.Triggers.$parameter)[$i]) $result += @($Value)[$i] -eq $startBoundaryDateTime Write-Verbose ("{0} : {1} ({2})" -f $parameter, $result[$i], $startBoundaryDateTime) } return $result | sort -Unique } function TestScheduledTaskScheduledRepetition { [OutputType([bool])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [Microsoft.Management.Infrastructure.CimInstance]$ScheduledTask, [parameter(Mandatory = $true)] [string]$Parameter, [parameter(Mandatory = $false)] [TimeSpan[]]$Value ) # skip null if ($Value -eq $null) { Write-Debug ("Skipping {0} as passed value is null" -f $Parameter) return $true } $valueCount = ($Value | measure).Count $scheduleCount = ($ScheduledTask.Triggers | measure).Count if ($valueCount -ne $scheduleCount) { throw New-Object System.ArgumentException ("Arugument length not match with current ScheduledAt {0} and passed ScheduledAt {1}." -f $scheduleCount, $valueCount) } $result = @() for ($i = 0; $i -le ($ScheduledTask.Triggers.Repetition.$Parameter.Count -1); $i++) { Write-Debug ("Checking {0} is match with : {1}" -f $Parameter, $Value[$i]) $target = [System.Xml.XmlConvert]::ToTimeSpan(@($ScheduledTask.Triggers.Repetition.$Parameter)[$i]) $result = @($Value)[$i] -eq $target Write-Verbose ("{0} : {1} ({2})" -f $Parameter, $result[$i], $target.TotalMinutes) } return $result | sort -Unique } function TestScheduledTaskTriggerBy { [OutputType([bool])] [CmdletBinding()] param ( [parameter(Mandatory = $true)] [System.Xml.XmlDocument]$ScheduledTaskXml, [parameter(Mandatory = $true)] [string]$Parameter, [parameter(Mandatory = $false)] [PSObject]$Value, [bool]$IsExist ) # skip when Parameter not use if ($IsExist -eq $false) { Write-Debug ("Skipping {0} as value not passed to function." -f $Parameter) return $true } $trigger = ($ScheduledTaskXml.task.Triggers.CalendarTrigger.ScheduleByDay | measure).Count $result = $false switch ($Parameter) { "Daily" { Write-Debug "Checking Trigger is : Daily" $result = if ($Value) { $trigger -ne 0 } else { $trigger-eq 0 } Write-Verbose ("{0} : {1} ({2})" -f $Parameter, $result, $trigger) } "Once" { Write-Debug "Checking Trigger is : Once" $result = if ($Value) { $trigger -eq 0 } else { $trigger -ne 0 } Write-Verbose ("{0} : {1} ({2})" -f $Parameter, $result, $trigger) } } return $result } } end { #region Root $private:result = $true # get whole task $root = Get-ScheduledTask # TaskPath $taskResult = GetScheduledTask -ScheduledTask $root -Parameter TaskPath -Value $TaskPath if ($taskResult.result -eq $false){ return $taskResult.Result; } # TaskName $taskResult = GetScheduledTask -ScheduledTask $taskResult.task -Parameter Taskname -Value $TaskName if ($taskResult.result -eq $false){ return $taskResult.Result; } # default $current = $taskResult.task if (($current | measure).Count -eq 0){ return $false } # export as xml [xml]$script:xml = Export-ScheduledTask -TaskName $current.TaskName -TaskPath $current.TaskPath # Description $result = TestScheduledTask -ScheduledTask $current -Parameter Description -Value $Description -Type ([ValentiaScheduledParameterType]::Root) -IsExist ($PSBoundParameters.ContainsKey('Description')) if ($result -eq $false){ return $result; } #endregion #region Action # Execute $result = TestScheduledTask -ScheduledTask $current -Parameter Execute -Value $Execute -Type ([ValentiaScheduledParameterType]::Actions) -IsExist ($PSBoundParameters.ContainsKey('Execute')) if ($result -eq $false){ return $result; } # Arguments $result = TestScheduledTask -ScheduledTask $current -Parameter Arguments -Value $Argument -Type ([ValentiaScheduledParameterType]::Actions) -IsExist ($PSBoundParameters.ContainsKey('Argument')) if ($result -eq $false){ return $result; } # WorkingDirectory $result = TestScheduledTask -ScheduledTask $current -Parameter WorkingDirectory -Value $WorkingDirectory -Type ([ValentiaScheduledParameterType]::Actions) -IsExist ($PSBoundParameters.ContainsKey('WorkingDirectory')) if ($result -eq $false){ return $result; } #endregion #region Principal # UserId $result = TestScheduledTask -ScheduledTask $current -Parameter UserId -Value $Credential.UserName -Type ([ValentiaScheduledParameterType]::Principal) -IsExist ($PSBoundParameters.ContainsKey('Credential')) if ($result -eq $false){ return $result; } # RunLevel $result = TestScheduledTask -ScheduledTask $current -Parameter RunLevel -Value $Runlevel -Type ([ValentiaScheduledParameterType]::Principal) -IsExist ($PSBoundParameters.ContainsKey('Runlevel')) if ($result -eq $false){ return $result; } #endregion #region Settings # Compatibility $result = TestScheduledTask -ScheduledTask $current -Parameter Compatibility -Value $Compatibility -Type ([ValentiaScheduledParameterType]::Settings) -IsExist ($PSBoundParameters.ContainsKey('Compatibility')) if ($result -eq $false){ return $result; } # ExecutionTimeLimit $result = TestScheduledTaskExecutionTimeLimit -ScheduledTask $current -Value $ExecutionTimeLimit if ($result -eq $false){ return $result; } # Hidden $result = TestScheduledTask -ScheduledTask $current -Parameter Hidden -Value $Hidden -Type ([ValentiaScheduledParameterType]::Settings) -IsExist ($PSBoundParameters.ContainsKey('Hidden')) if ($result -eq $false){ return $result; } # Disable $result = TestScheduledTaskDisable -ScheduledTask $current -Value $Disable -IsExist ($PSBoundParameters.ContainsKey('Disable')) if ($result -eq $false){ return $result; } #endregion #region Triggers # SchduledAt $result = TestScheduledTaskScheduledAt -ScheduledTask $current -Value $ScheduledAt if ($result -contains $false){ return $false; } # ScheduledTimeSpan (Repetition Interval) $result = TestScheduledTaskScheduledRepetition -ScheduledTask $current -Value $ScheduledTimeSpan -Parameter Interval if ($result -contains $false){ return $false; } # ScheduledDuration (Repetition Duration) $result = TestScheduledTaskScheduledRepetition -ScheduledTask $current -Value $ScheduledDuration -Parameter Duration if ($result -contains $false){ return $false; } # Daily $result = TestScheduledTaskTriggerBy -ScheduledTaskXml $xml -Parameter Daily -Value $Daily -IsExist ($PSBoundParameters.ContainsKey('Daily')) if ($result -eq $false){ return $result; } # Once $result = TestScheduledTaskTriggerBy -ScheduledTaskXml $xml -Parameter Once -Value $Once -IsExist ($PSBoundParameters.ContainsKey('Once')) if ($result -eq $false){ return $result; } #endregion return $result } } # file loaded from path : \functions\Helper\ScheduledTask\Test-ValentiaScheduledTask.ps1 #Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# <# .SYNOPSIS PowerShell Sed alternate function .DESCRIPTION This cmdlet replace string in the file as like as sed on linux .NOTES Author: guitarrapc Created: 04/Oct/2013 .EXAMPLE Invoke-ValentiaSed -path D:\Deploygroup\*.ps1 -searchPattern "^10.0.0.10$" -replaceWith "#10.0.0.10" -overwrite -------------------------------------------- replace regex ^10.0.0.10$ with # 10.0.0.10 and replace file. (like sed -f "s/^10.0.0.10$/#10.0.0.10" -i) .EXAMPLE Invoke-ValentiaSed -path D:\Deploygroup\*.ps1 -searchPattern "^#10.0.0.10$" -replaceWith "10.0.0.10" -------------------------------------------- replace regex ^10.0.0.10$ with # 10.0.0.10 and not replace file. #> function Invoke-ValentiaSed { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [string]$path, [parameter(position = 1, mandatory = $true, ValueFromPipeline = 1,ValueFromPipelineByPropertyName = 1)] [string]$searchPattern, [parameter(position = 2, mandatory = $true,ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [string]$replaceWith, [parameter(position = 3, mandatory = $false)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode, [parameter(position = 4, mandatory = $false)] [switch]$overWrite, [parameter(position = 5, mandatory = $false)] [switch]$compress ) $read = Select-String -Path $path -Pattern $searchPattern -Encoding $encoding $read.path ` | sort -Unique ` | %{Write-Warning ("Executing string replace for '{0}'. 'overwrite': '{1}'." -f $path, ($PSBoundParameters.overWrite.IsPresent -eq $true)) $path = $_ $extention = [System.IO.Path]::GetExtension($path) if ($overWrite) { $tmpextension = "$extention" + "______" $tmppath = [System.IO.Path]::ChangeExtension($path,$tmpextension) ("execute replace string '{0}' with '{1}' for file '{2}', Output to '{3}'" -f $searchPattern, $replaceWith, $path, $tmppath) | Write-ValentiaVerboseDebug Get-Content -Path $path ` | %{$_ -replace $searchPattern,$replaceWith} ` | Out-File -FilePath $tmppath -Encoding $valentia.fileEncode -Force -Append ("remove original file '{0}'" -f $path, $tmppath) | Write-ValentiaVerboseDebug Remove-Item -Path $path -Force ("rename tmp file '{0}' to original file '{1}'" -f $tmppath, $path) | Write-ValentiaVerboseDebug Rename-Item -Path $tmppath -NewName ([System.IO.Path]::ChangeExtension($tmppath,$extention)) } else { ("execute replace string '{0}' with '{1}' for file '{2}'" -f $searchPattern, $replaceWith, $path) | Write-ValentiaVerboseDebug if (-not $PSBoundParameters.Compress.IsPresent) { Get-Content -Path $path -Encoding $encoding ` | %{$_ -replace $searchPattern,$replaceWith} } } } } # file loaded from path : \functions\Helper\Sed\Invoke-ValentiaSed.ps1 #Requires -Version 3.0 #-- SymbolicLink Functions --# <# .SYNOPSIS This function will detect only SymbolicLink items. .DESCRIPTION PowerShell SymbolicLink function. Alternative to mklink Symbolic Link. This function detect where input file fullpath item is file/directory SymbolicLink, then only Ennumerate if it is SymbolicLink. .NOTES Author: guitarrapc Created: 12/Aug/2014 .EXAMPLE ls d:\ | Get-ValentiaSymbolicLink -------------------------------------------- Pipeline Input to detect SymbolicLink items. .EXAMPLE Get-ValentiaSymbolicLink (ls d:\).FullName -------------------------------------------- Parameter Input to detect SymbolicLink items. #> function Get-ValentiaSymbolicLink { [OutputType([System.IO.DirectoryInfo[]])] [cmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('FullName')] [String[]]$Path ) begin { $private:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom function IsFile ([string]$Path) { if ([System.IO.File]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as File." -f $Path) return [System.IO.FileInfo]($Path) } } function IsDirectory ([string]$Path) { if ([System.IO.Directory]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as Directory." -f $Path) return [System.IO.DirectoryInfo] ($Path) } } function IsFileReparsePoint ([System.IO.FileInfo]$Path) { Write-Verbose ('File attribute detected as ReparsePoint') $fileAttributes = [System.IO.FileAttributes]::Archive, [System.IO.FileAttributes]::ReparsePoint -join ', ' $attribute = [System.IO.File]::GetAttributes($Path) $result = $attribute -eq $fileAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $attribute) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $attribute) return $result } } function IsDirectoryReparsePoint ([System.IO.DirectoryInfo]$Path) { $directoryAttributes = [System.IO.FileAttributes]::Directory, [System.IO.FileAttributes]::ReparsePoint -join ', ' $result = $Path.Attributes -eq $directoryAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $Path.Attributes) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $Path.Attributes) return $result } } } process { try { $Path ` | %{ if ($file = IsFile -Path $_) { if (IsFileReparsePoint -Path $file.FullName) { # [Valentia.SymbolicLinkGet]::GetSymbolicLinkTarget() # [System.Type]::GetType($typeQualifiedName)::GetSymbolicLinkTarget() $symTarget = [Valentia.CS.SymbolicLink]::GetSymbolicLinkTarget($file.FullName) Add-Member -InputObject $file -MemberType NoteProperty -Name SymbolicPath -Value $symTarget -Force return $file } } elseif ($directory = IsDirectory -Path $_) { if (IsDirectoryReparsePoint -Path $directory.FullName) { # [Valentia.SymbolicLinkGet]::GetSymbolicLinkTarget() # [System.Type]::GetType($typeQualifiedName)::GetSymbolicLinkTarget() $symTarget = [Valentia.CS.SymbolicLink]::GetSymbolicLinkTarget($directory.FullName) Add-Member -InputObject $directory -MemberType NoteProperty -Name SymbolicPath -Value $symTarget -Force return $directory } } } } catch { throw $_ } } } # file loaded from path : \functions\Helper\SymbolicLink\Get-ValentiaSymbolicLink.ps1 #Requires -Version 3.0 #-- SymbolicLink Functions --# <# .SYNOPSIS This function will Remove only SymbolicLink items. .DESCRIPTION PowerShell SymbolicLink function. Alternative to mklink Symbolic Link. This function detect where input file fullpath item is file/directory SymbolicLink, then only remove if it is SymbolicLink. You don't need to care about input Path is FileInfo or DirectoryInfo. .NOTES Author: guitarrapc Created: 12/Aug/2014 .EXAMPLE ls d:\ | Remove-ValentiaSymbolicLink -------------------------------------------- Pipeline Input to detect SymbolicLink items. .EXAMPLE Remove-ValentiaSymbolicLink (ls d:\).FullName -------------------------------------------- Parameter Input to detect SymbolicLink items. #> function Remove-ValentiaSymbolicLink { [OutputType([Void])] [cmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('FullName')] [String[]]$Path ) begin { $script:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom function IsFile ([string]$Path) { if ([System.IO.File]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as File." -f $Path) return [System.IO.FileInfo]($Path) } } function IsDirectory ([string]$Path) { if ([System.IO.Directory]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as Directory." -f $Path) return [System.IO.DirectoryInfo] ($Path) } } function IsFileReparsePoint ([System.IO.FileInfo]$Path) { Write-Verbose ('File attribute detected as ReparsePoint') $fileAttributes = [System.IO.FileAttributes]::Archive, [System.IO.FileAttributes]::ReparsePoint -join ', ' $attribute = [System.IO.File]::GetAttributes($Path.fullname) $result = $attribute -eq $fileAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $attribute) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $attribute) return $result } } function IsDirectoryReparsePoint ([System.IO.DirectoryInfo]$Path) { $directoryAttributes = [System.IO.FileAttributes]::Directory, [System.IO.FileAttributes]::ReparsePoint -join ', ' $result = $Path.Attributes -eq $directoryAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $Path.Attributes) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $Path.Attributes) return $result } } function RemoveFileReparsePoint ([System.IO.FileInfo]$Path) { [System.IO.File]::Delete($Path.FullName) } function RemoveDirectoryReparsePoint ([System.IO.DirectoryInfo]$Path) { [System.IO.Directory]::Delete($Path.FullName) } } process { try { $Path ` | %{ if ($file = IsFile -Path $_) { if (IsFileReparsePoint -Path $file) { RemoveFileReparsePoint -Path $file } } elseif ($directory = IsDirectory -Path $_) { if (IsDirectoryReparsePoint -Path $directory) { RemoveDirectoryReparsePoint -Path $directory } } } } catch { throw $_ } } } # file loaded from path : \functions\Helper\SymbolicLink\Remove-ValentiaSymbolicLink.ps1 #Requires -Version 3.0 <# .SYNOPSIS This function will Set SymbolicLink items for desired Path. .DESCRIPTION PowerShell SymbolicLink function. Alternative to mklink Symbolic Link. This function will create Symbolic Link for input file fullpath. Also it works as like LINQ Zip method for different number items was passed for each -Path and -SymbolicPath. As Zip use minimal number item, this function also follow it. .NOTES Author: guitarrapc Created: 12/Aug/2014 .EXAMPLE ls d:\ ` | select -Last 2 ` | %{ @{ Path = $_.FullName SymbolicPath = Join-Path "d:\zzzzz" $_.Name } } ` | Set-SymbolicLink -Verbose-------------------------------------------- Pipeline Input to create SymbolicLink items. This will make symbolic in d:\zzzz with samename of input Path name. This means you can easily create Symbolic for different Path. .EXAMPLE Set-SymbolicLink -Path (ls d:\ | select -Last 2).FullName -SymbolicPath d:\hoge1, d:\hoge2, d:\hoge3 -Verbose -------------------------------------------- Parameter Input. This will create Symbolic Link for -Path input 2 items, with -SymbolicPath input d:\hoge1 and d:\hoge2. As number input was less with -Path, d:\hoge3 will be ignore. #> function Set-ValentiaSymbolicLink { [OutputType([Void])] [cmdletBinding(DefaultParameterSetName = "ForceFile")] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('TargetPath')] [Alias('FullName')] [String[]]$Path, [parameter(mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = 1)] [String[]]$SymbolicPath, [parameter(mandatory = $false, Position = 2, ValueFromPipelineByPropertyName = 1, ParameterSetName = "ForceFile")] [bool]$ForceFile = $false, [parameter(mandatory = $false, Position = 2, ValueFromPipelineByPropertyName = 1, ParameterSetName = "ForceDirectory")] [bool]$ForceDirectory = $false ) begin { $private:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom $prefix = "_" $i = 0 # Initialize prefix Length function IsFile ([string]$Path) { if ([System.IO.File]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as File." -f $Path) return [System.IO.FileInfo]($Path) } } function IsDirectory ([string]$Path) { if ([System.IO.Directory]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as Directory." -f $Path) return [System.IO.DirectoryInfo] ($Path) } } function IsFileAttribute ([System.IO.FileInfo]$Path) { $fileAttributes = [System.IO.FileAttributes]::Archive $attribute = [System.IO.File]::GetAttributes($Path.fullname) $result = $attribute -eq $fileAttributes if ($result) { Write-Verbose ('Attribute detected as File Archive. : {0}' -f $attribute) return $result } else { Write-Verbose ('Attribute detected as NOT File archive. : {0}' -f $attribute) return $result } } function IsDirectoryAttribute ([System.IO.DirectoryInfo]$Path) { $directoryAttributes = [System.IO.FileAttributes]::Directory $result = $Path.Attributes -eq $directoryAttributes if ($result) { Write-Verbose ('Attribute detected as Directory. : {0}' -f $Path.Attributes) return $result } else { Write-Verbose ('Attribute detected as NOT Directory. : {0}' -f $Path.Attributes) return $result } } } process { # Work as like LINQ Zip() method $zip = New-ValentiaZipPairs -first $Path -second $SymbolicPath foreach ($x in $zip) { # reverse original key $targetPath = $x.item1 $SymbolicNewPath = $x.item2 if ($ForceFile -eq $true) { [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $Path, $false) } elseif ($ForceDirectory -eq $true) { [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $Path, $true) } elseif ($file = IsFile -Path $targetPath) { # Check File Type if (IsFileAttribute -Path $file) { Write-Verbose ("symbolicPath : '{0}', target : '{1}', isDirectory : '{2}'" -f $SymbolicNewPath, $file.fullname, $false) [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $file.fullname, $false) } } elseif ($directory = IsDirectory -Path $targetPath) { # Check Directory Type if (IsDirectoryAttribute -Path $directory) { Write-Verbose ("symbolicPath : '{0}', target : '{1}', isDirectory : '{2}'" -f $SymbolicNewPath, $directory.fullname, $true) [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $directory.fullname, $true) } } } } } # file loaded from path : \functions\Helper\SymbolicLink\Set-ValentiaSymbolicLink.ps1 #Requires -Version 3.0 #-- SymbolicLink Functions --# <# .SYNOPSIS This function will Test whether target path is Symbolic Link or not. .DESCRIPTION If target is Symbolic Link (reparse point), function will return $true. Others, return $false. .NOTES Author: guitarrapc Created: 12/Feb/2015 .EXAMPLE Test-ValentiaSymbolicLink -Path "d:\SymbolicLink" -------------------------------------------- As Path is Symbolic Link, this returns $true. #> function Test-ValentiaSymbolicLink { [OutputType([System.IO.DirectoryInfo[]])] [cmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('FullName')] [String]$Path ) begin { $script:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom } process { $result = Get-ValentiaSymbolicLink -Path $Path if ($null -eq $result) { return $false } return $true } } # file loaded from path : \functions\Helper\SymbolicLink\Test-ValentiaSymbolicLink.ps1 #Requires -Version 3.0 #-- Helper Function --# <# .SYNOPSIS Convert PowerShell script to Valentia Task format .DESCRIPTION You can specify "filepath for PowerShell Script" or "scriptBlock". This Cmldet will automatically add "task $taskname -Action {" on top and "}" on bottom. .NOTES Author: guitarrapc Created: 18/Nov/2013 .EXAMPLE ConvertTo-ValentiaTask -inputFilePath d:\hogehoge.ps1 -taskName hoge -outputFilePath d:\fuga.ps1 -------------------------------------------- Convert PowerShell Script written in inputFilePath into valentia Task file. .EXAMPLE ConvertTo-ValentiaTask -scriptBlock {ps} -taskName test -outputFilePath d:\test.ps1 -------------------------------------------- Convert ScriptBlock into valentia Task file. #> function ConvertTo-ValentiaTask { [CmdletBinding(DefaultParameterSetName = "File")] param ( # Path to PowerShell Script .ps1 you want to convert into Task [Parameter(Position = 0, mandatory = $true, ParameterSetName = "File")] [string]$inputFilePath, # Path to PowerShell Script .ps1 you want to convert into Task [Parameter(Position = 1, mandatory = $false, ParameterSetName = "File")] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode, # Script Block to Convert into Task [Parameter(Position = 0, mandatory = $true, ParameterSetName = "Script")] [scriptBlock]$scriptBlock, # Task Name you want to set [Parameter(Position = 1, mandatory = $true)] [string]$taskName, # Path to output Task [Parameter(Position = 2, mandatory = $true)] [string]$outputFilePath ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom if ($PSBoundParameters.inputFilePath) { if (Test-Path $inputFilePath) { $read = Get-Content -Path $inputFilePath -Encoding $encoding -Raw } else { throw ("Path not found exception. file path '{0}' not exists." -f $inputFilePath) } } elseif ($PSBoundParameters.scriptBlock) { $read = $scriptBlock } } process { try { # create String Builder $sb = New-Object System.Text.StringBuilder # append Header $sb.AppendLine($("Task {0} -Action {1}" -f $taskName,"{")) > $null # append Original source $sb.AppendLine($read) > $null # append end charactor $sb.AppendLine("}") > $null # serialize $output = $sb.ToString() } finally { $sb.Clear() > $null } } end { $output | Out-File -FilePath $outputFilePath -Encoding $valentia.fileEncode } } # file loaded from path : \functions\Helper\Task\ConvertTo-ValentiaTask.ps1 #Requires -Version 3.0 #-- Public Module Functions to load Task --# # Task <# .SYNOPSIS Load Task File format into $valentia.context.tasks.$taskname hashtable. .DESCRIPTION Loading ps1 file which format is task <taskname> -Action { <scriptblock> } .NOTES Author: guitarrapc Created: 20/June/2013 .EXAMPLE task taskname -Action { What you want to do in ScriptBlock} -------------------------------------------- This is format sample. .EXAMPLE task lstest -Action { Get-ChildItem c:\ } -------------------------------------------- Above example will create taskkey as lstest, run "Get-ChildItem c:\" when invoke. #> function Get-ValentiaTask { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input TaskName you want to set and not dupricated.")] [string]$Name = $null, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Write ScriptBlock Action to execute with this task.")] [scriptblock]$Action = $null ) # Load Task Write-Verbose $valeWarningMessages.warn_import_task_begin $newTask = @{ Name = $Name Action = $Action } # convert into LowerCase for keyname Write-Verbose $valeWarningMessages.warn_import_task_end $taskKey = $Name.ToLower() # Get current context variables Write-Verbose $valeWarningMessages.warn_get_current_context $currentContext = $valentia.context.Peek() # Check dupricate key name if ($currentContext.tasks.ContainsKey($taskKey)) { throw $valeErrorMessages.error_duplicate_task_name -F $Name } else { $valeWarningMessages.warn_set_taskkey | Write-ValentiaVerboseDebug $currentContext.tasks.$taskKey = $newTask } # return taskkey to determin key name in $valentia.context.tasks.$taskkey return $taskKey } # file loaded from path : \functions\Helper\Task\Get-ValentiaTask.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Create New Local User for Deployment .DESCRIPTION Deployment will use deploy user account credential to avoid any change for administartor. You must add all this user credential for each clients. # User Flag Property Samples. You should combinate these 0x00zz if required. # # &H0001 Run LogOn Script  # 0X0001 ADS_UF_SCRIPT # # &H0002 Account Disable # 0X0002 ADS_UF_ACCOUNTDISABLE # # &H0008 Account requires Home Directory # 0X0008 ADS_UF_HOMEDIR_REQUIRED # # &H0010 Account Lockout # 0X0010 ADS_UF_LOCKOUT # # &H0020 No Password reqyured for account # 0X0020 ADS_UF_PASSWD_NOTREQD # # &H0040 No change Password # 0X0040 ADS_UF_PASSWD_CANT_CHANGE # # &H0080 Allow Encypted Text Password # 0X0080 ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED # # 0X0100 ADS_UF_TEMP_DUPLICATE_ACCOUNT # 0X0200 ADS_UF_NORMAL_ACCOUNT # 0X0800 ADS_UF_INTERDOMAIN_TRUST_ACCOUNT # 0X1000 ADS_UF_WORKSTATION_TRUST_ACCOUNT # 0X2000 ADS_UF_SERVER_TRUST_ACCOUNT # # &H10000 Password infinit # 0X10000 ADS_UF_DONT_EXPIRE_PASSWD # # 0X20000 ADS_UF_MNS_LOGON_ACCOUNT # # &H40000 Smart Card Required # 0X40000 ADS_UF_SMARTCARD_REQUIRED # # 0X80000 ADS_UF_TRUSTED_FOR_DELEGATION # 0X100000 ADS_UF_NOT_DELEGATED # 0x200000 ADS_UF_USE_DES_KEY_ONLY # # 0x400000 ADS_UF_DONT_REQUIRE_PREAUTH # # &H800000 Password expired # 0x800000 ADS_UF_PASSWORD_EXPIRED # # 0x1000000 ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE New-valentiaOSUser -------------------------------------------- Recommend - Secure Input. secure prompt will up and mask your PASSWORD input as *****. .EXAMPLE New-valentiaOSUser -Password "1231231qawerqwe87$%" -------------------------------------------- NOT-Recommend - Unsecure Input Visible prompt will up and non-mask your PASSWORD input as *****. #> function New-ValentiaOSUser { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $false, HelpMessage = "PSCredential for New OS User setup.")] [PSCredential]$credential = (Get-Credential -Credential $valentia.users.deployUser), [parameter(position = 1, mandatory = $false, HelpMessage = "User account belonging UserGroup.")] [string]$Group = $valentia.group.Name, [parameter(position = 2, mandatory = $false, HelpMessage = "User flag bit to set.")] [string]$UserFlag = $valentia.group.userFlag ) process { if ($IsUserExist) { Set-UserPassword @paramUser } else { New-User @paramUser } $Domain= Get-DomainName $paramUserFlag = @{ targetUser = New-Object System.DirectoryServices.DirectoryEntry(("WinNT://{0}/{1}/{2}" -f $Domain, $HostPC, $user)) UserFlag = $UserFlag } Set-UserFlag @paramUserFlag if ((Get-UserAndGroup @paramUserAndGroup).Groups -ne $Group) { Add-UserToUserGroup @paramGroup } } end { Get-UserAndGroup @paramUserAndGroup } begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $HostPC = [System.Environment]::MachineName $user = $credential.UserName $DirectoryComputer = New-Object System.DirectoryServices.DirectoryEntry(("WinNT://{0},computer" -f $HostPC)) $IsUserExist = Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount='true'" | where Name -eq $user $paramUser = @{ user = $user HostPC = $HostPC Credential = $credential } $paramGroup = @{ Group = $Group HostPC = $HostPC user = $user } $paramUserAndGroup = @{ DirectoryComputer = $DirectoryComputer user = $user } function Get-DomainName { if ((Get-WMIObject Win32_ComputerSystem).PartOfDomain) { $dn = (Get-CimInstance -ClassName win32_computersystem).Domain return (Get-CimInstance -ClassName Win32_NTDomain | where DNSForestName -eq $dn).DomainName } else { return (Get-CimInstance -ClassName win32_computersystem).Domain } } function New-User ($user, $HostPC, $credential) { ("User '{0}' not exist, start creating user." -f $user) | Write-ValentiaVerboseDebug $NewUser = $DirectoryComputer.Create("user", $user) $NewUser.SetPassword(($credential.GetNetworkCredential().password)) $NewUser.SetInfo() } function Set-UserPassword ($user, $HostPC, $credential) { ("User '{0}' already exist, start reset password." -f $user) | Write-ValentiaVerboseDebug $SetUser = New-Object System.DirectoryServices.DirectoryEntry(("WinNT://{0}/{1}" -f $HostPC, $user)) $SetUser.psbase.invoke('SetPassword', $credential.GetNetworkCredential().Password) } function Set-UserFlag ($targetUser, $UserFlag) { "Set userflag to define account as bor '{0}'" -f $UserFlag | Write-ValentiaVerboseDebug $userFlags = $targetUser.Get("UserFlags") $userFlags = $userFlags -bor $UserFlag $targetUser.Put("UserFlags", $userFlags) $targetUser.SetInfo() } function Add-UserToUserGroup ($Group, $HostPC, $user) { ("Assign User to UserGroup '{0}'" -f $Group) | Write-ValentiaVerboseDebug $DirectoryGroup = $DirectoryComputer.GetObject("group", $Group) $DirectoryGroup.Add(("WinNT://{0}/{1}" -f $HostPC, $user)) } function Get-UserAndGroup ($DirectoryComputer, $user) { $DirectoryComputer.Children ` | where SchemaClassName -eq 'user' ` | where Name -eq $user ` | %{ $groups = $_.Groups() | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} $_ | %{ [PSCustomObject]@{ UserName = $_.Name Groups = $groups } } } } } } # file loaded from path : \functions\Helper\User\New-ValentiaOSUser.ps1 function New-ValentiaZipPairs { [CmdletBinding()] param ( [parameter(mandatory = $false, Position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [PSObject[]]$first, [parameter(mandatory = $false, Position = 1, ValueFromPipelineByPropertyName = 1)] [PSObject[]]$second, [parameter(mandatory = $false, Position = 2, ValueFromPipelineByPropertyName = 1)] [scriptBlock]$resultSelector ) process { if ([string]::IsNullOrWhiteSpace($first)){ break } if ([string]::IsNullOrWhiteSpace($second)){ break } try { $e1 = @($first).GetEnumerator() while ($e1.MoveNext() -and $e2.MoveNext()) { if ($PSBoundParameters.ContainsKey('resultSelector')) { $first = $e1.Current $second = $e2.Current $context = $resultselector.InvokeWithContext( $null, ($psvariable), { (New-Object System.Management.Automation.PSVariable ("first", $first)), (New-Object System.Management.Automation.PSVariable ("second", $second)) } ) $context } else { $tuple = New-Object 'System.Tuple[PSObject, PSObject]' ($e1.Current, $e2.current) $tuple } } } finally { if(($d1 = $e1 -as [IDisposable]) -ne $null) { $d1.Dispose() } if(($d2 = $e2 -as [IDisposable]) -ne $null) { $d2.Dispose() } if(($d3 = $psvariable -as [IDisposable]) -ne $null) {$d3.Dispose() } if(($d4 = $context -as [IDisposable]) -ne $null) {$d4.Dispose() } if(($d5 = $tuple -as [IDisposable]) -ne $null) {$d5.Dispose() } } } begin { $e2 = @($second).GetEnumerator() $psvariable = New-Object 'System.Collections.Generic.List[System.Management.Automation.psvariable]' } } # file loaded from path : \functions\Helper\Utils\New-ValentiaZpPairs.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Get reboot require status for client .DESCRIPTION When Windows Update or Change Hostname event is done, it will requires reboot to take change effect. You can obtain reboot required status with this cmdlet. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Get-ValentiaRebootRequiredStatus -------------------------------------------- Obtain reboot required status. #> function Get-ValentiaRebootRequiredStatus { [CmdletBinding()] param ( ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $WindowsUpdateRebootStatus = $false $FileRenameRebootStatus = $false $WindowsUpdateRebootPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" $FileRenameRebootPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" } process { if (Test-Path $WindowsUpdateRebootPath) { $WindowsUpdateRebootStatus = $true } if (Get-ItemProperty -Path $FileRenameRebootPath | Get-Member -MemberType NoteProperty | where Name -eq "PendingFileRenameOperations") { $FileRenameRebootStatus = $True } $Result = [PSCustomObject]@{ ComputerName = [Net.DNS]::GetHostName() PendingWindowsUpdateReboot= $WindowsUpdateRebootStatus PendingFileRenameReboot = $FileRenameRebootStatus } } end { return $Result } } # file loaded from path : \functions\Helper\Windows\Get-ValentiaRebootRequiredStatus.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# # rename <# .SYNOPSIS Change Computer name as specified usage. .DESCRIPTION To control hosts, set prefix for each client with IPAddress octets. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Set-valentiaHostName -HostUsage web -------------------------------------------- Change Hostname as web-$PrefixHostName-$PrefixIpString-Ip1-Ip2-Ip3-Ip4 #> function Set-ValentiaHostName { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "set usage for the host.")] [string]$HostUsage, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Set Prefix IpString for hostname if required.")] [string]$PrefixIpString = $valentia.prefic.ipstring, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Set this switch to check whatif.")] [switch]$WhatIf ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # Get IpAddress $ipAddress = ([Net.Dns]::GetHostAddresses('').IPAddressToString | Select-String -Pattern "^\d*.\.\d*.\.\d*.\.\d*.").line # Replace . of IpAddress to - $ipAddressString = $ipAddress -replace "\.","-" # Create New Host Name $newHostName = $HostUsage + "-" + $PrefixIpString + $ipAddressString $currentHostName = [Net.Dns]::GetHostName() } process { if ( $currentHostName -eq $newHostName) { Write-Verbose ("Current HostName [ {0} ] was same as new HostName [ {1} ]. Nothing Changed." -f $currentHostName, $newHostName) } else { if ($PSBoundParameters.WhatIf.IsPresent -ne $true) { Write-Warning -Message ("Current HostName [ {0} ] change to New HostName [ {1} ]" -f $currentHostName, $newHostName) Rename-Computer -NewName $newHostName -Force } else { $Host.UI.WriteLine("what if: Current HostName [ {0} ] change to New HostName [ {1} ]" -f $currentHostName, $newHostName) } } } } # file loaded from path : \functions\Helper\Windows\Set-ValentiaHostName.ps1 #Requires -Version 3.0 #-- Helper function --# #-- Check Current PowerShell session is elevated or not --# <# .SYNOPSIS Retrieve elavated status of PowerShell Console. .DESCRIPTION Test-ValentiaPowerShellElevated will check shell was elevated is required for some operations access to system folder, files and objects. .NOTES Author: guitarrapc Date: June 17, 2013 .OUTPUTS bool .EXAMPLE C:\PS> Test-ValentiaPowerShellElevated true .EXAMPLE C:\PS> Test-ValentiaPowerShellElevated false #> function Test-ValentiaPowerShellElevated { [CmdletBinding()] param ( ) $user = [Security.Principal.WindowsIdentity]::GetCurrent() return (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) } # file loaded from path : \functions\Helper\Windows\Private\Test-ValentiaPowerShellElevated.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Enable WsMan Trusted hosts .DESCRIPTION Specify Trustedhosts to allow .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Enable-WsManTrustedHosts -------------------------------------------- allow all hosts as * #> function Enable-ValentiaWsManTrustedHosts { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Specify TrustedHosts to allow.")] [string]$TrustedHosts, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Specify path to WSMan TrustedHosts.")] [string]$TrustedHostsPath = "WSman:localhost\client\TrustedHosts" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if (-not((Get-ChildItem $TrustedHostsPath).Value -eq $TrustedHosts)) { Set-Item -Path $TrustedHostsPath -Value $TrustedHosts -Force } else { ("WinRM Trustedhosts was alredy enabled for {0}." -f $TrustedHosts) | Write-ValentiaVerboseDebug Get-ChildItem $TrustedHostsPath } } # file loaded from path : \functions\Helper\WsMan\Enable-WsManTrustedHosts.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Set WsMan Max Memory Per user to prevent PowerShell failed with large memory usage. .DESCRIPTION This user is allowed a maximum memory. 0 will be unlimited. Default value : 1024 (Windows Server 2012) .NOTES Author: guitarrapc Created: 15/Feb/2014 .EXAMPLE Set-ValentiaWsManMaxMemoryPerShellMB -MaxMemoryPerShellMB 0 -------------------------------------------- set as unlimited #> function Set-ValentiaWsManMaxMemoryPerShellMB { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input MaxMemoryPerShellMB. 0 will be unlimited.")] [int]$MaxMemoryPerShellMB, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Set WSMan Path.")] [string]$MaxMemoryPerShellMBPath = "WSMan:\localhost\Shell\MaxMemoryPerShellMB" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if (-not((Get-ChildItem $MaxMemoryPerShellMBPath).Value -eq $MaxMemoryPerShellMB)) { Set-Item -Path $MaxMemoryPerShellMBPath -Value $MaxMemoryPerShellMB -Force -PassThru } else { ("Current value for MaxMemoryPerShellMB is {0}." -f $MaxMemoryPerShellMB) | Write-ValentiaVerboseDebug Get-ChildItem $MaxMemoryPerShellMBPath } } # file loaded from path : \functions\Helper\WsMan\Set-ValentiaWsManMaxMemoryPerShellMB.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Set WsMan Max Proccesses Per Shell. .DESCRIPTION Unlimit process. Default value : 100 (Windows Server 2012) .NOTES Author: guitarrapc Created: 15/Feb/2014 .EXAMPLE Set-ValentiaWsManMaxProccessesPerShell -MaxProccessesPerShell 0 -------------------------------------------- set as 100 #> function Set-ValentiaWsManMaxProccessesPerShell { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input MaxProccessesPerShell value.")] [int]$MaxProccessesPerShell, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Set path to WSMan MaxProccessesPerShell.")] [string]$MaxProccessesPerShellPath = "WSMan:\localhost\Shell\MaxProcessesPerShell" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if (-not((Get-ChildItem $MaxProccessesPerShellPath).Value -eq $MaxProccessesPerShell)) { Set-Item -Path $MaxProccessesPerShellPath -Value $MaxProccessesPerShell -Force -PassThru } else { ("Current value for MaxShellsPerUser is {0}." -f $MaxProccessesPerShell) | Write-ValentiaVerboseDebug Get-ChildItem $MaxProccessesPerShellPath } } # file loaded from path : \functions\Helper\WsMan\Set-ValentiaWsManMaxProccessesPerShell.ps1 #Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Set WsMan Max Shells Per user to prevent "The WS-Management service cannot process the request. .DESCRIPTION This user is allowed a maximum number of xx concurrent shells, which has been exceeded." Default value : 25 (Windows Server 2012) .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Set-ValentiaWsManMaxShellsPerUser -ShellsPerUser 100 -------------------------------------------- set as 100 #> function Set-ValentiaWsManMaxShellsPerUser { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input ShellsPerUser count.")] [int]$ShellsPerUser, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Set path to WSMan MaxShellsPerUser.")] [string]$MaxShellsPerUserPath = "WSMan:\localhost\Shell\MaxShellsPerUser" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if (-not((Get-ChildItem $MaxShellsPerUserPath).Value -eq $ShellsPerUser)) { Set-Item -Path $MaxShellsPerUserPath -Value $ShellsPerUser -Force -PassThru } else { ("Current value for MaxShellsPerUser is {0}." -f $ShellsPerUser) | Write-ValentiaVerboseDebug Get-ChildItem $MaxShellsPerUserPath } } # file loaded from path : \functions\Helper\WsMan\Set-ValentiaWsManMaxShellsPerUser.ps1 #Requires -Version 3.0 #-- Public Functions for WSMan Parameter Configuration --# function Set-ValetntiaWSManConfiguration { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Configure WSMan MaxShellsPerUser to prevent error 'The WS-Management service cannot process the request. This user is allowed a maximum number of xx concurrent shells, which has been exceeded.'")] [ValidateNotNullOrEmpty()] [int]$ShellsPerUser = $valentia.wsman.MaxShellsPerUser, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Configure WSMan MaxShellsPerUser to prevent error 'The WS-Management service cannot process the request. This user is allowed a maximum number of xx concurrent shells, which has been exceeded.'")] [ValidateNotNullOrEmpty()] [int]$MaxMemoryPerShellMB = $valentia.wsman.MaxMemoryPerShellMB, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Configure WSMan MaxProccessesPerShell to improve performance")] [ValidateNotNullOrEmpty()] [int]$MaxProccessesPerShell = $valentia.wsman.MaxProccessesPerShell ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest "Configure WSMan MaxShellsPerUser to prevent error 'The WS-Management service cannot process the request. This user is allowed a maximum number of xx concurrent shells, which has been exceeded.'" | Write-ValentiaVerboseDebug Set-ValentiaWsManMaxShellsPerUser -ShellsPerUser $ShellsPerUser "Configure WSMan MaxMBPerUser to prevent huge memory consumption crach PowerShell issue." | Write-ValentiaVerboseDebug Set-ValentiaWsManMaxMemoryPerShellMB -MaxMemoryPerShellMB $MaxMemoryPerShellMB "Configure WSMan MaxProccessesPerShell to improve performance" | Write-ValentiaVerboseDebug Set-ValentiaWsManMaxProccessesPerShell -MaxProccessesPerShell $MaxProccessesPerShell "Restart-Service WinRM -PassThru" | Write-ValentiaVerboseDebug Restart-Service WinRM -PassThru } # file loaded from path : \functions\Helper\WsMan\Set-ValetntiaWSManConfiguration.ps1 #Requires -Version 3.0 #-- Public Module Job / Functions for Remote Execution --# # vale <# .SYNOPSIS 1 of invoking valentia by PowerShell Backgroud Job execution to remote host .DESCRIPTION Run Job valentia execution to remote host .NOTES Author: guitarrapc Created: 20/June/2013 .EXAMPLE vale 192.168.1.100 {Get-ChildItem} -------------------------------------------- Get-ChildItem ScriptBlock execute on 192.168.1.100 .EXAMPLE vale 192.168.1.100 {Get-ChildItem; hostname} -------------------------------------------- You can run multiple script in pipeline. .EXAMPLE vale 192.168.1.100 .\default.ps1 -------------------------------------------- You can prepare script file to run, and specify path. .EXAMPLE vale 192.168.1.100,192.168.1.200 .\default.ps1 -------------------------------------------- You can target multiple deploymember with comma separated. Running Synchronously. .EXAMPLE vale DeployGroupFile.ps1 {ScriptBlock} -------------------------------------------- Specify DeployGroupFile and ScriptBlock .EXAMPLE vale DeployGroupFile.ps1 .\default.ps1 -------------------------------------------- You can prepare script file to run, and specify path. #> function Invoke-Valentia { [CmdletBinding(DefaultParameterSetName = "TaskFileName")] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string[]]$DeployGroups, [Parameter(Position = 1, mandatory = $true, ParameterSetName = "TaskFileName", HelpMessage = "Move to Brach folder you sat taskfile, then input TaskFileName. exclusive with ScriptBlock.")] [ValidateNotNullOrEmpty()] [string]$TaskFileName, [Parameter(Position = 1, mandatory = $true, ParameterSetName = "SctriptBlock", HelpMessage = "Input Script Block {hogehoge} you want to execute with this commandlet. exclusive with TaskFileName")] [ValidateNotNullOrEmpty()] [ScriptBlock]$ScriptBlock, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Usually automatically sat to DeployGroup Folder. No need to modify.")] [ValidateNotNullOrEmpty()] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 3, mandatory = $false, HelpMessage = "Input parameter pass into task's arg[0....x].values")] [ValidateNotNullOrEmpty()] [hashtable]$TaskParameter, [Parameter(Position = 4, mandatory = $false, HelpMessage = "Hide execution progress.")] [switch]$Quiet, [Parameter(Position = 5, mandatory = $false, HelpMessage = "Input PSCredential to use for wsman.")] [PSCredential]$Credential = (Get-ValentiaCredential), [Parameter(Position = 6, mandatory = $false, HelpMessage = "Select Authenticateion for Credential.")] [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication = $valentia.Authentication, [Parameter(Position = 7, mandatory = $false, HelpMessage = "Select SSL is use or not.")] [switch]$UseSSL = $valentia.UseSSL, [Parameter(Position = 8, mandatory = $false, HelpMessage = "Return success result even if there are error.")] [bool]$SkipException = $false ) process { try { #region Prerequisite # Prerequisite setup $prerequisiteParam = @{ Stopwatch = $TotalstopwatchSession DeployGroups = $DeployGroups TaskFileName = $TaskFileName ScriptBlock = $ScriptBlock DeployFolder = $DeployFolder TaskParameter = $TaskParameter } Set-ValentiaInvokationPrerequisites @prerequisiteParam #endregion #region Process # Job execution $param = @{ Credential = $Credential TaskParameter = $TaskParameter Authentication = $Authentication UseSSL = $UseSSL SkipException = $SkipException ErrorAction = $originalErrorAction } Invoke-ValentiaJobProcess @param #endregion } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ if ($ErrorActionPreference -eq 'Stop') { throw $_ } } finally { # obtain Result $resultParam = @{ StopWatch = $TotalstopwatchSession Cmdlet = $($MyInvocation.MyCommand.Name) TaskFileName = $TaskFileName DeployGroups = $DeployGroups SkipException = $SkipException Quiet = $Quiet } Out-ValentiaResult @resultParam # Cleanup valentia Environment Invoke-ValentiaClean } } begin { # Initialize Stopwatch $TotalstopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Reset ErrorActionPreference if ($PSBoundParameters.ContainsKey('ErrorAction')) { $originalErrorAction = $ErrorActionPreference } else { $originalErrorAction = $ErrorActionPreference = $valentia.preference.ErrorActionPreference.original } } } # file loaded from path : \functions\Invokation\CommandExecution\Job\Invoke-Valentia.ps1 #Requires -Version 3.0 #-- Private Module Job / Functions for Remote Execution --# <# .SYNOPSIS Invoke Command as Job to remote host .DESCRIPTION Background job execution with Invoke-Command. Allowed to run from C# code. .NOTES Author: guitarrapc Created: 20/June/2013 .EXAMPLE Invoke-ValentiaCommand -ScriptToRun $ScriptToRun .EXAMPLE Invoke-ValentiaCommand -ScriptToRun {ls} .EXAMPLE Invoke-ValentiaCommand -ScriptToRun {ls | where {$_.extensions -eq ".txt"}} .EXAMPLE Invoke-ValentiaCommand {test-connection localhost} #> function Invoke-ValentiaCommand { [CmdletBinding(DefaultParameterSetName = "All")] param ( [Parameter(Position = 0, mandatory = $true, ParameterSetName = "Default", ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Input Session")] [string[]]$ComputerNames, [Parameter(Position = 1, mandatory = $true, ParameterSetName = "Default", ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Input ScriptBlock. ex) Get-ChildItem, Get-NetAdaptor | where MTUSize -gt 1400")] [ScriptBlock]$ScriptToRun, [Parameter(Position = 2, mandatory = $true, HelpMessage = "Input PSCredential for Remote Command execution.")] [System.Management.Automation.PSCredential]$Credential, [Parameter(Position = 3, mandatory = $false, HelpMessage = "Input parameter pass into task's arg[0....x].")] [hashtable]$TaskParameter, [Parameter(Position = 4, mandatory = $false, HelpMessage = "Input Authentication for credential.")] [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication, [Parameter(Position = 5, mandatory = $false, HelpMessage = "Input SSL is use or not.")] [bool]$UseSSL, [Parameter(Position = 6, mandatory = $false, HelpMessage = "Input Skip ErrorActionPreferenceOption.")] [bool]$SkipException ) process { foreach ($computerName in $ComputerNames) { # Run ScriptBlock in Job Write-Verbose ("ScriptBlock..... {0}" -f $($ScriptToRun)) Write-Verbose ("Argumentlist..... {0}" -f $($TaskParameter)) ("Running ScriptBlock to {0} as Job" -f $computerName) | Write-ValentiaVerboseDebug $job = Invoke-Command -ScriptBlock $ScriptToRun -ArgumentList $TaskParameter -ComputerName $computerName -Credential $Credential -Authentication $Authentication -UseSSL:$UseSSL -AsJob $list.Add($job) } # receive job result "Receive all job result." | Write-ValentiaVerboseDebug $jobParam = @{ listJob = $list SkipException = $skipException ErrorAction = $ErrorActionPreference } Receive-ValentiaResult @jobParam } begin { $list = New-Object System.Collections.Generic.List[System.Management.Automation.Job] # Set variable for output each task result $task = @{} # Cleanup previous Job before start if ((Get-Job).count -gt 0) { "Clean up previous Job" | Write-ValentiaVerboseDebug Get-Job | Remove-Job -Force -Verbose:$VerbosePreference } } } # file loaded from path : \functions\Invokation\CommandExecution\Job\Private\Invoke-ValentiaCommand.ps1 #Requires -Version 3.0 #-- Private Module Job / Functions for Remote Execution --# function Invoke-ValentiaJobProcess { [CmdletBinding()] param ( [parameter(mandatory = $false)] [string[]]$ComputerNames = $valentia.Result.DeployMembers, [parameter(mandatory = $false)] [scriptBlock]$ScriptToRun = $valentia.Result.ScriptTorun, [parameter(mandatory = $true)] [PSCredential]$Credential, [parameter(mandatory = $false)] [hashtable]$TaskParameter, [parameter(mandatory = $true)] [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication, [parameter(mandatory = $true)] [bool]$UseSSL, [parameter(mandatory = $true)] [bool]$SkipException ) # Splatting $param = @{ ComputerNames = $ComputerNames ScriptToRun = $ScriptToRun Credential = $Credential TaskParameter = $TaskParameter Authentication = $Authentication UseSSL = $UseSSL SkipException = $SkipException ErrorAction = $ErrorActionPreference } # Run ScriptBlock as Sequence for each DeployMember Write-Verbose ("Execute command : {0}" -f $param.ScriptToRun) Write-Verbose ("Target Computers : '{0}'" -f ($param.ComputerNames -join ", ")) # Executing job Invoke-ValentiaCommand @param ` | %{$valentia.Result.Result = New-Object 'System.Collections.Generic.List[PSCustomObject]' }{ $valentia.Result.ErrorMessageDetail += $_.ErrorMessageDetail $valentia.Result.SuccessStatus += $_.SuccessStatus if ($_.host -ne $null) { $hash = [ordered]@{ Hostname = $_.host Values = $_.result Success = $_.success } $valentia.Result.Result.Add([PSCustomObject]$hash) } if(!$quiet) { "Show result for host '{0}'" -f $_.host | Write-ValentiaVerboseDebug $_.result } } } # file loaded from path : \functions\Invokation\CommandExecution\Job\Private\Invoke-ValentiaJobProcess.ps1 #Requires -Version 3.0 #-- Private Module Job / Functions for Remote Execution --# <# .SYNOPSIS Receives a results of one or more jobs. .DESCRIPTION Get background job execution result. .NOTES Author: guitarrapc Created: 14/Feb/2014 .EXAMPLE Receive-ValentiaResult -listJob $listJob #> function Receive-ValentiaResult { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Input list<job> to recieve result of each job.")] [System.Collections.Generic.List[System.Management.Automation.Job]]$listJob, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Input Skip ErrorActionPreferenceOption.")] [bool]$SkipException ) process { # monitor job status "Waiting for job running complete." | Write-ValentiaVerboseDebug Wait-Job -Job $listJob -Force > $null foreach ($job in $listJob) { # Obtain HostName $task.host = $job.Location ("Receive ScriptBlock result from Job for '{0}'" -f $job.Location) | Write-ValentiaVerboseDebug if ($SkipException) { $task.result = Receive-Job -Job $job -ErrorAction SilentlyContinue -ErrorVariable ErrorVariable } else { $task.result = Receive-Job -Job $job -ErrorVariable ErrorVariable } # Error actions if (($ErrorVariable | measure).Count -ne 0) { $task.ErrorMessageDetail = $ErrorVariable $task.SuccessStatus = $false $task.success = $false if (-not $SkipException) { if ($ErrorActionPreference -eq 'Stop') { throw $ErrorVariable } } } else { $task.success = $true } # output $task ("Removing Job ID '{0}'" -f $job.id) | Write-ValentiaVerboseDebug Remove-Job -Job $job -Force } } begin { # Set variable for output $task = @{} } } # file loaded from path : \functions\Invokation\CommandExecution\Job\Private\Receive-ValentiaResult.ps1 #Requires -Version 3.0 #-- Public Module Asynchronous / Functions for Remote Execution --# # valea <# .SYNOPSIS Run Asynchronous valentia execution to remote host .DESCRIPTION Asynchronous running thread through AsyncPipeLine handling PS Runspace. Allowed to run from C# code. .NOTES Author: guitarrapc Created: 20/June/2013 .EXAMPLE valea 192.168.1.100 {Get-ChildItem} -------------------------------------------- Get-ChildItem ScriptBlock execute on 192.168.1.100 .EXAMPLE valea 192.168.1.100 {Get-ChildItem; hostname} -------------------------------------------- You can run multiple script in pipeline. .EXAMPLE valea 192.168.1.100 .\default.ps1 -------------------------------------------- You can prepare script file to run, and specify path. .EXAMPLE valea 192.168.1.100,192.168.1.200 .\default.ps1 -------------------------------------------- You can target multiple deploymember with comma separated. Running Asynchronously. .EXAMPLE valea DeployGroupFile.ps1 {ScriptBlock} -------------------------------------------- Specify DeployGroupFile and ScriptBlock .EXAMPLE valea DeployGroupFile.ps1 .\default.ps1 -------------------------------------------- You can prepare script file to run, and specify path. #> function Invoke-ValentiaAsync { [CmdletBinding(DefaultParameterSetName = "TaskFileName")] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string[]]$DeployGroups, [Parameter(Position = 1, mandatory = $true, ParameterSetName = "TaskFileName", HelpMessage = "Move to Brach folder you sat taskfile, then input TaskFileName. exclusive with ScriptBlock.")] [ValidateNotNullOrEmpty()] [string]$TaskFileName, [Parameter(Position = 1, mandatory = $true, ParameterSetName = "SctriptBlock", HelpMessage = "Input Script Block {hogehoge} you want to execute with this commandlet. exclusive with TaskFileName")] [ValidateNotNullOrEmpty()] [ScriptBlock]$ScriptBlock, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Usually automatically sat to DeployGroup Folder. No need to modify.")] [ValidateNotNullOrEmpty()] [string]$DeployFolder = (Join-Path $script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 3, mandatory = $false, HelpMessage = "Input parameter pass into task's arg[0....x].Values")] [ValidateNotNullOrEmpty()] [hashtable]$TaskParameter, [Parameter(Position = 4, mandatory = $false, HelpMessage = "Hide execution progress.")] [switch]$Quiet, [Parameter(Position = 5, mandatory = $false, HelpMessage = "Input PSCredential to use for wsman.")] [PSCredential]$Credential = (Get-ValentiaCredential), [Parameter(Position = 6, mandatory = $false, HelpMessage = "Select Authenticateion for Credential.")] [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication = $valentia.Authentication, [Parameter(Position = 7, mandatory = $false, HelpMessage = "Select SSL is use or not.")] [switch]$UseSSL = $valentia.UseSSL, [Parameter(Position = 8, mandatory = $false, HelpMessage = "Return success result even if there are error.")] [bool]$SkipException = $false ) process { try { #region Prerequisite # Prerequisite setup $prerequisiteParam = @{ Stopwatch = $TotalstopwatchSession DeployGroups = $DeployGroups TaskFileName = $TaskFileName ScriptBlock = $ScriptBlock DeployFolder = $DeployFolder TaskParameter = $TaskParameter } Set-ValentiaInvokationPrerequisites @prerequisiteParam #endregion #region Process # RunSpace execution $param = @{ Credential = $Credential TaskParameter = $TaskParameter Authentication = $Authentication UseSSL = $UseSSL SkipException = $SkipException ErrorAction = $originalErrorAction quiet = $Quiet } Invoke-ValentiaRunspaceProcess @param #endregion } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ if (-not $SkipException) { throw $_ } } finally { # obtain Result $resultParam = @{ StopWatch = $TotalstopwatchSession Cmdlet = $($MyInvocation.MyCommand.Name) TaskFileName = $TaskFileName DeployGroups = $DeployGroups SkipException = $SkipException Quiet = $PSBoundParameters.ContainsKey("quiet") -and $quiet } Out-ValentiaResult @resultParam # Cleanup valentia Environment Invoke-ValentiaClean } } begin { # Initialize Stopwatch $TotalstopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Reset ErrorActionPreference if ($PSBoundParameters.ContainsKey('ErrorAction')) { $originalErrorAction = $ErrorActionPreference } else { $originalErrorAction = $ErrorActionPreference = $valentia.preference.ErrorActionPreference.original } } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Invoke-ValentiaAsync.ps1 #Requires -Version 3.0 #-- Private Module Function for Async execution --# <# .SYNOPSIS Creating a PowerShell pipeline then executes a ScriptBlock Asynchronous with Remote Host. .DESCRIPTION Pipeline will execute less overhead then Invoke-Command, Job, or PowerShell Cmdlet. All cmdlet will execute with Invoke-Command -ComputerName -Credential wrapped by Invoke-ValentiaAsync pipeline. Wrapped by Pipeline will give you avility to run Invoke-Command Asynchronous. (Usually Sencronous) Asynchrnous execution will complete much faster then Syncronous execution. .NOTES Author: guitarrapc Created: 13/July/2013 .EXAMPLE Invoke-ValeinaAsyncCommand -RunspacePool $(New-ValentiaRunspacePool 10) ` -ScriptBlock { Get-ChildItem } ` -Computers $(Get-Content .\ComputerList.txt) -Credential $(Get-Credential) -------------------------------------------- Above example will concurrently running with 10 processes for each Computers. #> function Invoke-ValentiaAsyncCommand { [Cmdletbinding()] Param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Runspace Poll required to set one or more, easy to create by New-ValentiaRunSpacePool.")] [System.Management.Automation.Runspaces.RunspacePool]$RunspacePool, [Parameter(Position = 1, mandatory = $true, HelpMessage = "The scriptblock to be executed to the Remote host.")] [HashTable]$ScriptToRunHash, [Parameter(Position = 2, mandatory = $true, HelpMessage = "Target Computers to be execute.")] [string[]]$DeployMembers, [Parameter(Position = 3, mandatory = $true, HelpMessage = "Remote Login PSCredentail for PS Remoting. (Get-Credential format)")] [HashTable]$CredentialHash, [Parameter(Position = 4, mandatory = $true, HelpMessage = "Input parameter pass into task's arg[0....x].")] [HashTable]$TaskParameterHash, [Parameter(Position = 5, mandatory = $true, HelpMessage = "Input Authentication for credential.")] [HashTable]$AuthenticationHash, [Parameter(Position = 6, mandatory = $true, HelpMessage = "Select SSL is use or not.")] [HashTable]$UseSSLHash ) end { try { # Create PowerShell Instance "Creating PowerShell Instance" | Write-ValentiaVerboseDebug $Pipeline = [System.Management.Automation.PowerShell]::Create() # Add Script and Parameter arguments from Hashtables "Adding Script and Arguments Hastables to PowerShell Instance" | Write-ValentiaVerboseDebug Write-Verbose ('Add InvokeCommand Script : {0}' -f $InvokeCommand) Write-Verbose ("Add ScriptBlock Argument..... Keys : {0}, Values : {1}" -f $($ScriptToRunHash.Keys) , $($ScriptToRunHash.Values)) Write-Verbose ("Add ComputerName Argument..... Keys : {0}, Values : {1}" -f $($ComputerName.Keys) , $($ComputerName.Values)) Write-Verbose ("Add Credential Argument..... Keys : {0}, Values : {1}" -f $($CredentialHash.Keys) , $($CredentialHash.Values)) Write-Verbose ("Add ArgumentList Argument..... Keys : {0}, Values : {1}" -f $($TaskParameterHash.Keys) , $($TaskParameterHash.Values)) Write-Verbose ("Add Authentication Argument..... Keys : {0}, Values : {1}" -f $($AuthenticationHash.Keys), $($AuthenticationHash.Values)) Write-Verbose ("Add UseSSL Argument..... Keys : {0}, Values : {1}" -f $($UseSSLHash.Keys), $($UseSSLHash.Values)) $Pipeline. AddScript($InvokeCommand). AddArgument($ScriptToRunHash). AddArgument($ComputerName). AddArgument($CredentialHash). AddArgument($TaskParameterHash). AddArgument($AuthenticationHash). AddArgument($UseSSLHash) > $null # Add RunSpacePool to PowerShell Instance ("Adding Runspaces {0}" -f $RunspacePool) | Write-ValentiaVerboseDebug $Pipeline.RunspacePool = $RunspacePool # Invoke PowerShell Command "Invoking PowerShell Instance" | Write-ValentiaVerboseDebug $AsyncResult = $Pipeline.BeginInvoke() # Get Result Write-Verbose "Obtain result" $Output = New-Object AsyncPipeline # Output Pipeline Infomation $Output.Pipeline = $Pipeline # Output AsyncCommand Result $Output.AsyncResult = $AsyncResult ("Output Result '{0}' and '{1}'" -f $Output.Pipeline, $Output.AsyncResult) | Write-ValentiaVerboseDebug return $Output } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ Write-Error $_ } } begin { # Create Hashtable for ComputerName passed to Pipeline $ComputerName = @{ComputerName = $DeployMember} # Declare execute Comdlet format as Invoke-Command $InvokeCommand = { param( $ScriptToRunHash, $ComputerName, $CredentialHash, $TaskParameterHash, $AuthenticationHash, $UseSSLHash ) $param = @{ ScriptBlock = $($ScriptToRunHash.Values) ComputerName = $($ComputerName.Values) Credential = $($CredentialHash.Values) ArgumentList = $($TaskParameterHash.Values) Authentication = $($AuthenticationHash.Values) UseSSL = $($UseSSLHash.Values) } Invoke-Command @param } } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\Invoke-ValentiaAsyncCommand.ps1 #Requires -Version 3.0 #-- Private Module Function for Async execution --# function Invoke-ValentiaRunspaceProcess { [CmdletBinding()] param ( [parameter(mandatory = $false)] [string[]]$ComputerNames = $valentia.Result.DeployMembers, [parameter(mandatory = $false)] [scriptBlock]$ScriptToRun = $valentia.Result.ScriptTorun, [parameter(mandatory = $true)] [PSCredential]$Credential, [parameter(mandatory = $false)] [hashtable]$TaskParameter, [parameter(mandatory = $true)] [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication, [parameter(mandatory = $true)] [bool]$UseSSL, [parameter(mandatory = $true)] [bool]$SkipException, [parameter(mandatory = $false)] [bool]$quiet ) process { try { # Execute Async Job $asyncPipelineparam = @{ scriptBlock = $scriptBlock Credential = $credential TaskParameter = $TaskParameter Authentication = $Authentication UseSSL = $UseSSL } Invoke-ValentiaAsyncPipeline @asyncPipelineparam # Monitoring status for Async result (Even if no monitoring, but asynchronous result will obtain after all hosts available) Watch-ValentiaAsyncPipelineStatus -AsyncPipelines $valentia.runspace.asyncPipeline # Obtain Async Command Result $asyncResultParam = @{ AsyncPipelines = $valentia.runspace.asyncPipeline quiet = $quiet ErrorAction = $ErrorActionPreference skipException = $skipException } Receive-ValentiaAsyncResults @asyncResultParam ` | %{$valentia.Result.Result = New-Object 'System.Collections.Generic.List[PSCustomObject]' }{ $valentia.Result.ErrorMessageDetail += $_.ErrorMessageDetail $valentia.Result.SuccessStatus += $_.SuccessStatus if ($_.host -ne $null) { $hash = [ordered]@{ Hostname = $_.host Values = $_.result Success = $_.success } $valentia.Result.Result.Add([PSCustomObject]$hash) } if (-not $quiet) { "Show result for host '{0}'" -f $_.host | Write-ValentiaVerboseDebug $_.result } } } finally { # Dispose RunspacePool Remove-ValentiaRunSpacePool # Dispose AsyncPipeline variables $valentia.runspace.asyncPipeline = $null } } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\Invoke-ValentiaRunspaceProcess.ps1 #Requires -Version 3.0 #-- Private Module Function for Async execution --# <# .SYNOPSIS Receives a results of one or more asynchronous pipelines. .DESCRIPTION This function receives the results of a pipeline running in a separate runspace. Since it is unknown what exists in the results stream of the pipeline, this function will not have a standard return type. .NOTES Author: guitarrapc Created: 13/July/2013 .EXAMPLE $AsyncPipelines += Invoke-ValentiaAsyncCommand -RunspacePool $valentia.runspace.pool.instance -ScriptToRun $ScriptToRun -Deploymember $DeployMember -Credential $credential -Verbose Receive-ValentiaAsyncResults -AsyncPipelines $AsyncPipelines -ShowProgress -------------------------------------------- Above will retrieve Async Result #> function Receive-ValentiaAsyncResults { [Cmdletbinding()] Param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "An array of Async Pipeline objects, returned by Invoke-ValentiaAsync.")] [System.Collections.Generic.List[AsyncPipeline]]$AsyncPipelines, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Hide execution progress.")] [bool]$quiet, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input Skip ErrorActionPreferenceOption.")] [bool]$SkipException ) process { foreach($Pipeline in $AsyncPipelines) { try { # Get HostName of Pipeline $task.host = $Pipeline.Pipeline.Commands.Commands.parameters.Value.ComputerName if (-not $quiet) { Write-Warning -Message ("{0} Asynchronous execution done." -f $task.host) } # output Asyanc result $task.result = $Pipeline.Pipeline.EndInvoke($Pipeline.AsyncResult) # Check status of stream if($Pipeline.Pipeline.Streams.Error) { $task.SuccessStatus = $false $task.ErrorMessageDetail = $Pipeline.Pipeline.Streams.Error $task.success = $false if (-not $SkipException) { if ($ErrorActionPreference -eq "Stop") { throw $Pipeline.Pipeline.Streams.Error } else { Write-Error "$($Pipeline.Pipeline.Streams.Error)" } } } else { $task.success = $true } # Output $task variable to file. This will obtain by other cmdlet outside function. $task } catch { $task.SuccessStatus = $false $task.ErrorMessageDetail = $_ Write-Error $_ } finally { # Dispose Pipeline $Pipeline.Pipeline.Dispose() } } } begin { # Inherite variable [HashTable]$task = @{} } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\Receive-ValentiaAsyncResults.ps1 #Requires -Version 3.0 #-- Private Module Function for Async execution --# <# .SYNOPSIS Receives one or more Asynchronous pipeline State. .DESCRIPTION Asynchronous execution required to check status whether it done or not. .NOTES Author: guitarrapc Created: 13/July/2013 .EXAMPLE $AsyncPipelines += Invoke-ValentiaAsyncCommand -RunspacePool $valentia.runspace.pool.instance -ScriptToRun $ScriptToRun -Deploymember $DeployMember -Credential $credential -Verbose Receive-ValentiaAsyncStatus -Pipelines $AsyncPipelines -------------------------------------------- Above will retrieve Async Result #> function Receive-ValentiaAsyncStatus { [Cmdletbinding()] Param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "An array of Async Pipeline objects, returned by Invoke-ValentiaAsync.")] [System.Collections.Generic.List[AsyncPipeline]] $Pipelines ) foreach($Pipeline in $Pipelines) { [PSCustomObject]@{ HostName = $Pipeline.Pipeline.Commands.Commands.parameters.Value.ComputerName InstanceID = $Pipeline.Pipeline.Instance_Id State = $Pipeline.Pipeline.InvocationStateInfo.State Reason = $Pipeline.Pipeline.InvocationStateInfo.Reason Completed = $Pipeline.AsyncResult.IsCompleted AsyncState = $Pipeline.AsyncResult.AsyncState Error = $Pipeline.Pipeline.Streams.Error } } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\Receive-ValentiaAsyncStatus.ps1 #Requires -Version 3.0 #-- Private Module Function for AsyncPipelline execution --# function Invoke-ValentiaAsyncPipeline { [CmdletBinding()] param ( [parameter(mandatory = $false)] [scriptBlock]$ScriptBlock, [parameter(mandatory = $true)] [PSCredential]$Credential, [parameter(mandatory = $false)] [hashtable]$TaskParameter, [parameter(mandatory = $true)] [System.Management.Automation.Runspaces.AuthenticationMechanism]$Authentication, [parameter(mandatory = $true)] [bool]$UseSSL ) # Create RunSpacePools [System.Management.Automation.Runspaces.RunspacePool]$valentia.runspace.pool.instance = New-ValentiaRunSpacePool Write-Verbose ("Target Computers : [{0}]" -f ($ComputerNames -join ", ")) $param = @{ RunSpacePool = $valentia.runspace.pool.instance ScriptToRunHash = @{ScriptBlock = $ScriptToRun} credentialHash = @{Credential = $Credential} TaskParameterHash = @{TaskParameter = $TaskParameter} AuthenticationHash = @{Authentication = $Authentication} UseSSL = @{UseSSL = $UseSSL} } $valentia.runspace.asyncPipeline = New-Object 'System.Collections.Generic.List[AsyncPipeline]' foreach ($DeployMember in $valentia.Result.DeployMembers) { $AsyncPipeline = Invoke-ValentiaAsyncCommand @param -Deploymember $DeployMember $valentia.runspace.asyncPipeline.Add($AsyncPipeline) } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\AsyncPipeline\Invoke-ValentiaAsyncPipeline.ps1 #Requires -Version 3.0 #-- Private Module Function for AsyncPipelline monitor --# function Watch-ValentiaAsyncPipelineStatus { [Cmdletbinding()] Param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "An array of Async Pipeline objects, returned by Invoke-ValentiaAsync.")] [System.Collections.Generic.List[AsyncPipeline]]$AsyncPipelines ) process { while ((($ReceiveAsyncStatus = (Receive-ValentiaAsyncStatus -Pipelines $AsyncPipelines | group state, hostname -NoElement)) | where name -like "Running*").count -ne 0) { $count++ $completed = $ReceiveAsyncStatus | where name -like "Completed*" $running = $ReceiveAsyncStatus | where name -like "Running*" $statusPercent = ($completed.count/$ReceiveAsyncStatus.count) * 100 # hide progress or not if (-not $quiet -and ($sw.Elapsed.TotalMilliseconds -ge 500)) { # hide progress or not if ($statusPercent -ne 100) { $paramProgress = @{ Activity = 'Async Execution Running Status.... ({0}sec elapsed)' -f $TotalstopwatchSession.Elapsed.TotalSeconds PercentComplete = $statusPercent status = ("{0}/{1}({2:0.00})% Completed" -f $completed.count, $ReceiveAsyncStatus.count, $statusPercent) } Write-Progress @paramProgress $sw.Reset() $sw.Start() } } # Log Current Status if (-not $null -eq $prevRunningCount) { if ($running.count -lt $prevRunningCount) { $ReceiveAsyncStatus.Name | OutValentiaModuleLogHost -hideDataAsString [PSCustomObject]@{ Running = $running.count Completed = $completed.count } | OutValentiaModuleLogHost -hideDataAsString } } $prevRunningCount = $running.count # Wait a moment sleep -Milliseconds $valentia.runspace.async.sleepMS # safety release if ($count -ge $valentia.runspace.async.limitCount) { break } } } end { # Clear Progress bar from Host, YOU MUST CLEAR PROGRESS BAR, other wise host output will be terriblly slow down. Write-Progress "done" "done" -Completed # Dispose variables if (-not ($null -eq $ReceiveAsyncStatus)) { $ReceiveAsyncStatus = $null } } begin { $sw = [System.Diagnostics.Stopwatch]::StartNew() } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\AsyncPipeline\Watch-ValentiaAsyncPipelineStatus.ps1 #Requires -Version 3.0 #-- Private Module Function for Async execution --# <# .SYNOPSIS Create a PowerShell Runspace Pool. .DESCRIPTION This function returns a runspace pool, a collection of runspaces that PowerShell pipelines can be executed. The number of available pools determines the maximum number of processes that can be running concurrently. This enables multithreaded execution of PowerShell code. .NOTES Author: guitarrapc Created: 13/July/2013 .EXAMPLE $pool = New-ValentiaRunspacePool -minPoolSize 50 -maxPoolSize 50 -------------------------------------------- Above will creates a pool of 10 runspaces #> function New-ValentiaRunSpacePool { [Cmdletbinding()] Param ( [Parameter(Position =0, mandatory = $false, HelpMessage = "Defines the minium number of pipelines that can be concurrently (asynchronously) executed on the pool.")] [int]$minPoolSize = $valentia.runspace.pool.minSize, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Defines the maximum number of pipelines that can be concurrently (asynchronously) executed on the pool.")] [int]$maxPoolSize = $valentia.runspace.pool.maxSize ) try { $sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() # RunspaceFactory.CreateRunspacePool (Int32, Int32, InitialSessionState, PSHost) # - Creates a runspace pool that specifies minimum and maximum number of opened runspaces, # and a custom host and initial session state information that is used by each runspace in the pool. $pool = [runspacefactory]::CreateRunspacePool($minPoolSize, $maxPoolSize, $sessionstate, $Host) # Only support STA mode. No MTA mode. $pool.ApartmentState = "STA" # open RunSpacePool $pool.Open() return $pool } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ Write-Error $_ } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\RunSpacePool\New-ValentiaRunSpacePool.ps1 #Requires -Version 3.0 #-- Private Module Function for Async execution --# <# .SYNOPSIS Close and Dispose PowerShell Runspace Pool. .DESCRIPTION This function Close runspace pool, then dispose. .NOTES Author: guitarrapc Created: 14/Feb/2014 .EXAMPLE Remove-ValentiaRunspacePool -RunSpacePool $valentia.runspace.pool.instance #> function Remove-ValentiaRunSpacePool { [Cmdletbinding()] Param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Specify RunSpace Pool to close and dispose.")] [System.Management.Automation.Runspaces.RunspacePool]$Pool = $valentia.runspace.pool.instance ) $script:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom try { if ($Pool) { $Pool.Close() $Pool.Dispose() } } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ Write-Error $_ } } # file loaded from path : \functions\Invokation\CommandExecution\RunSpacePool\Private\RunSpacePool\Remove-ValentiaRunSpacePool.ps1 #Requires -Version 3.0 #-- Public Module Functions for Download Files --# # download <# .SYNOPSIS Use BITS Transfer to downlpad a file from remote server. If -Force switch enable, then use smbmapping and copy -force will run. .DESCRIPTION If target path was directory then download files below path. (None recurse) If target path was file then download specific file. .NOTES Author: guitarrapc Created: 14/Aug/2013 .EXAMPLE download -SourcePath c:\logs\white\20130719 -DestinationFolder c:\logs\white -DeployGroup production-g1.ps1 -Directory -Async -------------------------------------------- download remote sourthdirectory items to local destinationfolder in backgroud job. .EXAMPLE download -SourcePath c:\logs\white\20130716\Http.0001.log -DestinationFolder c:\test -DeployGroup.ps1 production-first -File -------------------------------------------- download remote sourth item to local destinationfolder .EXAMPLE download -SourcePath c:\logs\white\20130716 -DestinationFolder c:\test -DeployGroup production-first.ps1 -Directory -------------------------------------------- download remote sourthdirectory items to local destinationfolder in backgroud job. Omit parameter name. #> function Invoke-ValentiaDownload { [CmdletBinding(DefaultParameterSetName = "File")] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input Client SourcePath to be downloaded.")] [String]$SourcePath, [Parameter(Position = 1, mandatory = $true, HelpMessage = "Input Server Destination Folder to save download items.")] [string]$DestinationFolder = $null, [Parameter(Position = 2, mandatory = $true, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string]$DeployGroups, [Parameter(position = 3, ParameterSetName = "File", HelpMessage = "Set this switch to execute command for File. exclusive with Directory Switch.")] [switch]$File = $true, [Parameter(position = 3, ParameterSetName = "Directory", HelpMessage = "Set this switch to execute command for Directory. exclusive with File Switch.")] [switch]$Directory, [Parameter(position = 4, mandatory = $false, HelpMessage = "Set this switch to execute command as Async (Job).")] [switch]$Async = $false, [Parameter(Position = 5, mandatory = $false, HelpMessage = "Input DeployGroup Folder path if changed from default.")] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 6, mandatory = $false, HelpMessage = "Set this switch if you want to Force download. This will smbmap with source folder and Copy-Item -Force. (default is BitTransfer)")] [switch]$force = $false, [Parameter(Position = 7, mandatory = $false, HelpMessage = "Return success result even if there are error.")] [bool]$SkipException = $false, [Parameter(Position = 8, mandatory = $false, HelpMessage = "Input PSCredential to use for wsman.")] [PSCredential]$Credential = (Get-ValentiaCredential) ) try { ### Begin $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom # Initialize Stopwatch [decimal]$TotalDuration = 0 $TotalstopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Initialize Errorstatus $SuccessStatus = $ErrorMessageDetail = @() # Get Start Time $TimeStart = (Get-Date).DateTime # Import default Configurations & Modules if ($PSBoundParameters['Verbose']) { # Import default Configurations $valeWarningMessages.warn_import_configuration | Write-ValentiaVerboseDebug Import-ValentiaConfiguration -Verbose # Import default Modules $valeWarningMessages.warn_import_modules | Write-ValentiaVerboseDebug Import-valentiaModules -Verbose } else { Import-ValentiaConfiguration Import-valentiaModules } # Log Setting New-ValentiaLog # Obtain DeployMember IP or Hosts for BITsTransfer "Get hostaddresses to connect." | Write-ValentiaVerboseDebug $DeployMembers = Get-ValentiaGroup -DeployFolder $DeployFolder -DeployGroup $DeployGroups if ($DeployMembers.SuccessStatus -eq $false) { $SuccessStatus += $DeployMembers.SuccessStatus $ErrorMessageDetail += $DeployMembers.ErrorMessageDetail } # Parse Network Source ("Parsing Network SourcePath {0} as :\ should change to $." -f $SourcrePath) | Write-ValentiaVerboseDebug $SourcePath = "$SourcePath".Replace(":","$") # Show Stopwatch for Begin section $TotalDuration = $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tDuration Second for Begin Section: {0}" -f $TotalDuration) "" ### Process ("Downloading {0} from Target Computer : [{1}] `n" -f $SourcePath, $DeployMembers) | Write-ValentiaVerboseDebug # Stopwatch [decimal]$DurationTotal = 0 # Create PSSession for each DeployMember foreach ($DeployMember in $DeployMembers){ # Stopwatch $stopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Set Source $Source = Join-Path "\\" $(Join-Path "$DeployMember" "$SourcePath") if (Test-Path $Source) { if ($Directory) { # Set Source files in source try { # Remove last letter of \ or / if (($Source[-1] -eq "\") -or ($Source[-1] -eq "/")) { $Source = $Source.Substring(0,($Source.Length-1)) } # Get File Information - No recurse $SourceFiles = Get-ChildItem -Path $Source } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ throw $_ } } elseif ($File) { # Set Source files in source try { # Get File Information $SourceFiles = Get-Item -Path $Source if ($SourceFiles.Attributes -eq "Directory") { $SuccessStatus += $false $ErrorMessageDetail += "Target is Directory, you must set Filename with -File Switch." throw "Target is Directory, you must set Filename with -File Switch." } } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ throw $_ } } else { $SuccessStatus += $false $ErrorMessageDetail += $_ throw "Missing File or Directory switch. Please set -File or -Directory Switch to specify download type." } # Set Destination with date and DeproyMemberName if ($DestinationFolder -eq $null) { $DestinationFolder = $(Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Download)) } $Date = (Get-Date).ToString("yyyyMMdd") $DestinationPath = Join-Path $DestinationFolder $Date $Destination = Join-Path $DestinationPath $DeployMember # Create Destination if not exist if (-not(Test-Path $Destination)) { New-Item -Path $Destination -ItemType Directory -Force > $null } if ($force) { # Show Start-BitsTransfer Parameter ("Downloading {0} from {1}." -f $SourceFiles, $DeployMember) | Write-ValentiaVerboseDebug Write-Verbose ("DeployFolder : {0}" -f $DeployFolder) Write-Verbose ("DeployMembers : {0}" -f $DeployMembers) Write-Verbose ("DeployMember : {0}" -f $DeployMember) Write-Verbose ("Source : {0}" -f $Source) Write-Verbose ("Destination : {0}" -f $Destination) Write-Verbose "Aync Mode : You cannot use Async switch with force" # Get Cimsession for target Computer "cim : New-CimSession to the ComputerName '{0}'" -f $DeployMember | Write-ValentiaVerboseDebug $cim = New-CimSession -Credential $Credential -ComputerName $DeployMember # Create SMB Mapping to target parent directory if ($Directory) { "Directory switch Selected" | Write-ValentiaVerboseDebug $smbRemotePath = (Get-Item $Source).FullName } elseif ($file) { "File switch Selected" | Write-ValentiaVerboseDebug $smbRemotePath = (Get-Item $source).DirectoryName } # Running Copy-Item cmdlet, switch with $force try { #Only start download for file. foreach($SourceFile in $SourceFiles) { if (-not((Get-Item $SourceFile.fullname).Attributes -eq "Directory")) { Write-Warning ("Downloading {0} from {1} to {2}" -f ($SourceFile).fullname, $DeployMember, $Destination) $ScriptToRun = "Copy-Item -Path $(($SourceFile).fullname) -Destination $Destination -Force" Copy-Item -Path $(($SourceFile).fullname) -Destination $Destination -Force } } } catch [System.Management.Automation.ActionPreferenceStopException] { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } finally { # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" } } else # Not Force Swtich { # Show Start-BitsTransfer Parameter ("Downloading {0} from {1}." -f $SourceFiles, $DeployMember) | Write-ValentiaVerboseDebug Write-Verbose ("DeployFolder : {0}" -f $DeployFolder) Write-Verbose ("DeployMembers : {0}" -f $DeployMembers) Write-Verbose ("DeployMember : {0}" -f $DeployMember) Write-Verbose ("Source : {0}" -f $Source) Write-Verbose ("Destination : {0}" -f $Destination) Write-Verbose ("Aync Mode : {0}" -f $Async) # Running Bits Transfer, switch with $Async and no $Async try { switch ($true) { # Async Transfer $Async { try { $ScriptToRun = "Start-BitsTransfer -Source $(($SourceFile).fullname) -Destination $Destination -Credential $Credential -Asynchronous -DisplayName $DeployMember -Priority High -TransferType Download" foreach($SourceFile in $SourceFiles) { try { #Only start download for file. if (-not((Get-Item $SourceFile.fullname).Attributes -eq "Directory")) { # Run Job Write-Warning ("Async Downloading {0} from {1} to {2}" -f ($SourceFile).fullname, $DeployMember, $Destination) $Job = Start-BitsTransfer -Source $(($SourceFile).fullname) -Destination $Destination -Credential $Credential -Asynchronous -DisplayName $DeployMember -Priority High -TransferType Download # Waiting for complete job $Sleepms = 10 "Current States was {0}" -f $Job.JobState | Write-ValentiaVerboseDebug } } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } } # Retrieving transfer status and monitor for transffered $Sleepms = 10 while (((Get-BitsTransfer).JobState -contains "Transferring") -or ((Get-BitsTransfer).JobState -contains "Connecting") -or ((Get-BitsTransfer).JobState -contains "Queued")) ` { "Current Job States was {0}, waiting for {1} ms {2}" -f ((Get-BitsTransfer).JobState | sort -Unique), $Sleepms, (((Get-BitsTransfer | where JobState -eq "Transferred").count) / $((Get-BitsTransfer).count)) | Write-ValentiaVerboseDebug Sleep -Milliseconds $Sleepms } # Retrieve all files when completed Get-BitsTransfer | Complete-BitsTransfer } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } finally { # Delete all not compelte job Get-BitsTransfer | Remove-BitsTransfer # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" $DurationTotal += $Duration } } default { # NOT Async Transfer try { $ScriptToRun = "Start-BitsTransfer -Source $(($SourceFiles).fullname) -Destination $Destination -Credential $Credential -TransferType Download" foreach($SourceFile in $SourceFiles) { #Only start download for file. if (-not((Get-Item $SourceFile.fullname).Attributes -eq "Directory")) { Write-Warning ("Downloading {0} from {1} to {2}" -f ($SourceFile).fullname, $DeployMember, $Destination) Start-BitsTransfer -Source $(($SourceFile).fullname) -Destination $Destination -Credential $Credential -TransferType Download } } } catch [System.Management.Automation.ActionPreferenceStopException] { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } finally { # Delete all not compelte job Get-BitsTransfer | Remove-BitsTransfer # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" } } } } catch { # Show Error Message Write-Error $_ # Set ErrorResult $SuccessStatus += $false $ErrorMessageDetail += $_ } } } else { Write-Warning ("{0} could find from {1}. Skip to next." -f $Source, $DeployGroups) } } ### End Write-Verbose "All transfer with BitsTransfer had been removed." } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ if (-not $SkipException) { throw $_ } } finally { # obtain Result $resultParam = @{ StopWatch = $TotalstopwatchSession Cmdlet = $($MyInvocation.MyCommand.Name) TaskFileName = $TaskFileName DeployGroups = $DeployGroups SkipException = $SkipException Quiet = $PSBoundParameters.ContainsKey("quiet") -and $quiet } Out-ValentiaResult @resultParam # Cleanup valentia Environment Invoke-ValentiaClean } } # file loaded from path : \functions\Invokation\Download\Invoke-ValentiaDownload.ps1 #Requires -Version 3.0 #-- ping Connection to the host --# # PingAsync <# .SYNOPSIS Ping to the host by IP Address Asynchronous .DESCRIPTION This Cmdlet will ping and get reachability to the host. .NOTES Author: guitarrapc Created: 03/Feb/2014 .EXAMPLE Ping-ValentiaGroupAsync production-hoge.ps1 -------------------------------------------- Ping production-hoge.ps1 from deploy group branch path #> function Ping-ValentiaGroupAsync { [OutputType([Valentia.CS.PingResponse[]])] [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, ValueFromPipeLine = 1, ValueFromPipeLineByPropertyName = 1, HelpMessage = "Input target computer name or ipaddress to test ping.")] [string[]]$HostNameOrAddresses, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Input timeout ms wait for the responce answer.")] [ValidateNotNullOrEmpty()] [int]$Timeout = $valentia.ping.timeout, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input timeout ms wait for the responce answer.")] [ValidateNotNullOrEmpty()] [int]$DnsTimeout = $valentia.ping.timeout, [Parameter(Position = 3, mandatory = $false, HelpMessage = "Change return type to bool only.")] [ValidateNotNullOrEmpty()] [switch]$quiet ) begin { $list = New-Object System.Collections.Generic.List["string"]; } process { $target = (Get-ValentiaGroup -DeployGroup $HostNameOrAddresses); foreach ($item in $target){ $list.Add($item); } } end { if ($quiet) { [Valentia.CS.NetworkInformationExtensions]::PingAsync($list, [TimeSpan]::FromMilliseconds($Timeout), [TimeSpan]::FromMilliseconds($DnsTimeout)).Result.Status; } else { [Valentia.CS.NetworkInformationExtensions]::PingAsync($list, [TimeSpan]::FromMilliseconds($Timeout), [TimeSpan]::FromMilliseconds($DnsTimeout)).Result; } } } # file loaded from path : \functions\Invokation\Ping\Ping-ValentiaGroupAsync.ps1 #Requires -Version 3.0 #-- ping Connection to the host --# # PingAsync <# .SYNOPSIS Monitor host by Ping for selected Second .DESCRIPTION This function will pingasync to the host. You can set Interval seconds and endup limitCount to prevent eternal execution. .NOTES Author: guitarrapc Created: 27/July/2014 .EXAMPLE Watch-ValentiaPingAsyncReplyStatus -deploygroups 192.168.100.100 -DesiredStatus $true -limitCount 1000 | ft -------------------------------------------- Continuous ping to the 192.168.100.100 for sleepSec 1 sec. (default) This will break if host is reachable or when count up to limitCount 1000. #> function Watch-ValentiaPingAsyncReplyStatus { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [string[]]$deploygroups, [parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [bool]$DesiredStatus = $true, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [int]$sleepSec = 1, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [int]$limitCount = 100 ) process { $i = 0 while ($true) { $date = Get-Date $hash = pingAsync -HostNameOrAddresses $ipaddress ` | %{ Add-Member -InputObject $_ -MemberType NoteProperty -Name Date -Value $date -Force -PassThru } Write-Verbose ("Filtering status as '{0}'" -f $DesiredStatus) $hash ` | where IsSuccess -eq $DesiredStatus ` | where HostNameOrAddress -in $ipaddress.IPAddressToString ` | %{$result = $ipaddress.Remove($_.HostNameOrAddress) if ($result -eq $false) { throw "failed to remove ipaddress '{0}' from list" -f $_.HostNameOrAddress } else { Write-Host ("ipaddress '{0}' turned to be DesiredStatus '{1}'" -f "$($_.HostNameOrAddress -join ', ')", $DesiredStatus) -ForegroundColor Green } } $count = ($ipaddress | measure).count if ($count -eq 0) { Write-Host ("HostnameOrAddress '{0}' IsSuccess : '{1}'. break monitoring" -f $($hash.HostNameOrAddress -join ", "), $DesiredStatus) -ForegroundColor Cyan $hash break; } elseif ($i -ge $limitCount) { write-Warning ("exceeed {0} count of sleep. break." -f $limitCount) $hash break; } else { Write-Verbose ("sleep {0} second for next status check." -f $sleepSec) $hash sleep -Seconds $sleepSec $i++ } } } end { $end = Get-Date Write-Host ("Start Time : {0}" -f $start) -ForegroundColor Cyan Write-Host ("End Time : {0}" -f $end) -ForegroundColor Cyan Write-Host ("Total Watch : {0}sec" -f $sw.Elapsed.TotalSeconds) -ForegroundColor Cyan } begin { $start = Get-Date $sw = New-Object System.Diagnostics.Stopwatch $sw.Start() $ipaddress = New-Object 'System.Collections.Generic.List[ipaddress]' Get-ValentiaGroup -DeployGroups $deploygroups | %{$ipaddress.Add($_)} } } # file loaded from path : \functions\Invokation\Ping\Watch-ValentiaPingAsyncReplyStatus.ps1 #Requires -Version 3.0 #-- Public Module Functions for Sync Files or Directories--# # Sync <# .SYNOPSIS Use fastcopy.exe to Sync Folder for Diff folder/files not consider Diff from remote server. .DESCRIPTION You must install fastcopy.exe to use this function. .NOTES Author: gutiarrapc Created: 13/July/2013 .EXAMPLE Sync -Source sourcepath -Destination desitinationSharePath -DeployGroup DeployGroup.ps1 -------------------------------------------- Sync sourthpath and destinationsharepath directory in Diff mode. (Will not delete items but only update to add new) .EXAMPLE Sync c:\deployment\upload c:\deployment\upload 192.168.1.100 -------------------------------------------- Sync c:\deployment\upload directory and remote server listed in new.ps1 c:\deployment\upload directory in Diff mode. (Will not delete items but only update to add new) .EXAMPLE Sync -Source c:\upload.txt -Destination c:\share\ -DeployGroup 192.168.1.100,192.168.1.102 -------------------------------------------- Sync c:\upload.txt file and c:\share directory in Diff mode. (Will not delete items but only update to add new) #> function Invoke-ValentiaSync { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input Deploy Server Source Folder Sync to Client PC.")] [string]$SourceFolder, [Parameter(Position = 1, mandatory = $true, HelpMessage = "Input Client Destination Folder Sync with Desploy Server.")] [String]$DestinationFolder, [Parameter(Position = 2, mandatory = $true, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string]$DeployGroups, [Parameter(Position = 3, mandatory = $false, HelpMessage = "Input DeployGroup Folder path if changed.")] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 4, mandatory = $false, HelpMessage = "Return success result even if there are error.")] [bool]$SkipException = $false, [Parameter(Position = 5, mandatory = $false, HelpMessage = "Input PSCredential to use for wsman.")] [PSCredential]$Credential = (Get-ValentiaCredential), [Parameter(Position = 6, mandatory = $false, HelpMessage = "Input fastCopy.exe location folder if changed.")] [string]$FastCopyFolder = $valentia.fastcopy.folder, [Parameter(Position = 7, mandatory = $false, HelpMessage = "Input fastCopy.exe name if changed.")] [string]$FastcopyExe = $valentia.fastcopy.exe ) try { ### Begin $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom # Initialize Stopwatch [decimal]$TotalDuration = 0 $TotalstopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Initialize Errorstatus $SuccessStatus = $ErrorMessageDetail = @() # Get Start Time $TimeStart = (Get-Date).DateTime # Import default Configurations & Modules if ($PSBoundParameters['Verbose']) { # Import default Configurations $valeWarningMessages.warn_import_configuration | Write-ValentiaVerboseDebug Import-ValentiaConfiguration -Verbose # Import default Modules $valeWarningMessages.warn_import_modules | Write-ValentiaVerboseDebug Import-valentiaModules -Verbose } else { Import-ValentiaConfiguration Import-valentiaModules } # Log Setting New-ValentiaLog # Check FastCopy.exe path "Checking FastCopy Folder is exist or not." | Write-ValentiaVerboseDebug if (-not(Test-Path $FastCopyFolder)) { New-Item -Path $FastCopyFolder -ItemType Directory } # Set FastCopy.exe path Write-Verbose "Set FastCopy.exe path." $FastCopy = Join-Path $FastCopyFolder $FastcopyExe # Check SourceFolder Exist or not if (-not(Test-Path $SourceFolder)) { $SuccessStatus += $false $ErrorMessageDetail += "SourceFolder [ $SourceFolder ] not found exeptions! exit job." throw "SourceFolder [ {0} ] not found exeptions! exit job." -f $SourceFolder } # Obtain DeployMember IP or Hosts for FastCopy "Get hostaddresses to connect." | Write-ValentiaVerboseDebug $DeployMembers = Get-valentiaGroup -DeployFolder $DeployFolder -DeployGroup $DeployGroups # Parse Network Destination Path ("Parsing Network Destination Path {0} as :\ should change to $." -f $DestinationFolder) | Write-ValentiaVerboseDebug $DestinationPath = "$DestinationFolder".Replace(":","$") # Safety exit for root drive if ($SourceFolder.Length -ge 3) { Write-Verbose ("SourceFolder[-2]`t:`t$($SourceFolder[-2])") Write-Verbose ("SourceFolder[-1]`t:`t$($SourceFolder[-1])") if (($SourceFolder[-2] + $SourceFolder[-1]) -in (":\",":/")) { $SuccessStatus += $false $ErrorMessageDetail += ("SourceFolder path was Root Drive [ {0} ] exception! Exist for safety." -f $SourceFolder) throw ("SourceFolder path was Root Drive [ {0} ] exception! Exist for safety." -f $SourceFolder) } } # Show Stopwatch for Begin section $TotalDuration = $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tDuration Second for Begin Section: {0}" -f $TotalDuration) "" ### Process Write-Warning "Starting Sync Below files" Write-Verbose (" Syncing {0} to Target Computer : [{1}] {2} `n" -f $SourceFolder, $DeployMembers, $DestinationFolder) (Get-ChildItem $SourceFolder).FullName # Stopwatch [decimal]$DurationTotal = 0 foreach ($DeployMember in $DeployMembers) { # Stopwatch $stopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Create Destination $Destination = Join-Path "\\" $(Join-Path "$DeployMember" "$DestinationPath") # Set FastCopy.exe Argument for Sync $FastCopyArgument = "/cmd=sync /bufsize=512 /speed=full /wipe_del=FALSE /acl /stream /reparse /force_close /estimate /error_stop=FALSE /log=True /logfile=""$($valentia.log.fullPath)"" ""$SourceFolder"" /to=""$Destination""" # Run FastCopy Write-Warning ("[{0}]:Uploading {1} to {2}." -f $DeployMember ,$SourceFolder, $Destination) Write-Verbose ("FastCopy : {0}" -f $FastCopy) Write-Verbose ("FastCopyArgument : {0}" -f $FastCopyArgument) if (Ping-ValentiaGroupAsync -HostNameOrAddresses $DeployMember) { try { 'Command : Start-Process $FastCopy -ArgumentList $FastCopyArgument -Wait -PassThru -Credential $Credential' | Write-ValentiaVerboseDebug $Result = Start-Process $FastCopy -ArgumentList $FastCopyArgument -Wait -PassThru -Credential $Credential } catch { Write-Error $_ $SuccessStatus += $false $ErrorMessageDetail += $_ } } else { Write-Error ("Target Host {0} unreachable. Check DeployGroup file [ {1} ] again" -f $DeployMember, $DeployGroups) $SuccessStatus += $false $ErrorMessageDetail += ("Target Host {0} unreachable. Check DeployGroup file [ {1} ] again" -f $DeployMember, $DeployGroups) } # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" $DurationTotal += $Duration } ### End "All Sync job complete." | Write-ValentiaVerboseDebug if (Test-Path $valentia.log.fullPath) { if (-not((Select-String -Path $valentia.log.fullPath -Pattern "No Errors").count -ge $DeployMembers.count)) { $SuccessStatus += $false $ErrorMessageDetail += ("One or more host was reachable with ping, but not authentiacate to DestinationFolder [ {0} ]" -f $DestinationFolder) Write-Error ("One or more host was reachable with ping, but not authentiacate to DestinationFolder [ {0} ]" -f $DestinationFolder) } } else { $SuccessStatus += $false $ErrorMessageDetail += ("None of the host was reachable with ping with DestinationFolder [ {0} ]" -f $DestinationFolder) Write-Error ("None of the host was reachable with ping with DestinationFolder [ {0} ]" -f $DestinationFolder) } } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ if (-not $SkipException) { throw $_ } } finally { # Show Stopwatch for Total section $TotalDuration += $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tTotal duration Second`t: {0}" -f $TotalDuration) # Get End Time $TimeEnd = (Get-Date).DateTime # obtain Result $CommandResult = [ordered]@{ Success = !($SuccessStatus -contains $false) TimeStart = $TimeStart TimeEnd = $TimeEnd TotalDuration = $TotalDuration Module = "$($MyInvocation.MyCommand.Module)" Cmdlet = "$($MyInvocation.MyCommand.Name)" Alias = "$((Get-Alias -Definition $MyInvocation.MyCommand.Name).Name)" ScriptBlock = "Start-Process $FastCopy -ArgumentList $FastCopyArgument -Wait" DeployGroup = "$DeployGroups" TargetHosCount = $($DeployMembers.count) TargetHosts = "$DeployMembers" Result = $result SkipException = $SkipException ErrorMessage = $($ErrorMessageDetail | where {$_ -ne $null} | sort -Unique) } # show result $quiet = $PSBoundParameters.ContainsKey("quiet") -and $quiet WriteValentiaResultHost -quiet $quiet -CommandResult $CommandResult # output result OutValentiaResultLog -CommandResult $CommandResult -Append # Cleanup valentia Environment Invoke-ValentiaClean } } # file loaded from path : \functions\Invokation\Sync\Invoke-ValentiaSync.ps1 #Requires -Version 3.0 #-- Public Module Functions for Upload Files --# # upload <# .SYNOPSIS Use BITS Transfer to upload a file to remote server. .DESCRIPTION This function supports multiple file transfer, if you want to fix file in list then use uploadList function. .NOTES Author: guitarrapc Created: 13/July/2013 .EXAMPLE upload -SourcePath C:\hogehoge.txt -DestinationPath c:\ -DeployGroup production-first.ps1 -File -------------------------------------------- upload file to destination for hosts written in production-first.ps1 .EXAMPLE upload -SourcePath C:\deployment\Upload -DestinationPath c:\ -DeployGroup production-first.ps1 -Directory -------------------------------------------- upload folder to destination for hosts written in production-first.ps1 .EXAMPLE upload C:\hogehoge.txt c:\ production-first -Directory production-fist.ps1 -Async -------------------------------------------- upload folder as Background Async job for hosts written in production-first.ps1 .EXAMPLE upload C:\hogehoge.txt c:\ production-first -Directory 192.168.0.10 -Async -------------------------------------------- upload file to Directory as Background Async job for host ip 192.168.0.10 .EXAMPLE upload C:\hogehoge* c:\ production-first -Directory production-fist.ps1 -Async -------------------------------------------- upload files in target to Directory as Background Async job for hosts written in production-first.ps1 #> function Invoke-ValentiaUpload { [CmdletBinding(DefaultParameterSetName = "File")] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "Input Deploy Server SourcePath to be uploaded.")] [string]$SourcePath, [Parameter(Position = 1, mandatory = $true, HelpMessage = "Input Clinet DestinationPath to save upload items.")] [String]$DestinationPath = $null, [Parameter(Position = 2, mandatory = $true, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string]$DeployGroups, [Parameter(position = 3, mandatory = $false, ParameterSetName = "File", HelpMessage = "Set this switch to execute command for File. exclusive with Directory Switch.")] [switch]$File = $null, [Parameter(position = 3, mandatory = $false, ParameterSetName = "Directory", HelpMessage = "Set this switch to execute command for Directory. exclusive with File Switch.")] [switch]$Directory, [Parameter(Position = 4, mandatory = $false, HelpMessage = "Set this switch to execute command as Async (Job).")] [switch]$Async = $false, [Parameter(Position = 5, mandatory = $false, HelpMessage = "Input DeployGroup Folder path if changed from default.")] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 6, mandatory = $false, HelpMessage = "Input PSCredential to use for wsman.")] [PSCredential]$Credential = (Get-ValentiaCredential), [Parameter(Position = 7, mandatory = $false, HelpMessage = "Return success result even if there are error.")] [bool]$SkipException = $false ) try { ### Begin $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom # Initialize Stopwatch [decimal]$TotalDuration = 0 $TotalstopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Initialize Errorstatus $SuccessStatus = $ErrorMessageDetail = @() # Get Start Time $TimeStart = (Get-Date).DateTime # Import default Configurations & Modules if ($PSBoundParameters['Verbose']) { # Import default Configurations $valeWarningMessages.warn_import_configuration | Write-ValentiaVerboseDebug Import-ValentiaConfiguration -Verbose # Import default Modules $valeWarningMessages.warn_import_modules | Write-ValentiaVerboseDebug Import-valentiaModules -Verbose } else { Import-ValentiaConfiguration Import-valentiaModules } # Log Setting New-ValentiaLog # Obtain DeployMember IP or Hosts for BITsTransfer "Get hostaddresses to connect." | Write-ValentiaVerboseDebug $DeployMembers = Get-valentiaGroup -DeployFolder $DeployFolder -DeployGroup $DeployGroups # Parse Network Destination Path ("Parsing Network Destination Path {0} as :\ should change to $." -f $DestinationFolder) | Write-ValentiaVerboseDebug $DestinationPath = "$DestinationPath".Replace(":","$") # Show Stopwatch for Begin section $TotalDuration = $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tDuration Second for Begin Section: {0}" -f $TotalDuration) "" ### Process ("Uploading {0} to Target Computer : [{1}] `n" -f $SourcePath, $DeployMembers) | Write-ValentiaVerboseDebug # Stopwatch [decimal]$DurationTotal = 0 # Create PSSession for each DeployMember foreach ($DeployMember in $DeployMembers) { # Stopwatch $stopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Set Destination $Destination = Join-Path "\\" $(Join-Path "$DeployMember" "$DestinationPath") if ($Directory) { # Set Source files in source try { # No recurse $SourceFiles = Get-ChildItem -Path $SourcePath } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ throw $_ } } elseif ($File) { # Set Source files in source try { # No recurse $SourceFiles = Get-Item -Path $SourcePath if ($SourceFiles.Attributes -eq "Directory") { $SuccessStatus += $false $ErrorMessageDetail += "Target is Directory, you must set Filename with -File Switch." throw "Target is Directory, you must set Filename with -File Switch." } } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ throw $_ } } else { $SuccessStatus += $false $ErrorMessageDetail += $_ throw "Missing File or Directory switch. Please set -File or -Directory Switch to specify download type." } # Show Start-BitsTransfer Parameter Write-Warning ("[{0}]:Uploading {1} to {2}." -f $DeployMember,"$($SourceFiles.Name)", $Destination) Write-Verbose ("DestinationDeployFolder : {0}" -f $DeployFolder) Write-Verbose ("Aync Mode : {0}" -f $Async) if (Test-Path $SourcePath) { try { switch ($true) { # Async Transfer $Async { $ScriptToRun = "Start-BitsTransfer -Source $(($Sourcefile).FullName) -Destination $Destination -Credential $Credential -Asynchronous -DisplayName $DeployMember -Priority High -TransferType Upload" try { foreach ($SourceFile in $SourceFiles) { try { # Run Job ("Running Async Job upload to {0}" -f $DeployMember) | Write-ValentiaVerboseDebug $Job = Start-BitsTransfer -Source $(($Sourcefile).FullName) -Destination $Destination -Credential $Credential -Asynchronous -DisplayName $DeployMember -Priority High -TransferType Upload # Waiting for complete job $Sleepms = 10 } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } } $Sleepms = 10 # Retrieving transfer status and monitor for transffered while (((Get-BitsTransfer).JobState -contains "Transferring") -or ((Get-BitsTransfer).JobState -contains "Connecting") -or ((Get-BitsTransfer).JobState -contains "Queued")) ` { ("Current Job States was {0}, waiting for {1}ms {2}" -f ((Get-BitsTransfer).JobState | sort -Unique), $Sleepms, (((Get-BitsTransfer | where JobState -eq "Transferred").count) / $((Get-BitsTransfer).count))) | Write-ValentiaVerboseDebug Sleep -Milliseconds $Sleepms } # Retrieve all files when completed Get-BitsTransfer | Complete-BitsTransfer } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } finally { # Delete all not compelte job Get-BitsTransfer | Remove-BitsTransfer # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" $DurationTotal += $Duration } } # NOT Async Transfer default { $ScriptToRun = "Start-BitsTransfer -Source $(($SourceFiles).fullname) -Destination $Destination -Credential $Credential -TransferType" try { foreach($SourceFile in $SourceFiles) { #Only start upload for file. if (-not((Get-Item $SourceFile.fullname).Attributes -eq "Directory")) { ("Uploading {0} to {1}'s {2}" -f $(($SourceFile).fullname), $DeployMember, $Destination) | Write-ValentiaVerboseDebug Start-BitsTransfer -Source $(($SourceFile).fullname) -Destination $Destination -Credential $Credential } } } catch [System.Management.Automation.ActionPreferenceStopException] { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } finally { # Delete all not compelte job Get-BitsTransfer | Remove-BitsTransfer # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" } } } } catch { # Show Error Message Write-Error $_ # Set ErrorResult $SuccessStatus += $false $ErrorMessageDetail += $_ } } else { Write-Warning ("{0} could find from {1}. Skip to next." -f $Source, $DeployGroups) } } ### End } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ if (-not $SkipException) { throw $_ } } finally { # Stopwatch $TotalDuration = $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tTotal duration Second`t: {0}" -f $TotalDuration) "" | Out-Default # Get End Time $TimeEnd = (Get-Date).DateTime # obtain Result $CommandResult = [ordered]@{ Success = !($SuccessStatus -contains $false) TimeStart = $TimeStart TimeEnd = $TimeEnd TotalDuration = $TotalDuration Module = "$($MyInvocation.MyCommand.Module)" Cmdlet = "$($MyInvocation.MyCommand.Name)" Alias = "$((Get-Alias -Definition $MyInvocation.MyCommand.Name).Name)" ScriptBlock = "$ScriptToRun" DeployGroup = "$DeployGroups" TargetHosCount = $($DeployMembers.count) TargetHosts = "$DeployMembers" SkipException = $SkipException ErrorMessage = $($ErrorMessageDetail | where {$_ -ne $null} | sort -Unique) } # show result $quiet = $PSBoundParameters.ContainsKey("quiet") -and $quiet WriteValentiaResultHost -quiet $quiet -CommandResult $CommandResult # output result OutValentiaResultLog -CommandResult $CommandResult # Cleanup valentia Environment Invoke-ValentiaClean } } # file loaded from path : \functions\Invokation\Upload\Invoke-ValentiaUpload.ps1 #Requires -Version 3.0 #-- Public Module Functions for Upload Listed Files --# # uploadL <# .SYNOPSIS Use BITS Transfer to upload list files to remote server. .DESCRIPTION This function only support files listed in csv sat in upload context. Make sure destination path format is not "c:\" but use "c$\" as UNC path. .NOTES Author: guitarrapc Created: 13/July/2013 .EXAMPLE uploadList -ListFile list.csv -DeployGroup DeployGroup.ps1 -------------------------------------------- upload sourthfile to destinationfile as define in csv for hosts written in DeployGroup.ps1. # # CSV SAMPLE # # Source, Destination # C:\Deployment\Upload\Upload.txt,C$\hogehoge\Upload.txt # C:\Deployment\Upload\DownLoad.txt,C$\hogehoge\DownLoad.txt .EXAMPLE uploadList list.csv -DeployGroup DeployGroup.ps1 -------------------------------------------- upload sourthfile to destinationfile as define in csv for hosts written in DeployGroup.ps1. You can omit -listFile parameter. # # CSV SAMPLE # # Source, Destination # C:\Deployment\Upload\Upload.txt,C$\hogehoge\Upload.txt # C:\Deployment\Upload\DownLoad.txt,C$\hogehoge\DownLoad.txt #> function Invoke-ValentiaUploadList { [CmdletBinding()] param ( [Parameter(Position = 0, Mandatory, HelpMessage = "Input Clinet DestinationPath to save upload items.")] [string]$ListFile, [Parameter(Position = 1, Mandatory, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string]$DeployGroups, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input DeployGroup Folder path if changed from default.")] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 3, mandatory = $false, HelpMessage = "Set this switch to execute command as Async (Job).")] [switch]$Async = $false, [Parameter(Position = 4, mandatory = $false, HelpMessage = "Input PSCredential to use for wsman.")] [PSCredential]$Credential = (Get-ValentiaCredential), [Parameter(Position = 5, mandatory = $false, HelpMessage = "Return success result even if there are error.")] [bool]$SkipException = $false ) try { ### Begin $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom # Initialize Stopwatch [decimal]$TotalDuration = 0 $TotalstopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() # Initialize Errorstatus $SuccessStatus = $ErrorMessageDetail = @() # Get Start Time $TimeStart = (Get-Date).DateTime # Import default Configurations & Modules if ($PSBoundParameters['Verbose']) { # Import default Configurations $valeWarningMessages.warn_import_configuration | Write-ValentiaVerboseDebug Import-ValentiaConfiguration -Verbose # Import default Modules $valeWarningMessages.warn_import_modules | Write-ValentiaVerboseDebug Import-valentiaModules -Verbose } else { Import-ValentiaConfiguration Import-valentiaModules } # Log Setting New-ValentiaLog # Obtain DeployMember IP or Hosts for BITsTransfer "Get hostaddresses to connect." | Write-ValentiaVerboseDebug $DeployMembers = Get-valentiaGroup -DeployFolder $DeployFolder -DeployGroup $DeployGroups # Set SourcePath to retrieve target File full path (default Upload folder of deployment) $SourceFolder = Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Upload) if (-not(Test-Path $SourceFolder)) { ("SourceFolder not found creating {0}" -f $SourceFolder) | Write-ValentiaVerboseDebug New-Item -Path $SourceFolder -ItemType Directory } try { "Defining ListFile full path." | Write-ValentiaVerboseDebug $SourcePath = Join-Path $SourceFolder $ListFile -Resolve } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ throw $_ } # Obtain List of File upload ("Retrive souce file list from {0} `n" -f $SourcePath) | Write-ValentiaVerboseDebug $List = Import-Csv $SourcePath -Delimiter "," # Show Stopwatch for Begin section $TotalDuration = $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tDuration Second for Begin Section: {0}" -f $TotalDuration) "" ### Process (" Uploading Files written in {0} to Target Computer : [{1}] `n" -f $SourcePath, $DeployMembers) | Write-ValentiaVerboseDebug # Stopwatch [decimal]$DurationTotal = 0 foreach ($DeployMember in $DeployMembers){ # Stopwatch $stopwatchSession = [System.Diagnostics.Stopwatch]::StartNew() #Create New List $NewList = $List | %{ [PSCustomObject]@{ Source = $_.source Destination = "\\" + $DeployMember + "\" + $($_.destination) } } try { # Run Start-BitsTransfer Write-Warning ("[{0}]: Uploading {1} to {2} ." -f $DeployMember ,"$($NewList.Source)", "$($NewList.Destination)") Write-Verbose ("ListFile : {0}" -f $SourcePath) Write-Verbose ("Aysnc : {0}" -f $Async) if ($Async) { #Command Detail $ScriptToRun = '$NewList | Start-BitsTransfer -Credential $Credential -Async' # Run Start-BitsTransfer retrieving files from List csv with Async switch ("Running Async uploadL to '{0}'" -f $DeployMember) | Write-ValentiaVerboseDebug $BitsJob = $NewList | Start-BitsTransfer -Credential $Credential -Async # Monitoring Bits Transfer States complete $Sleepms = 10 while (((Get-BitsTransfer).JobState -contains "Transferring") -or ((Get-BitsTransfer).JobState -contains "Connecting") -or ((Get-BitsTransfer).JobState -contains "Queued")) ` { ("Current Job States was '{0}', waiting for '{1}' ms '{2}'" -f "$((Get-BitsTransfer).JobState | sort -Unique)", $Sleepms, (((Get-BitsTransfer | where JobState -eq "Transferred").count) / $((Get-BitsTransfer).count))) | Write-ValentiaVerboseDebug sleep -Milliseconds $Sleepms } # Send Complete message to make file from ****.Tmp ("Completing Async uploadL to '{0}'" -f $DeployMember) | Write-ValentiaVerboseDebug # Retrieve all files when completed Get-BitsTransfer | Complete-BitsTransfer } else { #Command Detail $ScriptToRun = "$NewList | Start-BitsTransfer -Credential $Credential" # Run Start-BitsTransfer retrieving files from List csv ("Running Sync uploadL to {0}" -f $DeployMember) | Write-ValentiaVerboseDebug $NewList | Start-BitsTransfer -Credential $Credential } } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ # Show Error Message throw $_ } finally { "Delete all not compelte job" | Write-ValentiaVerboseDebug Get-BitsTransfer | Remove-BitsTransfer # Stopwatch $Duration = $stopwatchSession.Elapsed.TotalSeconds Write-Verbose ("Session duration Second : {0}" -f $Duration) "" } } ### End } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ if (-not $SkipException) { throw $_ } } finally { # Stopwatch $TotalDuration = $TotalstopwatchSession.Elapsed.TotalSeconds Write-Verbose ("`t`tTotal duration Second`t: {0}" -f $TotalDuration) "" | Out-Default # Get End Time $TimeEnd = (Get-Date).DateTime # obtain Result $CommandResult = [ordered]@{ Success = !($SuccessStatus -contains $false) TimeStart = $TimeStart TimeEnd = $TimeEnd TotalDuration = $TotalDuration Module = "$($MyInvocation.MyCommand.Module)" Cmdlet = "$($MyInvocation.MyCommand.Name)" Alias = "$((Get-Alias -Definition $MyInvocation.MyCommand.Name).Name)" ScriptBlock = "$ScriptToRun" DeployGroup = "$DeployGroups" TargetHosCount = $($DeployMembers.count) TargetHosts = "$DeployMembers" SkipException = $SkipException ErrorMessage = $($ErrorMessageDetail | where {$_ -ne $null} | sort -Unique) } # show result $quiet = $PSBoundParameters.ContainsKey("quiet") -and $quiet WriteValentiaResultHost -quiet $quiet -CommandResult $CommandResult # output result OutValentiaResultLog -CommandResult $CommandResult # Cleanup valentia Environment Invoke-ValentiaClean } } # file loaded from path : \functions\Invokation\Upload\Invoke-ValentiaUploadList.ps1
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Type.ps1
Type.ps1
#Requires -Version 3.0 #-- Public Class load for Asynchronous execution (MultiThread) --# Add-Type @' public class AsyncPipeline { public System.Management.Automation.PowerShell Pipeline ; public System.IAsyncResult AsyncResult ; } '@ #-- PublicEnum for CredRead/Write Type --# Add-Type -TypeDefinition @" public enum ValentiaWindowsCredentialManagerType { Generic = 1, DomainPassword = 2, DomainCertificate = 3 } "@ #-- PublicEnum for Location Type --# Add-Type -TypeDefinition @" public enum ValentiaBranchPath { Application = 1, Deploygroup = 2, Download = 3, Maintenance = 4, Upload = 5, Utils = 6 } "@ #-- PublicEnum Enum for ScheduledTaskTest --# Add-Type -TypeDefinition @" public enum ValentiaScheduledParameterType { Root, Actions, Principal, Settings, Triggers } "@ # file loaded from path : \type\Type.ps1
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Type/Type.ps1
Type.ps1
#Requires -Version 3.0 #-- Public Class load for Asynchronous execution (MultiThread) --# Add-Type @' public class AsyncPipeline { public System.Management.Automation.PowerShell Pipeline ; public System.IAsyncResult AsyncResult ; } '@ #-- PublicEnum for CredRead/Write Type --# Add-Type -TypeDefinition @" public enum ValentiaWindowsCredentialManagerType { Generic = 1, DomainPassword = 2, DomainCertificate = 3 } "@ #-- PublicEnum for Location Type --# Add-Type -TypeDefinition @" public enum ValentiaBranchPath { Application = 1, Deploygroup = 2, Download = 3, Maintenance = 4, Upload = 5, Utils = 6 } "@ #-- PublicEnum Enum for ScheduledTaskTest --# Add-Type -TypeDefinition @" public enum ValentiaScheduledParameterType { Root, Actions, Principal, Settings, Triggers } "@
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Config/valentia-config.ps1
valentia-config.ps1
#-- Public Loading Module Parameters (Recommend to use ($valentia.defaultconfigurationfile) for customization) --# # contains context for default. $valentia.context.push( @{ executedTasks = New-Object System.Collections.Stack; callStack = New-Object System.Collections.Stack; originalEnvPath = $env:Path; originalDirectory = Get-Location; originalErrorActionPreference = $valentia.preference.ErrorActionPreference.original; errorActionPreference = $valentia.preference.ErrorActionPreference.custom; originalDebugPreference = $valentia.preference.DebugPreference.original; debugPreference = $valentia.preference.DebugPreference.custom; originalProgressPreference = $valentia.preference.ProgressPreference.original; progressPreference = $valentia.preference.ProgressPreference.custom; name = $valentia.name; modulePath = $valentia.modulePath; helpersPath = Join-Path $valentia.modulePath $valentia.helpersPath; supportWindows = $valentia.supportWindows; fileEncode = $valentia.fileEncode; tasks = @{}; includes = New-Object System.Collections.Queue; Result = $valentia.Result; } ) # contains default OS user configuration $valentia.users = [PSCustomObject]@{ CurrentUser = $env:USERNAME; deployUser = "deployment"; } $valentia.group = [PSCustomObject]@{ name = "Administrators"; userFlag = "0X10040"; # #UserFlag for password (ex. infinity & No change Password) } # contains valentia execution policy for initial setup $valentia.ExecutionPolicy = [Microsoft.PowerShell.ExecutionPolicy]::Bypass # contains valentia remote invokation authentication mechanism $valentia.Authentication = [System.Management.Automation.Runspaces.AuthenticationMechanism]::Negotiate # contains valentia remote invokation SSL setting $valentia.UseSSL = $false # contains valentia configuration Information $valentia.PSDrive = "V:"; # Set Valentia Mapping Drive with SMBMapping $valentia.deployextension = ".ps1"; # contains default DeployGroup file extension # Define Prefix for Deploy Client NetBIOS name $valentia.prefix = New-Object psobject -property @{ hostName = "web"; ipstring = "ip"; } # contains default deployment Path configuration. $valentia.RootPath = "{0}\Deployment" -f $env:SystemDrive; # contains certificate configuration $valentia.certificate = [PSCustomObject]@{ ThumbPrint = "INPUT THUMBPRINT YOU WANT TO USE" CN = "dsc" # cer subject name you want to export from and import to FilePath = @{ Cert = Join-Path $valentia.appdataconfig.root "\cert\{0}.cer" # cer save location PFX = Join-Path $valentia.appdataconfig.root "\cert\{0}.pfx" # pfx save location } export = @{ CertStoreLocation = [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine # cer Store Location export from CertStoreName = [System.Security.Cryptography.X509Certificates.StoreName]::My # cer Store Name export from CertType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert # export Type should be cert PFXType = [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx # export Type should be pfx } import = @{ CertStoreLocation = [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine # cer Store Location import to CertStoreName = [System.Security.Cryptography.X509Certificates.StoreName]::My # cer Store Name import to } Encrypt = @{ CertPath = "Cert:\LocalMachine\My" ThumbPrint = "INPUT THUMBPRINT YOU WANT TO USE" } } # Define External program path $valentia.fastcopy = [PSCustomObject]@{ folder = '{0}\lib\FastCopy.2.0.11.0\bin' -f $env:ChocolateyInstall; exe = 'FastCopy.exe'; } # contains default configuration, can be overriden in ($valentia.defaultconfigurationfile) in directory with valentia.psm1 or in directory with current task script $valentia.config_default = [PSCustomObject]([ordered]@{ TaskFileName = 'default.ps1'; Result = $valentia.Result TaskFileDir = [ValentiaBranchPath]::Application; taskNameFormat = 'Executing {0}'; verboseError = $false; modules = $null; PSDrive = $valentia.PSDrive; deployextension= $valentia.deployextension; prefix = $valentia.prefix; fastcopy = $valentia.fastcopy; RootPath = $valentia.RootPath; BranchFolder = [Enum]::GetNames([ValentiaBranchPath]); log = $valentia.log; })
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Windows/Set-ValentiaHostName.ps1
Set-ValentiaHostName.ps1
#Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# # rename <# .SYNOPSIS Change Computer name as specified usage. .DESCRIPTION To control hosts, set prefix for each client with IPAddress octets. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Set-valentiaHostName -HostUsage web -------------------------------------------- Change Hostname as web-$PrefixHostName-$PrefixIpString-Ip1-Ip2-Ip3-Ip4 #> function Set-ValentiaHostName { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, HelpMessage = "set usage for the host.")] [string]$HostUsage, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Set Prefix IpString for hostname if required.")] [string]$PrefixIpString = $valentia.prefic.ipstring, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Set this switch to check whatif.")] [switch]$WhatIf ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # Get IpAddress $ipAddress = ([Net.Dns]::GetHostAddresses('').IPAddressToString | Select-String -Pattern "^\d*.\.\d*.\.\d*.\.\d*.").line # Replace . of IpAddress to - $ipAddressString = $ipAddress -replace "\.","-" # Create New Host Name $newHostName = $HostUsage + "-" + $PrefixIpString + $ipAddressString $currentHostName = [Net.Dns]::GetHostName() } process { if ( $currentHostName -eq $newHostName) { Write-Verbose ("Current HostName [ {0} ] was same as new HostName [ {1} ]. Nothing Changed." -f $currentHostName, $newHostName) } else { if ($PSBoundParameters.WhatIf.IsPresent -ne $true) { Write-Warning -Message ("Current HostName [ {0} ] change to New HostName [ {1} ]" -f $currentHostName, $newHostName) Rename-Computer -NewName $newHostName -Force } else { $Host.UI.WriteLine("what if: Current HostName [ {0} ] change to New HostName [ {1} ]" -f $currentHostName, $newHostName) } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Windows/Get-ValentiaRebootRequiredStatus.ps1
Get-ValentiaRebootRequiredStatus.ps1
#Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Get reboot require status for client .DESCRIPTION When Windows Update or Change Hostname event is done, it will requires reboot to take change effect. You can obtain reboot required status with this cmdlet. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Get-ValentiaRebootRequiredStatus -------------------------------------------- Obtain reboot required status. #> function Get-ValentiaRebootRequiredStatus { [CmdletBinding()] param ( ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $WindowsUpdateRebootStatus = $false $FileRenameRebootStatus = $false $WindowsUpdateRebootPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired" $FileRenameRebootPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" } process { if (Test-Path $WindowsUpdateRebootPath) { $WindowsUpdateRebootStatus = $true } if (Get-ItemProperty -Path $FileRenameRebootPath | Get-Member -MemberType NoteProperty | where Name -eq "PendingFileRenameOperations") { $FileRenameRebootStatus = $True } $Result = [PSCustomObject]@{ ComputerName = [Net.DNS]::GetHostName() PendingWindowsUpdateReboot= $WindowsUpdateRebootStatus PendingFileRenameReboot = $FileRenameRebootStatus } } end { return $Result } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Windows/Private/Test-ValentiaPowerShellElevated.ps1
Test-ValentiaPowerShellElevated.ps1
#Requires -Version 3.0 #-- Helper function --# #-- Check Current PowerShell session is elevated or not --# <# .SYNOPSIS Retrieve elavated status of PowerShell Console. .DESCRIPTION Test-ValentiaPowerShellElevated will check shell was elevated is required for some operations access to system folder, files and objects. .NOTES Author: guitarrapc Date: June 17, 2013 .OUTPUTS bool .EXAMPLE C:\PS> Test-ValentiaPowerShellElevated true .EXAMPLE C:\PS> Test-ValentiaPowerShellElevated false #> function Test-ValentiaPowerShellElevated { [CmdletBinding()] param ( ) $user = [Security.Principal.WindowsIdentity]::GetCurrent() return (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CleanupVariables/Invoke-ValentiaClean.ps1
Invoke-ValentiaClean.ps1
#Requires -Version 3.0 #-- Helper for valentia --# # clean <# .SYNOPSIS Clean up valentia task variables. .DESCRIPTION Clear valentia variables for each task, and remove then. valentia only keep default variables after this cmdlet has been run. .NOTES Author: guitarrapc Created: 13/Jul/2013 .EXAMPLE Invoke-ValentiaClean -------------------------------------------- Clean up valentia variables stacked in the $valentia variables. #> function Invoke-ValentiaClean { [CmdletBinding()] param ( ) if ($valentia.context.Count -gt 0) { $currentContext = $valentia.context.Peek() $env:path = $currentContext.originalEnvPath Set-Location $currentContext.originalDirectory $global:ErrorActionPreference = $currentContext.originalErrorActionPreference # Erase Context [void] $valentia.context.Clear() } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CleanupVariables/Invoke-ValentiaCleanResult.ps1
Invoke-ValentiaCleanResult.ps1
#Requires -Version 3.0 #-- Helper for valentia --# # cleanResult <# .SYNOPSIS Clean up valentia task previous result. .DESCRIPTION Clear valentia last result. .NOTES Author: guitarrapc Created: 13/Jul/2013 .EXAMPLE Invoke-ValentiaCleanResult #> function Invoke-ValentiaCleanResult { [CmdletBinding()] param ( ) $valentia.Result = [ordered]@{ SuccessStatus = @() TimeStart = [datetime]::Now.DateTime ScriptToRun = "" DeployMembers = @() Result = New-Object 'System.Collections.Generic.List[PSCustomObject]' ErrorMessageDetail = @() } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Folder/New-ValentiaFolder.ps1
New-ValentiaFolder.ps1
#Requires -Version 3.0 #-- Prerequisite Deploy Setting Module Functions --# <# .SYNOPSIS Configure Deployment Path .DESCRIPTION This cmdlet will create valentis deploy folders for each Branch path. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE New-valentiaFolder -------------------------------------------- create as default #> function New-ValentiaFolder { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Root Folder path.")] [ValidateNotNullOrEmpty()] [string]$RootPath = $valentia.RootPath, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Branch Path path.")] [ValidateNotNullOrEmpty()] [ValentiaBranchPath[]]$BranchPath = [Enum]::GetNames([ValentiaBranchPath]), [Parameter(Position = 2, mandatory = $false, HelpMessage = "Log Folder path.")] [ValidateNotNullOrEmpty()]$LogFolder = $valentia.Log.path, [Parameter(Position = 3, mandatory = $false, HelpMessage = "Suppress output directory create info.")] [switch]$Quiet ) begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # Create Fullpath String if (($BranchPath).count -ne 0) { $DeployFolders = $BranchPath | %{Join-Path $RootPath $_} } $directories = New-Object System.Collections.Generic.List[System.IO.DirectoryInfo] } process { # Check each Fupllpath and create if not exist. foreach ($Deployfolder in $DeployFolders) { if(-not (Test-Path $DeployFolder)) { ("'{0}' not exist, creating." -f $DeployFolder) | Write-ValentiaVerboseDebug $output = New-Item -Path $DeployFolder -ItemType directory -Force $directories.Add($output) } else { ("'{0}' already exist, skip." -f $DeployFolder) | Write-ValentiaVerboseDebug $output = Get-Item -Path $DeployFolder $directories.Add($output) } } # Check Log Folder and create if not exist if(-not (Test-Path $LogFolder)) { ("'{0}' not exist, creating." -f $LogFolder) | Write-ValentiaVerboseDebug $output = New-Item -Path $LogFolder -ItemType directory -Force $directories.Add($output) } else { ("'{0}' already exist, skip." -f $LogFolder) | Write-ValentiaVerboseDebug $output = Get-Item -Path $LogFolder $directories.Add($output) } } end { if (-not $Quiet) { ($directories).FullName } # Cleanup valentia Environment Invoke-ValentiaClean } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/DynamicParam/New-ValentiaDynamicParamMulti.ps1
New-ValentiaDynamicParamMulti.ps1
#Requires -Version 3.0 #-- function helper for Dynamic Param --# <# .SYNOPSIS This cmdlet will return Dynamic param dictionary .DESCRIPTION You can use this cmdlet to define Dynamic Param .NOTES Author: guitrrapc Created: 02/03/2014 .EXAMPLE function Show-ValentiaDynamicParamMulti { [CmdletBinding()] param( [parameter(position = 6)] $nyao ) dynamicParam { $dynamicParams = ( @{Mandatory = $true name = "hoge" Options = "hoge","piyo" position = 0 Type = "System.String[]" validateSet = $true valueFromPipelineByPropertyName = $true}, @{Mandatory = $true name = "foo" Options = 1,2,3,4,5 position = 1 Type = "System.Int32[]" validateSet = $true}, @{DefaultValue = (4,2,5) Mandatory = $false name = "bar" Options = 1,2,3,4,5 position = 2 Type = "System.Int32[]" validateSet = $false} ) $dynamic = New-ValentiaDynamicParamMulti -dynamicParams $dynamicParams return $dynamic } begin { } process { $PSBoundParameters.hoge $PSBoundParameters.foo if ($PSBoundParameters.ContainsKey('bar')) { $PSBoundParameters.bar $PSBoundParameters.bar.GetType().FullName } else { $bar = $dynamic.bar.Value $bar $bar.GetType().FullName } } } "Test 1 ---------------------" Show-ValentiaDynamicParamMulti -hoge hoge -foo 1,2,3,4 "Test 2 ---------------------" Show-ValentiaDynamicParamMulti -hoge piyo -foo 2 -bar 2 #> function New-ValentiaDynamicParamMulti { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0, valueFromPipeline = 1, valueFromPipelineByPropertyName = 1)] [hashtable[]]$dynamicParams ) begin { $dynamicParamLists = New-ValentiaDynamicParamList -dynamicParams $dynamicParams $dictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary } process { foreach ($dynamicParamList in $dynamicParamLists) { # create attributes $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "__AllParameterSets" ( "helpMessage", "mandatory", "parameterSetName", "position", "valueFromPipeline", "valueFromPipelineByPropertyName", "valueFromRemainingArguments" ) ` | %{ if($dynamicParamList.$_) { $attributes.$_ = $dynamicParamList.$_ } } # create attributes Collection $attributesCollection = New-Object 'Collections.ObjectModel.Collection[System.Attribute]' $attributesCollection.Add($attributes) # create validation set if ($dynamicParamList.validateSet) { $validateSetAttributes = New-Object System.Management.Automation.ValidateSetAttribute $dynamicParamList.options $attributesCollection.Add($validateSetAttributes) } # Set default type or get from dynamicparam # Priority # 1. Type KV # 2. Type of DefaultValue # 3. System.Object[] if ($dynamicParamList.type) { $type = [Type]::GetType($dynamicParamList.Type) } else { if ($dynamicParamList.defaultValue) { $DefaultValueType = $dynamicParamList.defaultValue.GetType().FullName $type = [Type]::GetType($DefaultValueType) } else { $type = [Type]::GetType("System.Object[]") } } if ($null -eq $type) { throw "type not defined or Null exception! Make sure you have set fullname for the type : '{0}'" -f $dynamicParamList.type } # create RuntimeDefinedParameter $runtimeDefinedParameter = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter @($dynamicParamList.name, $type, $attributesCollection) # Set Default Value if passed if ($dynamicParamList.defaultValue) { if ($dynamicParamList.defaultValue -is $type) { $runtimeDefinedParameter.Value = $dynamicParamList.defaultValue } elseif ($dynamicParamList.defaultValue -as $type) { Write-Verbose ("Convert Type for ParameterName '{0}'. DefaultValue '{1}' convert from '{2}' to '{3}'" ` -f $dynamicParamList.name, $dynamicParamLists.defaultValue, $dynamicParamList.defaultValue.GetType().FullName, $type) $runtimeDefinedParameter.Value = $dynamicParamList.defaultValue -as $type } else { throw "Cannot convert Type for ParameterName '{0}'. DefaultValue '{1}' could not convert from '{2}' to '{3}'" ` -f $dynamicParamList.name, $dynamicParamLists.defaultValue, $dynamicParamList.defaultValue.GetType().FullName, $type } } # create Dictionary $dictionary.Add($dynamicParamList.name, $runtimeDefinedParameter) } } end { # return result return $dictionary } } <# .SYNOPSIS This cmdlet will return Dynamic param list item for dictionary .DESCRIPTION You can pass this list to DynamicPramMulti to create Dynamic Param #> function New-ValentiaDynamicParamList { [CmdletBinding()] param ( [parameter( mandatory = $true, position = 0, valueFromPipeline = 1, valueFromPipelineByPropertyName = 1)] [hashtable[]] $dynamicParams ) begin { # create generic list $list = New-Object System.Collections.Generic.List[HashTable] # create key check array [string[]]$keyCheckInputItems = "helpMessage", "mandatory", "name", "parameterSetName", "options", "position", "valueFromPipeline", "valueFromPipelineByPropertyName", "valueFromRemainingArguments", "validateSet", "Type", "DefaultValue" $keyCheckList = New-Object System.Collections.Generic.List[String] $keyCheckList.AddRange($keyCheckInputItems) # sort dynamicParams hashtable by position $newDynamicParams = Sort-ValentiaDynamicParamHashTable -dynamicParams $dynamicParams } process { foreach ($dynamicParam in $newDynamicParams) { $invalidParamter = $dynamicParam.Keys | where {$_ -notin $keyCheckList} if ($($invalidParamter).count -ne 0) { throw ("Invalid parameter '{0}' found. Please use parameter from '{1}'" -f $invalidParamter, ("$keyCheckInputItems" -replace " "," ,")) } else { if (-not $dynamicParam.Keys.contains("name")) { throw ("You must specify mandatory parameter '{0}' to hashtable key." -f "name") } elseif (-not $dynamicParam.Keys.contains("options")) { throw ("You must specify mandatory parameter '{0}' to hashtable key." -f "options") } else { $list.Add($dynamicParam) } } } } end { return $list } } function Sort-ValentiaDynamicParamHashTable { [CmdletBinding()] param ( [parameter( mandatory = $true, position = 0, valueFromPipeline = 1, valueFromPipelineByPropertyName = 1)] [hashtable[]] $dynamicParams ) begin { # get max number of position for null position item $max = ($dynamicParams.position | measure -Maximum).Maximum } process { # output PSCustomObject[Name<SortedPosition>,Value<DynamicParamHashTable>]. posision is now sorted. $h = $dynamicParams ` | %{ $history = New-Object System.Collections.Generic.List[int] $hash = @{} # temp posision for null item. This set as (max + number of collection items) $num = $max + $parameters.Length }{ Write-Verbose ("position is '{0}'." -f $position) $position = $_.position #region null check if ($null -eq $position) { Write-Verbose ("position is '{0}'. set current max index '{1}'" -f $position, $num) $position = $num $num++ } #endregion #region dupricate check if ($position -notin $history) { Write-Verbose ("position '{0}' not found in '{1}'. Add to history." -f $position, ($history -join ", ")) $history.Add($position) } else { $changed = $false while ($position -in $history) { Write-Verbose ("position '{0}' found in '{1}'. Start increment." -f $position, ($history -join ", ")) $position++ $changed = $true } Write-Verbose (" incremented position '{0}' not found in '{1}'. Add to history." -f $position, ($history -join ", ")) if ($changed){$history.Add($position)} } #endregion #region set temp hash Write-Verbose ("Set position '{0}' as name of temp hash." -f $position) $hash."$position" = $_ #endregion }{[PSCustomObject]$hash} } end { # get index for each object $index = [int[]](($h | Get-Member -MemberType NoteProperty).Name) | sort # return sorted hash order by index return $index | %{$h.$_} } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Group/Get-ValentiaGroup.ps1
Get-ValentiaGroup.ps1
#Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# # target <# .SYNOPSIS Get ipaddress or NetBIOS from DeployGroup File specified .DESCRIPTION This cmdlet will read Deploy Group path and set them into array of Deploygroups. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE target production-hoge.ps1 -------------------------------------------- read production-hoge.ps1 from deploy group branch path. .EXAMPLE target production-hoge.ps1 c:\test -------------------------------------------- read production-hoge.ps1 from c:\test. #> function Get-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Input target of deploy clients as [DeployGroup filename you sat at deploygroup Folder] or [ipaddress].")] [string[]]$DeployGroups, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Input DeployGroup Folder path if changed from default.")] [ValidateNotNullOrEmpty()] [string]$DeployFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)) ) process { foreach ($DeployGroup in $DeployGroups) { # Get valentia.deployextension information ('Set DeployGroupFile Extension as "$valentia.deployextension" : {0}' -f $valentia.deployextension) | Write-ValentiaVerboseDebug $DeployExtension = $valentia.deployextension 'Read DeployGroup and return $DeployMemebers' | Write-ValentiaVerboseDebug Read-ValentiaGroup -DeployGroup $DeployGroup } } begin { # Get valentiaGroup function Read-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, Mandatory)] [string] $DeployGroup ) if ($DeployGroup.EndsWith($DeployExtension)) # if DeployGroup last letter = Extension is same as $DeployExtension { $DeployGroupPath = Join-Path $DeployFolder $DeployGroup -Resolve ("Read DeployGroupPath {0} where letter not contain # inline." -f $DeployGroupPath) | Write-ValentiaVerboseDebug return (Select-String -path $DeployGroupPath -Pattern ".*#.*" -notmatch -Encoding $valentia.fileEncode | Select-String -Pattern "\w" -Encoding $valentia.fileEncode).line } else { return $DeployGroup } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Group/New-ValentiaGroup.ps1
New-ValentiaGroup.ps1
#Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# <# .SYNOPSIS Create new DeployGroup File written "target PC IP/hostname" for PS-RemoteSession .DESCRIPTION This cmdlet will create valentis deploy group file to specify deploy targets. .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE New-valentiaGroup -DeployClients "10.0.4.100","10.0.4.101" -FileName new.ps1 -------------------------------------------- write 10.0.4.100 and 10.0.4.101 to create deploy group file as "new.ps1". #> function New-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1, HelpMessage = "Specify IpAddress or NetBIOS name for deploy target clients.")] [string[]]$DeployClients, [Parameter(Position = 1, mandatory = $true, HelpMessage = "Input filename to output DeployClients")] [string]$FileName, [Parameter(Position = 2, mandatory = $false, HelpMessage = "Specify folder path to deploy group. defailt is Deploygroup branchpath")] [string]$DeployGroupsFolder = (Join-Path $Script:valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [Parameter(Position = 3, mandatory = $false, HelpMessage = "If you want to add item to exist file.")] [switch]$Add, [Parameter(Position = 4, mandatory = $false, HelpMessage = "If you want to popup confirm message when file created.")] [switch]$Confirm, [Parameter(Position = 5, mandatory = $false, HelpMessage = "If you want to Show file information when operation executed.")] [switch]$PassThru ) process { if($PSBoundParameters.ContainsKey('Add')) { $DeployClients | Add-Content @param } else { $DeployClients | Set-Content @param } } begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest # check FileName is null or empty try { if ([string]::IsNullOrEmpty($FileName)) { throw '"$FileName" was Null or Enpty, input DeployGroup FileName.' } else { $DeployPath = Join-Path $DeployGroupsFolder $FileName } } catch { throw $_ } # set splatting $param = @{ path = $DeployPath Encoding = $valentia.fileEncode Force = $true Confirm = $PSBoundParameters.ContainsKey('Confirm') PassThru = $PSBoundParameters.ContainsKey('PassThru') } } end { if (Test-Path $DeployPath) { Get-ChildItem -Path $DeployPath } else { Write-Error ("{0} not existing." -f $DeployPath) } # Cleanup valentia Environment Invoke-ValentiaClean } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Group/Invoke-ValentiaDeployGroupUnremark.ps1
Invoke-ValentiaDeployGroupUnremark.ps1
#Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# # ipunremark <# .SYNOPSIS Unremark Deploy ip from deploygroup file .DESCRIPTION This cmdlet unremark deploygroup ipaddresses from $valentia.root\$valentia.branch.deploygroup to refer the ipaddress. .NOTES Author: guitarrapc Created: 04/Oct/2013 .EXAMPLE Invoke-valentiaDeployGroupUnremark -unremarkIPAddresses 10.0.0.10,10.0.0.11 -overWrite -Verbose -------------------------------------------- replace #10.0.0.10 and #10.0.0.11 with 10.0.0.10 and 10.0.0.11 then replace file (like sed -f "s/^#10.0.0.10$/10.0.0.10" -i) Invoke-valentiaDeployGroupUnremark -unremarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -------------------------------------------- replace #10.0.0.10 and #10.0.0.11 with 10.0.0.10 and 10.0.0.11 (like sed -f "s/^#10.0.0.10$/10.0.0.10") Invoke-valentiaDeployGroupUnremark -remarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -Recurse $false -Path d:\hoge -------------------------------------------- Check d:\hoge folder without recursive. This means it only check path you desired. #> function Invoke-ValentiaDeployGroupUnremark { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [Alias("IPAddress", "HostName")] [string[]]$unremarkIPAddresses, [parameter(position = 1, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [string]$Path = (Join-Path $valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [parameter(position = 2, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [bool]$Recurse = $true, [parameter(position = 3, mandatory = $false)] [switch]$overWrite, [parameter(position = 4, mandatory = $false)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $encoding = $valentia.fileEncode ) begin { if (-not (Test-Path $Path)){ throw New-Object System.IO.FileNotFoundException ("Path $Path not found Exception!!", "$Path")} } end { Get-ChildItem -Path $Path -Recurse:$Recurse -File ` | %{ foreach ($unremarkIPAddress in $unremarkIPAddresses) { if ($overWrite) { Invoke-ValentiaSed -path $_.FullName -searchPattern "^#$unremarkIPAddress$" -replaceWith "$unremarkIPAddress" -encoding $encoding -overWrite } else { Invoke-ValentiaSed -path $_.FullName -searchPattern "^#$unremarkIPAddress$" -replaceWith "$unremarkIPAddress" -encoding $encoding } } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Group/Show-ValentiaGroup.ps1
Show-ValentiaGroup.ps1
#Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# <# .SYNOPSIS Show valentia deploygroup file (.ps1) list .DESCRIPTION This cmdlet will show files (extension = $valentia.deployextension = default is '.ps1') in [ValentiaBranchPath]::Deploygroup folder. .NOTES Author: guitarrapc Created: 29/Oct/2013 .EXAMPLE Show-ValentiaGroup -------------------------------------------- show files in $valentia.Root\([ValentiaBranchPath]::Deploygroup) folder. #> function Show-ValentiaGroup { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Input branch folder to show.")] [ValentiaBranchPath[]]$Branches = ([ValentiaBranchPath]::Deploygroup), [Parameter(Position = 1, mandatory = $false, HelpMessage = "Use if you want to search directory recursibly.")] [switch]$recurse ) $DeployExtension = $valentia.deployextension foreach ($branch in $Branches) { if ($branch.Length -eq 0) { throw '"$Branch" was Null or Empty, input BranchName.' } else { ("Creating full path and resolving with '{0}' and '{1}'" -f $valentia.RootPath, ([ValentiaBranchPath]::$branch)) | Write-ValentiaVerboseDebug $BranchFolder = Join-Path $valentia.RootPath $branch -Resolve # show items $param = @{ Path = $BranchFolder Recurse = if($PSBoundParameters.recurse.IsPresent){$true}else{$false} } Get-ChildItem @param | where extension -eq $DeployExtension } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Group/Invoke-ValentiaDeployGroupRemark.ps1
Invoke-ValentiaDeployGroupRemark.ps1
#Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# # ipremark <# .SYNOPSIS Remark Deploy ip from deploygroup file .DESCRIPTION This cmdlet remark deploygroup ipaddresses from $valentia.root\$valentia.branch.deploygroup not to refer the ipaddress .NOTES Author: guitarrapc Created: 04/Oct/2013 .EXAMPLE Invoke-valentiaDeployGroupRemark -remarkIPAddresses 10.0.0.10,10.0.0.11 -overWrite -Verbose -------------------------------------------- replace 10.0.0.10 and 10.0.0.11 with #10.0.0.10 and #10.0.0.11 then replace file. (like sed -f "s/^10.0.0.10$/#10.0.0.10" -i) Invoke-valentiaDeployGroupRemark -remarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -------------------------------------------- replace 10.0.0.10 and 10.0.0.11 with #10.0.0.10 and #10.0.0.11 (like sed -f "s/^10.0.0.10$/#10.0.0.10") Invoke-valentiaDeployGroupRemark -remarkIPAddresses 10.0.0.10,10.0.0.11 -Verbose -Recurse $false -Path d:\hoge -------------------------------------------- Check d:\hoge folder without recursive. This means it only check path you desired. #> function Invoke-ValentiaDeployGroupRemark { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [Alias("IPAddress", "HostName")] [string[]]$remarkIPAddresses, [parameter(position = 1, mandatory = $false,ValueFromPipelineByPropertyName = 1)] [string]$Path = (Join-Path $valentia.RootPath ([ValentiaBranchPath]::Deploygroup)), [parameter(position = 2, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [bool]$Recurse = $true, [parameter(position = 3, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [switch]$overWrite, [parameter(position = 4, mandatory = $false, ValueFromPipelineByPropertyName = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode ) begin { if (-not (Test-Path $Path)){ throw New-Object System.IO.FileNotFoundException ("Path $Path not found Exception!!", "$Path")} } end { Get-ChildItem -Path $Path -Recurse:$Recurse -File ` | %{ foreach ($remarkIPAddress in $remarkIPAddresses) { if ($overWrite) { Invoke-ValentiaSed -path $_.FullName -searchPattern "^$remarkIPAddress$" -replaceWith "#$remarkIPAddress" -encoding $encoding -overWrite } else { Invoke-ValentiaSed -path $_.FullName -searchPattern "^$remarkIPAddress$" -replaceWith "#$remarkIPAddress" -encoding $encoding } } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/SymbolicLink/Remove-ValentiaSymbolicLink.ps1
Remove-ValentiaSymbolicLink.ps1
#Requires -Version 3.0 #-- SymbolicLink Functions --# <# .SYNOPSIS This function will Remove only SymbolicLink items. .DESCRIPTION PowerShell SymbolicLink function. Alternative to mklink Symbolic Link. This function detect where input file fullpath item is file/directory SymbolicLink, then only remove if it is SymbolicLink. You don't need to care about input Path is FileInfo or DirectoryInfo. .NOTES Author: guitarrapc Created: 12/Aug/2014 .EXAMPLE ls d:\ | Remove-ValentiaSymbolicLink -------------------------------------------- Pipeline Input to detect SymbolicLink items. .EXAMPLE Remove-ValentiaSymbolicLink (ls d:\).FullName -------------------------------------------- Parameter Input to detect SymbolicLink items. #> function Remove-ValentiaSymbolicLink { [OutputType([Void])] [cmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('FullName')] [String[]]$Path ) begin { $script:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom function IsFile ([string]$Path) { if ([System.IO.File]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as File." -f $Path) return [System.IO.FileInfo]($Path) } } function IsDirectory ([string]$Path) { if ([System.IO.Directory]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as Directory." -f $Path) return [System.IO.DirectoryInfo] ($Path) } } function IsFileReparsePoint ([System.IO.FileInfo]$Path) { Write-Verbose ('File attribute detected as ReparsePoint') $fileAttributes = [System.IO.FileAttributes]::Archive, [System.IO.FileAttributes]::ReparsePoint -join ', ' $attribute = [System.IO.File]::GetAttributes($Path.fullname) $result = $attribute -eq $fileAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $attribute) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $attribute) return $result } } function IsDirectoryReparsePoint ([System.IO.DirectoryInfo]$Path) { $directoryAttributes = [System.IO.FileAttributes]::Directory, [System.IO.FileAttributes]::ReparsePoint -join ', ' $result = $Path.Attributes -eq $directoryAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $Path.Attributes) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $Path.Attributes) return $result } } function RemoveFileReparsePoint ([System.IO.FileInfo]$Path) { [System.IO.File]::Delete($Path.FullName) } function RemoveDirectoryReparsePoint ([System.IO.DirectoryInfo]$Path) { [System.IO.Directory]::Delete($Path.FullName) } } process { try { $Path ` | %{ if ($file = IsFile -Path $_) { if (IsFileReparsePoint -Path $file) { RemoveFileReparsePoint -Path $file } } elseif ($directory = IsDirectory -Path $_) { if (IsDirectoryReparsePoint -Path $directory) { RemoveDirectoryReparsePoint -Path $directory } } } } catch { throw $_ } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/SymbolicLink/Get-ValentiaSymbolicLink.ps1
Get-ValentiaSymbolicLink.ps1
#Requires -Version 3.0 #-- SymbolicLink Functions --# <# .SYNOPSIS This function will detect only SymbolicLink items. .DESCRIPTION PowerShell SymbolicLink function. Alternative to mklink Symbolic Link. This function detect where input file fullpath item is file/directory SymbolicLink, then only Ennumerate if it is SymbolicLink. .NOTES Author: guitarrapc Created: 12/Aug/2014 .EXAMPLE ls d:\ | Get-ValentiaSymbolicLink -------------------------------------------- Pipeline Input to detect SymbolicLink items. .EXAMPLE Get-ValentiaSymbolicLink (ls d:\).FullName -------------------------------------------- Parameter Input to detect SymbolicLink items. #> function Get-ValentiaSymbolicLink { [OutputType([System.IO.DirectoryInfo[]])] [cmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('FullName')] [String[]]$Path ) begin { $private:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom function IsFile ([string]$Path) { if ([System.IO.File]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as File." -f $Path) return [System.IO.FileInfo]($Path) } } function IsDirectory ([string]$Path) { if ([System.IO.Directory]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as Directory." -f $Path) return [System.IO.DirectoryInfo] ($Path) } } function IsFileReparsePoint ([System.IO.FileInfo]$Path) { Write-Verbose ('File attribute detected as ReparsePoint') $fileAttributes = [System.IO.FileAttributes]::Archive, [System.IO.FileAttributes]::ReparsePoint -join ', ' $attribute = [System.IO.File]::GetAttributes($Path) $result = $attribute -eq $fileAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $attribute) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $attribute) return $result } } function IsDirectoryReparsePoint ([System.IO.DirectoryInfo]$Path) { $directoryAttributes = [System.IO.FileAttributes]::Directory, [System.IO.FileAttributes]::ReparsePoint -join ', ' $result = $Path.Attributes -eq $directoryAttributes if ($result) { Write-Verbose ('Attribute detected as ReparsePoint. : {0}' -f $Path.Attributes) return $result } else { Write-Verbose ('Attribute detected as NOT ReparsePoint. : {0}' -f $Path.Attributes) return $result } } } process { try { $Path ` | %{ if ($file = IsFile -Path $_) { if (IsFileReparsePoint -Path $file.FullName) { # [Valentia.SymbolicLinkGet]::GetSymbolicLinkTarget() # [System.Type]::GetType($typeQualifiedName)::GetSymbolicLinkTarget() $symTarget = [Valentia.CS.SymbolicLink]::GetSymbolicLinkTarget($file.FullName) Add-Member -InputObject $file -MemberType NoteProperty -Name SymbolicPath -Value $symTarget -Force return $file } } elseif ($directory = IsDirectory -Path $_) { if (IsDirectoryReparsePoint -Path $directory.FullName) { # [Valentia.SymbolicLinkGet]::GetSymbolicLinkTarget() # [System.Type]::GetType($typeQualifiedName)::GetSymbolicLinkTarget() $symTarget = [Valentia.CS.SymbolicLink]::GetSymbolicLinkTarget($directory.FullName) Add-Member -InputObject $directory -MemberType NoteProperty -Name SymbolicPath -Value $symTarget -Force return $directory } } } } catch { throw $_ } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/SymbolicLink/Set-ValentiaSymbolicLink.ps1
Set-ValentiaSymbolicLink.ps1
#Requires -Version 3.0 <# .SYNOPSIS This function will Set SymbolicLink items for desired Path. .DESCRIPTION PowerShell SymbolicLink function. Alternative to mklink Symbolic Link. This function will create Symbolic Link for input file fullpath. Also it works as like LINQ Zip method for different number items was passed for each -Path and -SymbolicPath. As Zip use minimal number item, this function also follow it. .NOTES Author: guitarrapc Created: 12/Aug/2014 .EXAMPLE ls d:\ ` | select -Last 2 ` | %{ @{ Path = $_.FullName SymbolicPath = Join-Path "d:\zzzzz" $_.Name } } ` | Set-SymbolicLink -Verbose-------------------------------------------- Pipeline Input to create SymbolicLink items. This will make symbolic in d:\zzzz with samename of input Path name. This means you can easily create Symbolic for different Path. .EXAMPLE Set-SymbolicLink -Path (ls d:\ | select -Last 2).FullName -SymbolicPath d:\hoge1, d:\hoge2, d:\hoge3 -Verbose -------------------------------------------- Parameter Input. This will create Symbolic Link for -Path input 2 items, with -SymbolicPath input d:\hoge1 and d:\hoge2. As number input was less with -Path, d:\hoge3 will be ignore. #> function Set-ValentiaSymbolicLink { [OutputType([Void])] [cmdletBinding(DefaultParameterSetName = "ForceFile")] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('TargetPath')] [Alias('FullName')] [String[]]$Path, [parameter(mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = 1)] [String[]]$SymbolicPath, [parameter(mandatory = $false, Position = 2, ValueFromPipelineByPropertyName = 1, ParameterSetName = "ForceFile")] [bool]$ForceFile = $false, [parameter(mandatory = $false, Position = 2, ValueFromPipelineByPropertyName = 1, ParameterSetName = "ForceDirectory")] [bool]$ForceDirectory = $false ) begin { $private:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom $prefix = "_" $i = 0 # Initialize prefix Length function IsFile ([string]$Path) { if ([System.IO.File]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as File." -f $Path) return [System.IO.FileInfo]($Path) } } function IsDirectory ([string]$Path) { if ([System.IO.Directory]::Exists($Path)) { Write-Verbose ("Input object : '{0}' detected as Directory." -f $Path) return [System.IO.DirectoryInfo] ($Path) } } function IsFileAttribute ([System.IO.FileInfo]$Path) { $fileAttributes = [System.IO.FileAttributes]::Archive $attribute = [System.IO.File]::GetAttributes($Path.fullname) $result = $attribute -eq $fileAttributes if ($result) { Write-Verbose ('Attribute detected as File Archive. : {0}' -f $attribute) return $result } else { Write-Verbose ('Attribute detected as NOT File archive. : {0}' -f $attribute) return $result } } function IsDirectoryAttribute ([System.IO.DirectoryInfo]$Path) { $directoryAttributes = [System.IO.FileAttributes]::Directory $result = $Path.Attributes -eq $directoryAttributes if ($result) { Write-Verbose ('Attribute detected as Directory. : {0}' -f $Path.Attributes) return $result } else { Write-Verbose ('Attribute detected as NOT Directory. : {0}' -f $Path.Attributes) return $result } } } process { # Work as like LINQ Zip() method $zip = New-ValentiaZipPairs -first $Path -second $SymbolicPath foreach ($x in $zip) { # reverse original key $targetPath = $x.item1 $SymbolicNewPath = $x.item2 if ($ForceFile -eq $true) { [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $Path, $false) } elseif ($ForceDirectory -eq $true) { [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $Path, $true) } elseif ($file = IsFile -Path $targetPath) { # Check File Type if (IsFileAttribute -Path $file) { Write-Verbose ("symbolicPath : '{0}', target : '{1}', isDirectory : '{2}'" -f $SymbolicNewPath, $file.fullname, $false) [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $file.fullname, $false) } } elseif ($directory = IsDirectory -Path $targetPath) { # Check Directory Type if (IsDirectoryAttribute -Path $directory) { Write-Verbose ("symbolicPath : '{0}', target : '{1}', isDirectory : '{2}'" -f $SymbolicNewPath, $directory.fullname, $true) [Valentia.CS.SymbolicLink]::CreateSymLink($SymbolicNewPath, $directory.fullname, $true) } } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/SymbolicLink/Test-ValentiaSymbolicLink.ps1
Test-ValentiaSymbolicLink.ps1
#Requires -Version 3.0 #-- SymbolicLink Functions --# <# .SYNOPSIS This function will Test whether target path is Symbolic Link or not. .DESCRIPTION If target is Symbolic Link (reparse point), function will return $true. Others, return $false. .NOTES Author: guitarrapc Created: 12/Feb/2015 .EXAMPLE Test-ValentiaSymbolicLink -Path "d:\SymbolicLink" -------------------------------------------- As Path is Symbolic Link, this returns $true. #> function Test-ValentiaSymbolicLink { [OutputType([System.IO.DirectoryInfo[]])] [cmdletBinding()] param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline =1, ValueFromPipelineByPropertyName = 1)] [Alias('FullName')] [String]$Path ) begin { $script:ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom } process { $result = Get-ValentiaSymbolicLink -Path $Path if ($null -eq $result) { return $false } return $true } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Credential/Set-ValentiaCredential.ps1
Set-ValentiaCredential.ps1
#Requires -Version 3.0 function Set-ValentiaCredential { [OutputType([void])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential]$Credential = (Get-Credential -User $valentia.Users.DeployUser -Message "Input password to be save."), [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic ) [Valentia.CS.CredentialManager]::Write($TargetName, $Credential, $Type) }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Credential/Test-ValentiaCredential.ps1
Test-ValentiaCredential.ps1
#Requires -Version 3.0 function Test-ValentiaCredential { [OutputType([bool])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic ) [Valentia.CS.CredentialManager]::Exists($TargetName, $Type); }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Credential/Remove-ValentiaCredential.ps1
Remove-ValentiaCredential.ps1
#Requires -Version 3.0 function Remove-ValentiaCredential { [OutputType([void])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic ) [Valentia.CS.CredentialManager]::Remove($TargetName, $Type); }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Credential/Get-ValentiaCredential.ps1
Get-ValentiaCredential.ps1
#Requires -Version 3.0 function Get-ValentiaCredential { [OutputType([PSCredential])] [CmdletBinding()] param ( [Parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$TargetName = $valentia.name, [Parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [Valentia.CS.CredType]$Type = [Valentia.CS.CredType]::Generic, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [string]$AsUserName = "" ) return [Valentia.CS.CredentialManager]::Read($TargetName, $Type, $AsUserName); }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/HostOutput/Write-ValentiaVerboseDebug.ps1
Write-ValentiaVerboseDebug.ps1
#Requires -Version 3.0 #-- helper for write verbose and debug --# <# .SYNOPSIS Pass to write-verbose / debug for input. .DESCRIPTION You can show same message for verbose and debug. .NOTES Author: guitarrapc Created: 16/Feb/2014 .EXAMPLE "hoge" | Write-ValentiaVerboseDebug -------------------------------------------- Will show both Verbose message and Debug. #> filter Write-ValentiaVerboseDebug { Write-Verbose -Message $_ Write-Debug -Message $_ }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Location/Set-ValentiaLocation.ps1
Set-ValentiaLocation.ps1
#Requires -Version 3.0 #-- Helper for valentia --# # go <# .SYNOPSIS Move location to valentia folder .DESCRIPTION You can specify branch path in configuration. If you changed from default, then change validation set for BranchPath for intellisence. .NOTES Author: guitarrapc Created: 13/Jul/2013 .EXAMPLE go -------------------------------------------- just move to root deployment path. .EXAMPLE go application -------------------------------------------- change location to BranchPath c:\deployment\application (in default configuration.) #> function Set-ValentiaLocation { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Select branch deploy folder to change directory.")] [ValentiaBranchPath]$BranchPath ) begin { $prevLocation = (Get-Location).Path $newlocation = Join-Path $valentia.RootPath ([ValentiaBranchPath]::$BranchPath) } process { # Move to BrachPath if exist ("moving to new location as '{0}' : '{1}'" -f $BranchPath, $newlocation) | Write-ValentiaVerboseDebug if (Test-Path $newlocation) { Set-Location -Path $newlocation } else { throw "Path not found exception! Make sure {0} is exist." -f $newlocation } } end { ("moved Location : '{0}', previous Location : '{1}'" -f (Get-Location).Path, $prevLocation) | Write-ValentiaVerboseDebug if ((Get-Location).Path -ne $prevLocation) { ("Location change to '{0}'" -f (Get-Location).Path) | Write-ValentiaVerboseDebug } else { Write-Warning "Location not changed." } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/User/New-ValentiaOSUser.ps1
New-ValentiaOSUser.ps1
#Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Create New Local User for Deployment .DESCRIPTION Deployment will use deploy user account credential to avoid any change for administartor. You must add all this user credential for each clients. # User Flag Property Samples. You should combinate these 0x00zz if required. # # &H0001 Run LogOn Script  # 0X0001 ADS_UF_SCRIPT # # &H0002 Account Disable # 0X0002 ADS_UF_ACCOUNTDISABLE # # &H0008 Account requires Home Directory # 0X0008 ADS_UF_HOMEDIR_REQUIRED # # &H0010 Account Lockout # 0X0010 ADS_UF_LOCKOUT # # &H0020 No Password reqyured for account # 0X0020 ADS_UF_PASSWD_NOTREQD # # &H0040 No change Password # 0X0040 ADS_UF_PASSWD_CANT_CHANGE # # &H0080 Allow Encypted Text Password # 0X0080 ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED # # 0X0100 ADS_UF_TEMP_DUPLICATE_ACCOUNT # 0X0200 ADS_UF_NORMAL_ACCOUNT # 0X0800 ADS_UF_INTERDOMAIN_TRUST_ACCOUNT # 0X1000 ADS_UF_WORKSTATION_TRUST_ACCOUNT # 0X2000 ADS_UF_SERVER_TRUST_ACCOUNT # # &H10000 Password infinit # 0X10000 ADS_UF_DONT_EXPIRE_PASSWD # # 0X20000 ADS_UF_MNS_LOGON_ACCOUNT # # &H40000 Smart Card Required # 0X40000 ADS_UF_SMARTCARD_REQUIRED # # 0X80000 ADS_UF_TRUSTED_FOR_DELEGATION # 0X100000 ADS_UF_NOT_DELEGATED # 0x200000 ADS_UF_USE_DES_KEY_ONLY # # 0x400000 ADS_UF_DONT_REQUIRE_PREAUTH # # &H800000 Password expired # 0x800000 ADS_UF_PASSWORD_EXPIRED # # 0x1000000 ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE New-valentiaOSUser -------------------------------------------- Recommend - Secure Input. secure prompt will up and mask your PASSWORD input as *****. .EXAMPLE New-valentiaOSUser -Password "1231231qawerqwe87$%" -------------------------------------------- NOT-Recommend - Unsecure Input Visible prompt will up and non-mask your PASSWORD input as *****. #> function New-ValentiaOSUser { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $false, HelpMessage = "PSCredential for New OS User setup.")] [PSCredential]$credential = (Get-Credential -Credential $valentia.users.deployUser), [parameter(position = 1, mandatory = $false, HelpMessage = "User account belonging UserGroup.")] [string]$Group = $valentia.group.Name, [parameter(position = 2, mandatory = $false, HelpMessage = "User flag bit to set.")] [string]$UserFlag = $valentia.group.userFlag ) process { if ($IsUserExist) { Set-UserPassword @paramUser } else { New-User @paramUser } $Domain= Get-DomainName $paramUserFlag = @{ targetUser = New-Object System.DirectoryServices.DirectoryEntry(("WinNT://{0}/{1}/{2}" -f $Domain, $HostPC, $user)) UserFlag = $UserFlag } Set-UserFlag @paramUserFlag if ((Get-UserAndGroup @paramUserAndGroup).Groups -ne $Group) { Add-UserToUserGroup @paramGroup } } end { Get-UserAndGroup @paramUserAndGroup } begin { $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest $HostPC = [System.Environment]::MachineName $user = $credential.UserName $DirectoryComputer = New-Object System.DirectoryServices.DirectoryEntry(("WinNT://{0},computer" -f $HostPC)) $IsUserExist = Get-CimInstance -ClassName Win32_UserAccount -Filter "LocalAccount='true'" | where Name -eq $user $paramUser = @{ user = $user HostPC = $HostPC Credential = $credential } $paramGroup = @{ Group = $Group HostPC = $HostPC user = $user } $paramUserAndGroup = @{ DirectoryComputer = $DirectoryComputer user = $user } function Get-DomainName { if ((Get-WMIObject Win32_ComputerSystem).PartOfDomain) { $dn = (Get-CimInstance -ClassName win32_computersystem).Domain return (Get-CimInstance -ClassName Win32_NTDomain | where DNSForestName -eq $dn).DomainName } else { return (Get-CimInstance -ClassName win32_computersystem).Domain } } function New-User ($user, $HostPC, $credential) { ("User '{0}' not exist, start creating user." -f $user) | Write-ValentiaVerboseDebug $NewUser = $DirectoryComputer.Create("user", $user) $NewUser.SetPassword(($credential.GetNetworkCredential().password)) $NewUser.SetInfo() } function Set-UserPassword ($user, $HostPC, $credential) { ("User '{0}' already exist, start reset password." -f $user) | Write-ValentiaVerboseDebug $SetUser = New-Object System.DirectoryServices.DirectoryEntry(("WinNT://{0}/{1}" -f $HostPC, $user)) $SetUser.psbase.invoke('SetPassword', $credential.GetNetworkCredential().Password) } function Set-UserFlag ($targetUser, $UserFlag) { "Set userflag to define account as bor '{0}'" -f $UserFlag | Write-ValentiaVerboseDebug $userFlags = $targetUser.Get("UserFlags") $userFlags = $userFlags -bor $UserFlag $targetUser.Put("UserFlags", $userFlags) $targetUser.SetInfo() } function Add-UserToUserGroup ($Group, $HostPC, $user) { ("Assign User to UserGroup '{0}'" -f $Group) | Write-ValentiaVerboseDebug $DirectoryGroup = $DirectoryComputer.GetObject("group", $Group) $DirectoryGroup.Add(("WinNT://{0}/{1}" -f $HostPC, $user)) } function Get-UserAndGroup ($DirectoryComputer, $user) { $DirectoryComputer.Children ` | where SchemaClassName -eq 'user' ` | where Name -eq $user ` | %{ $groups = $_.Groups() | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} $_ | %{ [PSCustomObject]@{ UserName = $_.Name Groups = $groups } } } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Log/New-ValentiaLog.ps1
New-ValentiaLog.ps1
#Requires -Version 3.0 #-- Helper for valentia --# #-- Log Settings -- # <# .SYNOPSIS Setup Valentia Log Folder .DESCRIPTION Check Valentia Log folder and return log full path .NOTES Author: guitarrapc Created: 18/Sep/2013 .EXAMPLE New-ValentiaLog -LogFolder c:\logs\deployment -LogFile "hoge.log" -------------------------------------------- This is format sample. .EXAMPLE New-ValentiaLog -------------------------------------------- As New-ValentiaLog have default value in parameter, you do not required to specify log information #> function New-ValentiaLog { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Path to LogFolder.")] [string]$LogFolder = $(Join-Path $valentia.Log.path (Get-Date).ToString("yyyyMMdd")), [Parameter(Position = 1, mandatory = $false, HelpMessage = "Name of LogFile.")] [string]$LogFile = "$($valentia.Log.name)_$((Get-Date).ToString("yyyyMMdd_HHmmss"))_$([Guid]::NewGuid().ToString())$($valentia.Log.extension)" ) if (-not(Test-Path $LogFolder)) { ("LogFolder not found creating {0}" -f $LogFolder) | Write-ValentiaVerboseDebug New-Item -Path $LogFolder -ItemType Directory > $null } try { "Defining LogFile full path." | Write-ValentiaVerboseDebug $valentia.Log.fullPath = Join-Path $LogFolder $LogFile } catch { $SuccessStatus += $false $ErrorMessageDetail += $_ $ErrorCmdletName += ($MyInvocation.MyCommand).Name throw $_ } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Log/Out-ValentiaResult.ps1
Out-ValentiaResult.ps1
#Requires -Version 3.0 #-- Helper for valentia --# #-- End Result Execution -- # function Out-ValentiaResult { [CmdletBinding()] param ( [parameter(mandatory = $true)] [System.Diagnostics.Stopwatch]$StopWatch, [parameter(mandatory = $true)] [string]$Cmdlet, [parameter(mandatory = $false)] [string]$TaskFileName = "", [parameter(mandatory = $true)] [string[]]$DeployGroups, [parameter(mandatory = $true)] [bool]$SkipException, [parameter(mandatory = $true)] [bool]$Quiet ) # obtain Result $CommandResult = [ordered]@{ Success = !($valentia.Result.SuccessStatus -contains $false) TimeStart = $valentia.Result.TimeStart TimeEnd = (Get-Date).DateTime TotalDuration = $stopwatch.Elapsed.TotalSeconds Module = "$($MyInvocation.MyCommand.Module)" Cmdlet = $Cmdlet Alias = "$((Get-Alias | where ResolvedCommandName -eq $Cmdlet).Name)" TaskFileName = $TaskFileName ScriptBlock = "{0}" -f $valentia.Result.ScriptTorun DeployGroup = "{0}" -f "$($DeployGroups -join ', ')" TargetHostCount = $($valentia.Result.DeployMembers).count TargetHosts = "{0}" -f ($valentia.Result.DeployMembers -join ', ') Result = $valentia.Result.Result SkipException = $SkipException ErrorMessage = $($valentia.Result.ErrorMessageDetail | where {$_ -ne $null} | sort -Unique) } # show result WriteValentiaResultHost -quiet $Quiet -CommandResult $CommandResult # output result Log as json OutValentiaResultLog -CommandResult $CommandResult }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Log/Private/WriteValentiaResultHost.ps1
WriteValentiaResultHost.ps1
#Requires -Version 3.0 #-- Helper for valentia --# #-- Log Output Result Settings -- # function WriteValentiaResultHost { [CmdletBinding()] param ( [parameter(mandatory = $true)] [bool]$quiet, [parameter(mandatory = $true)] [System.Collections.Specialized.OrderedDictionary]$CommandResult ) if (-not $quiet) { # Show Stopwatch for Total section Write-Verbose ("`t`tTotal duration Second`t: {0}" -f $CommandResult.TotalDuration) [PSCustomObject]$CommandResult } else { ([PSCustomObject]$Commandresult).Success } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Log/Private/OutValentiaModuleLogHost.ps1
OutValentiaModuleLogHost.ps1
#Requires -Version 3.0 #-- Helper for valentia --# # - Out Log and Host -# filter OutValentiaModuleLogHost { [CmdletBinding(DefaultParameterSetName = "message")] param ( [parameter(mandatory = $false, position = 0, valuefromPipeline = 1, ValuefromPipelineByPropertyName = 1)] [string]$logmessage, [parameter(mandatory = $false, position = 1)] [string]$logfile = $valentia.log.fullpath, [parameter(mandatory = $false, position = 2)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode, [parameter(mandatory = $false, position = 3, ParameterSetName = "message")] [switch]$message, [parameter(mandatory = $false, position = 3, ParameterSetName = "showdata")] [switch]$showdata, [parameter(mandatory = $false, position = 3, ParameterSetName = "hidedata")] [switch]$hidedata, [parameter(mandatory = $false, position = 3, ParameterSetName = "hidedataAsString")] [switch]$hidedataAsString, [parameter(mandatory = $false, position = 3, ParameterSetName = "warning")] [switch]$warning, [parameter(mandatory = $false, position = 3, ParameterSetName = "verbosing")] [switch]$verbosing, [parameter(mandatory = $false, position = 3, ParameterSetName = "error")] [switch]$error, [parameter(mandatory = $false, position = 3, ParameterSetName = "result")] [switch]$result, [parameter(mandatory = $false, position = 3, ParameterSetName = "resultAppend")] [switch]$resultAppend ) process { if($message) { $item = "[$(Get-Date)][message][$_]" Write-Host "$item" -ForegroundColor Cyan $item | Out-File -FilePath $logfile -Encoding $encoding -Append -Force -Width 1048 } elseif($showdata) { $_ $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($hidedata) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($hideDataAsString) { $item = "[$(Get-Date)][message][$_]" $item | Out-File -FilePath $logfile -Encoding $encoding -Append -Force -Width 1048 } elseif($warning) { Write-Warning $_ $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($verbosing) { Write-Verbose $_ $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($error) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Append -Width 512 } elseif($result) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Force -Width 1048 } elseif($resultAppend) { $_ | Out-File -FilePath $logfile -Encoding $encoding -Force -Width 1048 -Append } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Log/Private/OutValentiaResultLog.ps1
OutValentiaResultLog.ps1
#Requires -Version 3.0 #-- Helper for valentia --# #-- Log Output Result Settings -- # function OutValentiaResultLog { [CmdletBinding()] param ( [parameter(mandatory = $true)] [System.Collections.Specialized.OrderedDictionary]$CommandResult, [parameter(mandatory = $false)] [string]$removeProperty = "Result", [bool]$Append = $false ) try { $json = $CommandResult | ConvertTo-Json } catch { $json = $CommandResult.Remove($removeProperty) | ConvertTo-Json } finally { if ($Append) { $json | OutValentiaModuleLogHost -resultAppend } else { $json | OutValentiaModuleLogHost -result } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Prerequisites/Private/Set-ValentiaInvokationPrerequisites.ps1
Set-ValentiaInvokationPrerequisites.ps1
#Requires -Version 3.0 #-- Helper for valentia Invokation Prerequisite setup--# function Set-ValentiaInvokationPrerequisites { [CmdletBinding()] param ( [parameter(mandatory = $true)] [System.Diagnostics.Stopwatch]$StopWatch, [Parameter(Position = 0, mandatory = $true)] [string[]]$DeployGroups, [Parameter(Position = 1, mandatory = $false)] [string]$TaskFileName, [Parameter(Position = 2, mandatory = $false)] [ScriptBlock]$ScriptBlock, [Parameter(Position = 3, mandatory = $false)] [string]$DeployFolder, [Parameter(Position = 4, mandatory = $false)] [string[]]$TaskParameter ) # clear previous result Invoke-ValentiaCleanResult # Initialize Error status $valentia.Result.SuccessStatus = $valentia.Result.ErrorMessageDetail = @() # Get Start Time $valentia.Result.TimeStart = (Get-Date).DateTime # Import default Configurations $valeWarningMessages.warn_import_configuration | Write-ValentiaVerboseDebug Import-ValentiaConfiguration # Import default Modules $valeWarningMessages.warn_import_modules | Write-ValentiaVerboseDebug Import-valentiaModules # Log Setting New-ValentiaLog # Set Task and push CurrentContext $task = Push-ValentiaCurrentContextToTask -ScriptBlock $ScriptBlock -TaskFileName $TaskFileName # Set Task as CurrentContext with task key $valentia.Result.ScriptTorun = $task.Action # Obtain DeployMember IP or Hosts for deploy try { "Get host addresses to connect." | Write-ValentiaVerboseDebug $valentia.Result.DeployMembers = Get-valentiaGroup -DeployFolder $DeployFolder -DeployGroup $DeployGroups } catch { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += $_ Write-Error $_ } # Show Stopwatch for Begin section Write-Verbose ("{0}Duration Second for Begin Section: {1}" -f "`t`t", $Stopwatch.Elapsed.TotalSeconds) }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Prerequisites/Private/Push-ValentiaCurrentContextToTask.ps1
Push-ValentiaCurrentContextToTask.ps1
#Requires -Version 3.0 #-- Public Module Functions to load Task --# # Task <# .SYNOPSIS Execute Task and push into CurrentContext .NOTES Author: guitarrapc Created: 31/July/2014 .EXAMPLE Push-ValentiaCurrentContextToTask -ScriptBlock $scriptBlock -TaskFileName $TaskFileName #> function Push-ValentiaCurrentContextToTask { [CmdletBinding()] param ( [parameter(mandatory = $false)] [ScriptBlock]$ScriptBlock, [parameter(mandatory = $false)] [string]$TaskFileName ) # Swtich ScriptBlock or ScriptFile was selected switch ($true) { {$ScriptBlock} { # run Task with ScriptBlock ("ScriptBlock parameter [ {0} ] was selected." -f $ScriptBlock) | Write-ValentiaVerboseDebug $taskkey = Task -name ScriptBlock -action $ScriptBlock # Read Current Context $currentContext = $valentia.context.Peek() } {$TaskFileName} { # check file exist or not if (-not(Test-Path (Join-Path (Get-Location).Path $TaskFileName))) { $TaskFileStatus = [PSCustomObject]@{ ErrorMessageDetail = "TaskFileName '{0}' not found in '{1}' exception!!" -f $TaskFileName,(Join-Path (Get-Location).Path $TaskFileName) SuccessStatus = $false } $valentia.Result.SuccessStatus += $TaskFileStatus.SuccessStatus $valentia.Result.ErrorMessageDetail += $TaskFileStatus.ErrorMessageDetail } # Read Task File and get Action to run ("TaskFileName parameter '{0}' was selected." -f $TaskFileName) | Write-ValentiaVerboseDebug # run Task $TaskFileName inside functions and obtain scriptblock written in. $taskkey = & $TaskFileName # Read Current Context $currentContext = $valentia.context.Peek() } default { $valentia.Result.SuccessStatus += $false $valentia.Result.ErrorMessageDetail += "TaskFile or ScriptBlock parameter must not be null" throw "TaskFile or ScriptBlock parameter must not be null" } } return $currentContext.tasks.$taskKey }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ACL/Test-ValentiaACL.ps1
Test-ValentiaACL.ps1
#Requires -Version 3.0 <# .SYNOPSIS Test ACL from selected source path. .DESCRIPTION You can Test ACL information to selected source path. This is same logic as gACLResource. .NOTES Author: guitarrapc Created: 3/Sep/2014 .EXAMPLE Test-ValentiaACL -Path c:\Deployment -Account Users -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- TestACL to the c:\Deployment for user "Users", means no Computer/Domain user name checking. .EXAMPLE Test-ValentiaACL -Path c:\Deployment -Account contoso\John -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- TestACL to the c:\Deployment for user "contoso\John", means strict user name checking. .ExternalHelp "https://github.com/guitarrapc/DSCResources/tree/master/Custom/gACLResource" #> function Test-ValentiaACL { [CmdletBinding()] [OutputType([Boolean])] param ( [Parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false, position = 3)] [ValidateSet("Present", "Absent")] [ValidateNotNullOrEmpty()] [String]$Ensure = "Present", [Parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [ValidateSet("Allow", "Deny")] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false, position = 5)] [Bool]$Inherit = $false, [Parameter(mandatory = $false, position = 6)] [Bool]$Recurse = $false, [Parameter(mandatory = $false, position = 7)] [Bool]$Strict = $false ) $desiredRule = GetDesiredRule -Path $Path -Account $Account -Rights $Rights -Access $Access -Inherit $Inherit -Recurse $Recurse $currentACL = (Get-Item $Path).GetAccessControl("Access") $currentRules = $currentACL.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $match = IsDesiredRuleAndCurrentRuleSame -DesiredRule $desiredRule -CurrentRules $currentRules -Strict $Strict $presence = if ($true -eq $match) { "Present" } else { "Absent" } return $presence -eq $Ensure }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ACL/Get-ValentiaACL.ps1
Get-ValentiaACL.ps1
#Requires -Version 3.0 <# .SYNOPSIS Get ACL from selected source path. .DESCRIPTION You can get ACL information from selected source path. This is same logic as gACLResource. .NOTES Author: guitarrapc Created: 3/Sep/2014 .EXAMPLE Get-ValentiaACL -Path c:\Deployment -Account Users -------------------------------------------- Get ACL Information from c:\Deployment for user "Users", means no Computer/Domain user name checking. .EXAMPLE Get-ValentiaACL -Path c:\Deployment -Account contoso\John -------------------------------------------- Get ACL Information from c:\Deployment for user "contoso\John", means strict user name checking. .ExternalHelp "https://github.com/guitarrapc/DSCResources/tree/master/Custom/gACLResource" #> function Get-ValentiaACL { [CmdletBinding()] [OutputType([Hashtable])] param ( [Parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false, position = 3)] [ValidateSet("Present", "Absent")] [ValidateNotNullOrEmpty()] [String]$Ensure = "Present", [Parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [ValidateSet("Allow", "Deny")] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false, position = 5)] [Bool]$Inherit = $false, [Parameter(mandatory = $false, position = 6)] [Bool]$Recurse = $false, [Parameter(mandatory = $false, position = 7)] [Bool]$Strict = $false ) $desiredRule = GetDesiredRule -Path $Path -Account $Account -Rights $Rights -Access $Access -Inherit $Inherit -Recurse $Recurse $currentACL = (Get-Item $Path).GetAccessControl("Access") $currentRules = $currentACL.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $match = IsDesiredRuleAndCurrentRuleSame -DesiredRule $desiredRule -CurrentRules $currentRules -Strict $Strict $presence = if ($true -eq $match) { "Present" } else { "Absent" } return @{ Ensure = $presence Path = $Path Account = $Account Rights = $Rights Access = $Access Inherit = $Inherit Recurse = $Recurse } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ACL/Set-ValentiaACL.ps1
Set-ValentiaACL.ps1
#Requires -Version 3.0 <# .SYNOPSIS Set ACL from selected source path. .DESCRIPTION You can Set ACL information to selected source path. This is same logic as gACLResource. .NOTES Author: guitarrapc Created: 3/Sep/2014 .EXAMPLE Set-ValentiaACL -Path c:\Deployment -Account Users -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- Add FullControl to the c:\Deployment for user "Users", means no Computer/Domain user name checking. .EXAMPLE Set-ValentiaACL -Path c:\Deployment -Account contoso\John -Rights Modify -Ensure Present -Access Allow -Inherit $false -Recurse $false -------------------------------------------- Add FullControl to the c:\Deployment for user "BuiltIn\Users", means strict user name checking. .ExternalHelp "https://github.com/guitarrapc/DSCResources/tree/master/Custom/gACLResource" #> function Set-ValentiaACL { [CmdletBinding()] param ( [Parameter(mandatory = $true, position = 0)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true, position = 1)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false, position = 3)] [ValidateSet("Present", "Absent")] [ValidateNotNullOrEmpty()] [String]$Ensure = "Present", [Parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [ValidateSet("Allow", "Deny")] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false, position = 5)] [Bool]$Inherit = $false, [Parameter(mandatory = $false, position = 6)] [Bool]$Recurse = $false, [Parameter(mandatory = $false, position = 7)] [Bool]$Strict = $false ) $desiredRule = GetDesiredRule -Path $Path -Account $Account -Rights $Rights -Access $Access -Inherit $Inherit -Recurse $Recurse $currentACL = (Get-Item $Path).GetAccessControl("Access") $currentRules = $currentACL.GetAccessRules($true, $true, [System.Security.Principal.NTAccount]) $match = IsDesiredRuleAndCurrentRuleSame -DesiredRule $desiredRule -CurrentRules $currentRules -Strict $Strict if ($Ensure -eq "Present") { $CurrentACL.AddAccessRule($DesiredRule) $CurrentACL | Set-Acl -Path $Path } elseif ($Ensure -eq "Absent") { $CurrentACL.RemoveAccessRule($DesiredRule) > $null $CurrentACL | Set-Acl -Path $Path } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ACL/Private/IsDesiredRuleAndCurrentRuleSame.ps1
IsDesiredRuleAndCurrentRuleSame.ps1
#Requires -Version 3.0 function IsDesiredRuleAndCurrentRuleSame { [OutputType([Bool])] [CmdletBinding()] param ( [System.Security.AccessControl.FileSystemAccessRule]$DesiredRule, [System.Security.AccessControl.AuthorizationRuleCollection]$CurrentRules, [bool]$Strict ) $match = if ($Strict) { Write-Verbose "Using strict name checking. It does not split AccountName with \''." $currentRules ` | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} ` | where FileSystemRights -eq $DesiredRule.FileSystemRights ` | where AccessControlType -eq $DesiredRule.AccessControlType ` | where Inherit -eq $_.InheritanceFlags ` | measure } else { Write-Verbose "Using non-strict name checking. It split AccountName with \''." $currentRules ` | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} ` | where FileSystemRights -eq $DesiredRule.FileSystemRights ` | where AccessControlType -eq $DesiredRule.AccessControlType ` | where Inherit -eq $_.InheritanceFlags ` | measure } if ($match.Count -eq 0) { Write-Verbose "Current ACL result." Write-Verbose ($CurrentRules | Format-List | Out-String) Write-Verbose "Desired ACL result." Write-Verbose ($DesiredRule | Format-List | Out-String) Write-Verbose "Result does not match as desired. Showing Desired v.s. Current Status." [PSCustomObject]@{ DesiredRuleIdentity = $DesiredRule.IdentityReference.Value CurrentRuleIdentity = $currentRules.IdentityReference.Value StrictCurrentRuleIdentity = $currentRules.IdentityReference.Value.Split("\")[1] StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose [PSCustomObject]@{ DesiredFileSystemRights = $DesiredRule.FileSystemRights CurrentFileSystemRights = $currentRules.FileSystemRights StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose [PSCustomObject]@{ DesiredAccessControlType = $DesiredRule.AccessControlType CurrentAccessControlType = $currentRules.AccessControlType StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose [PSCustomObject]@{ DesiredInherit = $DesiredRule.Inherit CurrentInherit = $currentRules.Inherit StrictResult = ($currentRules | where {$_.IdentityReference.Value -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | where Inherit -eq $DesiredRule.Inherit | measure).Count -ne 0 NoneStrictResult = ($currentRules | where {$_.IdentityReference.Value.Split("\")[1] -eq $DesiredRule.IdentityReference.Value} | where FileSystemRights -eq $DesiredRule.FileSystemRights | where AccessControlType -eq $DesiredRule.AccessControlType | where Inherit -eq $DesiredRule.Inherit | measure).Count -ne 0 } | Format-List | Out-String -Stream | Write-Verbose } return $match.Count -ge 1 }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ACL/Private/GetDesiredRule.ps1
GetDesiredRule.ps1
#Requires -Version 3.0 function GetDesiredRule { [OutputType([System.Security.AccessControl.FileSystemAccessRule])] [CmdletBinding()] param ( [Parameter(mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Path, [Parameter(mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Account, [Parameter(mandatory = $false)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.FileSystemRights]$Rights = "ReadAndExecute", [Parameter(mandatory = $false)] [ValidateNotNullOrEmpty()] [System.Security.AccessControl.AccessControlType]$Access = "Allow", [Parameter(mandatory = $false)] [Bool]$Inherit = $false, [Parameter(mandatory = $false)] [Bool]$Recurse = $false ) $InheritFlag = if ($Inherit) { "{0}, {1}" -f [System.Security.AccessControl.InheritanceFlags]::ContainerInherit, [System.Security.AccessControl.InheritanceFlags]::ObjectInherit } elseif ($Recurse) { "{0}, {1}" -f [System.Security.AccessControl.InheritanceFlags]::ContainerInherit, [System.Security.AccessControl.InheritanceFlags]::ObjectInherit } else { [System.Security.AccessControl.InheritanceFlags]::None } $desiredRule = New-Object System.Security.AccessControl.FileSystemAccessRule($Account, $Rights, $InheritFlag, "None", $Access) return $desiredRule }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Sed/Invoke-ValentiaSed.ps1
Invoke-ValentiaSed.ps1
#Requires -Version 3.0 #-- Deploy Folder/File Module Functions --# <# .SYNOPSIS PowerShell Sed alternate function .DESCRIPTION This cmdlet replace string in the file as like as sed on linux .NOTES Author: guitarrapc Created: 04/Oct/2013 .EXAMPLE Invoke-ValentiaSed -path D:\Deploygroup\*.ps1 -searchPattern "^10.0.0.10$" -replaceWith "#10.0.0.10" -overwrite -------------------------------------------- replace regex ^10.0.0.10$ with # 10.0.0.10 and replace file. (like sed -f "s/^10.0.0.10$/#10.0.0.10" -i) .EXAMPLE Invoke-ValentiaSed -path D:\Deploygroup\*.ps1 -searchPattern "^#10.0.0.10$" -replaceWith "10.0.0.10" -------------------------------------------- replace regex ^10.0.0.10$ with # 10.0.0.10 and not replace file. #> function Invoke-ValentiaSed { [CmdletBinding()] param ( [parameter(position = 0, mandatory = $true, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [string]$path, [parameter(position = 1, mandatory = $true, ValueFromPipeline = 1,ValueFromPipelineByPropertyName = 1)] [string]$searchPattern, [parameter(position = 2, mandatory = $true,ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [string]$replaceWith, [parameter(position = 3, mandatory = $false)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $valentia.fileEncode, [parameter(position = 4, mandatory = $false)] [switch]$overWrite, [parameter(position = 5, mandatory = $false)] [switch]$compress ) $read = Select-String -Path $path -Pattern $searchPattern -Encoding $encoding $read.path ` | sort -Unique ` | %{Write-Warning ("Executing string replace for '{0}'. 'overwrite': '{1}'." -f $path, ($PSBoundParameters.overWrite.IsPresent -eq $true)) $path = $_ $extention = [System.IO.Path]::GetExtension($path) if ($overWrite) { $tmpextension = "$extention" + "______" $tmppath = [System.IO.Path]::ChangeExtension($path,$tmpextension) ("execute replace string '{0}' with '{1}' for file '{2}', Output to '{3}'" -f $searchPattern, $replaceWith, $path, $tmppath) | Write-ValentiaVerboseDebug Get-Content -Path $path ` | %{$_ -replace $searchPattern,$replaceWith} ` | Out-File -FilePath $tmppath -Encoding $valentia.fileEncode -Force -Append ("remove original file '{0}'" -f $path, $tmppath) | Write-ValentiaVerboseDebug Remove-Item -Path $path -Force ("rename tmp file '{0}' to original file '{1}'" -f $tmppath, $path) | Write-ValentiaVerboseDebug Rename-Item -Path $tmppath -NewName ([System.IO.Path]::ChangeExtension($tmppath,$extention)) } else { ("execute replace string '{0}' with '{1}' for file '{2}'" -f $searchPattern, $replaceWith, $path) | Write-ValentiaVerboseDebug if (-not $PSBoundParameters.Compress.IsPresent) { Get-Content -Path $path -Encoding $encoding ` | %{$_ -replace $searchPattern,$replaceWith} } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/FireWall/Firewall/New-ValentiaPSRemotingFirewallRule.ps1
New-ValentiaPSRemotingFirewallRule.ps1
#Requires -Version 3.0 #-- Prerequisite OS Setting Module Functions --# <# .SYNOPSIS Create New Firewall Rule for PowerShell Remoting .DESCRIPTION Will allow PowerShell Remoting port for firewall .NOTES Author: guitarrapc Created: 18/Jul/2013 .EXAMPLE Enable-PSRemotingFirewallRule -------------------------------------------- Add PowerShellRemoting-In accessible rule to Firewall. #> function New-ValentiaPSRemotingFirewallRule { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $false, HelpMessage = "Input PowerShellRemoting-In port. default is 5985")] [int]$PSRemotePort = 5985, [Parameter(Position = 1, mandatory = $false, HelpMessage = "Input Name of Firewall rule for PowerShellRemoting-In.")] [string]$Name = "Windows Remote Management (HTTP-In)", [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input Decription of Firewall rule for PowerShellRemoting-In.")] [string]$Description = "Windows PowerShell Remoting required to open for public connection. not for private network.", [Parameter(Position = 2, mandatory = $false, HelpMessage = "Input Group of Firewall rule for PowerShellRemoting-In.")] [string]$Group = "Windows Remote Management" ) $ErrorActionPreference = $valentia.preference.ErrorActionPreference.custom Set-StrictMode -Version latest if (-not((Get-NetFirewallRule | where Name -eq $Name) -and (Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq $PSRemotePort))) { Write-Verbose ("Windows PowerShell Remoting port TCP $PSRemotePort was not opend. Set new rule '{1}'" -f $PSRemotePort, $Name) New-NetFirewallRule ` -Name $Name ` -DisplayName $Name ` -Description $Description ` -Group $Group ` -Enabled True ` -Profile Any ` -Direction Inbound ` -Action Allow ` -EdgeTraversalPolicy Block ` -LooseSourceMapping $False ` -LocalOnlyMapping $False ` -OverrideBlockRules $False ` -Program Any ` -LocalAddress Any ` -RemoteAddress Any ` -Protocol TCP ` -LocalPort $PSRemotePort ` -RemotePort Any ` -LocalUser Any ` -RemoteUser Any } else { "Windows PowerShell Remoting port TCP 5985 was alredy opened. Get Firewall Rule." | Write-ValentiaVerboseDebug Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq 5985 } if ((Get-WinSystemLocale).Name -eq "ja-JP") { $japanesePSRemoteingEnableRule = "Windows リモート管理 (HTTP 受信)" if (-not((Get-NetFirewallRule | where DisplayName -eq $japanesePSRemoteingEnableRule | where Profile -eq "Any") -and (Get-NetFirewallPortFilter -Protocol TCP | where Localport -eq $PSRemotePort))) { ("日本語OSと検知しました。'{0}' という名称で TCP '{1}' をファイアウォールに許可します。" -f $japanesePSRemoteingEnableRule, 5985) | Write-ValentiaVerboseDebug New-NetFirewallRule ` -Name $japanesePSRemoteingEnableRule ` -DisplayName $japanesePSRemoteingEnableRule ` -Description $Description ` -Group $Group ` -Enabled True ` -Profile Any ` -Direction Inbound ` -Action Allow ` -EdgeTraversalPolicy Block ` -LooseSourceMapping $False ` -LocalOnlyMapping $False ` -OverrideBlockRules $False ` -Program Any ` -LocalAddress Any ` -RemoteAddress Any ` -Protocol TCP ` -LocalPort $PSRemotePort ` -RemotePort Any ` -LocalUser Any ` -RemoteUser Any } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Config/Backup-valentiaConfig.ps1
Backup-valentiaConfig.ps1
#requires -Version 3.0 function Backup-ValentiaConfig { <# .Synopsis Backup CurrentConfiguration with timestamp. .DESCRIPTION Backup configuration in $Valentia.appdataconfig.root .EXAMPLE Backup-ValentiaConfig #> [OutputType([void])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $Valentia.fileEncode ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) $rootPath = $valentia.originalconfig.root $fileName = $valentia.originalconfig.file } } if (Test-Path $configPath) { $private:datePrefix = ([System.DateTime]::Now).ToString($valentia.log.dateformat) $private:backupConfigName = $datePrefix + "_" + $fileName $private:backupConfigPath = Join-Path $rootPath $backupConfigName Write-Verbose ("Backing up config file '{0}' => '{1}'." -f $configPath, $backupConfigPath) Get-Content -Path $configPath -Encoding $encoding -Raw | Out-File -FilePath $backupConfigPath -Encoding $encoding -Force } else { Write-Verbose ("Could not found configuration file '{0}'." -f $configPath) } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Config/Show-ValentiaConfig.ps1
Show-ValentiaConfig.ps1
#Requires -Version 3.0 <# .Synopsis Show Valentia Config in Console .DESCRIPTION Read config and show in the console .EXAMPLE Show-ValentiaConfig #> function Show-ValentiaConfig { [OutputType([string[]])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $Valentia.fileEncode ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) } } if (Test-Path $configPath) { Get-Content -Path $configPath -Encoding $encoding } else { ("Could not found configuration file '{0}'." -f $configPath) | Write-ValentiaVerboseDebug } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Config/Reset-ValentiaConfig.ps1
Reset-ValentiaConfig.ps1
#Requires -Version 3.0 <# .Synopsis Edit Valentia Config in Console .DESCRIPTION Read config and edit in the console .EXAMPLE Edit-ValentiaConfig #> function Reset-ValentiaConfig { [OutputType([void])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$encoding = $Valentia.fileEncode ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) } } if (Test-Path $configPath) { . $configPath } else { ("Could not found configuration file '{0}'." -f $configPath) | Write-ValentiaVerboseDebug } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Config/Edit-ValentiaConfig.ps1
Edit-ValentiaConfig.ps1
#Requires -Version 3.0 <# .Synopsis Edit Valentia Config in Console .DESCRIPTION Read config and edit in the console .EXAMPLE Edit-ValentiaConfig #> function Edit-ValentiaConfig { [OutputType([void])] [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [string]$configPath = "", [parameter(mandatory = $false, position = 1)] [switch]$NoProfile ) if (($configPath -eq "") -or (-not (Test-Path $configPath))) { if (Test-Path (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file)) { $configPath = (Join-Path $valentia.originalconfig.root $valentia.originalconfig.file) } } if (Test-Path $configPath) { if ($NoProfile) { PowerShell_ise.exe -File $configPath -NoProfile } else { PowerShell_ise.exe -File $configPath } } else { ("Could not found configuration file '{0}'." -f $configPath) | Write-ValentiaVerboseDebug } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Get-ValentiaCertificateFromCert.ps1
Get-ValentiaCertificateFromCert.ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Get-ValentiaCertificateFromCert { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocation = $valentia.certificate.export.CertStoreLocation, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreName = $valentia.certificate.export.CertStoreName ) "Obtain Cert from CertStoreLocation." | Write-ValentiaVerboseDebug $certStoreLocationPath = Join-Path "cert:" $certStoreLocation -Resolve $certStoreFullPath = Join-Path $certStoreLocationPath $certStoreName -Resolve $cert = (Get-ChildItem $certStoreFullPath | where Subject -eq "CN=$cn") | select -First 1 if ($null -eq $cert) { throw "Certificate for CN '{0}' not found." -f $CN } return [System.Security.Cryptography.X509Certificates.X509Certificate2]$cert }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Convert-ValentiaEncryptPassword .ps1
Convert-ValentiaEncryptPassword .ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Convert-ValentiaEncryptPassword { param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [pscredential[]]$Credential, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$thumbprint = $valentia.certificate.Encrypt.ThumbPrint, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$certPath = $valentia.certificate.Encrypt.CertPath ) process { foreach ($cred in $Credential) { $passwordByte = [Text.Encoding]::UTF8.GetBytes($Cred.GetNetworkCredential().Password) $contentInfo = New-Object Security.Cryptography.Pkcs.ContentInfo @(,$passwordByte) $EnvelopedCms = New-Object Security.Cryptography.Pkcs.EnvelopedCms $contentInfo $EnvelopedCms.Encrypt((New-Object System.Security.Cryptography.Pkcs.CmsRecipient($Cert))) [Convert]::ToBase64String($EnvelopedCms.Encode()) } } begin { try { Add-type –AssemblyName System.Security } catch { } $Path = Join-Path $certPath $thumbprint if (Test-Path $Path) { $Cert = Get-Item $Path } else { Write-Warning ("Certification not found exception!! Cert: '{0}'" -f $Path) } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Convert-ValentiaDecryptPassword .ps1
Convert-ValentiaDecryptPassword .ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Convert-ValentiaDecryptPassword { param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$EncryptedKey, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$thumbprint = $valentia.certificate.Encrypt.ThumbPrint, [parameter(mandatory = $false, position = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$certPath = $valentia.certificate.Encrypt.CertPath ) process { $EnvelopedCms = New-Object Security.Cryptography.Pkcs.EnvelopedCms $EnvelopedCms.Decode([convert]::FromBase64String($EncryptedKey)) $EnvelopedCms.Decrypt($Cert) [Text.Encoding]::UTF8.GetString($EnvelopedCms.ContentInfo.Content) } begin { try { Add-type –AssemblyName System.Security } catch { } $Path = Join-Path $certPath $thumbprint if (Test-Path $Path) { $Cert = Get-Item $Path } else { Write-Warning ("Certification not found exception!! Cert: '{0}'" -f $Path) } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Export-ValentiaCertificatePFX.ps1
Export-ValentiaCertificatePFX.ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Export-ValentiaCertificatePFX { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509Certificate2]$pfx, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [string]$exportFilePath = $valentia.certificate.FilePath.PFX, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509ContentType]$PFXType = $valentia.certificate.export.PFXType, [parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [PSCredential]$Credential = $null ) process { "Export pfx '{0}' as object." -f $cert.ThumbPrint | Write-ValentiaVerboseDebug $pfxToExportInBytes = $pfx.Export($PFXType, $credential.GetNetworkCredential().Password) [System.IO.File]::WriteAllBytes($FilePath, $pfxToExportInBytes) } begin { "Export Path setup." | Write-ValentiaVerboseDebug $FilePath = $exportFilePath -f $CN $dir = Split-Path $FilePath -Parent if (-not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force } elseif (Test-Path $FilePath) { Remove-Item -Path $FilePath -Confirm -Force } "Get pfx password to export." | Write-ValentiaVerboseDebug if ($null -eq $Credential) { $credential = Get-Credential -Credential "INPUT Password FOR PFX export." } if (Test-Path $FilePath) { throw "Certificate already exist in '{0}'. Make sure you have delete exist cert before export." -f $FilePath } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Remove-ValentiaCertificate.ps1
Remove-ValentiaCertificate.ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Remove-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 1, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [string]$CertFilePath = $valentia.certificate.FilePath.Cert, [parameter(mandatory = $false, position = 2)] [switch]$force = $false ) $param = @{ Path = $CertFilePath -f $CN Confirm = (-not $force) Force = $force } if (Test-Path $param.Path) { Remove-Item @param } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Export-ValentiaCertificate.ps1
Export-ValentiaCertificate.ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Export-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $true, position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509Certificate2]$cert, [parameter(mandatory = $false, position = 1)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [string]$exportFilePath = $valentia.certificate.FilePath.Cert, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.X509ContentType]$certType = $valentia.certificate.export.CertType ) process { "Export cert '{0}' to '{1}'." -f $cert.ThumbPrint ,$FilePath | Write-ValentiaVerboseDebug $certToExportInBytes = $cert.Export($certType) [System.IO.File]::WriteAllBytes($FilePath, $certToExportInBytes) } begin { "Export Path setup." | Write-ValentiaVerboseDebug $FilePath = $exportFilePath -f $CN $dir = Split-Path $FilePath -Parent if (-not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force } elseif (Test-Path $FilePath) { Remove-Item -Path $FilePath -Confirm -Force } if (Test-Path $FilePath) { throw "Certificate already exist in '{0}'. Make sure you have delete exist cert before export." -f $FilePath } } end { Get-Item $FilePath } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Show-ValentiaCertificate.ps1
Show-ValentiaCertificate.ps1
#Requires -Version 3.0 #-- Helper for certificate --# function Show-ValentiaCertificate { [CmdletBinding()] param ( [parameter(mandatory = $false, position = 0)] [ValidateNotNullOrEmpty()] [string]$CN = $valentia.certificate.CN, [parameter(mandatory = $false,position = 1)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocationExport = $valentia.certificate.export.CertStoreLocation, [parameter(mandatory = $false, position = 2)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreNameExport = $valentia.certificate.export.CertStoreName, [parameter(mandatory = $false, position = 3)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreLocation]$certStoreLocationImport = $valentia.certificate.import.CertStoreLocation, [parameter(mandatory = $false, position = 4)] [ValidateNotNullOrEmpty()] [System.Security.Cryptography.X509Certificates.StoreName]$certStoreNameImport = $valentia.certificate.import.CertStoreName, [parameter(mandatory = $false, position = 5)] [ValidateNotNullOrEmpty()] [string]$CertFilePath = $valentia.certificate.FilePath.Cert, [parameter(mandatory = $false, position = 6)] [ValidateNotNullOrEmpty()] [string]$PFXFilePath = $valentia.certificate.FilePath.PFX ) "Obtain CERT from export CertStoreLocation." | Write-ValentiaVerboseDebug $certExport = Get-ValentiaCertificateFromCert if ($null -eq $certExport) { Write-Warning ("Certificate for CN '{0}' not found." -f $CN) } "Obtain CERT from Import CertStoreLocation." | Write-ValentiaVerboseDebug $certStoreLocationPathImport= Join-Path "cert:" $certStoreLocationImport -Resolve $certStoreFullPathImport = Join-Path $certStoreLocationPathImport $certStoreNameImport -Resolve $certImport = (Get-ChildItem $certStoreFullPathImport | where Subject -eq "CN=$cn") | select -First 1 if ($null -eq $certImport) { Write-Warning ("Certificate for CN '{0}' not found." -f $CN) } "Obtain Cer file." | Write-ValentiaVerboseDebug $certPath = $CertFilePath -f $CN if (Test-Path $certPath) { $certFile = Get-Item $certPath } else { Write-Warning ("Certificate file not found '{0}'." -f $certPath) } "Obtain PFX file." | Write-ValentiaVerboseDebug $pfxPath = $PFXFilePath -f $CN if (Test-Path $pfxPath) { $pfxFile = Get-Item $pfxPath } else { Write-Warning ("PFX file not found '{0}'." -f $pfxPath) } return [PSCustomObject]@{ ExportCert = $certExport ImportCert = $certImport CertFile = $certFile PFXFile = $pfxFile } }