full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Import-ValentiaCertificate.ps1
Import-ValentiaCertificate.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Import-ValentiaCertificatePFX.ps1
Import-ValentiaCertificatePFX.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Certificate/Remove-ValentiaCertificatePFX.ps1
Remove-ValentiaCertificatePFX.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Encoding/Get-ValentiaFileEncoding.ps1
Get-ValentiaFileEncoding.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) } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Add-ValentiaCredSSPDelegateRegKey.ps1
Add-ValentiaCredSSPDelegateRegKey.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Get-ValentiaCredSSPDelegateRegKeyProperty.ps1
Get-ValentiaCredSSPDelegateRegKeyProperty.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Enable-ValentiaCredSSP.ps1
Enable-ValentiaCredSSP.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Remove-ValentiaCredSSPDelegateRegKey.ps1
Remove-ValentiaCredSSPDelegateRegKey.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} } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Add-ValentiaCredSSPDelegateReg.ps1
Add-ValentiaCredSSPDelegateReg.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Add-ValentiaCredSSPDelegateRegKeyProperty.ps1
Add-ValentiaCredSSPDelegateRegKeyProperty.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Get-ValentiaCredSSPDelegateRegKey.ps1
Get-ValentiaCredSSPDelegateRegKey.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/CredSSP/Private/Get-ValentiaCredSSPDelegateReg.ps1
Get-ValentiaCredSSPDelegateReg.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Initialize/Initialize-ValentiaEnvironment.ps1
Initialize-ValentiaEnvironment.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 } } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/IE/Private/Disable-ValentiaEnhancedIESecutiry.ps1
Disable-ValentiaEnhancedIESecutiry.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) } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ScheduledTask/Test-ValentiaScheduledTask.ps1
Test-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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ScheduledTask/Set-ValentiaScheduledTask.ps1
Set-ValentiaScheduledTask.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; } } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ScheduledTask/Enable-ValentiaScheduledTaskLogSetting.ps1
Enable-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() } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ScheduledTask/Remove-ValentiaScheduledTaskEmptyDirectoryPath.ps1
Remove-ValentiaScheduledTaskEmptyDirectoryPath.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 }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ScheduledTask/Remove-ValentiaScheduledTask.ps1
Remove-ValentiaScheduledTask.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ScheduledTask/Disable-ValentiaScheduledTaskLogSetting.ps1
Disable-ValentiaScheduledTaskLogSetting.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() } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/WsMan/Enable-WsManTrustedHosts.ps1
Enable-WsManTrustedHosts.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/WsMan/Set-ValentiaWsManMaxMemoryPerShellMB.ps1
Set-ValentiaWsManMaxMemoryPerShellMB.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/WsMan/Set-ValentiaWsManMaxShellsPerUser.ps1
Set-ValentiaWsManMaxShellsPerUser.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/WsMan/Set-ValentiaWsManMaxProccessesPerShell.ps1
Set-ValentiaWsManMaxProccessesPerShell.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/WsMan/Set-ValetntiaWSManConfiguration.ps1
Set-ValetntiaWSManConfiguration.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 }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/DNS/Get-ValentiaHostEntryAsync.ps1
Get-ValentiaHostEntryAsync.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]' } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/PromptForChoice/Show-ValentiaPromptForChoice.ps1
Show-ValentiaPromptForChoice.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 $_ } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ComputerName/Get-ValentiaComputerName.ps1
Get-ValentiaComputerName.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 } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/ComputerName/Rename-ValentiaComputerName.ps1
Rename-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 } } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Utils/New-ValentiaZpPairs.ps1
New-ValentiaZpPairs.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]' } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Task/Get-ValentiaTask.ps1
Get-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 }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Helper/Task/ConvertTo-ValentiaTask.ps1
ConvertTo-ValentiaTask.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/Sync/Invoke-ValentiaSync.ps1
Invoke-ValentiaSync.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/Download/Invoke-ValentiaDownload.ps1
Invoke-ValentiaDownload.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/Upload/Invoke-ValentiaUpload.ps1
Invoke-ValentiaUpload.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/Upload/Invoke-ValentiaUploadList.ps1
Invoke-ValentiaUploadList.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 } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/Ping/Watch-ValentiaPingAsyncReplyStatus.ps1
Watch-ValentiaPingAsyncReplyStatus.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($_)} } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/Ping/Ping-ValentiaGroupAsync.ps1
Ping-ValentiaGroupAsync.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; } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/Job/Invoke-Valentia.ps1
Invoke-Valentia.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/Job/Private/Receive-ValentiaResult.ps1
Receive-ValentiaResult.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 = @{} } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/Job/Private/Invoke-ValentiaJobProcess.ps1
Invoke-ValentiaJobProcess.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/Job/Private/Invoke-ValentiaCommand.ps1
Invoke-ValentiaCommand.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Invoke-ValentiaAsync.ps1
Invoke-ValentiaAsync.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/Invoke-ValentiaRunspaceProcess.ps1
Invoke-ValentiaRunspaceProcess.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/Receive-ValentiaAsyncStatus.ps1
Receive-ValentiaAsyncStatus.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/Receive-ValentiaAsyncResults.ps1
Receive-ValentiaAsyncResults.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 = @{} } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/Invoke-ValentiaAsyncCommand.ps1
Invoke-ValentiaAsyncCommand.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 } } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/AsyncPipeline/Invoke-ValentiaAsyncPipeline.ps1
Invoke-ValentiaAsyncPipeline.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) } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/AsyncPipeline/Watch-ValentiaAsyncPipelineStatus.ps1
Watch-ValentiaAsyncPipelineStatus.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() } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/RunSpacePool/Remove-ValentiaRunSpacePool.ps1
Remove-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 $_ } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Functions/Invokation/CommandExecution/RunSpacePool/Private/RunSpacePool/New-ValentiaRunSpacePool.ps1
New-ValentiaRunSpacePool.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 $_ } }
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Tools/install.ps1
install.ps1
#Requires -Version 2.0 # Windows 7 and later is requires. function Main { [CmdletBinding()] Param ( [string]$Modulepath = (GetModulePath), [bool]$Renew = $false, [switch]$Force = $false, [switch]$Whatif = $false ) $ErrorActionPreference = "Stop" $path = [System.IO.Directory]::GetParent((Split-Path (Resolve-Path -Path $PSCommandPath) -Parent)) $moduleName = Get-ModuleName -path $path $moduleFullPath = Join-Path $modulepath $moduleName Write-Verbose ("Checking Module Root Path '{0}' is exist not not." -f $modulepath) if(-not(Test-ModulePath -modulepath $modulepath)) { Write-Warning "$modulepath not found. creating module path." New-Item -Path $modulepath -ItemType directory -Force > $null } # Remove Existing if($reNew -and (Test-ModulePath -modulepath $moduleFullPath)) { Write-Warning ("'{0}' already exist. Removing Existing modules." -f $moduleFullPath) Remove-Item -Path $moduleFullPath -Recurse -Force } try { # Copy Module Write-Host ("Copying module '{0}' to Module path '{1}'." -f $moduleName, $moduleFullPath) -ForegroundColor Cyan Copy-ItemEX -path $path -destination $moduleFullPath -Targets * -Recurse -Force exit 0 } catch { exit 1 } } function GetModulePath { $ModulePath = $env:PSModulePath -split ";" | where {$_ -like ("{0}*" -f [environment]::GetFolderPath("MyDocuments"))} if (($ModulePath | measure).count -eq 1){ return $ModulePath } if (($ModulePath | measure).count -eq 0) { $answer = Read-Host -Prompt "PSModulePath detected as not include Documents path. Please input path to install valentia." if (-not (Test-Path $answer)){ throw New-Object New-Object System.IO.FileNotFoundException ("Specified Path not found exception!!", $answer) } return $answer } if (($ModulePath | measure).count -gt 1) { $param = @{ title = "PSModulePath contains more than 2 Documents directory." message = "Please select which PSmodulePath to install valentia." questions = $ModulePath } return Show-PromptForChoice @param } } Function Test-ModulePath { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true)] [string]$modulepath ) Write-Verbose "Checking Module Home." if (([System.Environment]::OSVersion.Version) -ge 6.1) { Write-Verbose "Your operating system is later then Windows 7 / Windows Server 2008 R2. Continue evaluation." return Test-Path -Path $modulepath } else { throw "Operation System not higher enough exception!! Make sure you are runnning Windows 7 / Windows Server 2008 R2 or Higher." } } Function Get-ModuleName { [CmdletBinding()] param ( [Parameter(Position = 0, mandatory = $true)] [string]$path ) if (Test-Path $path) { $moduleName = ((Get-ChildItem $path | where {$_.Extension -eq ".psm1"})).BaseName if ($null -eq $moduleName) { throw "Module file .psm1 not existing in path '{0}' exception!!" -f $path } return $moduleName } else { throw "Path '{0}' not existing exception!!" -f $path } } function Copy-ItemEX { param ( [parameter(mandatory = $true, Position = 0, ValueFromPipeline = 1, ValueFromPipelineByPropertyName =1)] [alias('PSParentPath')] [string]$Path, [parameter(mandatory = $true, Position = 1, ValueFromPipelineByPropertyName =1)] [string]$Destination, [parameter(mandatory = $false, Position = 2, ValueFromPipelineByPropertyName =1)] [string[]]$Targets, [parameter(mandatory = $false, Position = 3, ValueFromPipelineByPropertyName =1)] [string[]]$Excludes, [parameter(mandatory = $false, Position = 4, ValueFromPipelineByPropertyName =1)] [Switch]$Recurse, [parameter(mandatory = $false, Position = 5)] [switch]$Force, [parameter(mandatory = $false, Position = 6)] [switch]$WhatIf ) process { # Test Path if (-not (Test-Path $Path)){throw 'Path not found Exception!!'} # Get Filter Item Path as List<Tuple<string>,<string>,<string>> $filterPath = GetTargetsFiles -Path $Path -Targets $Targets -Recurse:$isRecurse -Force:$Force # Remove Exclude Item from Filter Item $excludePath = GetExcludeFiles -Path $filterPath -Excludes $Excludes # Execute Copy, confirmation and WhatIf can be use. CopyItemEX -Path $excludePath -RootPath $Path -Destination $Destination -Force:$isForce -WhatIf:$isWhatIf } begin { $isRecurse = $PSBoundParameters.ContainsKey('Recurse') $isForce = $PSBoundParameters.ContainsKey('Force') $isWhatIf = $PSBoundParameters.ContainsKey('WhatIf') function GetTargetsFiles { [CmdletBinding()] param ( [string]$Path, [string[]]$Targets, [bool]$Recurse, [bool]$Force ) # fullName, DirectoryName, Name $list = New-Object 'System.Collections.Generic.List[Tuple[string,string,string]]' $base = Get-ChildItem $Path -Recurse:$Recurse -Force:$Force if (($Targets | measure).count -ne 0) { foreach($target in $Targets) { $base ` | where Name -like $target ` | %{ if ($_ -is [System.IO.FileInfo]) { $tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.DirectoryName, $_.Name) } elseif ($_ -is [System.IO.DirectoryInfo]) { $tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.PSParentPath, $_.Name) } else { throw "Type '{0}' not imprement Exception!!" -f $_.GetType().FullName } $list.Add($tuple) } } } else { $base ` | %{ if ($_ -is [System.IO.FileInfo]) { $tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.DirectoryName, $_.Name) } elseif ($_ -is [System.IO.DirectoryInfo]) { $tuple = New-Object 'System.Tuple[[string], [string], [string]]' ($_.FullName, $_.PSParentPath, $_.Name) } else { throw "Type '{0}' not imprement Exception!!" -f $_.GetType().FullName } $list.Add($tuple) } } return $list } function GetExcludeFiles { param ( [System.Collections.Generic.List[Tuple[string,string,string]]]$Path, [string[]]$Excludes ) if (($Excludes | measure).count -ne 0) { Foreach ($exclude in $Excludes) { # name not like $exclude $Path | where Item3 -notlike $exclude } } else { $Path } } function CopyItemEX { [cmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param ( [System.Collections.Generic.List[Tuple[string,string,string]]]$Path, [string]$RootPath, [string]$Destination, [bool]$Force ) begin { # remove default bound "Force" $PSBoundParameters.Remove('Force') > $null } process { # convert to regex format $root = $RootPath.Replace('Microsoft.PowerShell.Core\FileSystem::','').Replace('\', '\\') $Path ` | %{ # create destination DirectoryName $directoryName = Join-Path $Destination ($_.Item2 -split $root | select -Last 1) [PSCustomObject]@{ Path = $_.Item1 DirectoryName = $directoryName Destination = Join-Path $directoryName $_.Item3 }} ` | where {$Force -or $PSCmdlet.ShouldProcess($_.Path, ('Copy Item to {0}' -f $_.Destination))} ` | %{ Write-Verbose ("Copying '{0}' to '{1}'." -f $_.Path, $_.Destination) New-Item -Path $_.DirectoryName -ItemType Directory -Force > $null Copy-Item -Path $_.Path -Destination $_.Destination -Force } } } } } Main -Renew $true -Force
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Tools/RemoteInstall.ps1
RemoteInstall.ps1
#Required -Version 3.0 function Main { # Uri Write-Debug "Creating GitHub zip uri." $GitHubURI = @{ github = "guitarrapc" repository = "valentia" } $uri = Get-GitHubRepositryURI @GitHubURI # Directory Write-Debug "Checking temp directory is already exist." $dir = Join-Path $env:TEMP $GitHubURI.repository $tempDir = Join-Path $dir "Install" New-Directory -tempDir $tempDir # Download Write-Debug "Donwloading zip file from repogitory." $source = Join-Path $tempDir "master.zip" $Download = @{ uri = $uri path = $source } Invoke-DownloadFileEX @Download # Unzip Write-Debug "Unzipping dowmloaded zip file." $destination = Join-Path $tempDir "master" $Unzip = @{ Source = $source Destination = $destination } New-ZipExtract @Unzip # Install Write-Verbose ("Installing {0} to the computer" -f $gitHubURI.repository) $installer = "Install.bat" $toolFolder = Join-Path $destination ("{0}-Master\{0}" -f $gitHubURI.repository) $InstallerPath = Join-Path $toolFolder ("Tools" + "\" + "Install.bat") Install-Repogisty -installerPath $InstallerPath # Clean up Write-Debug "Removing temp directory for clean up." Remove-Directory -tempDir $tempDir } function Get-GitHubRepositryURI { [CmdletBinding()] param ( [string]$GitHub, [string]$RepositoryName ) Write-Verbose ("Get URI for {0} with Repository {1}" -f $GitHub, $RepositoryName) return [uri]("https://github.com/{0}/{1}/archive/master.zip" -f $github, $RepositoryName) } function New-Directory { [CmdletBinding()] param ( [string]$tempDir ) if (-not [System.IO.Directory]::Exists($tempDir)) { Write-Verbose ("Could not found temp folder '{0}', creating new folder " -f $tempDir) [System.IO.Directory]::CreateDirectory($tempDir) } } function Invoke-DownloadFileEX ([uri]$uri, [string]$path) { try { Add-Type -AssemblyName System.Net.Http $httpClient = New-Object Net.Http.HttpClient $responseMessage = $httpClient.GetAsync($uri, [System.Net.Http.HttpCompletionOption]::ResponseContentRead) $fileStream = [System.IO.File]::Create($path) $httpStream = $responseMessage.Result.Content.ReadAsStreamAsync() $httpStream.ConfigureAwait($false) > $null $httpStream.Result.CopyToAsync($fileStream).Wait() $fileStream.Flush() } finally { $fileStream.Dispose() $httpClient.Dispose() } } function New-ZipExtract { [CmdletBinding(DefaultParameterSetName="safe")] param ( [parameter(mandatory, position = 0, valuefrompipeline, valuefrompipelinebypropertyname)] [string]$source, [parameter(mandatory = $false, position = 1, valuefrompipeline, valuefrompipelinebypropertyname)] [string]$destination ) begin { # only run with Verbose mode if ($PSBoundParameters.ContainsKey("Verbose")) { # start Stopwatch $sw = [System.Diagnostics.Stopwatch]::StartNew() $starttime = Get-Date } Write-Debug "import .NET Class for ZipFile" try { Add-Type -AssemblyName "System.IO.Compression.FileSystem" } catch { } } process { $zipExtension = ".zip" Write-Debug "Check source is input as .zip" if (-not($source.EndsWith($zipExtension))) { throw ("source parameter value [{0}] not end with extension {1}" -f $source, $zipExtension) } Write-Debug ("set desktop as destination path destination {0} is null" -f $destination) if ([string]::IsNullOrWhiteSpace($destination)) { $desktop = [System.Environment]::GetFolderPath([Environment+SpecialFolder]::Desktop) $directoryname = [System.IO.Path]::GetFileNameWithoutExtension($source) Write-Verbose ("Desktop : {0}" -f $desktop) Write-Verbose ("GetFileName : {0}" -f $directoryname) $destination = Join-Path $desktop $directoryname } Write-Debug "check destination is already exist, ExtractToDirectory Method will fail with same name of destination file." if (Test-Path $destination) { Write-Warning ("force replacing old zip file {0}" -f $destination) Remove-Item -Path $destination -Recurse -Force if (Test-Path $destination) { Write-Warning "Cancelled removing item. Quit cmdlet execution." return } } else { Write-Debug ("Destination not found. Check parent folder for destination {0} is exist." -f $destination) $parentpath = Split-Path $destination -Parent if (-not(Test-Path $parentpath)) { Write-Warning ("Parent folder {0} not found. Creating path." -f $parentpath) New-Item -Path $parentpath -ItemType Directory -Force } } try { Write-Debug "create source zip and complression" $sourcezip = [System.IO.Compression.Zipfile]::Open($source,"Update") $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal Write-Verbose ("sourcezip : {0}" -f $sourcezip) Write-Verbose ("destination : {0}" -f $destination) Write-Debug "Execute Main Process ExtractToDirectory." [System.IO.Compression.ZipFileExtensions]::ExtractToDirectory($sourcezip,$destination) } catch { Write-Error $_ } finally { Write-Debug ("Dispose Object {0} to remove file handler." -f $sourcezip) $sourcezip.Dispose() } } end { # only run with Verbose mode if ($PSBoundParameters.ContainsKey("Verbose")) { # end Stopwatch $endsw = $sw.Elapsed.TotalMilliseconds $endtime = Get-Date Write-Verbose ("Start time`t: {0:o}" -f $starttime) Write-Verbose ("End time`t: {0:o}" -f $endtime) Write-Verbose ("Duration`t: {0} ms" -f $endsw) } } } function Install-Repogisty { [CmdletBinding()] param ( [string]$installerPath ) .$installerPath } function Remove-Directory { [CmdletBinding()] param ( [string]$tempDir ) if ([System.IO.Directory]::Exists($tempDir)) { Write-Verbose ("temp folder '{0}' found, Removing folder for clean up." -f $tempDir) [System.IO.Directory]::Delete($tempDir, $true) } } . Main # To run this function paste below in PowerShell or Command Prompt(cmd) # 1. x not prefered : raw.github.com # powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.github.com/guitarrapc/valentia/master/valentia/Tools/RemoteInstall.ps1'))" # 2. o prefered : api.github.com # powershell -NoProfile -ExecutionPolicy unrestricted -Command 'iex ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String((irm "https://api.github.com/repos/guitarrapc/valentia/contents/valentia/Tools/RemoteInstall.ps1").Content))).Remove(0,1)'
PowerShellCorpus/PowerShellGallery/valentia/0.5.2.3/Tools/build.ps1
build.ps1
function CombineMultipleFileToSingle ([string]$InputRootPath, [string]$OutputPath, $Encoding) { try { $sb = New-Object System.Text.StringBuilder $sw = New-Object System.IO.StreamWriter ($OutputPath, $false, [System.Text.Encoding]::$Encoding) # Read All functions Get-ChildItem $InputRootPath -Recurse -File ` | Where-Object { -not ($_.FullName.Contains('.Tests.')) } ` | Where-Object Extension -eq '.ps1' ` | ForEach-Object { $sb.Append((Get-Content -Path $_.FullName -Raw -Encoding utf8)) > $null $sb.AppendLine() > $null $footer = '# file loaded from path : {0}' -f $_.FullName.Replace($valentia.modulePath, "") $sb.Append($footer) > $null $sb.AppendLine() > $null $sb.AppendLine() > $null } # Output into single file $sw.Write($sb.ToString()); } finally { # Dispose and release file handler $sb = $null $sw.Dispose() } } $Script:valentia = [ordered]@{} $valentia.name = 'valentia' $valentia.ExportPath = Split-Path $PSCommandPath -Parent $valentia.modulePath = Split-Path -parent $valentia.ExportPath $valentia.helpersPath = '\functions\' $valentia.typePath = '\type' $valentia.combineTempfunction = '{0}.ps1' -f $valentia.name $valentia.combineTemptype = 'Type.ps1' $valentia.fileEncode = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]'utf8' $valentia.moduleVersion = "0.5.2.3" $valentia.description = "PowerShell Remote deployment library for Windows Servers"; $valentia.copyright = "28/June/2013 -" $valentia.RequiredModules = @() $valentia.clrVersion = "4.0.0.0" # .NET 4.0 with StandAlone Installer "4.0.30319.1008" or "4.0.30319.1" , "4.0.30319.17929" (Win8/2012) $valentia.functionToExport = @( # Invokation # Invoke job "Invoke-Valentia", # Invoke RunSpacePool "Invoke-ValentiaAsync", # Download "Invoke-ValentiaDownload", # Ping "Ping-ValentiaGroupAsync", 'Watch-ValentiaPingAsyncReplyStatus', # Sync "Invoke-ValentiaSync", # Upload "Invoke-ValentiaUpload", "Invoke-ValentiaUploadList", # Helper # ACL "Get-ValentiaACL", "Set-ValentiaACL", "Test-ValentiaACL", # Certificate "Convert-ValentiaDecryptPassword", "Convert-ValentiaEncryptPassword", "Export-ValentiaCertificate", "Export-ValentiaCertificatePFX", "Get-ValentiaCertificateFromCert", "Import-ValentiaCertificate", "Import-ValentiaCertificatePFX", "Remove-ValentiaCertificate", "Remove-ValentiaCertificatePFX", "Show-ValentiaCertificate", # CleanupVariables "Invoke-ValentiaClean", # ComputerName 'Get-ValentiaComputerName', 'Rename-ValentiaComputerName', # Config "Backup-ValentiaConfig", "Edit-ValentiaConfig", 'Reset-ValentiaConfig', "Show-ValentiaConfig", # Credential "Get-ValentiaCredential", "Remove-ValentiaCredential", "Set-ValentiaCredential", "Test-ValentiaCredential", # DNS 'Get-ValentiaHostEntryAsync', # DynamicParam "New-ValentiaDynamicParamMulti", # Encoding "Get-ValentiaFileEncoding", # Folder "New-ValentiaFolder", # Group "Get-ValentiaGroup", "Invoke-ValentiaDeployGroupRemark", "Invoke-ValentiaDeployGroupUnremark", "New-ValentiaGroup", "Show-ValentiaGroup", # Initialize "Initialize-ValentiaEnvironment", # Location "Set-ValentiaLocation", # Log 'New-ValentiaLog', # PromptForChoice "Show-ValentiaPromptForChoice", # ScheduledTask 'Disable-ValentiaScheduledTaskLogSetting', 'Enable-ValentiaScheduledTaskLogSetting', 'Remove-ValentiaScheduledTask', 'Remove-ValentiaScheduledTaskEmptyDirectoryPath', 'Set-ValentiaScheduledTask', 'Test-ValentiaScheduledTask', # Sed "Invoke-ValentiaSed", # SymbolicLink 'Get-ValentiaSymbolicLink', 'Remove-ValentiaSymbolicLink', 'Set-ValentiaSymbolicLink', 'Test-ValentiaSymbolicLink', # Task "ConvertTo-ValentiaTask", "Get-ValentiaTask", # User "New-ValentiaOSUser", # Windows "Get-ValentiaRebootRequiredStatus", "Set-ValetntiaWSManConfiguration" ) $valentia.variableToExport = "valentia" $valentia.AliasesToExport = @( "Task", "Vale", "Valea", "Upload","UploadL", "Sync", "Download", "Go", "Clean","Reload", "Target","PingAsync","Sed", "ipremark","ipunremark", "Cred", "Rename", "DynamicParameter", "Initial" ) $script:moduleManufest = @{ Path = "{0}.psd1" -f $valentia.name Author = "guitarrapc"; CompanyName = "guitarrapc" Copyright = ""; ModuleVersion = $valentia.moduleVersion Description = $valentia.description PowerShellVersion = "3.0"; DotNetFrameworkVersion = "4.0"; ClrVersion = $valentia.clrVersion; RequiredModules = $valentia.RequiredModules; NestedModules = "{0}.psm1" -f $valentia.name; CmdletsToExport = "*"; FunctionsToExport = $valentia.functionToExport VariablesToExport = $valentia.variableToExport; AliasesToExport = $valentia.AliasesToExport; } if ($PSVersionTable.PSVersion.Major -ge 5) { $moduleManufest.ProjectUri = "https://github.com/guitarrapc/valentia" $moduleManufest.LicenseUri = "https://github.com/guitarrapc/valentia/blob/master/LICENSE" $moduleManufest.Tags = "RemoteManagement", "Orchestration", "Credential", "SymbolicLink" } New-ModuleManifest @moduleManufest # As Installer place on ModuleName\Tools. $psd1 = Join-Path $valentia.ExportPath ("{0}.psd1" -f $valentia.name); $newpsd1 = Join-Path $valentia.ModulePath ("{0}.psd1" -f $valentia.name); if (Test-Path -Path $psd1) { Get-Content -Path $psd1 -Encoding UTF8 -Raw -Force | Out-File -FilePath $newpsd1 -Encoding default -Force Remove-Item -Path $psd1 -Force } # Combine all types into single .ps1 $outputPath = Join-Path $valentia.modulePath $valentia.combineTemptype $InputRootPath = (Join-Path $valentia.modulePath $valentia.typePath) if(Test-Path $outputPath){ Remove-Item -Path $outputPath -Force } CombineMultipleFileToSingle -InputRootPath $InputRootPath -OutputPath $outputPath -Encoding UTF8 # Combine all functions into single .ps1 $outputPath = Join-Path $valentia.modulePath $valentia.combineTempfunction $InputRootPath = (Join-Path $valentia.modulePath $valentia.helpersPath) if(Test-Path $outputPath){ Remove-Item -Path $outputPath -Force } CombineMultipleFileToSingle -InputRootPath $InputRootPath -OutputPath $outputPath -Encoding UTF8
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/sitecore-sites.ps1
sitecore-sites.ps1
# # sitecore_sites.ps1 # function Get-SitecoreSites { [cmdletbinding()] Param( [parameter(ValueFromPipeline)] [ValidateNotNullOrEmpty()] [string[]]$Path ) Process { $colSites = @() $files = Get-ChildItem -Path $Path -Filter *.config foreach($file in $files) { [xml]$XmlDocument = Get-Content -Path $file.FullName $site = $XmlDocument.configuration.sitecore.sites.site if( $site -ne $null -and $site.startItem -ne $null) { Write-Verbose "Processing file $file" $colSites += $site } } return $colSites; } } Export-ModuleMember -Function Get-SitecoreSites
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/sitecore-tests.ps1
sitecore-tests.ps1
# # sitecore_tests.ps1 # Function Test-WebResponse { [cmdletbinding(SupportsShouldProcess=$true)] param( [parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String] $Url, [int] $Timeout = 10000 ) $result = $false $uri = "" $isUrlCorrect = [System.Uri]::TryCreate($Url, [System.UriKind]::Absolute,[ref] $uri) if( $isUrlCorrect -eq $false ) { Write-Warning "Can't create URI from '$Url'" return $result } else { $sw = [Diagnostics.Stopwatch]::StartNew() $HTTP_Request = [System.Net.WebRequest]::Create($uri) $HTTP_Request.Timeout = $Timeout $HTTP_Response = $null try { $HTTP_Response = $HTTP_Request.GetResponse(); # We then get the HTTP code as an integer. $HTTP_Status = [int]$HTTP_Response.StatusCode $sw.Stop() If ($HTTP_Status -eq 200) { Write-Verbose "Test SUCCESS for $uri - $($sw.Elapsed)" $result = $true } Else { Write-Verbose "Test FAIL for $uri. Response: $HTTP_Status" } } catch { Write-Warning "ERROR for $Url ($uri): Exception: $($_.Exception.Message)" } finally { # Finally, we clean up the http request by closing it. if( $HTTP_Response -ne $null) { $HTTP_Response.Close() } } return $result } } Export-ModuleMember -Function Test-WebResponse
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/sitecore-hosts.ps1
sitecore-hosts.ps1
# # sitecore_hosts.ps1 # function Get-DefaultHosts() { return Join-Path -Path $env:windir -ChildPath '\System32\drivers\etc\hosts' } <# .SYNOPSIS Adds host entry to hosts file. .DESCRIPTION .PARAMETER IpAddress The IP address for host entry. .PARAMETER HostName The hostname for host entry. .PARAMETER Comment The comment/description for host entry. .PARAMETER Path The path to the hosts file. The default value is '%WINDIR%\System32\drivers\etc\hosts' .EXAMPLE New-SitecoreHostsEntry -IpAddress 127.0.0.2 -HostName 'HostName4' -Path $hostsFile -Verbose .EXAMPLE New-SitecoreHostsEntry -IpAddress 127.0.0.2 -HostName 'HostName4' -Path $hostsFile -Verbose #> function New-SitecoreHostsEntry { [CmdletBinding(SupportsShouldProcess=$true)] param ( [parameter(Mandatory=$true)] [string]$IpAddress, [parameter(Mandatory=$true)] [string]$HostName, [parameter()] [string]$Comment, [parameter()] [string]$Path = (Get-DefaultHosts) ) Write-Verbose "Processing hosts file: '$Path'" Write-Verbose "Add host entry $IpAddress $HostName $Comment" $matchPattern = '^(?<IP>[0-9a-f.:]+)\s+(?<Hostname>[^\s#]+)(?<Comment>.*)$' $found = $false [System.Collections.ArrayList]$ArrayList = @() if( Test-Path -Path $Path ) { $content = Get-Content -Path $Path } else { Write-Warning "File '$Path' not exists." return } foreach( $line in $content) { if( ($line.StartsWith("#")) -or ($line.Length -eq 0)) { $ArrayList.Add($line) | Out-Null continue } elseif( $line -match $matchPattern ) { if( $Matches.Hostname -ne $null ) { if( $Matches.Hostname -eq $HostName ) { Write-Verbose "Host '$HostName' already exists with $($Matches.IP) $($Matches.Comment)" $found = $true } } } $ArrayList.Add($line) | Out-Null } if( -not $found ) { if( [string]::IsNullOrWhiteSpace($Comment) ) { $ArrayList.Add("$IPAddress`t$Hostname") | Out-Null } else { $ArrayList.Add("$IPAddress`t$Hostname`t#$Comment") | Out-Null } Set-Content -Path $Path -Value $ArrayList | Out-Null } } <# .SYNOPSIS Removes host entry from hosts file. .DESCRIPTION .PARAMETER HostName The hostname for host entry. .PARAMETER Path The path to the hosts file. The default value is '%WINDIR%\System32\drivers\etc\hosts' .EXAMPLE Remove-SitecoreHostsEntry -HostName 'HostName4' #> function Remove-SitecoreHostsEntry { [CmdletBinding(SupportsShouldProcess=$true)] param ( [parameter(Mandatory=$true)] [string]$HostName, [parameter()] [string]$Path = (Get-DefaultHosts) ) Write-Verbose "Processing hosts file: '$Path'" Write-Verbose "Delete host entry $HostName" $matchPattern = '^(?<IP>[0-9a-f.:]+)\s+(?<Hostname>[^\s#]+)(?<Comment>.*)$' $found = $false [System.Collections.ArrayList]$ArrayList = @() if( Test-Path -Path $Path ) { $content = Get-Content -Path $Path } else { Write-Warning "File '$Path' not exists." return } foreach( $line in $content) { if( ($line.StartsWith("#")) -or ($line.Length -eq 0)) { $ArrayList.Add($line) | Out-Null continue } elseif( $line -match $matchPattern ) { if( $Matches.Hostname -ne $null ) { if( $Matches.Hostname -eq $HostName ) { Write-Verbose "Host '$HostName' exists with $($Matches.IP) $($Matches.Comment)" $found = $true } } } if( -not $found ) { $ArrayList.Add($line) | Out-Null } } if( $found ) { Set-Content -Path $Path -Value $ArrayList | Out-Null } } Export-ModuleMember -Function New-SitecoreHostsEntry Export-ModuleMember -Function Remove-SitecoreHostsEntry
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/system-email.ps1
system-email.ps1
# # system_email.ps1 # function Get-EmailParameters { return @{ SmtpServer = "" SmtpPort = "" SmtpUsername = "" SmtpPassword = new-object SecureString UseSsl = $false From = "" To = "" Bcc = "" Subject = "" Body = "" } } function Send-Email { <# .Example $params = Get-EmailParameters $params.SmtpServer = "localhost" $params.From = "powershell@domain.com" $params.To = "me@domain.com" $params.Subject = "Test" $params.Body = "Test" Send-Email @params -Verbose #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$SmtpServer, [parameter()] [string]$SmtpPort = 25, [parameter()] [string]$SmtpUsername, [parameter()] [Security.SecureString]$SmtpPassword, [parameter()] [bool]$UseSsl = $false, [parameter(Mandatory=$true)] [string]$From, [parameter(Mandatory=$true)] [string]$To, [parameter()] [string]$Bcc, [parameter(Mandatory=$true)] [string]$Subject, [parameter(Mandatory=$true)] [string]$Body ) Write-Verbose "Server: $SmtpServer : $SmtpPort" $smtp = new-object Net.Mail.SmtpClient($SmtpServer, $SmtpPort) $smtp.EnableSsl = $UseSsl if( $SmtpUsername -ne '' -and $SmtpPassword.Length -ne 0) { $smtp.Credentials = new-object Net.NetworkCredential($SmtpUsername, $SmtpPassword) } $msg = new-object Net.Mail.MailMessage $msg.From = $From $msg.To.Add($To) if( $Bcc -ne '' ) { $msg.Bcc.Add($Bcc) } $msg.Subject = $Subject $msg.Body = $Body $smtp.Send($msg) } Export-ModuleMember -Function Send-Email Export-ModuleMember -Function Get-EmailParameters
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/sitecore-spe.ps1
sitecore-spe.ps1
# # sitecore_spe.ps1 # function Get-DefaultSpeConfig() { # $AppPath is SPE console variable, see Variables on https://doc.sitecorepowershell.com/interfaces.html if( $AppPath -ne $null ) { return Join-Path -Path $AppPath -ChildPath "App_Config\Include\Cognifide.PowerShell.config" } } function Set-UAC4SPE { <# .SYNOPSIS Sets an User Access Control parameters for Sitecore Powershell Extension .DESCRIPTION More about Sitecore Powershell Extension security https://doc.sitecorepowershell.com/security.html .PARAMETER Token An unique string used for the gate token attribute ('Default','Console','ISE','ItemSave') .PARAMETER Action An action to perform when session elevation is triggered (Allow, Block, Password) .PARAMETER Expiration A timespan used to determine the elevated session lifetime (hh:mm:ss) .PARAMETER SpeConfig A path to Cognifide.PowerShell.config. If this function is used in a SPE console then default parameter should be enough Get-DefaultSpeConfig .EXAMPLE Set-UAC4SPE -Token Console -Expiration '00:06:00' Set-UAC4SPE -Token Console -Expiration '00:06:00' -Action Allow .EXAMPLE PowerShell will number them for you when it displays your help text to a user. #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [parameter(Mandatory=$true)] [ValidateSet('Default','Console','ISE','ItemSave')] [string]$Token = $null, [parameter()] [ValidateSet('Block','Password','Allow')] [string]$Action = $null, [string]$Expiration = $null, [string]$SpeConfig = (Get-DefaultSpeConfig) ) Write-Verbose "Set User Account Control in file $SpeConfig" [xml]$XmlDocument = Get-Content -Path $SpeConfig $xpath = "//configuration/sitecore/powershell/userAccountControl/tokens//token[@name = '$Token' ]" $tokenNode = $XmlDocument.SelectSingleNode($xpath) if( $Action -ne '' ) { $tokenNode.Attributes["elevationAction"].Value = $Action if ($pscmdlet.ShouldProcess("Set elevationAction to $Action on $SpeConfig")) { $XmlDocument.Save($SpeConfig) } } if( $Expiration -ne '' ) { $tokenNode.Attributes["expiration"].Value = $Expiration if ($pscmdlet.ShouldProcess("Set expiration to $Expiration on $SpeConfig")) { $XmlDocument.Save($SpeConfig) } } } # function Get-UAC4SPE { <# .SYNOPSIS Gets information about settings of passed token. .DESCRIPTION More about Sitecore Powershell Extension security https://doc.sitecorepowershell.com/security.html .PARAMETER Token An unique string used for the gate token attribute ('Default','Console','ISE','ItemSave') .PARAMETER SpeConfig A path to Cognifide.PowerShell.config. If this function is used in a SPE console then default parameter should be enough Get-DefaultSpeConfig .EXAMPLE Get-UAC4SPE -Token Console #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [parameter(Mandatory=$true)] [ValidateSet('Default','Console','ISE','ItemSave')] [string]$Token = $null, [string]$SpeConfig = (Get-DefaultSpeConfig) ) Write-Verbose "Get User Account Control from file '$SpeConfig'" [xml]$XmlDocument = Get-Content -Path $SpeConfig $xpath = "//configuration/sitecore/powershell/userAccountControl/tokens//token[@name = '$Token' ]" $tokenNode = $XmlDocument.SelectSingleNode($xpath) return $tokenNode } Export-ModuleMember -Function Get-UAC4SPE Export-ModuleMember -Function Set-UAC4SPE
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/xml-utils.ps1
xml-utils.ps1
# # xml_utils.ps1 # function New-IISHandler { <# .SYNOPSIS Adds a new entry to the web.config handlers section .EXAMPLE This sample command: New-IISHandler -XmlPath 'C:\web.config' -Name "CaptchaAudio" -Path 'CaptchaAudio.axd' -Type "Sitecore.Form.Core.Pipeline.RequestProcessor.CaptchaResolver, Sitecore.Forms.Core" -Verb "*" Will add this element in web.config file: <add name="CaptchaAudio" path="CaptchaAudio.axd" type="Sitecore.Form.Core.Pipeline.RequestProcessor.CaptchaResolver, Sitecore.Forms.Core" verb="*" /> .LINK https://www.iis.net/configreference/system.webserver/handlers .LINK This is part of Sitecore-Automation module https://www.powershellgallery.com/packages/sitecore-automation #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$true)] [ValidateScript ({Test-Path $_})] [string]$XmlPath, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name, [Parameter(Mandatory=$true)] [string]$Path, [Parameter(Mandatory=$true)] [string]$Type, [Parameter(Mandatory=$true)] [string]$Verb, [string]$Comment, [bool]$Backup ) [xml]$XmlDocument = Get-Content -Path $XmlPath $handlers = $XmlDocument.SelectSingleNode("//configuration/system.webServer/handlers") if($handlers -eq $null) { $(throw "IIS Handlers does not Exists! Invalid Configuration File.") } $handler = $handlers.ChildNodes | Where-Object {$_ -ne $null -and $_.Name -eq $Name} if( $handler -eq $null ) { $item = $XmlDocument.CreateElement("add") $item.SetAttribute("name", $Name) $item.SetAttribute("path", $Path) $item.SetAttribute("type", $Type) $item.SetAttribute("verb", $Verb) if( [String]::IsNullOrWhiteSpace($Comment) -eq $false ) { $xmlComment = $XmlDocument.CreateComment($Comment); $handlers.AppendChild($xmlComment) } $handlers.AppendChild($item) if ($pscmdlet.ShouldProcess($XmlPath)) { if( $Backup -eq $true) { Backup-File -SourceFile $XmlPath } $XmlDocument.Save($XmlPath); } } else { Write-Verbose "A handler with a name '$Name' already exist." } } function Remove-IISHandler { [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$true)] [ValidateScript ({Test-Path $_})] [string]$XmlPath, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name ) [xml]$XmlDocument = Get-Content -Path $XmlPath $handlers = $XmlDocument.SelectSingleNode("//configuration/system.webServer/handlers") if($handlers -eq $null) { $(throw "IIS Handlers does not Exists! Invalid Configuration File.") } $handler = $handlers.ChildNodes | Where-Object {$_ -ne $null -and $_.Name -eq $Name} if( $handler -ne $null ) { Write-Verbose $handler.OuterXml if ($pscmdlet.ShouldProcess($XmlPath)) { if( $Backup -eq $true) { Backup-File -SourceFile $XmlPath } $handlers.RemoveChild($handler) $XmlDocument.Save($XmlPath); } } } function Disable-IISHandler { [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$true)] [ValidateScript ({Test-Path $_})] [string]$XmlPath, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name ) [xml]$XmlDocument = Get-Content -Path $XmlPath $handlers = $XmlDocument.SelectSingleNode("//configuration/system.webServer/handlers") if($handlers -eq $null) { $(throw "IIS Handlers does not Exists! Invalid Configuration File.") } $handler = $handlers.ChildNodes | Where-Object {$_ -ne $null -and $_.Name -eq $Name} if( $handler -ne $null ) { Write-Verbose $handler.OuterXml if ($pscmdlet.ShouldProcess($XmlPath)) { if( $Backup -eq $true) { Backup-File -SourceFile $XmlPath } $xmlComment = $XmlDocument.CreateComment($handler.OuterXml); $handlers.InsertBefore($xmlComment, $handler) $handlers.RemoveChild($handler) $XmlDocument.Save($XmlPath); } } } function New-SettingsFile { [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$true)] [string]$XmlPath, [string]$Comment ) [System.XML.XMLDocument]$XmlDocument = New-Object System.XML.XMLDocument #$configuration = $XmlDocument.CreateElement("patch","configuration","http://www.sitecore.net/xmlconfig/") $configuration = $XmlDocument.CreateElement("configuration") $configuration.SetAttribute("xmlns:patch", "http://www.sitecore.net/xmlconfig/") $sitecore = $XmlDocument.CreateElement("sitecore") $settings = $XmlDocument.CreateElement("settings") $XmlDocument.appendChild($configuration) $configuration.appendChild($sitecore) $sitecore.appendChild($settings) if( [String]::IsNullOrWhiteSpace($Comment) -eq $false ) { $xmlComment = $XmlDocument.CreateComment($Comment); $XmlDocument.InsertBefore($xmlComment,$configuration) } $XmlDocument.Save($XmlPath); } function New-SettingsPatch { [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$true)] [ValidateScript ({Test-Path $_})] [string]$XmlPath, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Name, [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]$Value, [string]$Comment, [bool]$Backup ) [xml]$XmlDocument = Get-Content -Path $XmlPath $sitecoreSettings = "//configuration/sitecore/settings" $appSettingsNode = $XmlDocument.SelectSingleNode($sitecoreSettings) if($appSettingsNode -eq $null) { $(throw "Sitecore Settings Does not Exists! Invalid Configuration File.") } $existingNode = $XmlDocument.SelectNodes("//configuration/sitecore/settings/setting") | Where-Object {$_ -ne $null -and $_.Name -eq $Name} if( $existingNode -ne $null ) { Write-Verbose "Patch for setting $Name already exist" return } [XmlElement]$item = $XmlDocument.CreateElement("setting") $item.SetAttribute("name", $Name) $patch = $XmlDocument.CreateElement("patch","attribute","http://www.sitecore.net/xmlconfig/") $patch.SetAttribute("name", "value") $patch.InnerText = $Value $item.AppendChild($patch) $appSettingsNode.AppendChild($item); if( [String]::IsNullOrWhiteSpace($Comment) -eq $false ) { $xmlComment = $XmlDocument.CreateComment($Comment); $appSettingsNode.InsertBefore($xmlComment,$item) } if ($pscmdlet.ShouldProcess($XmlPath)) { if( $Backup -eq $true) { Backup-File -SourceFile $XmlPath } $XmlDocument.Save($XmlPath); } } function Test-XmlAttribute { <# .SYNOPSIS Checks if passed node has an attribute and an attribute has an expected value .EXAMPLE This sample command: [System.Xml.XmlNode]$node = $XmlDocument.SelectSingleNode("//compilation") Test-XmlAttribute -Node $node -AttrName 'optimizeCompilations' -ExpectedValue 'true' If compilation node looks like belowe, then Test-XmlAttribute returns true. <compilation defaultLanguage="c#" debug="false" targetFramework="4.5.2" optimizeCompilations="true"> .LINK This is part of Sitecore-Automation module https://www.powershellgallery.com/packages/sitecore-automation #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [System.Xml.XmlNode] $Node, [string] $AttrName, [string] $ExpectedValue = $null ) $attr = $Node.Attributes[$AttrName] if( $attr -ne $null ) { if( $ExpectedValue -ne $null -and $attr.Value -ne $ExpectedValue ) { return $false } return $true } else { return $false } } function Set-XmlAttribute { <# .SYNOPSIS Sets an attribute value to expected value in the node passed as -Node parameter. .EXAMPLE [System.Xml.XmlNode]$node = $XmlDocument.SelectSingleNode("//compilation") Set-XmlAttribute -Node $compilation -AttrName 'debug' -ExpectedValue 'false' The 'compilation' node before run a command: <compilation defaultLanguage="c#" debug="true" targetFramework="4.5.2"> The 'compilation' node after run a command (attribute debug has changed value): <compilation defaultLanguage="c#" debug="false" targetFramework="4.5.2"> .EXAMPLE [System.Xml.XmlNode]$node = $XmlDocument.SelectSingleNode("//compilation") Set-XmlAttribute -Node $compilation -AttrName 'optimizeCompilations' -ExpectedValue 'true' -Verbose -Force The 'compilation' node before run a command: <compilation defaultLanguage="c#" debug="true" targetFramework="4.5.2"> The 'compilation' node after run a command (A new attribute was added because of -Force parameter): <compilation defaultLanguage="c#" debug="false" targetFramework="4.5.2" optimizeCompilations="true > .LINK This is part of Sitecore-Automation module https://www.powershellgallery.com/packages/sitecore-automation #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [System.Xml.XmlNode] $Node, [string] $AttrName, [string] $ExpectedValue, [switch] $Force = $false ) $attr = $Node.Attributes[$AttrName] if( $attr -ne $null ) { Write-Verbose "Current value of attribute $AttrName = $($attr.Value)" if( $attr.Value -ne $ExpectedValue ) { Write-Verbose "Set $AttrName to $ExpectedValue" $attr.Value = $ExpectedValue } } else { Write-Warning "Attribute '$AttrName' not exist." if( $Force -eq $true) { Write-Verbose "Add new attribute $AttrName with value $ExpectedValue" $Node.SetAttribute($AttrName, $ExpectedValue) } } }
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/system-utils.ps1
system-utils.ps1
# # system_utils.ps1 # #http://www.adminarsenal.com/admin-arsenal-blog/powershell-zip-up-files-using-net-and-add-type/ function Zip-Directory { Param( [Parameter(Mandatory=$True)][string]$DestinationFileName, [Parameter(Mandatory=$True)][string]$SourceDirectory, [Parameter(Mandatory=$False)][string]$CompressionLevel = "Optimal", [Parameter(Mandatory=$False)][switch]$IncludeParentDir ) Write-Verbose "Compress directory $SourceDirectory to $DestinationFileName" Add-Type -AssemblyName System.IO.Compression.FileSystem $CompressionLevel = [System.IO.Compression.CompressionLevel]::$CompressionLevel [System.IO.Compression.ZipFile]::CreateFromDirectory($SourceDirectory, $DestinationFileName, $CompressionLevel, $IncludeParentDir) } function UnZip-Directory { Param( [Parameter(Mandatory=$True)][string]$SourceZipFile, [Parameter(Mandatory=$True)][string]$DestinationDirectory ) Add-Type -AssemblyName System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($SourceZipFile, $DestinationDirectory) } function Backup-File { [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$True)] [string]$SourceFile ) #More about date formating - https://technet.microsoft.com/en-us/library/ee692801.aspx $date = Get-Date -Format d-M-yyyy-HH-MM-ss $backupFile = [System.IO.Path]::GetFileNameWithoutExtension($SourceFile) + "_" + $date + ".bak" $backupFolder = [System.IO.Path]::GetDirectoryName($SourceFile) $backupPath = Join-Path -Path $backupFolder -ChildPath $backupFile Copy-Item -Path $SourceFile -Destination $backupPath } function Set-FilesReadOnly { Param( [Parameter(Mandatory=$true)] [string]$Path ) Set-ItemProperty -Path $Path -Name IsReadOnly -Value $true }
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/sitecore-bindings.ps1
sitecore-bindings.ps1
# # sitecore_bindings.ps1 # function Add-Binding($SiteName, $HostHeader ) { $bindings = Get-WebBinding -Name $SiteName if( $bindings.bindingInformation -match $HostHeader ) { Write-Verbose "A binding '$HostHeader' already exist on site '$SiteName'" } else { try { Write-Verbose "Adds a binding '$HostHeader' to an IIS '$SiteName' site" New-WebBinding -Name $SiteName -IPAddress "*" -Port 80 -HostHeader $HostHeader; } catch { Write-Warning "Adds a binding '$HostHeader' failed - $($_.Exception.Message)" } } } function Add-SitecoreBindings { [cmdletbinding(SupportsShouldProcess=$true)] Param( [ValidateNotNullOrEmpty()] $Hosts, [ValidateNotNullOrEmpty()] [string]$WebSite, [switch]$www ) #region ValidatePreconditions if( -not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Warning "Add bindings requires Administrator rights" return } if( -not (Test-Path -Path (Join-Path 'IIS:\Sites' -ChildPath $WebSite ) ) ) { Write-Warning "Site '$WebSite' does not exist." return } #endregion foreach($hostName in $Hosts) { Add-Binding -Site $WebSite -HostHeader $hostName if( ($www -eq $true) -and ($hostName.StartsWith("www") -eq $false) ) { Add-Binding -Site $WebSite -HostHeader "www.$hostName" } } } function Remove-SitecoreBindings { [cmdletbinding(SupportsShouldProcess=$true)] Param( [ValidateNotNullOrEmpty()] $Hosts, [ValidateNotNullOrEmpty()] [string]$WebSite ) #region ValidatePreconditions if( -not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Warning "Add bindings requires Administrator rights" return } if( -not (Test-Path -Path (Join-Path "IIS:\Sites" -ChildPath $WebSite ) ) ) { Write-Warning "Site '$WebSite' does not exist." return } #endregion foreach($hostName in $Hosts) { $bindings = Get-WebBinding -Name $WebSite; if( $bindings.bindingInformation -match $hostName ) { Write-Verbose "Removes a binding '$hostName' from an IIS '$webSite' site." Remove-WebBinding -Name $WebSite -IPAddress "*" -Port 80 -HostHeader $hostName } if( $bindings.bindingInformation -match "www.$hostName" ) { Write-Verbose "Removes a binding 'www.$hostName' from an IIS '$webSite' site." Remove-WebBinding -Name $WebSite -IPAddress "*" -Port 80 -HostHeader "www.$hostName" } } } Export-ModuleMember -Function Add-SitecoreBindings Export-ModuleMember -Function Remove-SitecoreBindings
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/sitecore-csv.ps1
sitecore-csv.ps1
<# .Synopsis Processing Config Enable-Disable Sitecore_8.2-160906_RTM.csv file .DESCRIPTION This function is processing csv file, that contains guideline about enable/disable configuration files on each enviroment. #> function Set-SitecoreEnvironment { [CmdletBinding(SupportsShouldProcess=$true)] param ( [parameter(Mandatory=$true)] [string]$CsvPath, [parameter(Mandatory=$true)] [string]$WebPath, [parameter()] [ValidateSet('ContentDelivery','ContentManagement','Processing','CMProcessing','Reporting')] [string]$Environment = $null, [parameter()] [ValidateSet('Solr','Lucene')] [string]$Search = $null, [switch]$Backup ) $projectFolder = Split-Path -Parent $MyInvocation.MyCommand.Path Write-Verbose $projectFolder if($Backup -eq $true) { $sourceFolder = Join-Path -Path $WebPath -ChildPath "website\App_Config" # More about date formating - https://technet.microsoft.com/en-us/library/ee692801.aspx $date = Get-Date -Format d-M-yyyy-HH-MM-s $backupFile = "website\App_Config-$date.zip" $backupPath = Join-Path -Path $WebPath -ChildPath $backupFile Zip-Directory -DestinationFileName $backupPath -SourceDirectory $sourceFolder } if( ($Search -ne '') -and ($Environment -ne '')) { Write-Verbose "Configure $Search for environment: $Environment" # Prefilter all configuration files to select only files with values 'Solr is used' or 'Lucene is used' $searchProviderPreFilter = {$_.SearchProviderUsed -ne '' -and $_.SearchProviderUsed -ne 'Base' } # Set field 'Enable' to true if # configuration file is used by selected search engine # and configuration file should be enabled on selected environment $action = @{Name="Enable"; Expression = { ($_.SearchProviderUsed -eq "$Search is used" -and $_.$Environment -eq 'Enable')}} # Build full path to configuration file $file = @{Name="ConfigPath";Expression = { Combine-Path $WebPath $_.FilePath $_.ConfigFileName}} Import-Csv $CsvPath | Where-Object $searchProviderPreFilter | Select-Object $file, $action, @{Name="ProcessExample"; Expression={$true}} | Switch-SitecoreConfigFile } elseif( $Environment -ne '' -and $Search -eq '') { Write-Verbose "Configure environment: $Environment" # Prefilter all configuration files to select all files not connected with any search provider $searchProviderPreFilter = {$_.SearchProviderUsed -eq '' -or $_.SearchProviderUsed -eq 'Base' } # Set field 'Enable' to true if # and configuration file should be enabled on selected environment $action = @{Name="Enable"; Expression = { ( $_.$Environment -eq 'Enable')}} # Build full path to configuration file $file = @{Name="ConfigPath";Expression = { Combine-Path $WebPath $_.FilePath $_.ConfigFileName}} Import-Csv $CsvPath | Where-Object $searchProviderPreFilter | Select-Object $file, $action, @{Name="ProcessExample"; Expression={$false}} | Switch-SitecoreConfigFile } } <# .Synopsis Enable or disable Sitecore configuration file .DESCRIPTION This function is used to enable/disable configuration file. This functionality is realized by change file name extension. Enable configuration file means - remove extension '.disabled' Disable configuration file means - add extension '.disabled' This function process objects passed by pipeline. Object should have two properties ConfigPath and Enable. ConfigPath - this is path to configration file Enable - if set to true file is enabled, otherwise disabled .EXAMPLE #> function Switch-SitecoreConfigFile { process { $VerbosePreference = "Continue" $configFile = $_.ConfigPath; Write-Verbose "Processing $configFile..." if( -not (Test-Path -Path $configFile) ) { Write-Warning "File not exist" return; } $extension = [System.IO.Path]::GetExtension($configFile) $processExample = $_.ProcessExample # extension .example should be processed only when search configuration is processed if($processExample -eq $true -and $_.Enable -eq $true -and $extension -eq '.example') { $newConfigFile = $configFile -replace "\.example","" Write-Verbose "Enable example file $newConfigFile" Rename-Item $configFile -NewName $newConfigFile } elseif($_.Enable -eq $true -and $extension -eq '.disabled') { $newConfigFile = $configFile -replace ".disabled","" Write-Verbose "Enable file $newConfigFile" Rename-Item $configFile -NewName $newConfigFile } elseif($_.Enable -eq $false -and $extension -eq '.config' ) { $newConfigFile = $configFile -replace "\.config",".config.disabled" Write-Verbose "Disable file $newConfigFile" Rename-Item $configFile -NewName $newConfigFile } else { Write-Warning "Change is not necessary" } } } <# .EXAMPLE Combine-Path 'a' .EXAMPLE Combine-Path 'a' 'b' .EXAMPLE Combine-Path 'a' 'b' 'c' #> function Combine-Path { [CmdletBinding(SupportsShouldProcess=$true)] param ( [parameter(Mandatory=$true)] [string]$Path1, [parameter(Mandatory=$true)] [string]$Path2, [parameter()] [string]$Path3 ) return Join-Path $Path1 -ChildPath (Join-Path $Path2 -ChildPath $Path3) } Export-ModuleMember -Function Set-SitecoreEnvironment
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/vs-utils.ps1
vs-utils.ps1
# # vs_utils.ps1 # function Clear-CopyLocal { [CmdletBinding(SupportsShouldProcess=$true)] Param( [Parameter(Mandatory=$true)] [string]$Path ) $excludedList = @( 'Sitecore.*', 'Newtonsoft.*' ) $solutionReferences = @(); dir $path -Recurse *.csproj | ForEach-Object { $singleFile = $_.FullName; Write-Verbose "Processing '$singleFile' file" $xml = New-Object System.Xml.XmlDocument; $xml.Load($singleFile); $references = $xml.Project.ItemGroup.Reference; $referencesList = @(); $updateFile = $false foreach($reference in $references) { # Choose only references to Sitecore libraries if( $reference.Include -match "Sitecore.*" -or $reference.Include -match "Newtonsoft.*") { $referencesList += $reference; # Check if <Private/> element exist $node = $reference.ChildNodes | Where-Object {$_.Name -eq 'Private'} if( $node.Count -eq 0 ) { $private = $xml.CreateElement("Private", $xml.DocumentElement.NamespaceURI); $private.InnerText = "False"; $reference.AppendChild($private); $updateFile = $true Write-Verbose "`tAdd False - for $($reference.Include)." } elseif( $node.'#text' -eq $true ) { $node.'#text' = "False" Write-Verbose "`tSet $($node.'#text') - for $($reference.Include)" $updateFile = $true } else { Write-Verbose "`tWas $($node.'#text') - for $($reference.Include)" } } } if ($updateFile -eq $true -and $pscmdlet.ShouldProcess($singleFile)) { $xml.Save("$singleFile"); } } }
PowerShellCorpus/PowerShellGallery/sitecore-automation/1.3.0.2/system-credential.ps1
system-credential.ps1
# # system_credential.ps1 # # An array to store credentaials in memory (each object contains key,username,password) [System.Collections.ArrayList]$script:credentialsStore = @() function New-StoredCredential { <# .SYNOPSIS Adds a credentials to the in memory credential store. .DESCRIPTION A user will be asked to provide a username and password. Credentials will be stored in memory table. The credentails will be stored as secure string. You shall call Save-Credentials to save in memory table to file. .EXAMPLE New-StoredCredential -Key 'SMTP Credentials' -Message 'Provide a credentials for SMTP server' #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$Key, [parameter()] [string]$Username, [parameter()] [Security.SecureString]$Password = ( new-object SecureString ), [parameter()] [string]$Message="Please provide credentials:" ) $credentialsItem = Get-StoredCredential($Key) if( $credentialsItem -ne $null ) { Write-Warning "A key '$Key' already exist!" return } $user = $null $pwd = $null if( $Username -eq '' -and $Password.Length -eq 0) { $credentials = Get-Credential -Message $Message $user = $credentials.UserName | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString $pwd = $credentials.Password | ConvertFrom-SecureString } else { $user = $Username | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString $pwd = $Password | ConvertFrom-SecureString } $credentialsItem = New-Object PSObject $credentialsItem | Add-Member –MemberType NoteProperty –Name Key –Value $Key $credentialsItem | Add-Member –MemberType NoteProperty –Name Username –Value $user $credentialsItem | Add-Member –MemberType NoteProperty –Name Password –Value $pwd $script:credentialsStore += $credentialsItem; } function Export-CredentialStore { <# .SYNOPSIS Saves an in memory credentials table to the CSV file. .EXAMPLE Save-CredentialStore -Path 'C:\MyScriptsConfiguration' #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$Path ) $script:credentialsStore | Export-Csv -Path $Path -NoTypeInformation } function Import-CredentialStore { <# .SYNOPSIS Loads credentials from a CSV file and stores credentials in a memory table. .EXAMPLE Load-CredentialStore -Path 'C:\MyScriptsConfiguration' #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$Path ) $script:credentialsStore = Import-Csv -Path $Path } function Get-StoredCredential { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$Key ) return $script:credentialsStore | Where-Object { $_.Key -eq $Key } } function TryGet-StoredCredential { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$Key ) $credentialsItem = Get-StoredCredential($Key) if( $credentialsItem -eq $null ) { New-StoredCredential($Key) return Get-StoredCredential($Key) } } function ConvertTo-PlainText { <# .SYNOPSIS Converts a secure string to the plain text .EXAMPLE ConvertTo-PlainText -String 'jsjdakdajskdajsd' #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$Secret ) $secureString = $Secret | ConvertTo-SecureString $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR( $secureString ) return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) } Export-ModuleMember -Function ConvertTo-PlainText Export-ModuleMember -Function New-StoredCredential Export-ModuleMember -Function TryGet-StoredCredential Export-ModuleMember -Function Get-StoredCredential Export-ModuleMember -Function Import-CredentialStore Export-ModuleMember -Function Export-CredentialStore
PowerShellCorpus/PowerShellGallery/powerworks/0.0.17.55/Public/Test-Port.ps1
Test-Port.ps1
<# .Synopsis This cmdlet will test a given TCP port till the port is open .DESCRIPTION This cmdlet will continously test a given TCP port untill the cmdlet is halted or a connection to the given port is established. This is useful for testing connectivity while configuring firewall rules. This function also allows for the verbose switch to be used. .PARAMETER Computer This is the name of the computer you want to test connectivity to .PARAMETER IP This is the IP address of the computer you want to test connectivity to. Support both IPv4 and IPv6 .PARAMETER Port This is the port on the remote Computer you want to test connectivity to .EXAMPLE PS C:\> Test-Port -Computer somePC -Port 80 .EXAMPLE PS C:\> Test-Port -IP someIPv4 -Port 80 .EXAMPLE PS C:\> Test-Port -IP someIPv6 -Port 80 .EXAMPLE PS C:\> Test-Port -Computer somePC -Port 80 -Verbose .EXAMPLE PS C:\> Test-Port -IP someIPv4 -Port 80 -Verbose .EXAMPLE PS C:\> Test-Port -IP someIPv6 -Port 80 -Verbose .OUTPUTS This script has no outputs. .LINK http://powerworks.readthedocs.io/en/latest/functions/Test-Port .LINK https://github.com/RobertCGouge/PowerWorks/blob/master/PowerWorks/Public/Test-Port.ps1 #> function Test-Port { [CmdletBinding(HelpURI = 'http://powerworks.readthedocs.io/en/latest/functions/Test-Port')] [Alias()] Param ( [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ComputerName', HelpMessage = 'This is the name of the computer you want to test connectivity to')] [ValidateScript({ if([bool]($_ -as [ipaddress])) { throw "$_ is an IP address, please try again with -IP" } else { if([bool](Resolve-DnsName -Name asdthasdt)) { $true } else { throw "$_ could not be resolved, please try another computer name." } } })] $Computer, [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'IPAddress', HelpMessage = 'This is the IP address of the computer you want to test connectivity to')] [ValidateScript({ if([bool]($_ -as [ipaddress])) { $true } else { throw "$_ is not a valid IP Address" } })] [ipaddress] $IP, [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ComputerName', HelpMessage = 'This is the port on the remote Computer you want to test connectivity to')] [Parameter(ParameterSetName = 'IPAddress')] [ValidateRange(1,65535)] [int] $Port ) Begin { if($Computer -ne $null) { Write-Verbose -Message "Attempting to connect to port: $Port at computer: $Computer" } if($IP -ne $null) { Write-Verbose -Message "Attempting to connect to port: $Port at IP Address: $IP" } } Process { if($Computer -ne $null) { do { Start-Sleep -Seconds 5 Write-Verbose -Message "Unable to connect to Port: $Port on Computer: $Computer. `r`n Sleeping for 5 seconds" } until (Test-NetConnection -ComputerName $Computer -Port $Port) Write-Verbose -Message "Successfuly connected to Port: $Port on Computer: $Computer" } if($IP -ne $null) { do { Start-Sleep -Seconds 5 Write-Verbose -Message "Unable to connect to Port: $Port on IP: $IP. `r`n Sleeping for 5 seconds" } until (Test-NetConnection -ComputerName $IP -Port $Port) Write-Verbose -Message "Successfuly connected to Port: $Port on IP: $IP" } } End { } }
PowerShellCorpus/PowerShellGallery/xSafeHarbor/1.0.0.1/Assert-SafeHarborScenario.ps1
Assert-SafeHarborScenario.ps1
<# .SYNOPSIS This script is used to deploy and validate SafeHarbor example .DESCRIPTION This script allows you to exercise the SafeHarbor example which sets up a secure environment to run a particular application or service inside of an assume-breached network. This substantially reduces the attack surface of the application or service by configuring a highly customized, application specific environment, by limiting user access and by having “Just Enough” administrative control with full auditing. .EXAMPLE $baseVhdFilePath = "C:\BaseVhd\serverdatacenter_en-us.vhd" .\Assert-SafeHarborScenario.ps1 -BaseVhdFilePath $baseVhdFilePath -Validate .LINK http://gallery.technet.microsoft.com/scriptcenter/xSafeHarbor-Module-bd705379 http://blogs.msdn.com/b/powershell/archive/2014/07/21/creating-a-secure-environment-using-powershell-desired-state-configuration.aspx .NOTES SafeHarbor scenario uses xMachine synchronization feature (First released with Windows Management Framework 5.0 Experimental July 2014 (KB2969050)) to synchronize Hyper-V Host and Guest VMs. Hyper-V Host and BaseVhd must have 'Windows Management Framework 5.0 Experimental July 2014 (KB2969050)' installed to run this example. Following steps can be used to make the BaseVhd ready to run the SafeHarbor example: 1. Mount BaseVhd and copy WMF 5.0 update. 2. Create a VM using BaseVhd and then install WMF 5.0 on VM. 3. Run $Env:SystemDrive\Windows\System32\Sysprep\sysprep.exe /generalize /shutdown /oobe Run 'Install-Module -Name xActiveDirectory, xComputerManagement, xDhcpServer, xDnsServer, xHyper-V, xNetworking, xPSDesiredStateConfiguration -Force' to install the required DSC resources by SafeHarbor example. List of DSC resources that should be present on the system: - xIPAddress - xFirewall - xComputer - xADDomain - xADDomainTrust - xADUser - xDhcpServerScope - xDhcpServerOption - xDhcpServerReservation - xDnsServerZoneTransfer - xDnsServerSecondaryZone - xDSCWebService - xPSEndpoint - xVHD - xVhdFile - xVMHyperV - xVMSwitch #> Param ( # Path to Vhd file that would be used as base image for all the VMs [Parameter(Mandatory)] [String]$BaseVhdFilePath, # Collection of credentials for various user names. If not specified, script will prompt [PSCredential[]]$Credentials, # Path where differencing VHDs will be stored [String]$VHDDestinationPath = "$env:SystemDrive\SHVhd", # If specified, will run the validation steps at the end of example [Switch]$Validate, # If specified, pauses the script execution between various stages of example setup [Switch]$PauseBetweenStages ) $scriptLocation = $PSScriptRoot #--------------------------------------------------------------------------# # Verify prerequisites #--------------------------------------------------------------------------# Import-Module $scriptLocation\SafeHarborHelper.psm1 # Verify all the required DSC resources are present on Hyper-V Host. Test-DscResourcesForSHScenario # Verify 'Windows Management Framework 5.0 Experimental July 2014 (KB2969050)' update is isntalled on Hyper-V Host. If($PSVersionTable.BuildVersion -lt '6.4.9789.0') { Throw 'Cannot find the required update on Hyper-V Host, please install ''Windows Management Framework 5.0 Experimental July 2014 (KB2969050)'' or higher version of update to run SafeHarbor.' } Import-Module $scriptLocation\Configuration\SafeHarborConfiguration.psm1 # Create directory for SafeHarbor Virtual Machines. mkdir $VHDDestinationPath -ErrorAction SilentlyContinue # DSC Document location for SafeHarbor VMs $vmDocLocation = "$scriptLocation\ConfigurationData\VMData" #--------------------------------------------------------------------------# # Configure SafeHarbor Scenario #--------------------------------------------------------------------------# # Set credential for SafeHarbor users and serialize them into clixml. Set-SafeHarborUserCreds -Credentials $Credentials # Install certificates for password encryption & "$scriptLocation\ConfigurationData\VMData\ImportCerts.ps1" # Update trusted host settings to trust the SafeHarbor VMs Set-Item WSMan:\localhost\Client\TrustedHosts * -Force # Configuration data to setup SafeHarbor VMs and Host machine. $configData = & "$scriptLocation\ConfigurationData\SafeHarborConfigurationData.ps1" -BaseVhdPath $BaseVhdFilePath -VHDDestinationPath $VHDDestinationPath # Generate DSC documents for configuring DCHP Server, Corporate Domain Controller, Corporate Client, # SafeHarbor Domain Controller, SafeHarbor Pull Server, SafeHarbor Management Server and SafeHarbor File Server VMs. DHCPServer -ConfigurationData $configData -Role "DHCPServer" -OutputPath $vmDocLocation\DHCPServer DomainController -ConfigurationData $configData -Role "CorpDC" -OutputPath $vmDocLocation\CorpDC CorpClient -ConfigurationData $configData -Role "CorpClient" -OutputPath $vmDocLocation\CorpClient DomainController -ConfigurationData $configData -Role "SHDC" -OutputPath $vmDocLocation\SHDC PullServer -ConfigurationData $configData -Role "SHPullServer" -OutputPath $vmDocLocation\SHPullServer FileServer -ConfigurationData $configData -Role "FileServer" -OutputPath $vmDocLocation\SHPullServer\Configuration New-DSCCheckSum -ConfigurationPath $vmDocLocation\SHPullServer\Configuration -OutPath $vmDocLocation\SHPullServer\Configuration -Force # Configure Hyper-V Host HyperVHost -ConfigurationData $configData -Role "HyperVHost" -OutputPath . HyperVHostLCMSettings -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Set-DscLocalConfigurationManager -Path .\HyperVHostLCMSettings -Verbose -ComputerName localhost Start-DscConfiguration -Path .\HyperVHost -Wait -Force -Verbose # Configure DHCPServer to automatically assign an IP address to Corporate and SafeHarbor Domain VMs. DHCPServerVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\DHCPServerVM -Wait -Force -Verbose # Configure Corporate Domain Controller using xADDomain resource. CorpDCVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\CorpDCVM -Wait -Force -Verbose # Corporate Domain Controller configuration is completed but it is still busy updating DNS service. # Adding sleep so that Domain Controller will be ready to add client to the domain. Start-Sleep -Seconds 30 # Configure Corporate Client CorpClientVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\CorpClientVM -Wait -Force -Verbose # Pause script if($PauseBetweenStages.IsPresent) { "`nDONE: Corporate environment is now ready. `nNEXT: Setup SafeHarbor Domain Controller.`n" Pause } # Configure SafeHarbor Domain Controller using xADDomain resource. SHDCVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\SHDCVM -Wait -Force -Verbose # Adding sleep so that Domain Controller will be ready to add client to the domain. Start-Sleep -Seconds 100 # Pause script if($PauseBetweenStages.IsPresent) { "`nDONE:SafeHarbor Domain Controller is now ready. `nNEXT: Setup SafeHarbor Pull Server.`n" Pause } # Configure SafeHarbor Pull Server. SHPullServerVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\SHPullServerVM -Wait -Force -Verbose # Pause script if($PauseBetweenStages.IsPresent) { "`nDONE: Pull Server is now setup in Safeharbor. `nNEXT: Setup SafeHarbor Management Server.`n" Pause } # Safeharbor Management Server configuration requires PAPA user SID to configure the End Point. # Get the SID for Corporate\PAPA user. $domainCredential = Import-CliXml "$scriptLocation\ConfigurationData\VMData\CORPDomainCred.CliXml" $ADUserSid = Get-ADUserSid -VMName 'CorpDC' -UserName 'PAPA' -VMCredential $domainCredential # Configure SafeHarbor Management Server by setting up constrained endpoint with RunAs mapped to SafeHarbor\MATA user. $configData = & "$scriptLocation\ConfigurationData\SafeHarborConfigurationData.ps1" -BaseVhdPath $BaseVhdFilePath -VHDDestinationPath $VHDDestinationPath -ADUserSid $ADUserSid JeaManagementServer -ConfigurationData $configData -Role "DelegatedAdmin" -OutputPath $vmDocLocation\SHMgmtSrv SHJeaManagementServerVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\SHJeaManagementServerVM -Wait -Force -Verbose # Pause script if($PauseBetweenStages.IsPresent) { "`nDONE: Management Server is now setup in Safeharbor. `nNEXT: Setup SafeHarbor File Server.`n" Pause } # Configure SafeHarbor File Server, lock down the server by removing built-in Firewall rules, # disabling local admin and allowing only specific traffic. SHFileServerVM -ConfigurationData $configData -Role "HyperVHost" -OutputPath . Start-DscConfiguration -Path .\SHFileServerVM -Wait -Force -Verbose # Pause script if($PauseBetweenStages.IsPresent) { "`nDONE: File Server is now setup in Safeharbor. `nNEXT: Validate the SafeHarbor scenario.`n" Pause } # Delete the MOF files Remove-Item -Path ".\HyperVHostLCMSettings" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\HyperVHost" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\DHCPServerVM" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\CorpDCVM" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\CorpClientVM" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\SHDCVM" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\SHPullServerVM" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\SHJeaManagementServerVM" -Force -Recurse -ErrorAction SilentlyContinue Remove-Item -Path ".\SHFileServerVM" -Force -Recurse -ErrorAction SilentlyContinue #--------------------------------------------------------------------------# # Validate SafeHarbor Configuration #--------------------------------------------------------------------------# if($Validate.IsPresent) { $vmCorpClient = "CorpClient" Write-Verbose "Validating - Connection with CorpClient." -Verbose $resultInfo = @{ actualResult = Test-Connection -ComputerName $vmCorpClient -Quiet expectedResult = $true errorMsg = 'Failed to connect to CorpClient.' successMsg = 'Validated - Connection successfully established with CorpClient.' } ValidateResult @resultInfo #1. Validate PAPA is allowed to create a SMB Share on SafeHarbor File Server. Write-Verbose "Validating - PAPA is allowed to create a SMB Share on SafeHarbor File Server." -Verbose $papaCredential = Get-SafeHarborUserCreds -UserName "Corporate\Papa" $result = Invoke-Command -ComputerName $vmCorpClient -Authentication Negotiate -Credential $papaCredential -ScriptBlock { Set-Item WSMan:\localhost\Client\TrustedHosts "shmgmtsrv.safeharbor.contoso.com" -Force $psSession = New-PSSession -ComputerName "shmgmtsrv.safeharbor.contoso.com" -Credential $using:papaCredential -Authentication Negotiate -ConfigurationName secure Invoke-Command -Session $psSession -ScriptBlock { Get-Command 'New-SMBShare' -Source 'ProxyFunctions' } } $resultInfo = @{ actualResult = $result.Name expectedResult = 'New-SmbShare' errorMsg = 'User PAPA is not allowed to create SMB share on SafeHarbor File Server.' successMsg = 'Validated - User PAPA is allowed to create a SMB Share on SafeHarbor File Server.' } ValidateResult @resultInfo #2. Validate PAPA can create a SMB share on SafeHarbor File Server. Write-Verbose "Validating - PAPA can create a SMB share on SafeHarbor File Server." -Verbose $shareName = 'Share1' $result = Invoke-Command -ComputerName $vmCorpClient -Authentication Negotiate -Credential $papaCredential -ScriptBlock { Set-Item WSMan:\localhost\Client\TrustedHosts "shmgmtsrv.safeharbor.contoso.com" -Force $psSession = New-PSSession -ComputerName "shmgmtsrv.safeharbor.contoso.com" -Credential $using:papaCredential -Authentication Negotiate -ConfigurationName secure Invoke-Command -Session $psSession -ScriptBlock { New-SmbShare -CimSession "shfileserver.safeharbor.contoso.com" -Path 'C:\Program Files' -Name 'Share1' } } $resultInfo = @{ actualResult = $result.Name expectedResult = $shareName errorMsg = "Failed to create $shareName SMBShare." successMsg = "Validated - Successfully created SMBShare : $shareName." } ValidateResult @resultInfo #3. Validate Share is created on SafeHarbor File Server. Write-Verbose "Validating - Share is created on SafeHarbor File Server." -Verbose $result = Invoke-Command -ComputerName $vmCorpClient -Authentication Negotiate -Credential $papaCredential -ScriptBlock { Set-Item WSMan:\localhost\Client\TrustedHosts "shmgmtsrv.safeharbor.contoso.com" -Force $psSession = New-PSSession -ComputerName "shmgmtsrv.safeharbor.contoso.com" -Credential $using:papaCredential -Authentication Negotiate -ConfigurationName secure Invoke-Command -Session $psSession -ScriptBlock { Get-SmbShare -CimSession "shfileserver.safeharbor.contoso.com"-Name 'Share1' } } $resultInfo = @{ actualResult = $result.Name expectedResult = $shareName errorMsg = "Failed to get $shareName SMBShare." successMsg = "Validated - $shareName share is created on SafeHarbor File Server." } ValidateResult @resultInfo }
PowerShellCorpus/PowerShellGallery/xSafeHarbor/1.0.0.1/ConfigurationData/SafeHarborConfigurationData.ps1
SafeHarborConfigurationData.ps1
<# Configuration data for - - DHCP Server - Corporate Domain Controller - Corporate Client - SafeHarbor Domain Controller - SafeHarbor Management Server - SafeHarbor Pull Server - SafeHarbor File Server - Hyper-V Host #> param ([string]$BaseVhdPath, [string]$ADUserSid, [string]$VHDDestinationPath) $ConfigDataLocation = Split-Path $MyInvocation.MyCommand.Definition Import-Module $ConfigDataLocation\..\SafeHarborHelper.psm1 $xNetworkingModulePath = Get-DscResourceModulePath -DscResourceName 'xFirewall' $xComputerManagementModulePath = Get-DscResourceModulePath -DscResourceName 'xComputer' $xDhcpServerModulePath = Get-DscResourceModulePath -DscResourceName 'xDhcpServerReservation' $xActiveDirectoryModulePath = Get-DscResourceModulePath -DscResourceName 'xADDomain' $xDnsServerModulePath = Get-DscResourceModulePath -DscResourceName 'xDnsServerZoneTransfer' $xPSDesiredStateConfigurationModulePath = Get-DscResourceModulePath -DscResourceName 'xDSCWebService' @{ AllNodes = @( # Certificate ID for password encryption @{ NodeName = "*" CertificateID = "497258FCCFFFA0F38268BBD970B337D25C871D6D" } # DHCP Server configuration data @{ NodeName = "0df6ddb0-a958-406b-9694-9994928fa0d8" MachineName = "DHCPServer" Role = "DHCPServer" DHCPAdminCredFile = "$ConfigDataLocation\VMData\DHCPSrvCred.clixml" IPAddress = "192.168.10.5" InterfaceAlias = "*Ethernet*" PrefixLength = 24 ScopeName = "SafeHarborDemo" ScopeId = "192.168.10.0" StartRange = "192.168.10.7" EndRange = "192.168.10.254" SubnetMask = "255.255.255.0" LeaseDurationDays = "1" DNSServerIP = "192.168.10.2","192.168.10.1" IPReservations = @( @{ Name = "CorpDC" Mac = "00155D8A54A0" IP = "192.168.10.1" } @{ Name = "SHDC" Mac = "00155D8A54A1" IP = "192.168.10.2" } @{ Name = "SHMgmtSrv" Mac = "00155D8A54A2" IP = "192.168.10.3" } @{ Name = "SHPullServer" Mac = "00155D8A54A3" IP = "192.168.10.4" } ) }; # Corporate Domain Controller configuration data @{ NodeName = "41120e02-7e85-4a89-bae3-2e4443424b62" MachineName = "CorpDC" Role = "CorpDC" DomainName = "corporate.contoso.com" SecondaryDNSServer = "192.168.10.2" SecondaryZoneDomain = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\CORPDomainCred.clixml" Users = @( @{ UserName = "User1" UserCredFile = "$ConfigDataLocation\VMData\CORPUserCred.clixml" } @{ UserName = "PAPA" UserCredFile = "$ConfigDataLocation\VMData\CORPPapaCred.clixml" } @{ UserName = "DeptHead" UserCredFile = "$ConfigDataLocation\VMData\CORPDeptHeadCred.clixml" } ) }; # Corporate Domain Client configuration data @{ NodeName = "3b748ea1-cda5-4a68-aa4d-c88fbf03dd33" MachineName = "CorpClient" Role = "CorpClient" DomainName = "corporate.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\CORPDomainCred.clixml" }; # SafeHarbor Domain Controller configuration data @{ NodeName = "85ec034b-f343-4e26-bb60-6d564e9865e0" MachineName = "SHDC" Role = "SHDC" DomainName = "safeharbor.contoso.com" SecondaryDNSServer = "192.168.10.1" SecondaryZoneDomain = "corporate.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" Users = @( @{ UserName = "MATA" UserCredFile = "$ConfigDataLocation\VMData\SHMataCred.clixml" } ) SourceDomainName = "safeharbor.contoso.com" TrustDomainName = "corporate.contoso.com" TrustDomainCred = "$ConfigDataLocation\VMData\CORPDomainCred.clixml" TrustDirection = "Outbound" TrustType = "External" }; # SafeHarbor Pull Server configuration data @{ NodeName = "85ec034b-f343-4e26-bb60-6d564e986561" Role = "SHPullServer" MachineName = "SHPullServer" DomainName = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" PullCert = "9FE0BB64E4790CFFCFEB84C95C136BEB70B5F93B" ModulePath = "$env:PROGRAMFILES\DscService\Modules" ConfigurationPath = "$env:PROGRAMFILES\DscService\Configuration" }; # SafeHarbor Management Server configuration data @{ NodeName = "15dde6d1-6a1c-4b15-858a-51d703bfed29" MachineName = "SHMgmtSrv" Role = "DelegatedAdmin" DomainName = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" EPName = "secure" RunAsCredFile = "$ConfigDataLocation\VMData\SHMataCred.clixml" SDDL = "O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;$ADUserSid)(A;;GA;;;RM)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)" StartupScript = "$env:SystemDrive\Scripts\Startup.ps1" }; # SafeHarbor File Server VM configuration data @{ NodeName = "8cac052d-d3d4-423e-b088-f93979094d11" Role = "FileServer" MachineName = "SHFileServer" DomainName = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" AbsentInRules = @( @{ Name = "CoreNet ICMPv6-In" DisplayName = "Core Networking - Destination Unreachable (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet ICMPv4-In" DisplayName = "Core Networking - Destination Unreachable Fragmentation Needed (ICMPv4-In)"; Protocol = "ICMPv4" } @{ Name = "CoreNet DHCP-In" DisplayName = "Core Networking - Dynamic Host Configuration Protocol (DHCP-In)"; Protocol = "UDP" } @{ Name = "CoreNet DHCPv6-In" DisplayName = "Core Networking - Dynamic Host Configuration Protocol for IPv6(DHCPV6-In)"; Protocol = "UDP" } @{ Name = "CoreNet IGMP-In" DisplayName = "Core Networking - Internet Group Management Protocol (IGMP-In)"; Protocol = "2" } @{ Name = "CoreNet TCP-In" DisplayName = "Core Networking - IPHTTPS (TCP-In)"; Protocol = "TCP" } @{ Name = "CoreNet IPv6-In" DisplayName = "Core Networking - IPv6 (IPv6-In)"; Protocol = "41" } @{ Name = "CoreNet MultiListener-In" DisplayName = "Core Networking - Multicast Listener Done (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet MultiListener-Query-In" DisplayName = "Core Networking - Multicast Listener Query (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet MultiListener-Report-In" DisplayName = "Core Networking - Multicast Listener Report (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet MultiListener-Reportv2-In" DisplayName = "Core Networking - Multicast Listener Report v2 (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet NeighborDisc-Ad-In" DisplayName = "Core Networking - Neighbor Discovery Advertisement (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet NeighborDisc-Sol-In" DisplayName = "Core Networking - Neighbor Discovery Solicitation (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet PacketBig-In" DisplayName = "Core Networking - Packet Too Big (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet Parameter-In" DisplayName = "Core Networking - Parameter Problem (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet Router-Ad-In" DisplayName = "Core Networking - Router Advertisement (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet Router-Sol-In" DisplayName = "Core Networking - Router Solicitation (ICMPv6-In)"; Protocol = "ICMPv6" } @{ Name = "CoreNet Teredo-In" DisplayName = "Core Networking - Teredo (UDP-In)"; Protocol = "UDP" } @{ Name = "CoreNet TimeExceed-In" DisplayName = "Core Networking - Time Exceeded (ICMPv6-In)"; Protocol = "ICMPv6" } ) AbsentInFileRules = @( @{ Name = "File DCOM-In" DisplayName = "File Server Remote Management (DCOM-In)"; Protocol = "TCP" } @{ Name = "File WMI-In" DisplayName = "File Server Remote Management (WMI-In)"; Protocol = "TCP" } ) AllowedInRules = @( @{ Name = "File SMB-In" DisplayName = "File Server Remote Management (SMB-In)" Port = "445"; Protocol = "TCP"; } @{ Name = "WSMan HTTP-In" DisplayName = "Windows Remote Management (HTTP-In)" Port = "5985"; Protocol = "TCP"; } @{ Name = "WSMan HTTPS-In" DisplayName = "Windows Remote Management (HTTPS-In)" Port = "5986"; Protocol = "TCP"; } ) } # Hyper-V Host configuration data @{ NodeName = "localhost"; Role = "HyperVHost"; VHDDestinationPath = "$VHDDestinationPath\{0}.vhd"; SwitchName = "Contoso" SwitchType = "Internal" VMState = "Running" BaseVhdPath = $BaseVhdPath; IPAddress = "192.168.10.6" InterfaceAlias = "*vethernet*" PrefixLength = 24 RetryintervalSec = 10 RetryCount = 300 CertificateID = "497258FCCFFFA0F38268BBD970B337D25C871D6D" DHCPServer = @{ MachineName = "DHCPServer" MemorySizeofVM = 1024MB; AdminUserCredFile = "$ConfigDataLocation\VMData\DHCPSrvCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattend.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\SHVmSetup.cmd"; Destination = "Scripts\SHVmSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ConfigureVM.ps1"; Destination = "Scripts\ConfigureVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\DHCPServer\*.mof"; Destination = "Windows\System32\Configuration\Pending.mof" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = $xNetworkingModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xNetworking" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } @{ Source = $xDhcpServerModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xDhcpServer" } ); }; CorpDC = @{ DomainName = "corporate.contoso.com" MachineName = "CorpDC" MemorySizeofVM = 2048MB; MACAddress = "00155D8A54A0" AdminUserCredFile = "$ConfigDataLocation\VMData\CORPDomainCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattend.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\CorpDC\*.mof"; Destination = "Windows\System32\Configuration\Pending.mof" } @{ Source = "$ConfigDataLocation\VMData\SHVmSetup.cmd"; Destination = "Scripts\SHVmSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ConfigureVM.ps1"; Destination = "Scripts\ConfigureVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = $xNetworkingModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xNetworking" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } @{ Source = $xActiveDirectoryModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xActiveDirectory" } @{ Source = $xDnsServerModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xDnsServer" } ); }; CorpClient = @{ DomainName = "corporate.contoso.com" MachineName = "CorpClient" MemorySizeofVM = 1024MB; AdminUserCredFile = "$ConfigDataLocation\VMData\CORPDomainCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattend.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\CorpClient\*.mof"; Destination = "Windows\System32\Configuration\Pending.mof" } @{ Source = "$ConfigDataLocation\VMData\SHVmSetup.cmd"; Destination = "Scripts\SHVmSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ConfigureVM.ps1"; Destination = "Scripts\ConfigureVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } ); }; SHDC = @{ MachineName = "SHDC" MemorySizeofVM = 2048MB; MACAddress = "00155D8A54A1" AdminUserCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattend.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\SHDC\*.mof"; Destination = "Windows\System32\Configuration\Pending.mof" } @{ Source = "$ConfigDataLocation\VMData\SHVmSetup.cmd"; Destination = "Scripts\SHVmSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ConfigureVM.ps1"; Destination = "Scripts\ConfigureVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = $xNetworkingModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xNetworking" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } @{ Source = $xActiveDirectoryModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xActiveDirectory" } @{ Source = $xDnsServerModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xDnsServer" } ); }; SHPullServer = @{ MachineName = "SHPullServer" MemorySizeofVM = 2048MB; MACAddress = "00155D8A54A3" DomainName = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" PullCert = "9FE0BB64E4790CFFCFEB84C95C136BEB70B5F93B" AdminUserCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattend.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\SHPullServer\*.mof"; Destination = "Windows\System32\Configuration\Pending.mof" } @{ Source = "$ConfigDataLocation\VMData\SHVmSetup.cmd"; Destination = "Scripts\SHVmSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ConfigureVM.ps1"; Destination = "Scripts\ConfigureVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = "$ConfigDataLocation\VMData\PullServer.pfx"; Destination = "Scripts\PullServer.pfx" } @{ Source = "$ConfigDataLocation\VMData\SHPullServer\Configuration"; Destination = "Program Files\DscService\Configuration" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } @{ Source = $xPSDesiredStateConfigurationModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xPSDesiredStateConfiguration" } ); }; SHMgmtSrv = @{ MachineName = "SHMgmtSrv" MemorySizeofVM = 1024MB; MACAddress = "00155D8A54A2" DomainName = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" AdminUserCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattend.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\SHMgmtSrv\*.mof"; Destination = "Windows\System32\Configuration\Pending.mof" } @{ Source = "$ConfigDataLocation\VMData\SHVmSetup.cmd"; Destination = "Scripts\SHVmSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ConfigureVM.ps1"; Destination = "Scripts\ConfigureVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = "$ConfigDataLocation\VMData\Permission.csv"; Destination = "Scripts\Permission.csv" } @{ Source = "$ConfigDataLocation\VMData\ProxyFunctions.psm1"; Destination = "Scripts\ProxyFunctions.psm1" } @{ Source = "$ConfigDataLocation\VMData\Startup.ps1"; Destination = "Scripts\Startup.ps1" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } @{ Source = $xPSDesiredStateConfigurationModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xPSDesiredStateConfiguration" } ); }; SHFileServer = @{ MachineName = "SHFileServer" MemorySizeofVM = 1024MB; DomainName = "safeharbor.contoso.com" DomainCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" AdminUserCredFile = "$ConfigDataLocation\VMData\SHDomainCred.clixml" FilesToCopy = @( @{ Source = "$ConfigDataLocation\VMData\unattendFS.xml"; Destination = "unattend.xml" } @{ Source = "$ConfigDataLocation\VMData\metaconfigFS.mof"; Destination = "Windows\System32\Configuration\metaconfig.mof" } @{ Source = "$ConfigDataLocation\VMData\FileServerSetup.cmd"; Destination = "Scripts\FileServerSetup.cmd" } @{ Source = "$ConfigDataLocation\VMData\ImportCerts.ps1"; Destination = "Scripts\ImportCerts.ps1" } @{ Source = "$ConfigDataLocation\VMData\ConfigureFSVM.ps1"; Destination = "Scripts\ConfigureFSVM.ps1" } @{ Source = "$ConfigDataLocation\VMData\DSCTestRootAuthority.pfx"; Destination = "Scripts\DSCTestRootAuthority.pfx" } @{ Source = "$ConfigDataLocation\VMData\DSCDemo.pfx"; Destination = "Scripts\DSCDemo.pfx" } @{ Source = $xComputerManagementModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xComputerManagement" } @{ Source = $xNetworkingModulePath; Destination = "Program Files\WindowsPowerShell\Modules\xNetworking" } ); }; } ); }
PowerShellCorpus/PowerShellGallery/xSafeHarbor/1.0.0.1/ConfigurationData/VMData/ConfigureFSVM.ps1
ConfigureFSVM.ps1
# Trigger LCM pull using the CIM Method. function TriggerLCMByCallingCimMethod { param([ValidateSet(1,2,3)] [system.uint32]$flag = 1) Invoke-CimMethod -Namespace root/microsoft/windows/desiredstateconfiguration -class MSFT_DSCLocalConfigurationManager -name PerformRequiredConfigurationChecks -arguments @{Flags = $flag} -verbose } TriggerLCMByCallingCimMethod
PowerShellCorpus/PowerShellGallery/xSafeHarbor/1.0.0.1/ConfigurationData/VMData/ConfigureVM.ps1
ConfigureVM.ps1
$scriptFolder = Split-Path $script:MyInvocation.MyCommand.Path Configuration VMMetaConfig { Node localhost { LocalConfigurationManager { RebootNodeIfNeeded = "true" CertificateID = "497258FCCFFFA0F38268BBD970B337D25C871D6D" } } } VMMetaConfig -OutputPath $scriptFolder\VMMetaConfig # Setup DSC metaconfiguration Set-DscLocalConfigurationManager -Path $scriptFolder\VMMetaConfig -Verbose -ComputerName localhost # Starts a consistency check [system.uint32]$flag = 1 Invoke-CimMethod -Namespace root/microsoft/windows/desiredstateconfiguration -class MSFT_DSCLocalConfigurationManager -name PerformRequiredConfigurationChecks -arguments @{Flags = $flag} -verbose
PowerShellCorpus/PowerShellGallery/xSafeHarbor/1.0.0.1/ConfigurationData/VMData/Startup.ps1
Startup.ps1
Import-Module $env:SystemDrive\Windows\System32\WindowsPowerShell\v1.0\modules\SmbShare\SmbShare.cdxml Import-Module $PSScriptRoot\ProxyFunctions.psm1 $IRCommands = @("Get-Command","Out-Default","Exit-PSSession","Measure-Object","Select-Object") $allowedCommands = New-Object System.Collections.Generic.List[string] foreach ($command in $IRCommands) { $allowedCommands.Add($command) } if($PSSenderInfo.ConnectedUser -eq "Corporate\PAPA") { $userCommand = @("New-SmbShare","Get-SmbShare","Remove-SmbShare") foreach ($Command in $userCommand) { if ( (Get-Command $command).Count -eq 1) { $allowedCommands.Add($Command) } else { # when the command is a wildcard Get-Command $command| %{$allowedCommands.Add($_.Name)} } } } if($PSSenderInfo.ConnectedUser -eq "Corporate\User1") { $userCommand = @("dir","get-content") foreach ($Command in $userCommand) { if ( (Get-Command $command).Count -eq 1) { $allowedCommands.Add($Command) } else { # when the command is a wildcard Get-Command $command| %{$allowedCommands.Add($_.Name)} } } } $ExecutionContext.SessionState.Applications.Clear() $ExecutionContext.SessionState.Scripts.Clear() Get-Command | %{$_.Visibility="Private"} foreach($command in $allowedCommands) { Get-Command | ?{$_.Name -like $command} | %{$_.Visibility="Public"} } $ExecutionContext.SessionState.LanguageMode = "NoLanguage"
PowerShellCorpus/PowerShellGallery/xSafeHarbor/1.0.0.1/ConfigurationData/VMData/ImportCerts.ps1
ImportCerts.ps1
$scriptLocation = $PSScriptRoot $null = [Reflection.Assembly]::Load("System.Security, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a") $flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet ## LocalMachine\Root $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("$scriptLocation\DSCTestRootAuthority.pfx", "", $flags) $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("Root", [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine) $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Add($cert); $store.Close(); ## Personal\My $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("$scriptLocation\DSCDemo.pfx", "", $flags) $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine) $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Add($cert); $store.Close(); ## Personal\My if(Test-Path $scriptLocation\PullServer.pfx) { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("$scriptLocation\PullServer.pfx", "", $flags) $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine) $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); $store.Add($cert); $store.Close(); }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/ResizeASMDisk.ps1
ResizeASMDisk.ps1
function Set-AzureVMOSDiskSize { [CmdletBinding(SupportsShouldProcess=$true)] param ( [Parameter(ValueFromPipeline=$true, Mandatory=$true)] [Microsoft.WindowsAzure.Commands.ServiceManagement.Model.ServiceOperationContext] $VM, [Parameter(Mandatory=$true, Position=0)] [int] $SizeInGb ) $disk = Get-AzureOSDisk -VM $VM.VM $disk.MediaLink -match "https:\/\/(?<account>[^.]*)" | Out-Null $storageAccount = $Matches['account'] Set-AzureSubscription -SubscriptionId (Get-AzureSubscription -Current).SubscriptionId -CurrentStorageAccountName $storageAccount $currentDiskSize = (Get-AzureDisk -DiskName $disk.DiskName).DiskSizeInGB if($currentDiskSize -gt $SizeInGb) { $ConfirmPreference = 'Low' if (!$PSCmdlet.ShouldContinue('Are you sure that you want to shrink the OS disk (and lose data)?',"You're shrinking the disk!")) { Write-Warning 'You were trying to shrink the disk but decided to abort' Write-Warning 'No changes have been made' return } } # Stop and Deallocate VM prior to resizing data disk Stop-AzureVM -VM $VM.VM -ServiceName $VM.ServiceName -Force -Verbose Start-Sleep -Seconds 120 -Verbose # Cope with disks that were created without a Label and in this case label them with the disk name if([string]::IsNullOrEmpty($disk.DiskLabel)) { $diskLabel = $disk.DiskName } else { $diskLabel = $disk.DiskLabel } # Resize Data Disk to Larger Size Update-AzureDisk -Label $diskLabel -DiskName $disk.DiskName -ResizedSizeInGB $SizeInGb -Verbose # Start VM Start-AzureVM -VM $VM.VM -ServiceName $VM.ServiceName -Verbose }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzureKeyvaultHelpers.ps1
AzureKeyvaultHelpers.ps1
class EswUser { [string] $Username [securestring] $Password } # Taken from: https://gallery.technet.microsoft.com/scriptcenter/Generate-a-random-and-5c879ed5 function New-SWRandomPassword { <# .Synopsis Generates one or more complex passwords designed to fulfill the requirements for Active Directory .DESCRIPTION Generates one or more complex passwords designed to fulfill the requirements for Active Directory .EXAMPLE New-SWRandomPassword C&3SX6Kn Will generate one password with a length between 8 and 12 chars. .EXAMPLE New-SWRandomPassword -MinPasswordLength 8 -MaxPasswordLength 12 -Count 4 7d&5cnaB !Bh776T"Fw 9"C"RxKcY %mtM7#9LQ9h Will generate four passwords, each with a length of between 8 and 12 chars. .EXAMPLE New-SWRandomPassword -InputStrings abc, ABC, 123 -PasswordLength 4 3ABa Generates a password with a length of 4 containing atleast one char from each InputString .EXAMPLE New-SWRandomPassword -InputStrings abc, ABC, 123 -PasswordLength 4 -FirstChar abcdefghijkmnpqrstuvwxyzABCEFGHJKLMNPQRSTUVWXYZ 3ABa Generates a password with a length of 4 containing atleast one char from each InputString that will start with a letter from the string specified with the parameter FirstChar .OUTPUTS [String] .NOTES Written by Simon Wåhlin, blog.simonw.se .FUNCTIONALITY Generates random passwords .LINK http://blog.simonw.se/powershell-generating-random-password-for-active-directory/ #> [CmdletBinding(DefaultParameterSetName='FixedLength',ConfirmImpact='None')] [OutputType([String])] Param ( [Parameter(Mandatory=$false, ParameterSetName='RandomLength')] [ValidateScript({$_ -gt 0})] [Alias('Min')] [int]$MinPasswordLength = 8, [Parameter(Mandatory=$false, ParameterSetName='RandomLength')] [ValidateScript({ if($_ -ge $MinPasswordLength){$true} else{Throw 'Max value cannot be lesser than min value.'}})] [Alias('Max')] [int]$MaxPasswordLength = 12, [Parameter(Mandatory=$false, ParameterSetName='FixedLength')] [ValidateRange(1,2147483647)] [int]$PasswordLength = 8, [String[]]$InputStrings = @('abcdefghijklmnopqrstuvwxyz', 'ABCEFGHIJKLMNOPQRSTUVWXYZ', '0123456789', '!£$%^&*(){}[]'), [String] $FirstChar, [ValidateRange(1,2147483647)] [int]$Count = 1 ) Begin { Function Get-Seed{ # Generate a seed for randomization $RandomBytes = New-Object -TypeName 'System.Byte[]' 4 $Random = New-Object -TypeName 'System.Security.Cryptography.RNGCryptoServiceProvider' $Random.GetBytes($RandomBytes) [BitConverter]::ToUInt32($RandomBytes, 0) } } Process { For($iteration = 1;$iteration -le $Count; $iteration++){ $Password = @{} # Create char arrays containing groups of possible chars [char[][]]$CharGroups = $InputStrings # Create char array containing all chars $AllChars = $CharGroups | ForEach-Object {[Char[]]$_} # Set password length if($PSCmdlet.ParameterSetName -eq 'RandomLength') { if($MinPasswordLength -eq $MaxPasswordLength) { # If password length is set, use set length $PasswordLength = $MinPasswordLength } else { # Otherwise randomize password length $PasswordLength = ((Get-Seed) % ($MaxPasswordLength + 1 - $MinPasswordLength)) + $MinPasswordLength } } # If FirstChar is defined, randomize first char in password from that string. if($PSBoundParameters.ContainsKey('FirstChar')){ $Password.Add(0,$FirstChar[((Get-Seed) % $FirstChar.Length)]) } # Randomize one char from each group Foreach($Group in $CharGroups) { if($Password.Count -lt $PasswordLength) { $Index = Get-Seed While ($Password.ContainsKey($Index)){ $Index = Get-Seed } $Password.Add($Index,$Group[((Get-Seed) % $Group.Count)]) } } # Fill out with chars from $AllChars for($i=$Password.Count;$i -lt $PasswordLength;$i++) { $Index = Get-Seed While ($Password.ContainsKey($Index)){ $Index = Get-Seed } $Password.Add($Index,$AllChars[((Get-Seed) % $AllChars.Count)]) } Write-Output -InputObject $(-join ($Password.GetEnumerator() | Sort-Object -Property Name | Select-Object -ExpandProperty Value)) } } } ########################################################### # Add-MeToKeyvault ########################################################### function Add-MeToKeyvault { [CmdletBinding()] param ( [parameter(Mandatory=$true, Position=0)] [string] $KeyvaultName ) $userId = Get-MyUserObjectId Set-AzureRmKeyVaultAccessPolicy -VaultName $KeyvaultName -ObjectId $userId -PermissionsToKeys all -PermissionsToSecrets all } ########################################################### # Add-UserToKeyVault ########################################################### function Add-UserToKeyVault { [CmdletBinding()] [OutputType([String])] param ( [parameter(Mandatory=$true, Position=0)] [string] $KeyvaultName, [parameter(Mandatory=$true, Position=1)] [string] $Username ) $adUsers = Get-AzureRmADUser | where { $_.UserPrincipalName -match $Username } if($adUsers.Count -gt 1) { Write-Warning 'Found Multiple users using UserPrincipalName as the search query - Exiting ...' $adUsers |ft * return } elseif($adUsers.Count -eq 0) { Write-Warning 'Found no users using UserPrincipalName as the search query' $adUsers = Get-AzureRmADUser | where { $_.DisplayName -match $Username } if($adUsers.Count -gt 1) { Write-Warning 'Found Multiple users using DisplayName as the search query - Exiting ...' $adUsers |ft * return } if($adUsers.Count -eq 0) { Write-Warning 'Found no users using DisplayName as the search query - Exiting ...' return } } Write-Host '`nFound a user and adding him to Keyvault:' $adUsers |fl Set-AzureRmKeyVaultAccessPolicy -VaultName $KeyvaultName -ObjectId $adUsers[0].Id -PermissionsToKeys all -PermissionsToSecrets all > $null } function New-UserInKeyVault { <# .Synopsis Generates a strong password for a Username and stores both the Username and Password in the specified KeyVault. .DESCRIPTION Generates a strong password for a Username and stores both the Username and Password in the specified KeyVault. .EXAMPLE New-UserInKeyVault -KeyvaultName 'mykeyvault' -Name 'myuser' -Username 'ausername' -Type 'VM' Will generate a password for the user 'ausername' for a VM and store it in a named pair in keyvault 'mykeyvault' named 'myuser'. .NOTES Written by Simon Wåhlin, blog.simonw.se .FUNCTIONALITY Creates users stored in KeyVault for both DevOps automation code for VMs and Service Fabric #> [CmdletBinding()] param ( [parameter(Mandatory=$true, Position=1)] [string] $KeyvaultName, [parameter(Mandatory=$true, Position=2)] [string] $Name, [parameter(Mandatory=$true, Position=3)] [string] $Username, [parameter(Mandatory=$true, Position=4)] [validateset("VM", "Fabric")] [string] $Type, [int] $MinPasswordLength = 15, [int] $MaxPasswordLength = 20 ) $password = New-SWRandomPassword -MinPasswordLength 15 -MaxPasswordLength 20 Set-AzureKeyVaultSecret -VaultName $KeyVaultName ` -Name "$Name-$Type-user".ToLower() ` -SecretValue (ConvertTo-SecureString $Username -AsPlainText -Force) ` -Tags @{ ComponentName=$Name ComponentType=$Type Type='Username' } ` -Verbose > $null Set-AzureKeyVaultSecret -VaultName $KeyVaultName ` -Name "$Name-$Type-pwd".ToLower() ` -SecretValue (ConvertTo-SecureString $password -AsPlainText -Force) ` -Tags @{ ComponentName=$Name ComponentType=$Type Type='Password' } ` -Verbose > $null Write-Information "Generated password for the account $Username : $password" Write-Output -InputObject $password }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzurePrincipalWithSecret.ps1
AzurePrincipalWithSecret.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Scope="Function", Target="*")] param() ########################################################### # New-AzurePrincipalWithSecret ########################################################### function New-AzurePrincipalWithSecret { [CmdletBinding()] param ( [parameter(Mandatory=$true, Position=0)] [string] $SystemName, [parameter(Mandatory=$true, Position=1)] [ValidateSet('Configuration','Authentication')] [string] $PrincipalPurpose, [parameter(Mandatory=$true, Position=2)] [string] $EnvironmentName, [parameter(Mandatory=$true, Position=4)] [string] $PrincipalPassword, [parameter(Mandatory=$false, Position=5)] [string] $VaultSubscriptionId, [parameter(Mandatory=$false, Position=6)] [string] $PrincipalName ) # GUARD: There are no non letter characters on the Principal Name if(-not [string]::IsNullOrWhiteSpace($PrincipalName) -and -not ($PrincipalName -match "^([A-Za-z])*$")) { throw 'The CertName must be letters only, either lower and upper case. Cannot contain any digits or any non-alpha-numeric characters.' } # Uniform all the namings if([string]::IsNullOrWhiteSpace($PrincipalName)) { $principalIdDashed = "$($SystemName.ToLower())-$($PrincipalPurpose.ToLower())" $principalIdDotted = "$($SystemName.ToLower()).$($PrincipalPurpose.ToLower())" $identifierUri = "https://$($SystemName.ToLower()).$($PrincipalPurpose.ToLower()).$($EnvironmentName.ToLower())" } else { $principalIdDashed = "$($SystemName.ToLower())-$($PrincipalPurpose.ToLower())-$($PrincipalName.ToLower())" $principalIdDotted = "$($SystemName.ToLower()).$($PrincipalPurpose.ToLower()).$($PrincipalName.ToLower())" $identifierUri = "https://$($SystemName.ToLower()).$($PrincipalPurpose.ToLower()).$($EnvironmentName.ToLower()).$($PrincipalName.ToLower())" } # GUARD: AD application already exists, return the existing ad application $previousApplication = Get-AzureRmADApplication -DisplayNameStartWith $principalIdDotted if($previousApplication -ne $null) { Write-Warning 'An AD Application Already exists that looks identical to what you are trying to create' return $previousApplication } # GUARD: Certificate system vault exists $systemVaultName = "$($SystemName.ToLower())-$($EnvironmentName.ToLower())" if((Get-AzureRmKeyVault -VaultName $systemVaultName) -eq $null) { throw "The system vault $systemVaultName doesn't exist in the current subscription. Create it before running this cmdlet!" } # Aquire the tenant ID on the subscription we are creating the principal on, not on the vault subscription! $tenantId = (Get-AzureRmContext).Subscription.TenantId # Create the Azure Active Directory Application $azureAdApplication = New-AzureRmADApplication -DisplayName $principalIdDotted ` -HomePage $identifierUri ` -IdentifierUris $identifierUri ` -Password $PrincipalPassword ` -Verbose Write-Host -ForegroundColor DarkYellow 'Write down this ID because you will need it for future reference.' Write-Host -ForegroundColor DarkYellow 'You can still get it through PowerShell, but writing it down now will save you the hassle.' Write-Host -ForegroundColor Green "Application ID: $($azureAdApplication.ApplicationId)" # Create the Service Principal and connect it to the Application $null = New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId # Switch to the KeyVault Techops-Management subscription $currentSubId = (Get-AzureRmContext).Subscription.SubscriptionId if(($VaultSubscriptionId -ne $null) -and ($currentSubId -ne $VaultSubscriptionId)) { Select-AzureRmSubscription -SubscriptionId $VaultSubscriptionId -ErrorAction Stop } # Populate the system keyvault with all relevant principal configuration information $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-TenantId" -SecretValue (ConvertTo-SecureString -String $tenantId -AsPlainText –Force) $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-IdentifierUri" -SecretValue (ConvertTo-SecureString -String $identifierUri -AsPlainText –Force) $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-ApplicationId" -SecretValue (ConvertTo-SecureString -String $($azureAdApplication.ApplicationId) -AsPlainText –Force) $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-ApplicationSecret" -SecretValue (ConvertTo-SecureString -String $PrincipalPassword -AsPlainText –Force) # Swap back to the subscription the user was in if(($VaultSubscriptionId -ne $null) -and ($currentSubId -ne $VaultSubscriptionId)) { Select-AzureRmSubscription -SubscriptionId $currentSubId | Out-Null } return $azureAdApplication } ########################################################### # Remove-AzurePrincipalWithSecret ########################################################### function Remove-AzurePrincipalWithSecret { [CmdletBinding()] param ( [parameter(Mandatory=$false, Position=0)] [string] $ADApplicationId, [parameter( Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Microsoft.Azure.Commands.Resources.Models.ActiveDirectory.PSADApplication] $ADApplication, [parameter(Mandatory=$true, Position=2)] [string] $VaultSubscriptionId ) # GUARD: At least one parameter is supplied if((-not $ADApplicationId) -and (-not $ADApplication)) { throw 'You must either supply the PSADApplication object in the pipeline or the ApplicationID guid.' } if(-not $ADApplication) { $adApp = Get-AzureRmADApplication -ApplicationId $ADApplicationId # GUARD: If ADApplicationId is supplied, make sure it's a valid one that really exists if(-not $adApp) { throw "The specified ADApplicationID [$ADApplicationId] doesn't exist" } $identifierUri = $adApp.IdentifierUris[0] } else { $identifierUri = $ADApplication.IdentifierUris[0] } # Break the Identifier URI of the AD Application into it's individual components so that we can infer everything else. if(-not ($identifierUri -match 'https:\/\/(?<system>[^.]*).(?<purpose>[^.]*).(?<environment>[^.]*).*(?<principalName>[^.]*)')) { throw "Can't infer the correct system information from the identifier URI [$identifierUri] in the AD Application, was this service principal created with this Module?" } $systemName = $Matches['system'] $certPurpose = $Matches['purpose'] $environmentName = $Matches['environment'] $principalName = $Matches['principalName'] # Uniform all the namings if([string]::IsNullOrWhiteSpace($principalName)) { $dashName = "$systemName-$certPurpose" $dotName = "$systemName.$certPurpose" } else { $dashName = "$systemName-$certPurpose-$cerName" $dotName = "$systemName.$certPurpose.$cerName" } # Switch to the KeyVault Techops-Management subscription $currentSubId = (Get-AzureRmContext).Subscription.SubscriptionId if($currentSubId -ne $VaultSubscriptionId) { Select-AzureRmSubscription -SubscriptionId $VaultSubscriptionId -ErrorAction Stop } $systemVaultName = "$($systemName.ToLower())-$($environmentName.ToLower())" # 1. Remove the principal configuration information from the system keyvault Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-TenantId" -Force -Confirm:$false Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-IdentifierUri" -Force -Confirm:$false Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-ApplicationId" -Force -Confirm:$false Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-ApplicationSecret" -Force -Confirm:$false # Swap back to the subscription the user was in if($currentSubId -ne $VaultSubscriptionId) { Select-AzureRmSubscription -SubscriptionId $currentSubId | Out-Null } # 2. Remove the AD Service Principal $servicePrincipal = Get-AzureRmADServicePrincipal -SearchString $dotName -ErrorAction SilentlyContinue if($servicePrincipal) { Remove-AzureRmADServicePrincipal -ObjectId $servicePrincipal.Id -Force } else { Write-Warning "Couldn't find any Service Principal using the search string [$dotName]" } # 3. Remove the AD Application $adApplication = Get-AzureRmADApplication -DisplayNameStartWith $dotName -ErrorAction SilentlyContinue if($adApplication) { Remove-AzureRmADApplication -ApplicationObjectId $adApplication.ApplicationObjectId -Force } }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzureSubscriptionInKeyVault.ps1
AzureSubscriptionInKeyVault.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Scope="Function", Target="*")] param() function Get-EnvironmentForResourceName { param( [parameter(Mandatory=$true, Position=0)] [string] $EnvironmentRegex, [parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1)] [string] $Input ) $Input -match $EnvironmentRegex | Out-Null $Matches[1] -match '\W*(\w*)' | Out-Null return $Matches[1] } function Register-AzureStorage { param( [parameter(Mandatory=$true)] [string] $KeyVaultName, [parameter(Mandatory=$true)] [ValidateSet('Primary','Secondary')] [string] $KeyType, [parameter(Mandatory=$false)] [string] $ResourceGroup, [parameter(Mandatory=$false)] [string] $EnvironmentFilter, [parameter(Mandatory=$false)] [string] $EnvironmentRegex, [switch] $ARMOnly ) if($ARMOnly -eq $false) { Get-AzureStorageAccount | Get-AzureStorageKey | foreach { if(($EnvironmentFilter -ne $null) -and (($_.StorageAccountName | Get-EnvironmentForResourceName $EnvironmentRegex) -ne $EnvironmentFilter)) { continue } $keyName = $_.StorageAccountName -replace $EnvironmentRegex, '' $null = Set-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $keyName -SecretValue (ConvertTo-SecureString -String $_.$KeyType -AsPlainText ñForce) } } switch($KeyType) { "Primary" {$keyIndex = 0} "Secondary" {$keyIndex = 1} default {$keyIndex = 0} } if($ResourceGroup -eq $null) { $storageAccounts = Get-AzureRmStorageAccount } else { $storageAccounts = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroup } $storageAccounts | select StorageAccountName, @{Name="Key";Expression={(Get-AzureRmStorageAccountKey -ResourceGroupName $_.ResourceGroupName -Name $_.StorageAccountName)[$keyIndex].Value}} | foreach { if(($EnvironmentFilter -ne $null) -and (($_.StorageAccountName | Get-EnvironmentForResourceName $EnvironmentRegex) -ne $EnvironmentFilter)) { continue } $keyName = $_.StorageAccountName -replace $EnvironmentRegex, '' $null = Set-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $keyName -SecretValue (ConvertTo-SecureString -String $_.Key -AsPlainText ñForce) } } function Register-AzureServiceBus { param( [parameter(Mandatory=$true)] [string] $KeyVaultName, [parameter(Mandatory=$false)] [string] $EnvironmentFilter, [parameter(Mandatory=$false)] [string] $SbAccessRuleName, [parameter(Mandatory=$false)] [string] $EnvironmentRegex ) Get-AzureSBNamespace | foreach { Get-AzureSBAuthorizationRule -Namespace $_.Name } | where { $_.Name -eq 'RootManageSharedAccessKey' } | foreach { if(($EnvironmentFilter -ne $null) -and (($_.Namespace | Get-EnvironmentForResourceName $EnvironmentRegex) -ne $EnvironmentFilter)) { continue } $keyName = $_.Namespace -replace $EnvironmentRegex, '' $null = Set-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $keyName -SecretValue (ConvertTo-SecureString -String $_.ConnectionString -AsPlainText ñForce) } } function Register-AzureSqlDatabase { param( [parameter(Mandatory=$true)] [string] $KeyVaultName, [parameter(Mandatory=$true)] [string] $SqlPassword, [parameter(Mandatory=$false)] [string] $ResourceGroup, [parameter(Mandatory=$false)] [string] $EnvironmentFilter, [parameter(Mandatory=$false)] [string] $EnvironmentRegex, [switch] $SetSqlPassword ) if($ResourceGroup -eq $null) { $rgs = Get-AzureRmResourceGroup } else { $rgs = Get-AzureRmResourceGroup -Name $ResourceGroup } $rgs | Get-AzureRmSqlServer | Get-AzureRmSqlDatabase | where { $_.DatabaseName -ne 'master' } | foreach { if(($EnvironmentFilter -ne $null) -and (($_.DatabaseName | Get-EnvironmentForResourceName $EnvironmentRegex) -ne $EnvironmentFilter)) { continue } $server = $_ | Get-AzureRmSqlServer # Set the SqlPassword on the server if($SetSqlPassword) { $server | Set-AzureRmSqlServer -SqlAdministratorPassword (ConvertTo-SecureString -String $SqlPassword -AsPlainText ñForce) } $connectionString = "Server=tcp:$($server.ServerName).database.windows.net; Database=$($_.DatabaseName); User ID=$($server.SqlAdministratorLogin)@$($server.ServerName); Password=$SqlPassword; Trusted_Connection=False; Encrypt=True; MultipleActiveResultSets=True;" $keyName = $_.DatabaseName -replace $EnvironmentRegex, '' $null = Set-AzureKeyVaultSecret -VaultName $KeyVaultName -Name $keyName -SecretValue (ConvertTo-SecureString -String $connectionString -AsPlainText ñForce) } } ########################################################### # Register-AzureSubscriptionInKeyVault ########################################################### function Register-AzureSubscriptionInKeyVault { param( [parameter(Mandatory=$true, Position=0)] [string] $KeyVaultName, [parameter(Mandatory=$true, Position=1)] [ValidateSet('Primary','Secondary')] [string] $KeyType, [parameter(Mandatory=$true, Position=2)] [string] $SqlPassword, [parameter(Mandatory=$false)] [string] $ResourceGroup, [parameter(Mandatory=$false)] [string] $EnvironmentFilter, [parameter(Mandatory=$false)] [string] $StgEnvRegex = '(.{3})$', [parameter(Mandatory=$false)] [string] $SbEnvRegex = '(-[^-]*)$', [parameter(Mandatory=$false)] [string] $SqlEnvRegex = '(-[^-]*)$', [parameter(Mandatory=$false)] [string] $SbAccessRuleName = 'RootManageSharedAccessKey', [switch] $SetSqlPassword, [switch] $ARMOnly ) Register-AzureStorage -KeyVaultName $KeyVaultName -KeyType $KeyType -ResourceGroup $ResourceGroup -EnvironmentRegex $StgEnvRegex -ARMOnly:$ARMOnly Register-AzureSqlDatabase -KeyVaultName $KeyVaultName -SqlPassword $SqlPassword -ResourceGroup $ResourceGroup -EnvironmentRegex $SqlEnvRegex -SetSqlPassword:$SetSqlPassword if($ARMOnly -eq $false) { Register-AzureServiceBus -KeyVaultName $KeyVaultName -ResourceGroup $ResourceGroup -SbAccessRuleName $SbAccessRuleName -EnvironmentRegex $SbEnvRegex } }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzureProfileHelpers.ps1
AzureProfileHelpers.ps1
function Reset-Alias { <# .SYNOPSIS Creates and alias with replace functionality. .DESCRIPTION Checks if the alias already exists, if it does calls Set-Alias on it, if it doesn't it will create a new alias using New-Alias. Relays the alias scope. .PARAMETER Name Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number. .PARAMETER Value Specifies the name of the cmdlet or command element that is being aliased. .PARAMETER Scope Specifies the scope of the new alias. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see about_Scopes. .EXAMPLE Reset-Alias list get-childitem This command creates an alias named "list" to represent the Get-ChildItem cmdlet on the "Global" scope. .NOTES Currently CmdletBinding doesn't have any internal support built-in. #> [CmdletBinding()] param( [parameter(Mandatory=$true, Position=0)] [string] $Name, [parameter(Mandatory=$true, Position=1)] [string] $Value, [parameter(Mandatory=$false)] [ValidateSet('Global', 'Local', 'Script')] [string] $Scope = 'Global' ) if((Get-Alias -Name $Name -Scope $Scope -ErrorAction SilentlyContinue) -eq $null) { New-Alias -Name $Name -Value $Value -Scope $Scope } else { Set-Alias -Name $Name -Value $Value -Scope $Scope } } function Add-AzureAccounts { <# .SYNOPSIS Wraps Add-AzureAccount and Add-AzureRmAccount. .DESCRIPTION Logs you in ASM and ARM by wrapping Add-AzureAccount and Add-AzureRmAccount. .EXAMPLE Add-AzureAccounts This command will log you in both ASM and ARM. .NOTES Currently CmdletBinding only has internal support for -Verbose. #> [CmdletBinding()] param() Add-AzureAccount -Verbose:($PSBoundParameters["Verbose"].IsPresent -eq $true) Add-AzureRmAccount -Verbose:($PSBoundParameters["Verbose"].IsPresent -eq $true) } function Switch-AzureSubscription { <# .SYNOPSIS Help method with UI (Out-GridView) for switching across Azure subscriptions. .DESCRIPTION Shows you the list of available subscriptions (Out-GridView) and then selects the chosen one in both ASM and ARM. .EXAMPLE Switch-AzureSubscription This command will show you the list of available subscriptions and then select the chosen one in both ASM and ARM. .NOTES Currently CmdletBinding only has internal support for -Verbose. #> [CmdletBinding()] param() $sub = Get-AzureRmSubscription | select SubscriptionName, SubscriptionId | Out-GridView -PassThru Select-AzureSubscription -SubscriptionId $sub.SubscriptionId -Verbose:($PSBoundParameters["Verbose"].IsPresent -eq $true) Select-AzureRmSubscription -SubscriptionId $sub.SubscriptionId -Verbose:($PSBoundParameters["Verbose"].IsPresent -eq $true) }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzurePrincipalWithCert.ps1
AzurePrincipalWithCert.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "", Scope="Function", Target="*")] param() function Set-KeyVaultCertSecret { [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string] $CertFolderPath, [parameter(Mandatory=$true)] [string] $CertPassword, [parameter(Mandatory=$true)] [string] $SecretName, [parameter(Mandatory=$true)] [string] $VaultName ) $collection = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $collection.Import($CertFolderPath, $CertPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable) $clearBytes = $collection.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12) $fileContentEncoded = [System.Convert]::ToBase64String($clearBytes) $secret = ConvertTo-SecureString -String $fileContentEncoded -AsPlainText –Force $secretContentType = 'application/x-pkcs12' Set-AzureKeyVaultSecret -VaultName $VaultName -Name $SecretName -SecretValue $secret -ContentType $secretContentType -Verbose } ########################################################### # New-AzurePrincipalWithCert ########################################################### function New-AzurePrincipalWithCert { [CmdletBinding()] param ( [parameter(Mandatory=$true, Position=0)] [string] $SystemName, [parameter(Mandatory=$true, Position=1)] [ValidateSet('Configuration','Authentication')] [string] $PrincipalPurpose, [parameter(Mandatory=$true, Position=2)] [string] $EnvironmentName, [parameter(Mandatory=$true, Position=3)] [string] $CertFolderPath, [parameter(Mandatory=$true, Position=4)] [string] $CertPassword, [parameter(Mandatory=$false, Position=5)] [string] $VaultSubscriptionId, [parameter(Mandatory=$false, Position=6)] [string] $PrincipalName ) # GUARD: There are no non letter characters on the Cert Name if(-not [string]::IsNullOrWhiteSpace($PrincipalName) -and -not ($PrincipalName -match "^([A-Za-z])*$")) { throw 'The CertName must be letters only, either lower and upper case. Cannot contain any digits or any non-alpha-numeric characters.' } # Uniform all the namings if([string]::IsNullOrWhiteSpace($PrincipalName)) { $principalIdDashed = "$($SystemName.ToLower())-$($PrincipalPurpose.ToLower())" $principalIdDotted = "$($SystemName.ToLower()).$($PrincipalPurpose.ToLower())" $identifierUri = "https://$($SystemName.ToLower()).$($PrincipalPurpose.ToLower()).$($EnvironmentName.ToLower())" } else { $principalIdDashed = "$($SystemName.ToLower())-$($PrincipalPurpose.ToLower())-$($PrincipalName.ToLower())" $principalIdDotted = "$($SystemName.ToLower()).$($PrincipalPurpose.ToLower()).$($PrincipalName.ToLower())" $identifierUri = "https://$($SystemName.ToLower()).$($PrincipalPurpose.ToLower()).$($EnvironmentName.ToLower()).$($PrincipalName.ToLower())" } # GUARD: AD application already exists, return the existing ad application $previousApplication = Get-AzureRmADApplication -DisplayNameStartWith $principalIdDotted if($previousApplication -ne $null) { Write-Warning 'An AD Application Already exists that looks identical to what you are trying to create' return $previousApplication } # GUARD: Certificate system vault exists $systemVaultName = "$($SystemName.ToLower())-$($EnvironmentName.ToLower())" if((Get-AzureRmKeyVault -VaultName $systemVaultName) -eq $null) { throw "The system vault $systemVaultName doesn't exist in the current subscription. Create it before running this cmdlet!" } # Create the self signed cert $currentDate = Get-Date $endDate = $currentDate.AddYears(1) $notAfter = $endDate.AddYears(1) if($CertFolderPath.EndsWith("\") -eq $false) { $CertFolderPath = $CertFolderPath + "\" } $cert = New-SelfSignedCertificate -CertStoreLocation cert:\localmachine\my ` -DnsName $principalIdDotted ` -KeyExportPolicy Exportable ` -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" ` -NotAfter $notAfter ` -ErrorAction Stop $pwd = ConvertTo-SecureString -String $CertPassword -Force -AsPlainText $certPath = "$CertFolderPath$SystemName-$EnvironmentName.pfx" $null = Export-PfxCertificate -cert "cert:\localmachine\my\$($cert.Thumbprint)" -FilePath $certPath -Password $pwd -ErrorAction Stop # Load the certificate $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate($certPath, $pwd) Import-Module AzureRM.Resources $keyCredential = New-Object Microsoft.Azure.Commands.Resources.Models.ActiveDirectory.PSADKeyCredential $keyCredential.StartDate = $currentDate $keyCredential.EndDate= $endDate $keyCredential.KeyId = [guid]::NewGuid() $keyCredential.Type = 'AsymmetricX509Cert' $keyCredential.Usage = 'Verify' $keyCredential.Value = [System.Convert]::ToBase64String($cert.GetRawCertData()) # Aquire the tenant ID on the subscription we are creating the principal on, not on the vault subscription! $tenantId = (Get-AzureRmContext).Subscription.TenantId # Create the Azure Active Directory Application $azureAdApplication = New-AzureRmADApplication -DisplayName $principalIdDotted ` -HomePage $identifierUri ` -IdentifierUris $identifierUri ` -KeyCredentials $keyCredential ` -Verbose Write-Host -ForegroundColor DarkYellow 'Write down this ID because you will need it for future reference.' Write-Host -ForegroundColor DarkYellow 'You can still get it through PowerShell, but writing it down now will save you the hassle.' Write-Host -ForegroundColor Green "Application ID: $($azureAdApplication.ApplicationId)" # Create the Service Principal and connect it to the Application $null = New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId # Switch to the KeyVault Techops-Management subscription $currentSubId = (Get-AzureRmContext).Subscription.SubscriptionId if(($VaultSubscriptionId -ne $null) -and ($currentSubId -ne $VaultSubscriptionId)) { Select-AzureRmSubscription -SubscriptionId $VaultSubscriptionId -ErrorAction Stop } # Upload the cert and cert passwords to the right keyvaults $null = Set-KeyVaultCertSecret -VaultName $systemVaultName -CertFolderPath $certPath -CertPassword $CertPassword -SecretName "$principalIdDashed-Cert" $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-CertPwd" -SecretValue (ConvertTo-SecureString -String $CertPassword -AsPlainText –Force) # Populate the system keyvault with all relevant principal configuration information $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-TenantId" -SecretValue (ConvertTo-SecureString -String $tenantId -AsPlainText –Force) $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-IdentifierUri" -SecretValue (ConvertTo-SecureString -String $identifierUri -AsPlainText –Force) $null = Set-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$principalIdDashed-ApplicationId" -SecretValue (ConvertTo-SecureString -String $($azureAdApplication.ApplicationId) -AsPlainText –Force) # Swap back to the subscription the user was in if(($VaultSubscriptionId -ne $null) -and ($currentSubId -ne $VaultSubscriptionId)) { Select-AzureRmSubscription -SubscriptionId $currentSubId | Out-Null } return $azureAdApplication } ########################################################### # Remove-AzurePrincipalWithCert ########################################################### function Remove-AzurePrincipalWithCert { [CmdletBinding()] param ( [parameter(Mandatory=$false, Position=0)] [string] $ADApplicationId, [parameter( Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [Microsoft.Azure.Commands.Resources.Models.ActiveDirectory.PSADApplication] $ADApplication, [parameter(Mandatory=$false, Position=2)] [string] $VaultSubscriptionId ) # GUARD: At least one parameter is supplied if((-not $ADApplicationId) -and (-not $ADApplication)) { throw 'You must either supply the PSADApplication object in the pipeline or the ApplicationID guid.' } if(-not $ADApplication) { $adApp = Get-AzureRmADApplication -ApplicationId $ADApplicationId # GUARD: If ADApplicationId is supplied, make sure it's a valid one that really exists if(-not $adApp) { throw "The specified ADApplicationID [$ADApplicationId] doesn't exist" } $identifierUri = $adApp.IdentifierUris[0] } else { $identifierUri = $ADApplication.IdentifierUris[0] } # Break the Identifier URI of the AD Application into it's individual components so that we can infer everything else. if(-not ($identifierUri -match 'https:\/\/(?<system>[^.]*).(?<purpose>[^.]*).(?<environment>[^.]*).*(?<principalName>[^.]*)')) { throw "Can't infer the correct system information from the identifier URI [$identifierUri] in the AD Application, was this service principal created with this Module?" } $systemName = $Matches['system'] $principalPurpose = $Matches['purpose'] $environmentName = $Matches['environment'] $principalName = $Matches['principalName'] # Uniform all the namings if([string]::IsNullOrWhiteSpace($principalName)) { $dashName = "$systemName-$principalPurpose" $dotName = "$systemName.$principalPurpose" } else { $dashName = "$systemName-$principalPurpose-$cerName" $dotName = "$systemName.$principalPurpose.$cerName" } # Switch to the KeyVault Techops-Management subscription $currentSubId = (Get-AzureRmContext).Subscription.SubscriptionId if(($VaultSubscriptionId -ne $null) -and ($currentSubId -ne $VaultSubscriptionId)) { Select-AzureRmSubscription -SubscriptionId $VaultSubscriptionId -ErrorAction Stop } $systemVaultName = "$($systemName.ToLower())-$($environmentName.ToLower())" # Remove the cert and cert password from the system keyvault Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-Cert" -Force -Confirm:$false Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-CertPwd" -Force -Confirm:$false # Remove the principal configuration information from the system keyvault Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-TenantId" -Force -Confirm:$false Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-IdentifierUri" -Force -Confirm:$false Remove-AzureKeyVaultSecret -VaultName $systemVaultName -Name "$dashName-ApplicationId" -Force -Confirm:$false # Swap back to the subscription the user was in if(($VaultSubscriptionId -ne $null) -and ($currentSubId -ne $VaultSubscriptionId)) { Select-AzureRmSubscription -SubscriptionId $currentSubId | Out-Null } # Remove the AD Service Principal $servicePrincipal = Get-AzureRmADServicePrincipal -SearchString $dotName -ErrorAction SilentlyContinue if($servicePrincipal) { Remove-AzureRmADServicePrincipal -ObjectId $servicePrincipal.Id -Force } else { Write-Warning "Couldn't find any Service Principal using the search string [$dotName]" } # Remove the AD Application $adApplication = Get-AzureRmADApplication -DisplayNameStartWith $dotName -ErrorAction SilentlyContinue if($adApplication) { Remove-AzureRmADApplication -ApplicationObjectId $adApplication.ApplicationObjectId -Force } }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzureADHelpers.ps1
AzureADHelpers.ps1
########################################################### # Get-MyUserObjectId ########################################################### function Get-MyUserObjectId { [CmdletBinding()] param() $user = (Get-AzureRmContext).Account $adUser = Get-AzureRmADUser | where { $_.UserPrincipalName -match $user.Id } if($adUser -eq $null) { $adUser = Get-AzureRmADUser | where { $_.UserPrincipalName -match $user.Id.Replace("@", "_") } } if($adUser -eq $null) { throw "Couldn't find you in the AD!" } return $adUser.Id }
PowerShellCorpus/PowerShellGallery/DevOpsFlex.Automation.PowerShell/1.2.4/AzureVNetHelpers.ps1
AzureVNetHelpers.ps1
class vNet { [string] $Name [string] $AddressSpace [string] $Type [string] $Subscription } function Get-AzureAllVNets { <# .SYNOPSIS Help method to list all ASM and ARM VNets across all subscriptions that the account has access to. .DESCRIPTION Help method to list all ASM and ARM VNets across all subscriptions that the account has access to. .EXAMPLE Get-AzureAllVNets | ft * This will show you the list of all ARM and ASM VNets on all subscriptions you have access to and output an auto formatted table. #> [CmdletBinding()] param() $vnets = @() Get-AzureRmSubscription -WarningAction SilentlyContinue | % { $sub = $_.SubscriptionName Select-AzureRmSubscription -SubscriptionId $_.SubscriptionId -WarningAction SilentlyContinue > $null Select-AzureSubscription -SubscriptionId $_.SubscriptionId -WarningAction SilentlyContinue > $null # ASM Get-AzureRmVirtualNetwork | % { $vNet = $_.Name $_.AddressSpace.AddressPrefixes | % { $vnets += [vNet]@{ Name = $vNet; AddressSpace = $_; Type = 'ASM'; Subscription = $sub; } } } # ARM Get-AzureVNetSite | % { $vNet = $_.Name $_.AddressSpacePrefixes | % { $vnets += [vNet]@{ Name = $vNet; AddressSpace = $_; Type = 'ASM'; Subscription = $sub; } } } } Write-Output $vnets # return }
PowerShellCorpus/PowerShellGallery/AzureRM.Profile.NetCore.Preview/0.3.4/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# # # SIG # Begin signature block # MIIdkgYJKoZIhvcNAQcCoIIdgzCCHX8CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUt+/HvWqAtZ9Eq1tg0kkt5i2E # hFSgghhkMIIEwzCCA6ugAwIBAgITMwAAAJ1CaO4xHNdWvQAAAAAAnTANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw # HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTYwMzMwMTkyMTMw # WhcNMTcwNjMwMTkyMTMwWjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp # bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw # b3JhdGlvbjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO # OjE0OEMtQzRCOS0yMDY2MS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Hon5o64t7KEAumYZgGEc= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/tests/ADSchemaClass.tests.ps1
ADSchemaClass.tests.ps1
Describe "ADSchema Class Functions" { Context "Get-ADSchemaClass" { It "exists as a function in the module" { (Get-Command Get-ADSchemaClass).count | should be 1 } It "returns a schema object - test uses user class" { (Get-ADSchemaClass -Class 'User').Oid | Should Be '1.2.840.113556.1.5.9' } It "accepts wildcards" { ((Get-ADSchemaClass -class use*) | Where-Object {$_.Name -eq 'User'}).count | Should Be 1 } } Context "New-ADSchemaAttribute" { It "exists as a function in the module" { (Get-Command New-ADSchemaClass).count | should be 1 } } }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/tests/ADSchemaAttribute.tests.ps1
ADSchemaAttribute.tests.ps1
Describe "ADSchema Attribute Functions" { Context "Get-ADSchemaAttribute" { It "exists as a function in the module" { (Get-Command Get-ADSchemaAttribute).count | should be 1 } It "returns a schema object - test use CN Attribute" { (Get-ADSchemaAttribute -class User -Attribute cn).Oid | Should Be '2.5.4.3' } It "accepts wildcards" { ((Get-ADSchemaAttribute -class User -Attribute c*) | Where-Object {$_.Name -eq 'CN'}).count | Should Be 1 } } Context "New-ADSchemaAttribute" { It "exists as a function in the module" { (Get-Command New-ADSchemaAttribute).count | should be 1 } } }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/tests/ADSchemaModule.tests.ps1
ADSchemaModule.tests.ps1
Describe "ADSchema Class Functions" { Context "Help for functions" { foreach ($command in Get-Command -Module ADSchema) { It "$command has examples in the help" { $help = get-help -Full $command $help.examples.example | should not be $null } } } }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/Add-ADSchemaAttributeToClass.ps1
Add-ADSchemaAttributeToClass.ps1
<# .SYNOPSIS Adds an attribute to a class. .DESCRIPTION Add a New Custom Class to an existing Structural Class in Active Directory. For example if you want to add attributes to the User Class: 1. Create a new Auxiliary Class. 2. Add Attributes to that new Auxiliary Class. 3. Assign the new class as an Auxiliary Class to the User Class. .PARAMETER AuxiliaryClass The class that will be holding the new attributes you are creating. This will be an Auxiliary Class of the structural class. .PARAMETER Class The Structural Class you are adding an Auxiliary Class to. .EXAMPLE PS> Add-ADSchemaAuxiliaryClassToClass -AuxiliaryClass asTest -Class User Set the 'asTest' class as an Auxiliary Class of the User Class. #> Function Add-ADSchemaAttributeToClass { param( $Attribute, $Class ) $schemaPath = (Get-ADRootDSE).schemaNamingContext $Schema = Get-ADObject -SearchBase $schemaPath -Filter "name -eq `'$Class`'" $Schema | Set-ADObject -Add @{mayContain = $Attribute} }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/New-ADSchemaClass.ps1
New-ADSchemaClass.ps1
<# .SYNOPSIS Create a new class in the Active Directory Schema .DESCRIPTION New-ADSchemaClass will add a new class to the AD Schema. The majority of the time, any new classes will likely be an Auxiliary Class. It is a best practice to create an auxiliary class and add it as an auxliary class to an existing class. .PARAMETER Name The name of the attribute you are creating. This will be the CN and the LDAP Display Name, and Admin Display Name. Using a standard prefix is a good practice to follow. .PARAMETER AdminDescription This is the description of the class being created. Usually, a 3 or 4 word description is sufficient. .PARAMETER Category 99% of the time, you will chose an Auxiliary class. Becuase of this, the default value is automatically set to Auxililary. Please see https://technet.microsoft.com/en-us/library/cc961751.aspx for info on other categories if you wish to overwrite. .EXAMPLE $oid = New-ADSchemaTestOID New-ADSchemaClass -Name asPerson -AdminDescription 'host custom user attributes' -Category Auxiliary -AttributeID $oid #> Function New-ADSchemaClass { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param( [Parameter(Mandatory, ValueFromPipelinebyPropertyName)] $Name, [Parameter(Mandatory, ValueFromPipelinebyPropertyName)] [Alias('Description')] $AdminDescription, [Parameter(ValueFromPipelinebyPropertyName)] [ValidateSet("Auxiliary","Abstract","Structural","88 Class")] $Category = 'Auxiliary', [Parameter(ValueFromPipelinebyPropertyName)] [Alias('OID')] $AttributeID = (New-ADSchemaTestOID) ) BEGIN {} PROCESS { $schemaPath = (Get-ADRootDSE).schemaNamingContext switch ($Category) { 'Auxiliary' {$ObjectCategory = 3} 'Abstract' {$ObjectCategory = 2} 'Structural' {$ObjectCategory = 1} '88 Class' {$ObjectCategory = 0} } $attributes = @{ governsId = $AttributeID adminDescription = $AdminDescription objectClass = 'classSchema' ldapDisplayName = $Name adminDisplayName = $Name objectClassCategory = $ObjectCategory systemOnly = $FALSE # subclassOf: top subclassOf = "2.5.6.0" # rdnAttId: cn rdnAttId = "2.5.4.3" } $ConfirmationMessage = "$Name in $schemaPath. This cannot be undone" $Caption = 'Adding a new class to Active Directory Schema' if($AttributeID.StartsWith('1.2.840.113556.1.8000.2554')){ Write-Warning 'You are using a test OID. For Production use, use an OID with your registered PEN. See help about_adschema for more details. ' } if ($PSCmdlet.ShouldProcess($ConfirmationMessage, $Caption)) { New-ADObject -Name $Name -Type 'classSchema' -Path $schemapath -OtherAttributes $attributes } } END {} }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/New-ADSchemaAttribute.ps1
New-ADSchemaAttribute.ps1
<# .SYNOPSIS Create a new attribute in the Active Directory Schema .DESCRIPTION New-ADSchemaAttribute will add a new attribute to the AD Schema. Once the new attribute is created, you will need to add it to a class. AD Schema best practices suggest that you: 1) Create a new Auxiliary Class. 2) Add your attribute to that class. 3) Add your Auxiliary Class (containing your new Attribute) to an Existing Class. See help about_ADSchema for more details .PARAMETER Name The name of the attribute you are creating. This will be the CN and the LDAP Display Name. Using a standard prefix is a good practice to follow. .PARAMETER Description The Administrator description is a short description that is added as metadata to the attribute. Should not be much more than 3 or 4 words. .PARAMETER IsSingleValued Determine whether the new attribute can hold one value or an array of values. .PARAMETER AttributeType Determines what type of attribute you are creating. Use a DN to create an attribute that will hold a reference to another object in Active Directory. One example of an existing DN attribute is a user's manager, or a group's "ManagedBy" attribute. Strings are case-insenstive. .PARAMETER AttributeID AttributeID is the Object Identifier (OID) for the new attribute. OIDs have a specific syntax that looks something like '1.2.840.113556.1.8000.2554.13769.13577.20614' You can use the New-ADSchemaTestOid to generate one. However, in production, you should use your own OID based on your company's defined OID structure and your Private Enterprise Number. For more inforation, please look at help about_ADSchema. .PARAMETER SchemaAttributeHashTable This parameter is the rope that will let you hang yourself if you are not careful. It is for advanced users that want to generate highly customized attributes. Any of the attributes found in https://technet.microsoft.com/en-us/library/cc961746.aspx could be used. You will need to store them in a hashtable with their corresponding values. Using a custom hashtable, you can specify any of the attributes in attributeSchema objects and use any attributeSyntax you want. .EXAMPLE $oid = New-ADSchemaTestOID New-ADSchemaAttribute -Name as-favoriteColor -Description 'Favorite Color' -IsSingleValued $true -AttributeType String -AtributeID $oid .EXAMPLE $hash - Get-ADSchemaClass com* #> Function New-ADSchemaAttribute { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] param( [Parameter(Mandatory,ValueFromPipelinebyPropertyName, ParameterSetName = 'basic')] [String] $Name, [Parameter(Mandatory, ValueFromPipelinebyPropertyName, ParameterSetName = 'basic')] [Alias('AdminDescription')] [String] $Description, [Parameter(ValueFromPipelinebyPropertyName, ParameterSetName = 'basic')] [Alias('SingleValued')] [Boolean] $IsSingleValued = $True, [Parameter(Mandatory, ValueFromPipelinebyPropertyName, ParameterSetName = 'basic')] [ValidateSet('String','StringOctet','DN','Int','GeneralizedTime','Boolean')] [String] $AttributeType , [Parameter(ValueFromPipelinebyPropertyName,ParameterSetName = 'basic')] [Alias('OID')] [String] $AttributeID = (New-ADSchemaTestOID), [Parameter(ValueFromPipelineByPropertyName,ParameterSetName = 'advanced')] [String] $SchemaAttributeHashTable ) BEGIN {} PROCESS { $schemaPath = (Get-ADRootDSE).schemaNamingContext $type = 'attributeSchema' if($SchemaAttributeHashTable){ $attributes = $SchemaAttributeHashTable } else { # based on https://technet.microsoft.com/en-us/library/cc961740.aspx switch ($AttributeType) { 'String' {$attributeSyntax = '2.5.5.4'; $omSyntax = 20} 'StringOctet' {$attributeSyntax = '2.5.5.10'; $omSyntax = 4} 'DN' {$attributeSyntax = '2.5.5.1'; $omSyntax = 127} 'Int' {$attributeSyntax = '2.5.5.9'; $omSyntax = 2} 'GeneralizedTime' {$attributeSyntax = '2.5.5.11'; $omSyntax = 24} 'Boolean' {$attributeSyntax = '2.5.5.8'; $omSyntax = 1} Default {} } $attributes = @{ lDAPDisplayName = $Name; attributeId = $AttributeID; oMSyntax = $omSyntax; attributeSyntax = $attributeSyntax; isSingleValued = $IsSingleValued; adminDescription = $Description; searchflags = 1 } } $ConfirmationMessage = "$schemaPath. This cannot be undone" $Caption = "Updating Active Directory Schema. Creating attribute $Name" if($AttributeID.StartsWith('1.2.840.113556.1.8000.2554')){ Write-Warning 'You are using a test OID. For Production use, use an OID with your registered PEN. See help about_adschema for more details. ' } if ($PSCmdlet.ShouldProcess($ConfirmationMessage, $Caption)) { New-ADObject -Name $Name -Type $type -Path $schemapath -OtherAttributes $attributes } } END {} }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/Invoke-ADSchemaReload.ps1
Invoke-ADSchemaReload.ps1
<# .SYNOPSIS Reloads the Active Directory Schema .DESCRIPTION After the schema has been updated, it needs to be reloaded so your updates can be seen immediately. .EXAMPLE PS C:\> Invoke-ADSchemaReload #> Function Invoke-ADSchemaReload { $dse = Get-ADRootDSE $dse.schemaUpdateNow = $true }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/New-ADSchemaTestOID.ps1
New-ADSchemaTestOID.ps1
<# .SYNOPSIS Creates a random OID for dev and test purposes. .DESCRIPTION Creates a random Object Identifier for dev and test purposes. For production uses, use an OID with your company OID prefix and Private Enterprise Number. See help about_adschema for more information. .EXAMPLE PS> New-ADSchemaTestOID 1.2.840.113556.1.8000.2554.9398 .EXAMPLE PS> New-ADSchemaTestOID -Parts 5 -Prefix 1.2.3 1.2.3.6317.60671.47166.17019.42042 .EXAMPLE PS> New-ADSchemaTestOID -Parts 4 -Prefix 1.2.3 1.2.3.7279.9696.19673.18618 .EXAMPLE PS> New-ADSchemaTestOID -Parts 6 1.2.840.113556.1.8000.2554.59800.33270.113.17098.41534.37654 #> Function New-ADSchemaTestOID { param( [Parameter()] $Prefix = "1.2.840.113556.1.8000.2554", [Parameter()] [ValidateRange(1,6)] $Parts = 2 ) $guid = (New-Guid).Guid $p = @() for ($i = 0; $i -lt $Parts * 5 ; $i+=5) { if($i -eq 0) {$p += [UInt64]::Parse($guid.SubString($i , 4), "AllowHexSpecifier")} else {$p += [UInt64]::Parse($guid.SubString($i-1 , 4), "AllowHexSpecifier")} } return $prefix + '.' + ($p -join '.') }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/Add-ADSchemaAuxiliaryClassToClass.ps1
Add-ADSchemaAuxiliaryClassToClass.ps1
<# .SYNOPSIS Adds an Auxiliary Class to a Structural Class. .DESCRIPTION Add a new Custom Class to an existing Structural Class in Active Directory. For example if you want to add attributes to the user class, you should: 1) Create a new Auxiliary Class. 2) Add attributes to that Auxiliary Class. 3) Finally assign the New Class as an Auxiliary Class to the User Class. .PARAMETER AuxiliaryClass The class that will be holding the new attributes you are creating. This will be an auxiliary class of the structural class. .PARAMETER Class The structural class you are adding an Auxiliary Class to.. .EXAMPLE PS> Add-ADSchemaAuxiliaryClassToClass -AuxiliaryClass asTest -Class User Set the asTest class as an aux class of the User class. #> Function Add-ADSchemaAuxiliaryClassToClass { param( [Parameter()] $AuxiliaryClass, [Parameter()] $Class ) $schemaPath = (Get-ADRootDSE).schemaNamingContext $auxClass = Get-ADObject -SearchBase $schemaPath -Filter "name -eq `'$AuxiliaryClass`'" -Properties governsID $classToAddTo = Get-ADObject -SearchBase $schemaPath -Filter "name -eq `'$Class`'" $classToAddTo | Set-ADObject -Add @{auxiliaryClass = $($auxClass.governsID)} }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/Get-ADSchemaClass.ps1
Get-ADSchemaClass.ps1
<# .SYNOPSIS Gets classes in an AD Schema .DESCRIPTION Use this function to list or search for existing classes in the Active Directory Schema .PARAMETER Class The name of the class you want to search for. Supports wildcards .EXAMPLE Get-ADSchemaClass -Name User .EXAMPLE Get-ADSchemaClass com* #> Function Get-ADSchemaClass { param( [Parameter()] $Class = '*' ) $schema = [directoryservices.activedirectory.activedirectoryschema]::getcurrentschema() $classes = $schema.FindAllClasses() return $classes | Where-Object {$_.Name -like $Class} }
PowerShellCorpus/PowerShellGallery/ADSchema/0.0.3/scripts/Get-ADSchemaAttribute.ps1
Get-ADSchemaAttribute.ps1
<# .Synopsis Gets attributes in an AD Schema .DESCRIPTION Gets attributes in an AD Schema .EXAMPLE Get-ADSchemaAttribute -class User -Attribute c* .EXAMPLE Get-ADSchemaAttribute -class asTestClass -attribute asFavoriteColor #> Function Get-ADSchemaAttribute { param( [Parameter()] $Attribute = '*', [Parameter()] $Class = 'user' ) $schema = [directoryservices.activedirectory.activedirectoryschema]::getcurrentschema() $attributes = $schema.FindClass($Class).mandatoryproperties $attributes += $schema.FindClass($Class).optionalproperties return $attributes | Where-Object {$_.Name -like $Attribute} }
PowerShellCorpus/PowerShellGallery/Okta.Core.Automation/0.3.0.0/chocolatey/ChocolateyUninstall_New.ps1
ChocolateyUninstall_New.ps1
function Chocolatey-Uninstall { param( [string] $packageName, [string] $version = '', [string] $installerArguments = '' ) Write-Debug "Running 'Chocolatey-Uninstall' for $packageName with version:`'$version`', installerArguments: `'$installerArguments`'"; if(!$packageName) { Write-ChocolateyFailure "Chocolatey-Uninstall" "Missing PackageName input parameter." return } if ($packageName -eq 'all') { write-host "Uninstalling all packages is not yet supported in this version. " # by default this should prompt user 2x. Also can provide a -nuke switch for prompt bypass return } Write-Host "Chocolatey (v$chocVer) is uninstalling $packageName..." -ForegroundColor $RunNote -BackgroundColor Black $packages = $packageName foreach ($package in $packages) { $versions = Chocolatey-Version $package $source if ($versions.found -eq "no version") { write-host "not installed" } else { Write-Debug "Looking for $($package).$($versions.found)" $packageFolder = Join-Path $nugetLibPath "$($package).$($versions.found)" Write-host "Uninstalling from folder $packageFolder" Get-ChocolateyBins $packageFolder -uninstall Run-ChocolateyPS1 $packageFolder $package -action 'uninstall' Remove-Item -Recurse -Force $packageFolder } } }
PowerShellCorpus/PowerShellGallery/Okta.Core.Automation/0.3.0.0/chocolatey/ChocolateyUninstall.ps1
ChocolateyUninstall.ps1
$packageName = 'Okta.Core.Automation' $folder = "$($Home)\Documents\WindowsPowerShell\Modules\$($packageName)" Remove-Item "$($folder)" -recurse -force
PowerShellCorpus/PowerShellGallery/Okta.Core.Automation/0.3.0.0/chocolatey/ChocolateyInstall.ps1
ChocolateyInstall.ps1
# install Okta.Core.Automation -source '%cd%' $packageName = 'Okta.Core.Automation' $folder = "$($Home)\Documents\WindowsPowerShell\Modules\$($packageName)" $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition Set-Location $scriptPath # http://andyarismendi.blogspot.com/2012/02/unblocking-files-with-powershell.html function Unblock-File { [cmdletbinding(DefaultParameterSetName="ByName", SupportsShouldProcess=$True)] param ( [parameter(Mandatory=$true, ParameterSetName="ByName", Position=0)] [string] $FilePath, [parameter(Mandatory=$true, ParameterSetName="ByInput", ValueFromPipeline=$true)] $InputObject ) begin { Add-Type -Namespace Win32 -Name PInvoke -MemberDefinition @" // http://msdn.microsoft.com/en-us/library/windows/desktop/aa363915(v=vs.85).aspx [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeleteFile(string name); public static int Win32DeleteFile(string filePath) { bool is_gone = DeleteFile(filePath); return Marshal.GetLastWin32Error();} [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetFileAttributes(string lpFileName); public static bool Win32FileExists(string filePath) {return GetFileAttributes(filePath) != -1;} "@ } process { switch ($PSCmdlet.ParameterSetName) { 'ByName' {$input_paths = Resolve-Path -Path $FilePath | ? {[IO.File]::Exists($_.Path)} | Select -Exp Path} 'ByInput' {if ($InputObject -is [System.IO.FileInfo]) {$input_paths = $InputObject.FullName}} } $input_paths | % { if ([Win32.PInvoke]::Win32FileExists($_ + ':Zone.Identifier')) { if ($PSCmdlet.ShouldProcess($_)) { $result_code = [Win32.PInvoke]::Win32DeleteFile($_ + ':Zone.Identifier') if ([Win32.PInvoke]::Win32FileExists($_ + ':Zone.Identifier')) { Write-Error ("Failed to unblock '{0}' the Win32 return code is '{1}'." -f $_, $result_code) } } } } } } # Copy all the files to the Modules location if(!(Test-Path -Path "$($folder)")) { New-Item -ItemType directory -Path "$($folder)" } # Copy the psd1 Copy-Item .\Okta.Core.Automation.psd1 "$($folder)" # Copy all the dlls if(!(Test-Path -Path "$($folder)\bin")) { New-Item -ItemType directory -Path "$($folder)\bin" } Copy-Item .\bin\* "$($folder)\bin" # Unblock all the dlls #Get-ChildItem "$($folder)\bin" | Unblock-File
PowerShellCorpus/PowerShellGallery/AzureRM.profile/2.5.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIdpwYJKoZIhvcNAQcCoIIdmDCCHZQCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUrt58EopeEVPXRxPxV4sss2J/ #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gAAAAAAMgwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG # 9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDExODAxNDkwNlowIwYJKoZIhvcNAQkE # MRYEFEbcE0uc55tgvpRM+zYLuDHxfBN1MA0GCSqGSIb3DQEBBQUABIIBAJq+qrgU # 213X7SliOntg98k8thF9eOBsf9lzfWGJ5sIZVjtjasH3NnwOj060vru5IAU/NjZn # XqVyCM2MtK8YvGyrwxavgVLrOR4tS1Rxs0MH3tHCY6AALoXL1crcp1IeZLH4xvtq # QjBzJ4V9mt6CaF7ypskaAGqUbYG8ICGLWNuJv+mbbyck7Hk79Rcl9JPmmwxUc9AW # 1Bho77/yqY53KBMtPKkR9hYP5+BGghYyiTP8VKZUZwKr1xrAQLfTbqhcksS0c0+3 # b3xGSbAYtCQ/83O45JcrvIVjAJ2m07w13561D5Fh94SJHVKCDNC41+ZZe1LvStJ2 # BPo+YYwWYEsMmRM= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.profile/3.1.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; "Save-AzureRmProfile" = "Save-AzureRmContext"; "Select-AzureRmProfile" = "Import-AzureRmContext"; "Resolve-Error" = "Resolve-AzureRmError"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" #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0EgMjAxMAITMwAAAKGl/bnu # p/yenQAAAAAAoTANBglghkgBZQMEAgEFAKCCATIwGgYJKoZIhvcNAQkDMQ0GCyqG # SIb3DQEJEAEEMC8GCSqGSIb3DQEJBDEiBCB/E4TR8ATkZ88LXZ1pqnx0kMNZD7Wh # Bol8sI16wUSAtjCB4gYLKoZIhvcNAQkQAgwxgdIwgc8wgcwwgbEEFIKuifW05j8W # XCC8F+TBw0DNOetoMIGYMIGApH4wfDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh # c2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD # b3Jwb3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIw # MTACEzMAAAChpf257qf8np0AAAAAAKEwFgQUY4KCX9cHyEPhhSfFtcFq1F9t4qQw # DQYJKoZIhvcNAQELBQAEggEAi37c/jSc0Xr/GQxPQLCB49791CSXkUsmSjoWC4AH # oF+5eQ+cfFZ2a3KryfthhqmitNPwydx1fOFTa7ncTALbm9gabcWdwr+12g8gVIrv # 5I2Vic7is+lgWN3oBP6OPpr41jpo8yp6rJJPehWHMCTMHmvvi8KQ68U1ekjotAFM # b+bASnm1dQEROywV8Sty2K8y6VCZ+jPNgrSjQclbvhWJrGik3SQSlUK8rJAYvJAo # BwA36POvLAA3oC1usNsc+wB31zYvFrsMA37/gIfEwMo2hek29zDXEs/LPLEI4eTF # u8uGTxhtD3GmDBJr0mPb/PO9/fK4uVwwfyvU72OomhuBTw== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.profile/1.0.4.3/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC1PGhfmuH9GJTk # /MpksAv+PSrXA65VFUCSSwGj4IHJF6CCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD # VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy # b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p # bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL # MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v # bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UECxMETU9Q # UjEeMBwGA1UEAxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkqhkiG9w0B # AQEFAAOCAQ8AMIIBCgKCAQEA0IfUQit+ndnGetSiw+MVktJTnZUXyVI2+lS/qxCv # 6cnnzCZTw8Jzv23WAOUA3OlqZzQw9hYXtAGll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oU2CpHqEoSqkEcK7LLWUHw== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.profile/1.0.4.3/CheckVersions.ps1
CheckVersions.ps1
$AzureRMModules = @( "AzureRM.ApiManagement"; "AzureRM.Automation"; "AzureRM.Backup"; "AzureRM.Batch"; "AzureRM.Compute"; "AzureRM.DataFactories"; "AzureRM.Dns"; "AzureRM.HDInsight"; "AzureRM.Intune"; "AzureRM.KeyVault"; "AzureRM.Network"; "AzureRM.OperationalInsights"; "AzureRM.RedisCache"; "AzureRM.Resources"; "AzureRM.SiteRecovery"; "AzureRM.Sql"; "AzureRM.Storage"; "AzureRM.StreamAnalytics"; "AzureRM.Tags"; "AzureRM.TrafficManager"; "AzureRM.UsageAggregates"; "AzureRM.Websites" ) $global:AvailableModules = @() function CheckVersions { $profile = GetModuleInfo("AzureRM.Profile") if (-not $profile) { exit 0 } ForEach ($moduleName in $AzureRMModules) { $module = GetModuleInfo($moduleName) if ($module) { $module.RequiredModules | Where-Object {$_.Name -eq "AzureRM.Profile"} | ForEach { if ($profile.Version.Major -ne $_.Version.Major) { Write-Warning("$moduleName $($module.Version) is not compatible with $profile $($profile.Version)!") } } } } } function GetModuleInfo { param( [Parameter(Position=0)] [string] $ModuleName) if ($global:AvailableModules.Length -eq 0) { $global:AvailableModules = Get-Module -ListAvailable } return $global:AvailableModules ` | Where-Object { $_.Name -eq $ModuleName} ` | Select-Object -first 1 } CheckVersions # SIG # Begin signature block # MIIkHwYJKoZIhvcNAQcCoIIkEDCCJAwCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBc/RXURL9/rb9i # DE8pU2fyXIeqHxfqVVlqdiMcs/CgSKCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3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YXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQg # Q29ycG9yYXRpb24xJjAkBgNVBAMTHU1pY3Jvc29mdCBUaW1lLVN0YW1wIFBDQSAy # MDEwAhMzAAAAszm71BKTFan+AAAAAACzMBYEFFA9zBalwH5Qj0VAHQcQyZ6hPcbe # MA0GCSqGSIb3DQEBCwUABIIBAEX1yhtAuPR8AuaEEaYOyfI0yZBT1PJwnerdckZA # v7LvinNuW30BAak92gp/90eKEL0OFbHR/sqIN8ez//frq697p3Oug0GNvu508r7h # RmNyY+6RVNV5oRoYVwXNsZ/gwPpdc3NgvVKdgNynNL29KcEC5e0Sq7gksLFg/OSI # g9nPPRzy9eWyQhF45HxIX6TvrQ5VXG9+z4MSiVEh6AYd5HXCdENYgs6NDqGlVvwZ # aFVrhNTWqOVft2QpO3H4owCzLzQrtJgcEFXbgIpNnrA4+WSCCr86miRkNVaQred1 # tjM7V8PIRMrvkorEZmH/BKg1JR0xDOdIVOuRCfpfRCwuK6w= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.profile/2.8.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; "Save-AzureRmProfile" = "Save-AzureRmContext"; "Select-AzureRmProfile" = "Import-AzureRmContext"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -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