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 |
|---|---|---|---|---|---|
<#
This is designed for all paths you need configurations for.
#>
# The default path where dbatools stores persistent data
Set-DbaConfig -FullName 'Path.DbatoolsData' -Value "$env:AppData\PowerShell\dbatools" -Initialize -Validation string -Handler { } -Description "The path where dbatools stores persistent data on a per user basis."
# The default path where dbatools stores temporary data
Set-DbaConfig -FullName 'Path.DbatoolsTemp' -Value ([System.IO.Path]::GetTempPath()).TrimEnd("\") -Initialize -Validation string -Handler { } -Description "The path where dbatools stores temporary data."
# The default path for writing logs
Set-DbaConfig -FullName 'Path.DbatoolsLogPath' -Value "$env:AppData\PowerShell\dbatools" -Initialize -Validation string -Handler { [Sqlcollaborative.Dbatools.dbaSystem.DebugHost]::LoggingPath = $args[0] } -Description "The path where dbatools writes all its logs and debugging information."
# The default Path for where the tags Json is stored
Set-DbaConfig -FullName 'Path.TagCache' -Value "$ModuleRoot\bin\dbatools-index.json" -Initialize -Validation string -Handler { } -Description "The file in which dbatools stores the tag cache. That cache is used in Find-DbaCommand for more comfortable autocomplete"
# The default Path for the server list (Get-DbaServerList, etc)
Set-DbaConfig -FullName 'Path.Servers' -Value "$env:AppData\PowerShell\dbatools\servers.xml" -Initialize -Validation string -Handler { } -Description "The file in which dbatools stores the current user's server list, as managed by Get/Add/Update-DbaServerList"
| SirCaptainMitch/dbatools | internal/configurations/settings/paths.ps1 | PowerShell | mit | 1,572 |
$lastcommit = git rev-parse HEAD
jekyll build
cd _site
"" >> .nojekyll
git add -A
git commit -m "commit($lastcommit)"
git push origin master
cd .. | mvsouza/mvsouza.github.io | buildCommitSite.ps1 | PowerShell | mit | 146 |
function Import-XLSX {
<#
.SYNOPSIS
Import data from Excel
.DESCRIPTION
Import data from Excel
.PARAMETER Path
Path to an xlsx file to import
.PARAMETER Sheet
Index or name of Worksheet to import
.PARAMETER Header
Replacement headers. Must match order and count of your data's properties.
.PARAMETER FirstRowIsData
Indicates that the first row is data, not headers. Must be used with -Header.
.EXAMPLE
Import-XLSX -Path "C:\Excel.xlsx"
#Import data from C:\Excel.xlsx
.EXAMPLE
Import-XLSX -Path "C:\Excel.xlsx" -Header One, Two, Five
# Import data from C:\Excel.xlsx
# Replace headers with One, Two, Five
.EXAMPLE
Import-XLSX -Path "C:\Excel.xlsx" -Header One, Two, Five -FirstRowIsData -Sheet 2
# Import data from C:\Excel.xlsx
# Assume first row is data
# Use headers One, Two, Five
# Pull from sheet 2 (sheet 1 is default)
.NOTES
Thanks to Doug Finke for his example:
https://github.com/dfinke/ImportExcel/blob/master/ImportExcel.psm1
Thanks to Philip Thompson for an expansive set of examples on working with EPPlus in PowerShell:
https://excelpslib.codeplex.com/
.LINK
https://github.com/RamblingCookieMonster/PSExcel
.FUNCTIONALITY
Excel
#>
[cmdletbinding()]
param(
[parameter( Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[validatescript({Test-Path $_})]
[string[]]$Path,
$Sheet = 1,
[string[]]$Header,
[switch]$FirstRowIsData
)
Process
{
foreach($file in $path)
{
#Resolve relative paths... Thanks Oisin! http://stackoverflow.com/a/3040982/3067642
$file = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($file)
write-verbose "target excel file $($file)"
Try
{
$xl = New-Object OfficeOpenXml.ExcelPackage $file
$workbook = $xl.Workbook
}
Catch
{
Write-Error "Failed to open '$file':`n$_"
continue
}
Try
{
if( @($workbook.Worksheets).count -eq 0)
{
Throw "No worksheets found"
}
else
{
$worksheet = $workbook.Worksheets[$Sheet]
$dimension = $worksheet.Dimension
$Rows = $dimension.Rows
$Columns = $dimension.Columns
}
}
Catch
{
Write-Error "Failed to gather Worksheet '$Sheet' data for file '$file':`n$_"
continue
}
$RowStart = 2
if($Header -and $Header.count -gt 0)
{
if($Header.count -ne $Columns)
{
Write-Error "Found '$columns' columns, provided $($header.count) headers. You must provide a header for every column."
}
if($FirstRowIsData)
{
$RowStart = 1
}
}
else
{
$Header = @( foreach ($Column in 1..$Columns)
{
$worksheet.Cells.Item(1,$Column).Value
} )
}
[string[]]$SelectedHeaders = @( $Header | select -Unique )
Write-Verbose "Found $(($RowStart..$Rows).count) rows, $Columns columns, with headers:`n$($Headers | Out-String)"
foreach ($Row in $RowStart..$Rows)
{
$RowData = @{}
foreach ($Column in 0..($Columns - 1) )
{
$Name = $Header[$Column]
$Value = $worksheet.Cells.Item($Row, ($Column+1)).Value
Write-Debug "Row: $Row, Column: $Column, Name: $Name, Value = $Value"
#Handle dates, they're too common to overlook... Could use help, not sure if this is the best regex to use?
$Format = $worksheet.Cells.Item($Row, ($Column+1)).style.numberformat.format
if($Format -match '\w{1,4}/\w{1,2}/\w{1,4}( \w{1,2}:\w{1,2})?')
{
Try
{
$Value = [datetime]::FromOADate($Value)
}
Catch
{
Write-Verbose "Error converting '$Value' to datetime"
}
}
if($RowData.ContainsKey($Name) )
{
Write-Warning "Duplicate header for '$Name' found, with value '$Value', in row $Row"
}
else
{
$RowData.Add($Name, $Value)
}
}
New-Object -TypeName PSObject -Property $RowData | Select -Property $SelectedHeaders
}
$xl.Dispose()
$xl = $null
}
}
} | Samnor/Sheet-Conqueror | Modules/PSExcel/1.0/Import-XLSX.ps1 | PowerShell | mit | 5,392 |
$drives = Get-WmiObject win32_PerfFormattedData_PerfDisk_PhysicalDisk | ?{$_.name -ne "_Total"} | Select Name
$idx = 1
write-host "{"
write-host " `"data`":[`n"
foreach ($perfDrives in $drives)
{
if ($idx -lt $drives.Count)
{
$line= "{ `"{#DISKNUMLET}`" : `"" + $perfDrives.Name + "`" },"
write-host $line
}
elseif ($idx -ge $drives.Count)
{
$line= "{ `"{#DISKNUMLET}`" : `"" + $perfDrives.Name + "`" }"
write-host $line
}
$idx++;
}
write-host
write-host " ]"
write-host "}" | WZQ1397/zabbix | windows/windows/get_pdisks.ps1 | PowerShell | mit | 526 |
function Prepare-SAN-LUN-Detach-Remove {
<#
.Synopsis
This script creates batch files for remove of VMware datastores from ESXi hosts
.DESCRIPTION
This Script supports in the process of unmount/detach of SAN Luns from VMware ESXi hosts.
As this has to be done very, very carefully, this task is not fully automated.
Instead of this, this script provides 3 files that can be executed step-by-step,
even partially
The complete Process, abreviated, is as follows:
1.) Make sure DS to be removed is not in use by VMs, Snapshots, or as coredump destination
From now, this script will support You in the next steps:
2.) The datastore(s) to be selected for remove
- can be contained in a Datastorecluster (all DS will be removed)
- a single DS
- multiple DS under a Folder ( this makes sense if You want remove only a couple DS from a cluster )
Run this Script in the propriate way for the previous options
The Script generates 3 different files in a work dir:
$($FILEPREFIX)_UNMAP_VSPHERE_SAN_LUNs.txt
$($FILEPREFIX)_DETACH_VSPHERE_SAN_LUNs.txt
$($FILEPREFIX)_REMOVE_VSPHERE_SAN_LUNs.txt
3.) Move Datastores to be removed out of a Datastore Cluster
Execute $($FILEPREFIX)_UNMAP_VSPHERE_SAN_LUNs.txt
or:
Disable Storage IO Control using vSphere Web-Client (if necessary)
Unmount Datastore(s) from all ESXi Hosts using vSphere Web-Client
Delete Datastore(s) using vSphere Web-Client
4.) OPTIONAL TESTING FROM ESXi host commands:
Pickout 1 ESXi Server on which You want to test this.
Put this server into maintenance mode. That avoids, if something does not fit, your VMs don't loose their storage
Execute only this part from the scripts that is intend to be executed for this particulary ESXi host
After this, check, if everything was done as foreseen
5.) Execute Script #2
that sets all the required Datastores to be removed to "Offline"
6.) In coordination with your storage admin team remove access to those LUNs from your Storage array
7.) Execute Script #3
that removes all the required Datastores from all ESXi hosts
8.) Rescan All HBAs from all ESXi Hosts
.NOTES
Source: Robert Ebneth
Release: 1.2
Date: July, 12th, 2017
.LINK
For a complete explaination of Detach/Remove of SAN Luns from ESXi hosts see VMware KB2004605 and KB2032893 articles.
https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2004605
https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2032893
For this Script see
http://github.com/rebneth/RobertEbneth.VMware.vSphere.Automation
.EXAMPLE
Prepare-SAN-LUN-Detach-Remove F <Foldername that contains DS to be removed> -CLUSTER <vSphere Host Cluster> -OUTPUTDIR <DEFAULT: LOCATION of Script>
.EXAMPLE
Prepare-SAN-LUN-Detach-Remove DS <Datastorename> -CLUSTER <vSphere Host Cluster> -OUTPUTDIR <DEFAULT: LOCATION of Script>
.EXAMPLE
Prepare-SAN-LUN-Detach-Remove DSC <ALL DS from DatastoreCluster> -CLUSTER <vSphere Host Cluster> -OUTPUTDIR <DEFAULT: LOCATION of Script>
#>
[CmdletBinding()]
[OutputType([int])]
Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName=$false, Position = 0,
HelpMessage = "Enter Name of vCenter Datacenter")]
[ValidateNotNullOrEmpty()]
[ValidateSet("DSC", "DS", "F")]
[string]$MODE,
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName=$false, Position = 1,
HelpMessage = "Enter Datastore/DatastoreCluster/Folder with Datastores to be removed")]
[string]$MODEPARAMETER,
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName=$false, Position = 2,
HelpMessage = "Enter Name of vCenter Datacenter")]
[string]$CLUSTER,
[Parameter(Mandatory = $false, ValueFromPipelineByPropertyName=$false, Position = 3,
HelpMessage = "Enter Name of vCenter Datacenter")]
[string]$OUTPUTDIR
)
Begin
{
}
Process
{
if ( !$OUTPUTDIR ) { $WORK_DIR = Get-Location }
else { $WORK_DIR = $OUTPUTDIR }
$PathValid = Test-Path -Path "$WORK_DIR" -IsValid -ErrorAction Stop
If ( $PathValid -eq $false ) { break}
# Check and if not loaded add Powershell core module
if ( !(Get-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) ) {
Import-Module VMware.VimAutomation.Core
}
if ($ESXiCredential) {Remove-Variable ESXiCredential}
#$ESXiCredential = Get-Credential -Message "Please Enter root password for all ESXi servers" -UserName root
# pseudo, will be set in batchfile
$ESXiCredential = ""
if ($MODE -eq "DS" ) {
[ARRAY]$ALL_DS_TO_REMOVE = Get-Datastore -Name "$MODEPARAMETER"
If ( !$? ) { break}
}
if ($MODE -eq "DSC" ) {
[ARRAY]$ALL_DS_TO_REMOVE = Get-DatastoreCluster -Name "$MODEPARAMETER" | Get-Datastore # | get-view | select Name,@{n='wwn';e={$_.Info.Vmfs.Extent[0].DiskName}}
If ( !$? ) { break}
}
if ($MODE -eq "F" ) {
[ARRAY]$ALL_DS_TO_REMOVE = Get-Folder -Name "$MODEPARAMETER" | Get-Datastore #| get-view | select Name,@{n='wwn';e={$_.Info.Vmfs.Extent[0].DiskName}}
If ( !$? ) { break}
}
$ALL_CLUSTER_HOSTS = Get-Cluster -Name $CLUSTER | Get-VMHost | Sort Name
If ( !$? ) { break}
# Now we start creating the outputfiles
$FILEPREFIX = $CLUSTER
$OUTPUTFILE1 = "$($WORK_DIR)\$($FILEPREFIX)_DETACH_VSPHERE_SAN_LUNs.txt"
$OUTPUTFILE2 = "$($WORK_DIR)\$($FILEPREFIX)_REMOVE_VSPHERE_SAN_LUNs.txt"
$OUTPUTFILE3 = "$($WORK_DIR)\$($FILEPREFIX)_UNMAP_VSPHERE_SAN_LUNs.txt"
foreach ( $FILE in "$OUTPUTFILE1","$OUTPUTFILE2","$OUTPUTFILE3" ) {
if ((Test-Path $FILE ) -eq $True)
{Remove-Item $FILE }
Write-Host "Creating File ${FILE}..."
New-Item $FILE -type file | out-null}
# Beginn each of both output files with a string that prompts for the ESXi credentials for esxcli commands
# This credentials will be taken for each ESXi host (if multiple) and has to be the same on each host
# Set Storage IO Control to disabled
$string = '$VCCredential = Get-Credential -Message "Please Enter Admin Account for vCenter' + $VCSERVER + '"'
Write-Host $string
Add-Content $OUTPUTFILE3 $string
$string = "connect-viserver -Server $($VCSERVER) -Protocol https -Credential " + '$VCCredential' + " | Out-Null"
Write-Host $string
Add-Content $OUTPUTFILE3 $string
Add-Content $OUTPUTFILE3 "############################################################"
Add-Content $OUTPUTFILE3 "# Disable Storage IO Control on Datastore(s) to be removed #"
Add-Content $OUTPUTFILE3 "############################################################"
foreach ($DS in $ALL_DS_TO_REMOVE) {
$string = "Set-Datastore -Datastore $($DS.Name) -StorageIOControlEnabled " + '$false'
Write-Host $string
Add-Content $OUTPUTFILE3 $string
}
Add-Content $OUTPUTFILE3 "##################################################"
Add-Content $OUTPUTFILE3 "# Umount Datastore(s) from affected ESXi Host(s) #"
Add-Content $OUTPUTFILE3 "##################################################"
foreach ($DS in $ALL_DS_TO_REMOVE) {
$hostviewDSDiskName = $DS.ExtensionData.Info.vmfs.extent[0].Diskname
if ($DS.ExtensionData.Host) {
$attachedHosts = $DS.ExtensionData.Host
$string = "# Set Datastore removed from Hosts..."
Write-Host $string
Add-Content $OUTPUTFILE3 $string
$CMD = '$Datastore = Get-Datastore '+$DS.Name
Write-Host $CMD
Add-Content $OUTPUTFILE3 $CMD
Foreach ($VMHost in $attachedHosts) {
$MOUNTHOST = Get-VMHost -Id $VMHost.Key
$string = "# Unmounting VMFS Datastore $($DS.Name) from host $($MOUNTHOST)..."
Write-Host $string
Add-Content $OUTPUTFILE3 $string
$CMD = '$VMHost = Get-VMHost '+$MOUNTHOST
Write-Host $CMD
Add-Content $OUTPUTFILE3 $CMD
$CMD = '$hostview = Get-View $VMHost.Id'
$CMD
#Write-Host $CMD
Add-Content $OUTPUTFILE3 $CMD
$CMD = '$StorageSys = Get-View $HostView.ConfigManager.StorageSystem'
Write-Host $CMD
Add-Content $OUTPUTFILE3 $CMD
$CMD = '$StorageSys.UnmountVmfsVolume($Datastore.ExtensionData.Info.vmfs.uuid)'
Write-Host $CMD
Add-Content $OUTPUTFILE3 $CMD
}
}
}
#$string = "disconnect-viserver -Server $($VCSERVER) -Force -Confirm:" + '$False' + " | Out-Null"
#Write-Host $string
Add-Content $OUTPUTFILE3 $string
Add-Content $OUTPUTFILE1 "##########################################################################"
Add-Content $OUTPUTFILE1 "### Make sure that all Datastores/SAN Luns to be removed are unmounted ###"
Add-Content $OUTPUTFILE1 "##########################################################################"
Add-Content $OUTPUTFILE2 "######################################################################################"
Add-Content $OUTPUTFILE2 "### Make sure that all ESXi Hosts do not have access to all SUN Luns to be removed ###"
Add-Content $OUTPUTFILE2 "######################################################################################"
#$string = '$ESXiCredential = Get-Credential -Message "Please Enter root password for all ESXi servers" -UserName root'
#Write-Host $string
Add-Content $OUTPUTFILE1 $string
Add-Content $OUTPUTFILE2 $string
foreach ( $single_host in $ALL_CLUSTER_HOSTS ) {
write-Host "#"
write-Host "# Remove LUNs from Host $single_host"
write-Host "#"
#$string = '$ESXiCredential = Get-Credential -Message "Please Enter root password for ESXi server $single_host" -UserName root'
#$string = $string + "connect-viserver -Server $($single_host) $ESXiSERVER -Protocol https -Credential " + '$ESXiCredential' + " | Out-Null"
#$string = $string + "`r`n" + '$esxcli = Get-EsxCli -VMHost ' + $($single_host)
#Write-Host $string
Add-Content $OUTPUTFILE1 $string
Add-Content $OUTPUTFILE2 $string
# Now we fillup the file #1 with commands to set SAN Lun offline
foreach ( $DS_TO_REMOVE in $ALL_DS_TO_REMOVE ) {
# we have to generate a string like # $esxcli.storage.core.device.set($null, "naa.60000970000295700331533032384431", $null, $null, $null, $null, $null, $null, "off")
# $esxcli.storage.core.device.set($null, $null, "naa.68fc61463c5fa6dfd67c15a1b7055039", $null, $null, $null, $null, $null, $null, $null, $null, $null, "off", $null)
write-Host "# Permanently remove SAN LUN for Datastore $($DS_TO_REMOVE.Name)"
#$string = '$esxcli.storage.core.device.set($null, "' + "$($DS_TO_REMOVE.ExtensionData.Info.vmfs.extent[0].diskname)" +'", $null, $null, $null, $null, $null, $null, "off")'
$string = '$esxcli.storage.core.device.set($null, $null, "' + "$($DS_TO_REMOVE.ExtensionData.Info.vmfs.extent[0].diskname)" +'", $null, $null, $null, $null, $null, $null, $null, $null, $null, "off", $null)'
Write-Host $string
Add-Content $OUTPUTFILE1 $string
}
# Now we fillup the file #1 with commands to remove/detach SAN Lun
foreach ( $DS_TO_REMOVE in $ALL_DS_TO_REMOVE ) {
# we have to generate a string like # $esxcli.storage.core.device.detached.remove("naa.60000970000295700331533032384431")
# we have to generate a string like # $esxcli.storage.core.device.detached.remove($null, "naa.60000970000295700331533032384431")
write-Host "# Detach SAN LUN for Datastore $($DS_TO_REMOVE.Name)"
#$string = '$esxcli.storage.core.device.detached.remove("' + "$($DS_TO_REMOVE.ExtensionData.Info.vmfs.extent[0].diskname)" + '")'
$string = '$esxcli.storage.core.device.detached.remove($null, "' + "$($DS_TO_REMOVE.ExtensionData.Info.vmfs.extent[0].diskname)" + '")'
write-Host $string
Add-Content $OUTPUTFILE2 $string
}
$string = '$esxcli.storage.core.device.detached.list()'
Write-Host $string
Add-Content $OUTPUTFILE2 $string
#$string = "disconnect-viserver -Server $($single_host) -Force -Confirm:" + '$False' + " | Out-Null"
#Write-Host $string
Add-Content $OUTPUTFILE1 $string
Add-Content $OUTPUTFILE2 $string
Write-Host ""
}
}
End
{
}
}
# Disconnect-VIServer -Server $VCSERVER -Force -Confirm:$False | Out-Null
# SIG # Begin signature block
# MIIFmgYJKoZIhvcNAQcCoIIFizCCBYcCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUyihEkM3nuMpQiMlLTYitdM71
# ZfOgggMmMIIDIjCCAgqgAwIBAgIQPWSBWJqOxopPvpSTqq3wczANBgkqhkiG9w0B
# AQUFADApMScwJQYDVQQDDB5Sb2JlcnRFYm5ldGhJVFN5c3RlbUNvbnN1bHRpbmcw
# HhcNMTcwMjA0MTI0NjQ5WhcNMjIwMjA1MTI0NjQ5WjApMScwJQYDVQQDDB5Sb2Jl
# cnRFYm5ldGhJVFN5c3RlbUNvbnN1bHRpbmcwggEiMA0GCSqGSIb3DQEBAQUAA4IB
# DwAwggEKAoIBAQCdqdh2MLNnST7h2crQ7CeJG9zXfPv14TF5v/ZaO8yLmYkJVsz1
# tBFU5E1aWhTM/fk0bQo0Qa4xt7OtcJOXf83RgoFvo4Or2ab+pKSy3dy8GQ5sFpOt
# NsvLECxycUV/X/qpmOF4P5f4kHlWisr9R6xs1Svf9ToktE82VXQ/jgEoiAvmUuio
# bLLpx7/i6ii4dkMdT+y7eE7fhVsfvS1FqDLStB7xyNMRDlGiITN8kh9kE63bMQ1P
# yaCBpDegi/wIFdsgoSMki3iEBkiyF+5TklatPh25XY7x3hCiQbgs64ElDrjv4k/e
# WJKyiow3jmtzWdD+xQJKT/eqND5jHF9VMqLNAgMBAAGjRjBEMBMGA1UdJQQMMAoG
# CCsGAQUFBwMDMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQUXJLKHJBzYZdTDg9Z
# QMC1/OLMbxUwDQYJKoZIhvcNAQEFBQADggEBAGcRyu0x3vL01a2+GYU1n2KGuef/
# 5jhbgXaYCDm0HNnwVcA6f1vEgFqkh4P03/7kYag9GZRL21l25Lo/plPqgnPjcYwj
# 5YFzcZaCi+NILzCLUIWUtJR1Z2jxlOlYcXyiGCjzgEnfu3fdJLDNI6RffnInnBpZ
# WdEI8F6HnkXHDBfmNIU+Tn1znURXBf3qzmUFsg1mr5IDrF75E27v4SZC7HMEbAmh
# 107gq05QGvADv38WcltjK1usKRxIyleipWjAgAoFd0OtrI6FIto5OwwqJxHR/wV7
# rgJ3xDQYC7g6DP6F0xYxqPdMAr4FYZ0ADc2WsIEKMIq//Qg0rN1WxBCJC/QxggHe
# MIIB2gIBATA9MCkxJzAlBgNVBAMMHlJvYmVydEVibmV0aElUU3lzdGVtQ29uc3Vs
# dGluZwIQPWSBWJqOxopPvpSTqq3wczAJBgUrDgMCGgUAoHgwGAYKKwYBBAGCNwIB
# DDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEE
# AYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUx/htlS9oRnJU
# wSRbn9ok4H+t5wMwDQYJKoZIhvcNAQEBBQAEggEAJFL7oPQU1gIqhjkVhXkm4TsD
# z4MUOeTFfdAif4YHEEu9h/yw3uXe6ZuZEA4F0dVF8VYqQ/fKej7jz0cttmdSg0we
# TmZqavg6dgwSIfChavTUetkRmfAMorr2g62vO/d9JR3FfMxodSOx94JABer2u+qJ
# Ntq9xWBUWW5TbYRjp1EtNO2RcuysWP2boJ3bxRddIuXK40T2OKo8QfbioCWXnAoG
# r08Dc0SzNcV6bNfMoDwaa1nb9t9rzXWcWxjZJxyMd9epqz/s6K080TMSdW4ae6Xk
# Qh5YBJKJZrgser2zQPD+i9jBm5OZUzGAbro9LS0wXrFCDvzZQNY1CU9aMbxUow==
# SIG # End signature block
| rebneth/RobertEbneth.VMware.vSphere.Automation | Prepare-SAN-Lun-Detach.ps1 | PowerShell | mit | 14,795 |
Import-Module ActiveDirectory
$users = Import-Csv -Path C:\ScriptSources\AD_Update0215.csv
foreach ($user in $users)
{
$Manager = (get-aduser -filter "Userprincipalname -eq '$($user.Manager)'")
Get-ADUser -Filter "Userprincipalname -eq '$($user.Upn)'" -SearchBase "OU=CAH_Users,DC=colonyah,DC=local" | Set-ADUser -Title $($user.Title) -Manager $Manager -EmployeeID $($user.EmployeeID) -MobilePhone
}
-Company "Colony Starwood" -Office $($user.Office) -StreetAddress $($user.Address)
$users = Import-Csv -Path C:\ScriptSources\smart_Search_Results.csv
foreach ($user in $users)
{
$SAM = $User.'Username'
Get-ADUser $SAM | Set-ADUser -MobilePhone $($user.CellNumber)
}
#Dump Data
Get-ADUser -Filter * -Properties Displayname, Title, Office, Officephone, MobilePhone, userprincipalname, Department, Givenname -SearchBase "OU=CAH_Users,DC=colonyah,DC=local" |
Select-Object Displayname, Title, Department, Office, Officephone, MobilePhone, userprincipalname, Givenname, @{Name='Manager';Expression={(get-aduser (get-aduser $_ -Properties manager).manager).name}}, samaccountname |
Export-Csv C:\ScriptOutput\ADPull$((Get-Date).ToString('MM-dd-yyyy')).csv
Get-ADUser -Filter * -Properties Displayname, Title, Office, Officephone, MobilePhone, userprincipalname, Department, givenname -SearchBase "OU=CAH_Users,DC=colonyah,DC=local" |
Select-Object Displayname, givenname, Title, Department, Office, Officephone, MobilePhone, userprincipalname, @{Name='Manager';Expression={(get-aduser (get-aduser $_ -Properties manager).manager).name}}, samaccountname |
Export-Csv C:\ScriptOutput\ADPull$((Get-Date).ToString('MM-dd-yyyy')).csv
Get-ADUser -Filter * -Properties EmployeeID, Displayname, Title, Office, Officephone, MobilePhone, userprincipalname, Department, givenname -SearchBase "OU=CAH_Users,DC=colonyah,DC=local" |
Select-Object EmployeeID, Displayname, givenname, Title, Department, Office, Officephone, MobilePhone, userprincipalname, @{Name='Manager';Expression={(get-aduser (get-aduser $_ -Properties manager).manager).name}}, samaccountname |
Export-Csv C:\ScriptOutput\ADPull$((Get-Date).ToString('MM-dd-yyyy')).csv
| EmpressDeIT/PowerShell | ISE_Tabs/AD_BulkUpdate&Report.ps1 | PowerShell | mit | 2,284 |
# Helper script for those who want to run psake without importing the module.
# Example run from PowerShell:
# .\psake.ps1 "default.ps1" "BuildHelloWord" "4.0"
# Must match parameter definitions for psake.psm1/invoke-psake
# otherwise named parameter binding fails
param(
[Parameter(Position=0,Mandatory=0)]
[string]$buildFile,
[Parameter(Position=1,Mandatory=0)]
[string[]]$taskList = @(),
[Parameter(Position=2,Mandatory=0)]
[string]$framework,
[Parameter(Position=3,Mandatory=0)]
[switch]$docs = $false,
[Parameter(Position=4,Mandatory=0)]
[System.Collections.Hashtable]$parameters = @{},
[Parameter(Position=5, Mandatory=0)]
[System.Collections.Hashtable]$properties = @{},
[Parameter(Position=6, Mandatory=0)]
[alias("init")]
[scriptblock]$initialization = {},
[Parameter(Position=7, Mandatory=0)]
[switch]$nologo = $false,
[Parameter(Position=8, Mandatory=0)]
[switch]$help = $false,
[Parameter(Position=9, Mandatory=0)]
[string]$scriptPath,
[Parameter(Position=10,Mandatory=0)]
[switch]$detailedDocs = $false
)
# setting $scriptPath here, not as default argument, to support calling as "powershell -File psake.ps1"
if (!$scriptPath) {
$scriptPath = $(Split-Path -parent $MyInvocation.MyCommand.path)
}
# '[p]sake' is the same as 'psake' but $Error is not polluted
remove-module [p]sake
import-module (join-path $scriptPath psake\psake.psm1)
if ($help) {
Get-Help Invoke-psake -full
return
}
Remove-Module [B]uild
Import-Module (Join-Path $scriptPath Build.psm1)
Remove-Module [P]ublish
Import-Module (Join-Path $scriptPath Publish.psm1)
if ($buildFile -and (-not(test-path $buildFile))) {
$absoluteBuildFile = (join-path $scriptPath $buildFile)
if (test-path $absoluteBuildFile) {
$buildFile = $absoluteBuildFile
}
}
Invoke-psake $buildFile $taskList $framework $docs $parameters $properties $initialization $nologo $detailedDocs
| khaos-one/sakebuild | content/SakeBuild.ps1 | PowerShell | mit | 1,965 |
function Set-GitHubToken {
<#
.Synopsis
Internal function that obtains the username and Personal Access Token from the user.
.Notes
Created by Trevor Sullivan <trevor@trevorsullivan.net>
#>
[CmdletBinding()]
param (
)
### Invoke the GitHub Personal Access Token screen
Invoke-Expression -Command 'explorer https://github.com/settings/tokens';
### TODO: Consider using Read-Host to support non-GUI scenarios
$GitHubCredential = Get-Credential -Message 'Please enter your GitHub username and Personal Access Token. Visit https://github.com/settings/tokens to obtain a Personal Access Token.' -UserName '<GitHubUsername>';
$TokenPath = '{0}\token.json' -f (Split-Path -Path $MyInvocation.MyCommand.Module.Path -Parent);
@(@{
Username = $GitHubCredential.UserName;
PersonalAccessToken = $GitHubCredential.Password | ConvertFrom-SecureString;
}) | ConvertTo-Json | Out-File -FilePath $TokenPath;
}
| lweniger/PowerShell | Modules/downloaded/powershellgallery/PSGitHub/0.13.9/Functions/Public/Set-GitHubToken.ps1 | PowerShell | mit | 981 |
<#
.SYNOPSIS
script to download all sf package versions to extract .man file into separate directory for parsing sf .etl files
.LINK
[net.servicePointManager]::Expect100Continue = $true;[net.servicePointManager]::SecurityProtocol = [net.SecurityProtocolType]::Tls12;
iwr https://raw.githubusercontent.com/jagilber/powershellScripts/master/serviceFabric/sf-download-cab.ps1 -out $pwd/sf-download-cab.ps1;
./sf-download-cab.ps1
#>
param(
[string]$sfversion,
[switch]$all,
[string]$sfPackageUrl = "https://go.microsoft.com/fwlink/?LinkID=824848&clcid=0x409",
[string]$programDir = "c:\Program Files\Microsoft Service Fabric",
[switch]$force,
[bool]$removeCab = $false,
[string]$outputFolder = $pwd,
[bool]$extract = $true,
[bool]$install = $false
)
$allPackages = @(invoke-restmethod $sfPackageUrl).Packages
if ($sfversion) {
$packages = @($allPackages -imatch $sfversion)
}
elseif (!$all) {
$packages = @($allPackages[-1])
}
if(!$packages) {
write-host ($allPackages | out-string)
write-warning "no packages found for $sfversion"
return
}
$packages
foreach ($package in $packages) {
$package
if ((test-path "$outputFolder\$($package.Version)") -and !$force) {
write-warning "package $($package.Version) exists. use force to download"
continue
}
mkdir "$outputFolder\$($package.Version)"
invoke-webrequest -uri ($package.TargetPackageLocation) -outfile "$outputFolder\$($package.Version).cab"
if($extract -or $install) {
expand "$outputFolder\$($package.Version).cab" -F:* "$outputFolder\$($package.Version)"
}
if ($removeCab) {
remove-item "$outputFolder\$($package.Version).cab" -Force -Recurse
}
}
if($install){
$sfBinDir = "$programDir\bin\Fabric\Fabric.Code"
write-host "Copy-Item `"$outputFolder\$($package.Version)`" $programDir -Recurse -Force"
Copy-Item "$outputFolder\$($package.Version)" $programDir -Recurse -Force
write-host "start-process -Wait -FilePath `"$sfBinDir\FabricSetup.exe`" -ArgumentList `"/operation:install`" -WorkingDirectory $sfBinDir -NoNewWindow"
start-process -Wait -FilePath "$sfBinDir\FabricSetup.exe" -ArgumentList "/operation:install" -WorkingDirectory $sfBinDir -NoNewWindow
} | jagilber/powershellScripts | serviceFabric/sf-download-cab.ps1 | PowerShell | mit | 2,267 |
[CmdletBinding()]
$myPath = Split-Path $script:MyInvocation.MyCommand.Path
$scriptsInOrder = Get-ChildItem ($myPath) -Directory | ForEach-Object { Get-ChildItem (($_.FullName) + "\*.ps1") -Recurse } | Where-Object {!$_.Name.StartsWith("~")} | Sort-Object
$scriptsInOrder | % {
$shortname = $_.Name.Replace(".ps1","")
$longname = $_.FullName.Replace($myPath, "")
$scriptBlock = Get-Content -Path $_ -Raw
Write-Verbose -Message ("Running file: " + $_.FullName)
if ($shortname.StartsWith("_")) {
$script = Get-Content -Path $_ -Raw
if (![String]::IsNullOrWhiteSpace($script)) {
Invoke-Expression (gc $_ -Raw)
}
} else {
& $_.FullName
}
}
Start-Sleep -Seconds 10 | DBHeise/VM_Setup | run.ps1 | PowerShell | mit | 744 |
# culture ="en-US"
ConvertFrom-StringData -StringData @'
AddingType = Adding MIMEType '{0}' for extension '{1}'.
RemovingType = Removing MIMEType '{0}' for extension '{1}'.
TypeExists = MIMEType '{0}' for extension '{1}' is present.
TypeNotPresent = MIMEType '{0}' for extension '{1}' is not present.
VerboseGetTargetPresent = MIMEType is Present.
VerboseGetTargetAbsent = MIMEType is Absent.
'@
| remcoeissing/xWebAdministration | source/DSCResources/MSFT_xIisMimeTypeMapping/en-US/MSFT_xIisMimeTypeMapping.strings.psd1 | PowerShell | mit | 484 |
function Remove-Role {
<#
.SYNOPSIS
Remove a role.
.PARAMETER Name
The name of the role to remove.
.EXAMPLE
!remove-role itsm-modify
#>
[PoshBot.BotCommand(
Aliases = ('rr', 'remove-role'),
Permissions = 'manage-roles'
)]
[cmdletbinding()]
param(
[parameter(Mandatory)]
$Bot,
[parameter(Mandatory, Position = 0)]
[string[]]$Name
)
$removed = @()
$notFound = @()
$failedToRemove = @()
$response = @{
Type = 'Normal'
Text = ''
Title = $null
ThumbnailUrl = $thumb.success
}
# Remove role(s)
foreach ($roleName in $Name) {
if ($r = $Bot.RoleManager.GetRole($roleName)) {
$Bot.RoleManager.RemoveRole($r)
if ($r = $Bot.RoleManager.GetRole($roleName)) {
$failedToRemove += $roleName
} else {
$removed += $roleName
}
} else {
$notFound += $roleName
}
}
# Send success messages
if ($removed.Count -ge 1) {
if ($removed.Count -gt 1) {
$successMessage = 'Roles [{0}] removed.' -f ($removed -join ', ')
} else {
$successMessage = "Role [$removed] removed"
}
$response.Type = 'Normal'
$response.Text = $successMessage
$response.Title = $null
$response.ThumbnailUrl = $thumb.success
}
# Send warning messages
if ($notFound.Count -ge 1) {
if ($notFound.Count -gt 1) {
$warningMessage = 'Roles [{0}] not found :(' -f ($removed -join ', ')
} else {
$warningMessage = "Role [$notFound] not found :("
}
$response.Type = 'Warning'
$response.Text = $warningMessage
$response.Title = $null
$response.ThumbnailUrl = $thumb.rutrow
}
# Send failure messages
if ($failedToRemove.Count -ge 1) {
if ($failedToRemove.Count -gt 1) {
$errMsg = "Roles [{0}] could not be removed. Check logs for more information." -f ($failedToRemove -join ', ')
} else {
$errMsg = "Role [$failedToRemove] could not be created. Check logs for more information."
}
$response.Type = 'Error'
$response.Text = $errMsg
$response.Title = $null
$response.ThumbnailUrl = $thumb.error
}
New-PoshBotCardResponse @response
}
| poshbotio/PoshBot | PoshBot/Plugins/Builtin/Public/Remove-Role.ps1 | PowerShell | mit | 2,468 |
Describe "Issue 828: No NullReferenceExceptionin AlignAssignmentStatement rule when CheckHashtable is enabled" {
It "Should not throw" {
# For details, see here: https://github.com/PowerShell/PSScriptAnalyzer/issues/828
# The issue states basically that calling 'Invoke-ScriptAnalyzer .' with a certain settings file being in the same location that has CheckHashtable enabled
# combined with a script contatining the command '$MyObj | % { @{$_.Name = $_.Value} }' could make it throw a NullReferencException.
$cmdletThrewError = $false
$initialErrorActionPreference = $ErrorActionPreference
$initialLocation = Get-Location
try
{
Set-Location $PSScriptRoot
$ErrorActionPreference = 'Stop'
Invoke-ScriptAnalyzer .
}
catch
{
$cmdletThrewError = $true
}
finally
{
$ErrorActionPreference = $initialErrorActionPreference
Set-Location $initialLocation
}
$cmdletThrewError | Should -BeFalse
}
} | PowerShell/PSScriptAnalyzer | Tests/Engine/SettingsTest/Issue828/Issue828.tests.ps1 | PowerShell | mit | 1,103 |
configuration Sample_cFSRMQuota
{
Import-DscResource -Module cFSRMQuotas
Node $NodeName
{
cFSRMQuota DUsers
{
Path = 'd:\Users'
Description = '5 GB Hard Limit'
Ensure = 'Present'
Size = 5GB
SoftLimit = $False
ThresholdPercentages = @( 85, 100 )
} # End of cFSRMQuota Resource
cFSRMQuotaAction DUsersEmail85
{
Path = 'd:\Users'
Percentage = 85
Ensure = 'Present'
Type = 'Email'
Subject = '[Quota Threshold]% quota threshold exceeded'
Body = 'User [Source Io Owner] has exceed the [Quota Threshold]% quota threshold for quota on [Quota Path] on server [Server]. The quota limit is [Quota Limit MB] MB and the current usage is [Quota Used MB] MB ([Quota Used Percent]% of limit).'
MailBCC = ''
MailCC = 'fileserveradmins@contoso.com'
MailTo = '[Source Io Owner Email]'
DependsOn = "[cFSRMQuota]DUsers"
} # End of cFSRMQuotaAction Resource
cFSRMQuotaAction DUsersEvent85
{
Path = 'd:\Users'
Percentage = 85
Ensure = 'Present'
Type = 'Event'
Body = 'User [Source Io Owner] has exceed the [Quota Threshold]% quota threshold for quota on [Quota Path] on server [Server]. The quota limit is [Quota Limit MB] MB and the current usage is [Quota Used MB] MB ([Quota Used Percent]% of limit).'
EventType = 'Warning'
DependsOn = "[cFSRMQuotaTemplate]DUsers"
} # End of cFSRMQuotaAction Resource
cFSRMQuotaAction DUsersEmail100
{
Path = 'd:\Users'
Percentage = 100
Ensure = 'Present'
Type = 'Email'
Subject = '[Quota Threshold]% quota threshold exceeded'
Body = 'User [Source Io Owner] has exceed the [Quota Threshold]% quota threshold for quota on [Quota Path] on server [Server]. The quota limit is [Quota Limit MB] MB and the current usage is [Quota Used MB] MB ([Quota Used Percent]% of limit).'
MailBCC = ''
MailCC = 'fileserveradmins@contoso.com'
MailTo = '[Source Io Owner Email]'
DependsOn = "[cFSRMQuotaTemplate]DUsers"
} # End of cFSRMQuotaAction Resource
} # End of Node
} # End of Configuration
| PlagueHO/cFSRMQuotas | Examples/Sample_cFSRMQuota.ps1 | PowerShell | mit | 2,419 |
#requires -Version 2.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 Get-HostFileEntry {
<#
.SYNOPSIS
Dumps the HOSTS File to the Console
.DESCRIPTION
Dumps the HOSTS File to the Console
It dumps the WINDIR\System32\drivers\etc\hosts
.EXAMPLE
PS C:\> Get-HostFileEntry
IP Hostname
-- --------
10.211.55.123 GOV13714W7
10.211.55.10 jhwsrv08R2
10.211.55.125 KSWIN07DEV
Description
-----------
Dumps the HOSTS File to the Console
.NOTES
This is just a little helper function to make the shell more flexible
Sometimes I need to know what is set in the HOSTS File...
So I came up with that approach.
.LINK
NET-Experts http://www.net-experts.net
.LINK
Support https://github.com/jhochwald/NETX/issues
#>
[CmdletBinding()]
param ()
BEGIN {
# Cleanup
$HostOutput = @()
# Which File to load
Set-Variable -Name 'HostFile' -Scope Script -Value $($env:windir + '\System32\drivers\etc\hosts')
# REGEX Filter
[regex]$r = '\S'
}
PROCESS {
# Open the File from above
Get-Content -Path $HostFile |
Where-Object -FilterScript {(($r.Match($_)).value -ne '#') -and ($_ -notmatch '^\s+$') -and ($_.Length -gt 0)} |
ForEach-Object -Process {
$null = $_ -match '(?<IP>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(?<HOSTNAME>\S+)'
$HostOutput += New-Object -TypeName PSCustomObject -Property @{
'IP' = $matches.ip
'Hostname' = $matches.hostname
}
}
# Dump it to the Console
Write-Output -InputObject $HostOutput
}
}
# SIG # Begin signature block
# MIIfOgYJKoZIhvcNAQcCoIIfKzCCHycCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUOi+cvDZ8TPA7JrpBWwo19LBO
# hOKgghnLMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw
# VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV
# BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0
# MTMxMDAwMDBaFw0yODAxMjgxMjAwMDBaMFIxCzAJBgNVBAYTAkJFMRkwFwYDVQQK
# ExBHbG9iYWxTaWduIG52LXNhMSgwJgYDVQQDEx9HbG9iYWxTaWduIFRpbWVzdGFt
# cGluZyBDQSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlO9l
# +LVXn6BTDTQG6wkft0cYasvwW+T/J6U00feJGr+esc0SQW5m1IGghYtkWkYvmaCN
# d7HivFzdItdqZ9C76Mp03otPDbBS5ZBb60cO8eefnAuQZT4XljBFcm05oRc2yrmg
# jBtPCBn2gTGtYRakYua0QJ7D/PuV9vu1LpWBmODvxevYAll4d/eq41JrUJEpxfz3
# zZNl0mBhIvIG+zLdFlH6Dv2KMPAXCae78wSuq5DnbN96qfTvxGInX2+ZbTh0qhGL
# 2t/HFEzphbLswn1KJo/nVrqm4M+SU4B09APsaLJgvIQgAIMboe60dAXBKY5i0Eex
# +vBTzBj5Ljv5cH60JQIDAQABo4HlMIHiMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMB
# Af8ECDAGAQH/AgEAMB0GA1UdDgQWBBRG2D7/3OO+/4Pm9IWbsN1q1hSpwTBHBgNV
# HSAEQDA+MDwGBFUdIAAwNDAyBggrBgEFBQcCARYmaHR0cHM6Ly93d3cuZ2xvYmFs
# c2lnbi5jb20vcmVwb3NpdG9yeS8wMwYDVR0fBCwwKjAooCagJIYiaHR0cDovL2Ny
# bC5nbG9iYWxzaWduLm5ldC9yb290LmNybDAfBgNVHSMEGDAWgBRge2YaRQ2XyolQ
# L30EzTSo//z9SzANBgkqhkiG9w0BAQUFAAOCAQEATl5WkB5GtNlJMfO7FzkoG8IW
# 3f1B3AkFBJtvsqKa1pkuQJkAVbXqP6UgdtOGNNQXzFU6x4Lu76i6vNgGnxVQ380W
# e1I6AtcZGv2v8Hhc4EvFGN86JB7arLipWAQCBzDbsBJe/jG+8ARI9PBw+DpeVoPP
# PfsNvPTF7ZedudTbpSeE4zibi6c1hkQgpDttpGoLoYP9KOva7yj2zIhd+wo7AKvg
# IeviLzVsD440RZfroveZMzV+y5qKu0VN5z+fwtmK+mWybsd+Zf/okuEsMaL3sCc2
# SI8mbzvuTXYfecPlf5Y1vC0OzAGwjn//UYCAp5LUs0RGZIyHTxZjBzFLY7Df8zCC
# BJ8wggOHoAMCAQICEhEh1pmnZJc+8fhCfukZzFNBFDANBgkqhkiG9w0BAQUFADBS
# MQswCQYDVQQGEwJCRTEZMBcGA1UEChMQR2xvYmFsU2lnbiBudi1zYTEoMCYGA1UE
# AxMfR2xvYmFsU2lnbiBUaW1lc3RhbXBpbmcgQ0EgLSBHMjAeFw0xNjA1MjQwMDAw
# MDBaFw0yNzA2MjQwMDAwMDBaMGAxCzAJBgNVBAYTAlNHMR8wHQYDVQQKExZHTU8g
# R2xvYmFsU2lnbiBQdGUgTHRkMTAwLgYDVQQDEydHbG9iYWxTaWduIFRTQSBmb3Ig
# TVMgQXV0aGVudGljb2RlIC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
# AoIBAQCwF66i07YEMFYeWA+x7VWk1lTL2PZzOuxdXqsl/Tal+oTDYUDFRrVZUjtC
# oi5fE2IQqVvmc9aSJbF9I+MGs4c6DkPw1wCJU6IRMVIobl1AcjzyCXenSZKX1GyQ
# oHan/bjcs53yB2AsT1iYAGvTFVTg+t3/gCxfGKaY/9Sr7KFFWbIub2Jd4NkZrItX
# nKgmK9kXpRDSRwgacCwzi39ogCq1oV1r3Y0CAikDqnw3u7spTj1Tk7Om+o/SWJMV
# TLktq4CjoyX7r/cIZLB6RA9cENdfYTeqTmvT0lMlnYJz+iz5crCpGTkqUPqp0Dw6
# yuhb7/VfUfT5CtmXNd5qheYjBEKvAgMBAAGjggFfMIIBWzAOBgNVHQ8BAf8EBAMC
# B4AwTAYDVR0gBEUwQzBBBgkrBgEEAaAyAR4wNDAyBggrBgEFBQcCARYmaHR0cHM6
# Ly93d3cuZ2xvYmFsc2lnbi5jb20vcmVwb3NpdG9yeS8wCQYDVR0TBAIwADAWBgNV
# HSUBAf8EDDAKBggrBgEFBQcDCDBCBgNVHR8EOzA5MDegNaAzhjFodHRwOi8vY3Js
# Lmdsb2JhbHNpZ24uY29tL2dzL2dzdGltZXN0YW1waW5nZzIuY3JsMFQGCCsGAQUF
# BwEBBEgwRjBEBggrBgEFBQcwAoY4aHR0cDovL3NlY3VyZS5nbG9iYWxzaWduLmNv
# bS9jYWNlcnQvZ3N0aW1lc3RhbXBpbmdnMi5jcnQwHQYDVR0OBBYEFNSihEo4Whh/
# uk8wUL2d1XqH1gn3MB8GA1UdIwQYMBaAFEbYPv/c477/g+b0hZuw3WrWFKnBMA0G
# CSqGSIb3DQEBBQUAA4IBAQCPqRqRbQSmNyAOg5beI9Nrbh9u3WQ9aCEitfhHNmmO
# 4aVFxySiIrcpCcxUWq7GvM1jjrM9UEjltMyuzZKNniiLE0oRqr2j79OyNvy0oXK/
# bZdjeYxEvHAvfvO83YJTqxr26/ocl7y2N5ykHDC8q7wtRzbfkiAD6HHGWPZ1BZo0
# 8AtZWoJENKqA5C+E9kddlsm2ysqdt6a65FDT1De4uiAO0NOSKlvEWbuhbds8zkSd
# wTgqreONvc0JdxoQvmcKAjZkiLmzGybu555gxEaovGEzbM9OuZy5avCfN/61PU+a
# 003/3iCOTpem/Z8JvE3KGHbJsE2FUPKA0h0G9VgEB7EYMIIFTDCCBDSgAwIBAgIQ
# FtT3Ux2bGCdP8iZzNFGAXDANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJHQjEb
# MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRow
# GAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDEjMCEGA1UEAxMaQ09NT0RPIFJTQSBD
# b2RlIFNpZ25pbmcgQ0EwHhcNMTUwNzE3MDAwMDAwWhcNMTgwNzE2MjM1OTU5WjCB
# kDELMAkGA1UEBhMCREUxDjAMBgNVBBEMBTM1NTc2MQ8wDQYDVQQIDAZIZXNzZW4x
# EDAOBgNVBAcMB0xpbWJ1cmcxGDAWBgNVBAkMD0JhaG5ob2ZzcGxhdHogMTEZMBcG
# A1UECgwQS3JlYXRpdlNpZ24gR21iSDEZMBcGA1UEAwwQS3JlYXRpdlNpZ24gR21i
# SDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK8jDmF0TO09qJndJ9eG
# Fqra1lf14NDhM8wIT8cFcZ/AX2XzrE6zb/8kE5sL4/dMhuTOp+SMt0tI/SON6BY3
# 208v/NlDI7fozAqHfmvPhLX6p/TtDkmSH1sD8AIyrTH9b27wDNX4rC914Ka4EBI8
# sGtZwZOQkwQdlV6gCBmadar+7YkVhAbIIkSazE9yyRTuffidmtHV49DHPr+ql4ji
# NJ/K27ZFZbwM6kGBlDBBSgLUKvufMY+XPUukpzdCaA0UzygGUdDfgy0htSSp8MR9
# Rnq4WML0t/fT0IZvmrxCrh7NXkQXACk2xtnkq0bXUIC6H0Zolnfl4fanvVYyvD88
# qIECAwEAAaOCAbIwggGuMB8GA1UdIwQYMBaAFCmRYP+KTfrr+aZquM/55ku9Sc4S
# MB0GA1UdDgQWBBSeVG4/9UvVjmv8STy4f7kGHucShjAOBgNVHQ8BAf8EBAMCB4Aw
# DAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhCAQEE
# BAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcCARYd
# aHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQwYDVR0fBDwwOjA4oDagNIYy
# aHR0cDovL2NybC5jb21vZG9jYS5jb20vQ09NT0RPUlNBQ29kZVNpZ25pbmdDQS5j
# cmwwdAYIKwYBBQUHAQEEaDBmMD4GCCsGAQUFBzAChjJodHRwOi8vY3J0LmNvbW9k
# b2NhLmNvbS9DT01PRE9SU0FDb2RlU2lnbmluZ0NBLmNydDAkBggrBgEFBQcwAYYY
# aHR0cDovL29jc3AuY29tb2RvY2EuY29tMCMGA1UdEQQcMBqBGGhvY2h3YWxkQGty
# ZWF0aXZzaWduLm5ldDANBgkqhkiG9w0BAQsFAAOCAQEASSZkxKo3EyEk/qW0ZCs7
# CDDHKTx3UcqExigsaY0DRo9fbWgqWynItsqdwFkuQYJxzknqm2JMvwIK6BtfWc64
# WZhy0BtI3S3hxzYHxDjVDBLBy91kj/mddPjen60W+L66oNEXiBuIsOcJ9e7tH6Vn
# 9eFEUjuq5esoJM6FV+MIKv/jPFWMp5B6EtX4LDHEpYpLRVQnuxoc38mmd+NfjcD2
# /o/81bu6LmBFegHAaGDpThGf8Hk3NVy0GcpQ3trqmH6e3Cpm8Ut5UkoSONZdkYWw
# rzkmzFgJyoM2rnTMTh4ficxBQpB7Ikv4VEnrHRReihZ0zwN+HkXO1XEnd3hm+08j
# LzCCBdgwggPAoAMCAQICEEyq+crbY2/gH/dO2FsDhp0wDQYJKoZIhvcNAQEMBQAw
# gYUxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO
# BgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMSswKQYD
# VQQDEyJDT01PRE8gUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEwMDEx
# OTAwMDAwMFoXDTM4MDExODIzNTk1OVowgYUxCzAJBgNVBAYTAkdCMRswGQYDVQQI
# ExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoT
# EUNPTU9ETyBDQSBMaW1pdGVkMSswKQYDVQQDEyJDT01PRE8gUlNBIENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA
# kehUktIKVrGsDSTdxc9EZ3SZKzejfSNwAHG8U9/E+ioSj0t/EFa9n3Byt2F/yUsP
# F6c947AEYe7/EZfH9IY+Cvo+XPmT5jR62RRr55yzhaCCenavcZDX7P0N+pxs+t+w
# gvQUfvm+xKYvT3+Zf7X8Z0NyvQwA1onrayzT7Y+YHBSrfuXjbvzYqOSSJNpDa2K4
# Vf3qwbxstovzDo2a5JtsaZn4eEgwRdWt4Q08RWD8MpZRJ7xnw8outmvqRsfHIKCx
# H2XeSAi6pE6p8oNGN4Tr6MyBSENnTnIqm1y9TBsoilwie7SrmNnu4FGDwwlGTm0+
# mfqVF9p8M1dBPI1R7Qu2XK8sYxrfV8g/vOldxJuvRZnio1oktLqpVj3Pb6r/SVi+
# 8Kj/9Lit6Tf7urj0Czr56ENCHonYhMsT8dm74YlguIwoVqwUHZwK53Hrzw7dPamW
# oUi9PPevtQ0iTMARgexWO/bTouJbt7IEIlKVgJNp6I5MZfGRAy1wdALqi2cVKWlS
# ArvX31BqVUa/oKMoYX9w0MOiqiwhqkfOKJwGRXa/ghgntNWutMtQ5mv0TIZxMOmm
# 3xaG4Nj/QN370EKIf6MzOi5cHkERgWPOGHFrK+ymircxXDpqR+DDeVnWIBqv8mqY
# qnK8V0rSS527EPywTEHl7R09XiidnMy/s1Hap0flhFMCAwEAAaNCMEAwHQYDVR0O
# BBYEFLuvfgI9+qbxPISOre44mOzZMjLUMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB
# Af8EBTADAQH/MA0GCSqGSIb3DQEBDAUAA4ICAQAK8dVGhLeuUbtssk1BFACTTJzL
# 5cBUz6AljgL5/bCiDfUgmDwTLaxWorDWfhGS6S66ni6acrG9GURsYTWimrQWEmla
# jOHXPqQa6C8D9K5hHRAbKqSLesX+BabhwNbI/p6ujyu6PZn42HMJWEZuppz01yfT
# ldo3g3Ic03PgokeZAzhd1Ul5ACkcx+ybIBwHJGlXeLI5/DqEoLWcfI2/LpNiJ7c5
# 2hcYrr08CWj/hJs81dYLA+NXnhT30etPyL2HI7e2SUN5hVy665ILocboaKhMFrEa
# mQroUyySu6EJGHUMZah7yyO3GsIohcMb/9ArYu+kewmRmGeMFAHNaAZqYyF1A4CI
# im6BxoXyqaQt5/SlJBBHg8rN9I15WLEGm+caKtmdAdeUfe0DSsrw2+ipAT71VpnJ
# Ho5JPbvlCbngT0mSPRaCQMzMWcbmOu0SLmk8bJWx/aode3+Gvh4OMkb7+xOPdX9M
# i0tGY/4ANEBwwcO5od2mcOIEs0G86YCR6mSceuEiA6mcbm8OZU9sh4de826g+XWl
# m0DoU7InnUq5wHchjf+H8t68jO8X37dJC9HybjALGg5Odu0R/PXpVrJ9v8dtCpOM
# pdDAth2+Ok6UotdubAvCinz6IPPE5OXNDajLkZKxfIXstRRpZg6C583OyC2mUX8h
# wTVThQZKXZ+tuxtfdDCCBeAwggPIoAMCAQICEC58h8wOk0pS/pT9HLfNNK8wDQYJ
# KoZIhvcNAQEMBQAwgYUxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1h
# bmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBM
# aW1pdGVkMSswKQYDVQQDEyJDT01PRE8gUlNBIENlcnRpZmljYXRpb24gQXV0aG9y
# aXR5MB4XDTEzMDUwOTAwMDAwMFoXDTI4MDUwODIzNTk1OVowfTELMAkGA1UEBhMC
# R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9y
# ZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxIzAhBgNVBAMTGkNPTU9ETyBS
# U0EgQ29kZSBTaWduaW5nIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
# AQEAppiQY3eRNH+K0d3pZzER68we/TEds7liVz+TvFvjnx4kMhEna7xRkafPnp4l
# s1+BqBgPHR4gMA77YXuGCbPj/aJonRwsnb9y4+R1oOU1I47Jiu4aDGTH2EKhe7VS
# A0s6sI4jS0tj4CKUN3vVeZAKFBhRLOb+wRLwHD9hYQqMotz2wzCqzSgYdUjBeVoI
# zbuMVYz31HaQOjNGUHOYXPSFSmsPgN1e1r39qS/AJfX5eNeNXxDCRFU8kDwxRstw
# rgepCuOvwQFvkBoj4l8428YIXUezg0HwLgA3FLkSqnmSUs2HD3vYYimkfjC9G7WM
# crRI8uPoIfleTGJ5iwIGn3/VCwIDAQABo4IBUTCCAU0wHwYDVR0jBBgwFoAUu69+
# Aj36pvE8hI6t7jiY7NkyMtQwHQYDVR0OBBYEFCmRYP+KTfrr+aZquM/55ku9Sc4S
# MA4GA1UdDwEB/wQEAwIBhjASBgNVHRMBAf8ECDAGAQH/AgEAMBMGA1UdJQQMMAoG
# CCsGAQUFBwMDMBEGA1UdIAQKMAgwBgYEVR0gADBMBgNVHR8ERTBDMEGgP6A9hjto
# dHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9SU0FDZXJ0aWZpY2F0aW9uQXV0
# aG9yaXR5LmNybDBxBggrBgEFBQcBAQRlMGMwOwYIKwYBBQUHMAKGL2h0dHA6Ly9j
# cnQuY29tb2RvY2EuY29tL0NPTU9ET1JTQUFkZFRydXN0Q0EuY3J0MCQGCCsGAQUF
# BzABhhhodHRwOi8vb2NzcC5jb21vZG9jYS5jb20wDQYJKoZIhvcNAQEMBQADggIB
# AAI/AjnD7vjKO4neDG1NsfFOkk+vwjgsBMzFYxGrCWOvq6LXAj/MbxnDPdYaCJT/
# JdipiKcrEBrgm7EHIhpRHDrU4ekJv+YkdK8eexYxbiPvVFEtUgLidQgFTPG3UeFR
# AMaH9mzuEER2V2rx31hrIapJ1Hw3Tr3/tnVUQBg2V2cRzU8C5P7z2vx1F9vst/dl
# CSNJH0NXg+p+IHdhyE3yu2VNqPeFRQevemknZZApQIvfezpROYyoH3B5rW1CIKLP
# DGwDjEzNcweU51qOOgS6oqF8H8tjOhWn1BUbp1JHMqn0v2RH0aofU04yMHPCb7d4
# gp1c/0a7ayIdiAv4G6o0pvyM9d1/ZYyMMVcx0DbsR6HPy4uo7xwYWMUGd8pLm1Gv
# TAhKeo/io1Lijo7MJuSy2OU4wqjtxoGcNWupWGFKCpe0S0K2VZ2+medwbVn4bSoM
# fxlgXwyaiGwwrFIJkBYb/yud29AgyonqKH4yjhnfe0gzHtdl+K7J+IMUk3Z9ZNCO
# zr41ff9yMU2fnr0ebC+ojwwGUPuMJ7N2yfTm18M04oyHIYZh/r9VdOEhdwMKaGy7
# 5Mmp5s9ZJet87EUOeWZo6CLNuO+YhU2WETwJitB/vCgoE/tqylSNklzNwmWYBp7O
# SFvUtTeTRkF8B93P+kPvumdh/31J4LswfVyA4+YWOUunMYIE2TCCBNUCAQEwgZEw
# fTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G
# A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxIzAhBgNV
# BAMTGkNPTU9ETyBSU0EgQ29kZSBTaWduaW5nIENBAhAW1PdTHZsYJ0/yJnM0UYBc
# MAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3AgEMMQowCKACgAChAoAAMBkGCSqGSIb3
# DQEJAzEMBgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEV
# MCMGCSqGSIb3DQEJBDEWBBS52LzqWhxWmG2gAIpV4yqrSATUuzANBgkqhkiG9w0B
# AQEFAASCAQCAF5+TIrU3V38qmf5oxxJYnjb5eeWNUxuWvYLKGH2Agfbj/Lqi+i5G
# fA4xQOS+hdjGZOwFt1Ch0RNCGbLrfcIy2xrKzHJabyKZZn758Gicpk1tv/01ZEzs
# rbY0x/IlYMAhzoYfybgE2EkaYeW/2i4IVzqDTdI0zvMy/nLRsZe7lQd/0is5xZGY
# LBmEPIi2lm+98p3QO4Lj6qOEQZoZISzNmE7vXv6qLEkFz5WXtOU7AguDID5RiUag
# Qr4XidclhF6hlSkbmPWfUbR6oQS/nYVDNFbOnv2weGt75NbRPTpaBt0bmlhkjnmh
# y6q4vdMgYgPS7Ysuc9Oe+EBNtKmEIB7XoYICojCCAp4GCSqGSIb3DQEJBjGCAo8w
# ggKLAgEBMGgwUjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt
# c2ExKDAmBgNVBAMTH0dsb2JhbFNpZ24gVGltZXN0YW1waW5nIENBIC0gRzICEhEh
# 1pmnZJc+8fhCfukZzFNBFDAJBgUrDgMCGgUAoIH9MBgGCSqGSIb3DQEJAzELBgkq
# hkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE2MTAxMjEzMTMyNFowIwYJKoZIhvcN
# AQkEMRYEFCwuN0lPlIZnzXo3lRr/uq3S2MYeMIGdBgsqhkiG9w0BCRACDDGBjTCB
# ijCBhzCBhAQUY7gvq2H1g5CWlQULACScUCkz7HkwbDBWpFQwUjELMAkGA1UEBhMC
# QkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExKDAmBgNVBAMTH0dsb2JhbFNp
# Z24gVGltZXN0YW1waW5nIENBIC0gRzICEhEh1pmnZJc+8fhCfukZzFNBFDANBgkq
# hkiG9w0BAQEFAASCAQBXDJ56WVL6pYwvCMh9xt/g5kjEr2prckGgGSaCSFNg4vTW
# FnYpk6qWLY6wUuwUjix9mHXa533Q2Bf9BsvYNbQlUEhKUP0b8PONtgHj+74V96sK
# yFsuLBrsN633DGxn3L9Dl7vsWIFnHLx2jdHeoUU9TIX3ZJEnU3zaaf+4crw4mG7m
# hx24+SbDSX3SQjwNehm5+e07e3Cl/bOVfv1A5d5zxtTLpq2tpkGwA/ZeYSLt3qET
# qAY8F+ou/FUaRt+7mpl0zkoqOsaWk6OR8hLBPOEYSkdFZv6FgQoVS+IMSFC3XCWP
# IEKiXiXdQErOg8pneZ9osByZluvfpH/9rOhP25fL
# SIG # End signature block
| jhochwald/NETX | Profile/functions/Get-HostFileEntry.ps1 | PowerShell | bsd-3-clause | 15,029 |
$package = 'AdobeAIR'
try {
# http://forums.adobe.com/message/4677900
$airInstall = 'Adobe AIR\Versions\1.0'
$airPath = $Env:CommonProgramFiles, ${Env:CommonProgramFiles(x86)} |
% { Join-Path $_ $airInstall } |
? { Test-Path $_ } |
Select -First 1
$airSetup = Join-Path $airPath 'setup.msi'
# http://stackoverflow.com/questions/450027/uninstalling-an-msi-file-from-the-command-line-without-using-msiexec
msiexec.exe /x "`"$airSetup`"" /qb-! REBOOT=ReallySuppress
# alternate -> wmic product where name='Adobe AIR' call uninstall
Remove-Item $airInstall -Recurse -ErrorAction SilentlyContinue
Write-ChocolateySuccess $package
} catch {
Write-ChocolateyFailure $package "$($_.Exception.Message)"
throw
}
| michaelray/Iristyle-ChocolateyPackages | AdobeAIR/tools/chocolateyUninstall.ps1 | PowerShell | mit | 762 |
param($installPath, $toolsPath, $package, $project)
$analyzersFilesBasePath = Join-Path (Split-Path -Path $toolsPath -Parent) "analyzers"
$styleCopDotJsonBasePath = Join-Path $analyzersFilesBasePath "stylecop.json"
$caDictionaryBasePath = Join-Path $analyzersFilesBasePath "dictionary.xml"
$releaseRulesetBasePath = Join-Path $analyzersFilesBasePath "release.ruleset"
$testRulesetBasePath = Join-Path $analyzersFilesBasePath "test.ruleset"
$analyzersFolder = $project.ProjectItems | ?{$_.Name.Contains('.analyzers')}
if ($analyzersFolder -ne $null) {
$analyzersFolder.Delete() | Out-Null
}
$diskFolder = Join-Path (Split-Path -Path $project.FileName -Parent) '.analyzers'
if (Test-Path $diskFolder) {
$resolved = Resolve-Path $diskFolder
Remove-Item $resolved -Recurse
}
| NaosProject/Naos.Build | Analyzers/tools/uninstall.ps1 | PowerShell | mit | 781 |
[CmdletBinding()]
param([switch]$NoNewProcess)
if (!$NoNewProcess) {
# Run the update in a separate process since it requires importing the module.
Write-Host "Launching new process."
& (Get-Command -Name powershell.exe -CommandType Application) -Command ". '$($MyInvocation.MyCommand.Path)' -NoNewProcess"
return
}
function Get-HelpString {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Name,
[switch]$Full)
# Format the help as a string.
$str = Get-Help @PSBoundParameters |
Out-String -Width 110 # This width fits GitHub.
# Split the help string into sections.
$sections = @( )
$section = $null
foreach ($line in $str.Trim().Replace("`r", "").Split("`n")) {
$line = $line.TrimEnd()
$line = $line.Replace("http://go.microsoft.com", "https://go.microsoft.com")
$line = $line.Replace("https:/go.microsoft.com", "https://go.microsoft.com")
# Add the blank line.
if (!$line) {
# Prevent multiple blank lines.
if ($section.Lines[$section.Lines.Count - 1]) { $section.Lines += "" }
continue
# Append the section content line.
} elseif ($line.StartsWith(" ") -and !($isExample = $line -like "*----- EXAMPLE*")) {
$section.Lines += $line
continue
# Append the previous section.
} elseif ($section) {
$sections += $section
}
# Start a new section.
$section = @{ Name = $line ; Lines = @( $line ) }
if ($isExample) { $section.Lines += "" }
}
# Append the last section.
$sections += $section
# Recombine all sections into a single string.
$str = foreach ($section in $sections) {
# Skip specific sections.
if ($section.Name -in "ALIASES", "RELATED LINKS", "REMARKS") { continue }
# Collapse the section into a single string.
$sectionStr = ($section.Lines | Out-String -Width ([int]::MaxValue)).TrimEnd()
# Skip empty sections.
if ($sectionStr -eq $section.Name) { continue }
$sectionStr.TrimEnd() # Output the section as a string.
"" # Output a blank line between sections.
}
($str | Out-String -Width ([int]::MaxValue)).Trim()
}
# If the module is not already imported, then set a flag to remove it at the end of the script.
$removeModule = @(Get-Module -Name VstsTaskSdk).Count -eq 0
# Build the module.
Write-Host "Building the module."
Push-Location -LiteralPath $PSScriptRoot\.. -ErrorAction Stop
try {
& node make.js build
Write-Host "node exited with code '$LASTEXITCODE'"
if ($LASTEXITCODE) {
throw "Build failed."
}
} finally {
Pop-Location
}
# Build a mapping of which functions belong to which files.
Write-Host "Resolving raw function to file mappings."
$rawFunctionToFileMap = @{ }
foreach ($ps1File in Get-ChildItem -LiteralPath $PSScriptRoot\..\VstsTaskSdk -Filter '*.ps1') {
$parseErrors = $null
$tokens = [System.Management.Automation.PSParser]::Tokenize((Get-Content -LiteralPath $ps1File.FullName), [ref]$parseErrors)
if ($parseErrors) {
$OFS = " "
throw "Errors parsing file: $($ps1File.FullName) ; Errors: $parseErrors"
}
for ($i = 0 ; $i -lt $tokens.Count ; $i++) {
$token = $tokens[$i]
if ($token.Type -ne 'Keyword' -or $token.Content -ne 'function') {
continue
}
while (($nextToken = $tokens[++$i]).Type -ne 'CommandArgument') {
# Intentionally empty.
}
$rawFunctionToFileMap[$nextToken.Content] = $ps1File
}
}
# Import the module.
Write-Host "Importing the module."
$module = Import-Module -Name $PSScriptRoot\..\_build\VstsTaskSdk -Force -PassThru -ArgumentList @{ NonInteractive = $true }
# Build a mapping of function name to help text.
Write-Host "Generating help text."
$functionToHelpMap = @{ }
$functionToFullHelpMap = @{ }
foreach ($functionName in $module.ExportedFunctions.Keys) {
if ($functionName -eq 'Out-VstsDefault') { continue }
Write-Host " $functionName"
$rawFunctionName = $functionName.Replace('-Vsts', '-')
$functionToHelpMap[$functionName] = Get-HelpString -Name $functionName
$functionToFullHelpMap[$functionName] = Get-HelpString -Name $functionName -Full
}
# Build a mapping of help sections to functions.
Write-Host "Resolving section information."
$sectionToFunctionsMap = @{ }
foreach ($functionName in $functionToHelpMap.Keys) {
$rawFunctionName = $functionName.Replace('-Vsts', '-')
$ps1File = $rawFunctionToFileMap[$rawFunctionName]
if (!$ps1File) { throw "Raw function to file map not found for function '$functionName'." }
if (!$ps1File.Name.EndsWith('Functions.ps1')) { throw "Unexpected ps1 file name format '$($ps1File.Name)'." }
$rawSectionName = $ps1File.Name.Substring(0, $ps1File.Name.IndexOf('Functions.ps1'))
# Format the section name.
[string]$sectionName = ''
for ($i = 0 ; $i -lt $rawSectionName.Length ; $i++) {
$wasUpper = $false
if ($i -gt 0 -and
[char]::IsUpper($rawSectionName, $i)) {
$sectionName += ' '
$wasUpper = $true
}
$sectionName += $rawSectionName[$i]
if ($i -eq 0 -or $wasUpper) {
# If the next char is the last char, take it too.
# OR if the next two chars are both upper, take the first one too.
while (($i + 1 -eq $rawSectionName.Length - 1) -or
($i + 2 -lt $rawSectionName.Length -and [char]::IsUpper($rawSectionName, $i + 1) -and [char]::IsUpper($rawSectionName, $i + 2)))
{
$sectionName += $rawSectionName[++$i]
}
}
}
# Add the section to the dictionary or update the dictionary record.
if (!$sectionToFunctionsMap.ContainsKey($sectionName)) { $sectionToFunctionsMap[$sectionName] = @( ) }
$sectionToFunctionsMap[$sectionName] += @( $functionName )
}
# Build the Commands markdown content and write the full help files.
Write-Host "Creating markdown files."
$null = [System.IO.Directory]::CreateDirectory("$PSScriptRoot\FullHelp")
Get-ChildItem -LiteralPath $PSScriptRoot\FullHelp -Filter "*" | Remove-Item
[System.Text.StringBuilder]$tocContent = New-Object System.Text.StringBuilder
[System.Text.StringBuilder]$commandsContent = New-Object System.Text.StringBuilder
$null = $tocContent.AppendLine("# Commands (v$($module.Version))")
$null = $tocContent.AppendLine("## <a name=""toc"" />Table of Contents")
foreach ($sectionName in ($sectionToFunctionsMap.Keys | Sort-Object)) {
$functionNames = $sectionToFunctionsMap[$sectionName] | Sort-Object
$sectionId = $sectionName.Replace(" ", "").ToLowerInvariant()
$null = $tocContent.AppendLine("* [$sectionName](#$sectionId)")
$null = $commandsContent.AppendLine("## <a name=""$sectionId"" />$sectionName")
foreach ($functionName in $functionNames) {
$functionId = $functionName.Replace(" ", "").ToLowerInvariant()
$null = $tocContent.AppendLine(" * [$functionName](#$functionId)")
$null = $commandsContent.AppendLine("### <a name=""$functionId"" />$functionName")
$null = $commandsContent.AppendLine("[table of contents](#toc) | [full](FullHelp/$functionName.md)")
$null = $commandsContent.AppendLine('```')
$null = $commandsContent.AppendLine($functionToHelpMap[$functionName])
$null = $commandsContent.AppendLine('```')
# Write the full help file.
Set-Content -LiteralPath $PSScriptRoot\FullHelp\$functionName.md -Value @(
"# $functionName"
"[table of contents](../Commands.md#toc) | [brief](../Commands.md#$functionId)"
'```'
$functionToFullHelpMap[$functionName]
'```'
)
}
}
Set-Content -LiteralPath $PSScriptRoot\Commands.md -Value @(
$tocContent.ToString()
$commandsContent.ToString()
)
# Remove the module.
if ($removeModule) {
Remove-Module -ModuleInfo $module
} | Microsoft/vso-task-lib | powershell/Docs/Update-Docs.ps1 | PowerShell | mit | 8,051 |
$currentPath = Split-Path $MyInvocation.MyCommand.Path
$msbuildFile = Join-Path $currentPath src\VersionTasks.msbuild
& "$(get-content env:windir)\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" $msbuildFile /t:Build
Write-Host "Press any key to continue . . ."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | martinbuberl/VersionTasks | ClickToBuild.ps1 | PowerShell | mit | 316 |
Register-DbaConfigValidation -Name "double" -ScriptBlock {
Param (
$Value
)
$Result = New-Object PSOBject -Property @{
Success = $True
Value = $null
Message = ""
}
try { [double]$number = $Value }
catch {
$Result.Message = "Not a double: $Value"
$Result.Success = $False
return $Result
}
$Result.Value = $number
return $Result
} | SirCaptainMitch/dbatools | internal/configurations/validation/double.ps1 | PowerShell | mit | 429 |
# Originally based on https://github.com/serilog/serilog/blob/dev/Build.ps1 - (c) Serilog Contributors
Push-Location $PSScriptRoot
if(Test-Path .\artifacts) {
echo "build: Cleaning .\artifacts"
Remove-Item .\artifacts -Force -Recurse
}
& dotnet restore --no-cache
$branch = @{ $true = $env:APPVEYOR_REPO_BRANCH; $false = $(git symbolic-ref --short -q HEAD) }[$env:APPVEYOR_REPO_BRANCH -ne $NULL];
$revision = @{ $true = "{0:00000}" -f [convert]::ToInt32("0" + $env:APPVEYOR_BUILD_NUMBER, 10); $false = "local" }[$env:APPVEYOR_BUILD_NUMBER -ne $NULL];
$suffix = @{ $true = ""; $false = "$($branch.Substring(0, [math]::Min(10,$branch.Length)))-$revision"}[$branch -eq "master" -and $revision -ne "local"]
$commitHash = $(git rev-parse --short HEAD)
$buildSuffix = @{ $true = "$($suffix)-$($commitHash)"; $false = "$($branch)-$($commitHash)" }[$suffix -ne ""]
echo "build: Package version suffix is $suffix"
echo "build: Build version suffix is $buildSuffix"
foreach ($src in ls src/*) {
Push-Location $src
echo "build: Packaging project in $src"
& dotnet build -c Release --version-suffix=$buildSuffix
if ($suffix) {
& dotnet pack -c Release --include-source -o ..\..\artifacts --version-suffix=$suffix --no-build
} else {
& dotnet pack -c Release --include-source -o ..\..\artifacts --no-build
}
if($LASTEXITCODE -ne 0) { exit 1 }
Pop-Location
}
foreach ($test in ls test/*.Tests) {
Push-Location $test
echo "build: Testing project in $test"
& dotnet test -c Release
if($LASTEXITCODE -ne 0) { exit 3 }
Pop-Location
}
foreach ($test in ls test/*.PerformanceTests) {
Push-Location $test
echo "build: Building performance test project in $test"
& dotnet build -c Release
if($LASTEXITCODE -ne 0) { exit 2 }
Pop-Location
}
Pop-Location
| nblumhardt/influxdb-lineprotocol | Build.ps1 | PowerShell | apache-2.0 | 1,834 |
$packageName = 'dolphin'
$url = 'http://dl.dolphin-emu.org/builds/dolphin-master-4.0-8137-x64.7z'
$checksum = 'c8b9dcaa72bdbd00c03a2c951680437c32154e1b'
$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" | dtgm/chocolatey-packages | automatic/_output/dolphin/4.0.8137/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 761 |
# generated vars
$packageName = 'antidupl'
$url = 'https://sourceforge.net/projects/antidupl/files/bin/AntiDupl.NET-2.3.6.exe'
$checksum = '31558c2dcb18470803130417c83a2683371feab6'
# static vars
$checksumType = 'sha1'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$rarFile = Join-Path $toolsDir 'antidupl.rar'
# $Env:ChocolateyInstall\helpers\functions
Get-ChocolateyWebFile -PackageName "$packageName" `
-FileFullPath "$rarFile" `
-Url "$url" `
-Checksum "$checksum" `
-ChecksumType "$checksumType"
try {
if (Test-Path "${Env:ProgramFiles(x86)}\7-zip") {
$cmd7z = "${Env:ProgramFiles(x86)}\7-zip\7z.exe"
} elseif (Test-Path "$Env:ProgramFiles\7-zip") {
$cmd7z = "$Env:ProgramFiles\7-zip\7z.exe"
} else {
Write-Warning "7-zip is not installed. Please install 7-zip."
throw
}
Start-Process -FilePath "$cmd7z" -Wait -WorkingDirectory "$toolsDir" -ArgumentList "x $rarFile"
Remove-Item "$rarFile"
} catch {
throw $_.Exception
}
# create empty sidecar so shimgen creates shim for GUI rather than console
$installFile = Join-Path -Path $toolsDir `
-ChildPath "AntiDupl.NET-2.3.6" `
| Join-Path -ChildPath "AntiDupl.NET.exe.gui"
Set-Content -Path $installFile `
-Value $null | dtgm/chocolatey-packages | automatic/_output/antidupl/2.3.6/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 1,374 |
$p = @{
Name = "GistProvider"
NuGetApiKey = $NuGetApiKey
LicenseUri = "https://github.com/dfinke/OneGetGistProvider/blob/master/LICENSE"
Tag = "Gist","Github","PackageManagement","Provider"
ReleaseNote = "Updated to work with rename to PackageManagement"
ProjectUri = "https://github.com/dfinke/OneGetGistProvider"
}
Publish-Module @p | beni55/OneGetGistProvider | PublishToGallery.ps1 | PowerShell | apache-2.0 | 362 |
import-module au
$releases = 'https://www.bennewitz.com/bluefish/stable/binaries/win32/'
$softwareName = 'Bluefish*'
function global:au_BeforeUpdate { Get-RemoteFiles -Purge -NoSuffix }
function global:au_SearchReplace {
@{
".\legal\VERIFICATION.txt" = @{
"(?i)(^\s*location on\:?\s*)\<.*\>" = "`${1}<$releases>"
"(?i)(\s*1\..+)\<.*\>" = "`${1}<$($Latest.URL32)>"
"(?i)(^\s*checksum\s*type\:).*" = "`${1} $($Latest.ChecksumType32)"
"(?i)(^\s*checksum(32)?\:).*" = "`${1} $($Latest.Checksum32)"
}
".\tools\chocolateyInstall.ps1" = @{
"(?i)^(\s*softwareName\s*=\s*)'.*'" = "`${1}'$softwareName'"
"(?i)(^\s*file\s*=\s*`"[$]toolsPath\\).*" = "`${1}$($Latest.FileName32)`""
}
".\tools\chocolateyUninstall.ps1" = @{
"(?i)^(\s*softwareName\s*=\s*)'.*'" = "`${1}'$softwareName'"
}
}
}
function global:au_GetLatest {
$download_page = Invoke-WebRequest -UseBasicParsing -Uri $releases
$re = 'Bluefish-[\d\.]+-setup\.exe$'
$url = $download_page.links | ? href -match $re | select -Last 1 -expand href
$version = $url -split '[-]' | select -Last 1 -Skip 1
$url = if ($url) { $releases + $url } else { $url }
@{
URL32 = $url
Version = $version
}
}
update -ChecksumFor none
| jberezanski/chocolatey-coreteampackages | automatic/bluefish/update.ps1 | PowerShell | apache-2.0 | 1,269 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Describe "Tests for paths of submodules in module manifest" -tags "CI" {
$moduleName = 'ModuleA'
$moduleFileName = "$moduleName.psd1"
$submoduleName = 'ModuleB'
$submoduleFileName = "$submoduleName.psm1"
$moduleRootPath = Join-Path $TestDrive $moduleName
$moduleFilePath = Join-Path $moduleRootPath $moduleFileName
$nestedModulePath = Join-Path $moduleRootPath $submoduleName
$nestedModuleFilePath = Join-Path $nestedModulePath $submoduleFileName
BeforeEach {
Remove-Module $moduleName -Force -ErrorAction SilentlyContinue
Remove-Item $moduleRootPath -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $nestedModulePath
"function TestModuleFunction{'Hello from TestModuleFunction'}" | Out-File $nestedModuleFilePath
}
$testCases = @(
@{ SubModulePath = "$submoduleName" }
@{ SubModulePath = "$submoduleName\$submoduleName" }
@{ SubModulePath = "$submoduleName/$submoduleName" }
@{ SubModulePath = "$submoduleName\$submoduleFileName" }
@{ SubModulePath = "$submoduleName/$submoduleFileName" }
@{ SubModulePath = ".\$submoduleName" }
@{ SubModulePath = ".\$submoduleName\$submoduleName" }
@{ SubModulePath = ".\$submoduleName/$submoduleName" }
@{ SubModulePath = ".\$submoduleName\$submoduleFileName" }
@{ SubModulePath = ".\$submoduleName/$submoduleFileName" }
@{ SubModulePath = "./$submoduleName" }
@{ SubModulePath = "./$submoduleName/$submoduleName" }
@{ SubModulePath = "./$submoduleName\$submoduleName" }
@{ SubModulePath = "./$submoduleName/$submoduleFileName" }
@{ SubModulePath = "./$submoduleName\$submoduleFileName" }
)
It "Test if NestedModule path is <SubModulePath>" -TestCases $testCases {
param($SubModulePath)
New-ModuleManifest $moduleFilePath -NestedModules @($SubModulePath)
Import-Module $moduleFilePath
(Get-Module $moduleName).ExportedCommands.Keys.Contains('TestModuleFunction') | Should -BeTrue
}
It "Test if RootModule path is <SubModulePath>" -TestCases $testCases {
param($SubModulePath)
New-ModuleManifest $moduleFilePath -RootModule $SubModulePath
Import-Module $moduleFilePath
(Get-Module $moduleName).ExportedCommands.Keys.Contains('TestModuleFunction') | Should -BeTrue
}
}
| JamesWTruher/PowerShell-1 | test/powershell/engine/Module/SubmodulePathInManifest.Tests.ps1 | PowerShell | mit | 2,506 |
# Publishes our build assets to nuget, myget, dotnet/versions, etc ..
#
# The publish operation is best visioned as an optional yet repeatable post build operation. It can be
# run anytime after build or automatically as a post build step. But it is an operation that focuses on
# build outputs and hence can't rely on source code from the build being available
#
# Repeatable is important here because we have to assume that publishes can and will fail with some
# degree of regularity.
[CmdletBinding(PositionalBinding=$false)]
Param(
# Standard options
[string]$configuration = "",
[string]$branchName = "",
[string]$releaseName = "",
[switch]$test,
# Credentials
[string]$gitHubUserName = "",
[string]$gitHubToken = "",
[string]$gitHubEmail = "",
[string]$nugetApiKey = "",
[string]$myGetApiKey = ""
)
Set-StrictMode -version 2.0
$ErrorActionPreference="Stop"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
function Get-PublishKey([string]$uploadUrl) {
$url = New-Object Uri $uploadUrl
switch ($url.Host) {
"dotnet.myget.org" { return $myGetApiKey }
"api.nuget.org" { return $nugetApiKey }
default { throw "Cannot determine publish key for $uploadUrl" }
}
}
# Publish the NuGet packages to the specified URL
function Publish-NuGet([string]$packageDir, [string]$uploadUrl) {
Push-Location $packageDir
try {
Write-Host "Publishing $(Split-Path -leaf $packageDir) to $uploadUrl"
$apiKey = Get-PublishKey $uploadUrl
foreach ($package in Get-ChildItem *.nupkg) {
$nupkg = Split-Path -Leaf $package
Write-Host " Publishing $nupkg"
if (-not (Test-Path $nupkg)) {
throw "$nupkg does not exist"
}
if (-not $test) {
Exec-Console $dotnet "nuget push $nupkg --source $uploadUrl --api-key $apiKey"
}
}
}
finally {
Pop-Location
}
}
function Publish-Vsix([string]$uploadUrl) {
Write-Host "Publishing VSIX to $uploadUrl"
$apiKey = Get-PublishKey $uploadUrl
$extensions = [xml](Get-Content (Join-Path $EngRoot "config\PublishVsix.MyGet.config"))
foreach ($extension in $extensions.extensions.extension) {
$vsix = Join-Path $VSSetupDir ($extension.id + ".vsix")
if (-not (Test-Path $vsix)) {
throw "VSIX $vsix does not exist"
}
Write-Host " Publishing '$vsix'"
if (-not $test) {
$response = Invoke-WebRequest -Uri $uploadUrl -Headers @{"X-NuGet-ApiKey"=$apiKey} -ContentType 'multipart/form-data' -InFile $vsix -Method Post -UseBasicParsing
if ($response.StatusCode -ne 201) {
throw "Failed to upload VSIX extension: $vsix. Upload failed with Status code: $response.StatusCode"
}
}
}
}
function Publish-Channel([string]$packageDir, [string]$name) {
$publish = GetProjectOutputBinary "RoslynPublish.exe"
$args = "-nugetDir `"$packageDir`" -channel $name -gu $gitHubUserName -gt $gitHubToken -ge $githubEmail"
Write-Host "Publishing $packageDir to channel $name"
if (-not $test) {
Exec-Console $publish $args
}
}
# Do basic verification on the values provided in the publish configuration
function Test-Entry($publishData, [switch]$isBranch) {
if ($isBranch) {
if ($publishData.nuget -ne $null) {
foreach ($nugetKind in $publishData.nugetKind) {
if ($nugetKind -ne "PerBuildPreRelease" -and $nugetKind -ne "Shipping" -and $nugetKind -ne "NonShipping") {
throw "Branches are only allowed to publish Shipping, NonShipping, or PerBuildPreRelease"
}
}
}
}
}
# Publish a given entry: branch or release.
function Publish-Entry($publishData, [switch]$isBranch) {
Test-Entry $publishData -isBranch:$isBranch
# First publish the NuGet packages to the specified feeds
foreach ($url in $publishData.nuget) {
foreach ($nugetKind in $publishData.nugetKind) {
Publish-NuGet (Join-Path $PackagesDir $nugetKind) $url
}
}
# Next publish the VSIX to the specified feeds
$vsixData = $publishData.vsix
if ($vsixData -ne $null) {
Publish-Vsix $vsixData
}
# Finally get our channels uploaded to versions
foreach ($channel in $publishData.channels) {
foreach ($nugetKind in $publishData.nugetKind) {
Publish-Channel (Join-Path $PackagesDir $nugetKind) $channel
}
}
exit 0
}
try {
if ($configuration -eq "") {
Write-Host "Must provide the build configuration with -configuration"
exit 1
}
. (Join-Path $PSScriptRoot "build-utils.ps1")
$dotnet = Ensure-DotnetSdk
if ($branchName -ne "" -and $releaseName -ne "") {
Write-Host "Can only specify -branchName or -releaseName, not both"
exit 1
}
if ($branchName -ne "") {
$data = GetBranchPublishData $branchName
if ($data -eq $null) {
Write-Host "Branch $branchName not listed for publishing."
exit 0
}
Publish-Entry $data -isBranch:$true
}
elseif ($releaseName -ne "") {
$data = GetReleasePublishData $releaseName
if ($data -eq $null) {
Write-Host "Release $releaseName not listed for publishing."
exit 1
}
Publish-Entry $data -isBranch:$false
}
else {
Write-Host "Need to specify -branchName or -releaseName"
exit 1
}
}
catch {
Write-Host $_
Write-Host $_.Exception
Write-Host $_.ScriptStackTrace
exit 1
}
| abock/roslyn | eng/publish-assets.ps1 | PowerShell | mit | 5,317 |
function Move-BadInstall {
param(
[string] $packageName,
[string] $version = '',
[string] $packageFolder = ''
)
Write-Debug "Running 'Move-BadInstall' for $packageName version: `'$version`', packageFolder:`'$packageFolder`'";
#copy the bad stuff to a temp directory
$badPackageFolder = $badLibPath #Join-Path $badLibPath "$($installedPackageName).$($installedPackageVersion)"
try {
if ([System.IO.Directory]::Exists($badPackageFolder)) {
[System.IO.Directory]::Delete($badPackageFolder,$true) #| out-null
}
[System.IO.Directory]::CreateDirectory($badPackageFolder) | out-null
write-debug "Moving bad package `'$packageName v$version`' to `'$badPackageFolder`'."
#Get-Childitem "$badPackageFolder" -recurse | remove-item
Move-Item $packageFolder $badPackageFolder -force #| out-null
} catch {
Write-Error "Could not move bad package $packageName from `'$packageFolder`' to `'$badPackageFolder`': $($_.Exception.Message)"
}
} | chocolatey/chocolatey | src/functions/Move-BadInstall.ps1 | PowerShell | apache-2.0 | 1,010 |
Param(
#
[ValidateNotNullOrEmpty()]
$ProductId
)
Function Get-TempPassword()
{
Param(
[int] $length=10,
[string[]] $sourcedata
)
For ($loop=1; $loop -le $length; $loop++)
{
$tempPassword+=($sourcedata | GET-RANDOM)
}
return $tempPassword
}
# Ensure Powershell 3 or more is installed.
if ($PSVersionTable.PSVersion.Major -lt 3)
{
Write-Error "Prior to running this artifact, ensure you have Powershell 3 or higher installed."
[System.Environment]::Exit(1)
}
$ascii=$NULL;For ($a=33;$a -le 126;$a++) {$ascii+=,[char][byte]$a }
$userName = "artifactInstaller"
$password = Get-TempPassword -length 43 -sourcedata $ascii
$cn = [ADSI]"WinNT://$env:ComputerName"
# Create user
$user = $cn.Create("User", $userName)
$user.SetPassword($password)
$user.SetInfo()
$user.description = "DevTestLab artifact installer"
$user.SetInfo()
# Add user to the Administrators group
$group = [ADSI]"WinNT://$env:ComputerName/Administrators,group"
$group.add("WinNT://$env:ComputerName/$userName")
$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("$env:COMPUTERNAME\$($username)", $secPassword)
$command = $PSScriptRoot + "\InstallViaWebPICmd.ps1"
$scriptContent = Get-Content -Path $command -Delimiter ([char]0)
$scriptBlock = [scriptblock]::Create($scriptContent)
# Run Chocolatey as the artifactInstaller user
Enable-PSRemoting -Force -SkipNetworkProfileCheck
# Ensure that current process can run scripts.
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force
$exitCode = Invoke-Command -ScriptBlock $scriptBlock -Credential $credential -ComputerName $env:COMPUTERNAME -ArgumentList @($ProductId, $PSScriptRoot)
# Delete the artifactInstaller user
$cn.Delete("User", $userName)
# Delete the artifactInstaller user profile
gwmi win32_userprofile | where { $_.LocalPath -like "*$userName*" } | foreach { $_.Delete() }
exit $exitCode | rnithish/MyOpenGit | DevTestLabs/azure-devtestlab-master/Artifacts/windows-azurepowershell/StartChocolatey.ps1 | PowerShell | mit | 1,997 |
# @$mariadbVer MariaDBVer
# @$arch win32/winx64
# @$installSqlDir specify install.sql dir
Param(
[Parameter(mandatory=$false)][String]$mariadbVersion = $null,
[Parameter(mandatory=$false)][String]$mroongaVersion = $null,
[Parameter(mandatory=$false)][String[]]$platforms = $null
)
. ".\versions.ps1"
if (!$mariadbVersion) {
$mariadbVersion = $mariadbVer
}
if (!$mroongaVersion) {
$mroongaVersion = $mroongaVer
}
if (!$platforms) {
$platforms = "win32", "winx64"
}
cd $workDir
function Wait-UntilRunning($cmdName) {
do
{
$Running = Get-Process $cmdName -ErrorAction SilentlyContinue
Start-Sleep -m 500
} while (!$Running)
}
function Wait-UntilTerminate($cmdName) {
do
{
$Running = Get-Process $cmdName -ErrorAction SilentlyContinue
Start-Sleep -m 500
} while ($Running)
}
function Install-Mroonga($mariadbVer, $arch, $installSqlDir) {
cd "mariadb-$mariadbVer-$arch"
Start-Process .\bin\mysqld.exe
Wait-UntilRunning mysqld
Get-Content "$installSqlDir\install.sql" | .\bin\mysql.exe -uroot
Start-Sleep -m 1000
Start-Process .\bin\mysqladmin.exe -ArgumentList "-uroot shutdown"
Wait-UntilTerminate mysqld
cd ..
}
$installSqlDir = ".\share\mroonga"
foreach ($arch in $platforms)
{
Install-Mroonga $mariadbVersion $arch $installSqlDir
Start-Sleep -m 500
}
cd $originDir
| cosmo0920/PowerShell-for-Mroonga-building | powershell/install-mroonga.ps1 | PowerShell | mit | 1,394 |
$ErrorActionPreference = 'Stop';
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
#Based on NO DETECTION IN PRO
$packageArgs = @{
packageName = $env:ChocolateyPackageName
fileType = 'zip'
validExitCodes= @(0) #please insert other valid exit codes here
url = "https://s3.amazonaws.com/downloads.mirthcorp.com/connect-client-launcher/mirth-administrator-launcher-1.1.0-windows.zip" #download URL, HTTPS preferrred
checksum = '0CC7C85C46AD0D73659A8F759824825DE4FAF62C60A04957410937568AE609EE'
checksumType = 'sha256'
url64bit = "https://s3.amazonaws.com/downloads.mirthcorp.com/connect-client-launcher/mirth-administrator-launcher-1.1.0-windows-x64.zip" # 64bit URL here (HTTPS preferred) or remove - if installer contains both architectures (very rare), use $url
checksum64 = 'AD24DBE341E77229C7F644378992FB2D33FE48A760730DEBDB6914DEB2977D04'
checksumType64= 'sha256'
destination = $toolsDir
}
Install-ChocolateyZipPackage @packageArgs
$files = get-childitem $toolsDir -include *.exe -recurse
foreach ($file in $files) {
if (!($file.Name -eq "launcher.exe")) {
#generate an ignore file
New-Item "$file.ignore" -type file -force | Out-Null
}
} | flcdrg/au-packages | mirth-administrator-launcher.portable/tools/chocolateyinstall.ps1 | PowerShell | mit | 1,244 |
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string] $Itemspec = "$/",
[Parameter(Mandatory=$true)]
[ValidateSet("None", "Full", "OneLevel")]
[string] $Recursion = "None",
[Parameter(Mandatory=$false)]
[ValidateSet("true", "false")]
[string] $DeleteAdds = $false
)
Write-Verbose "Entering script $($MyInvocation.MyCommand.Name)"
Write-Verbose "Parameter Values"
$PSBoundParameters.Keys | %{ Write-Verbose "$_ = $($PSBoundParameters[$_])" }
Write-Verbose "Importing modules"
Import-Module -DisableNameChecking "$PSScriptRoot/vsts-tfvc-shared.psm1"
[string[]] $FilesToUndo = $ItemSpec -split ';|\r?\n'
Write-Output "Undo ItemSpec: $ItemSpec, Recursive: $Recursion, Delete Adds: $DeleteAdds"
Try
{
$provider = Get-SourceProvider
if (-not $provider)
{
return;
}
[array] $ItemSpecs = Convert-ToItemSpecs -Paths $FilesToUndo -RecursionType $Recursion
# Pending any deleted files to ensure they're picked up by Undo.
AutoPend-WorkspaceChanges -Provider $provider -Items @($FilesToUndo) -RecursionType $Recursion -ChangeType "Delete" | Out-Null
Write-Output "Undoing:"
$ItemSpecs | %{ Write-Output $_.Item }
$provider.Workspace.Undo(
@($ItemSpecs),
$true, # updateDisk,
$DeleteAdds -eq $true, # deleteAdds,
@(), # itemAttributeFilters,
@() # itemPropertyFilters
) | Out-Null
}
Finally
{
Invoke-DisposeSourceProvider -Provider $provider
} | jessehouwing/vsts-tfvc-tasks | tf-vc-undo/v1/TfvcUndo.ps1 | PowerShell | mit | 1,572 |
$cmdLets = (Get-Module pscx).ExportedCmdlets.Keys
$functions = (Get-Module pscx).ExportedFunctions.Keys
$cmdLetsAndFunctions = $cmdLets + $functions | Select -uniq | Sort-Object
$nounsAndCommands = @{}
foreach ( $cmdLet in ($cmdLetsAndFunctions) ) {
$noun = $cmdLet.split('-')[1]
if ( ! $noun ) {
continue
}
$description = (get-help $cmdLet).synopsis.replace('PSCX Cmdlet: ','')
# {
# tar: [
# {
# name: 'get-tar'
# description: 'this command does'
# },
# ....
# ],
# ...
# }
$helpEntry = @{'name' = $cmdLet; 'description' = $description;}
if ( ! $nounsAndCommands.ContainsKey($noun) ) {
$nounsAndCommands[$noun] = @()
}
$nounsAndCommands[$noun] += $helpEntry
}
$output = ''
# Now sort by the nouns and spit out the headings and documentation
foreach($item in $nounsAndCommands.GetEnumerator() | Sort Name) {
$noun = $item.Name
$output += @'
### {0}
'@ -f $noun
foreach ($commandNameAndDescription in $nounsAndCommands[$noun]) {
$output += @'
#### `{0}`
{1}
'@ -f $commandNameAndDescription.name, $commandNameAndDescription.description
}
}
echo $output
| Pscx/Pscx | Tools/generate-markdown-docs.ps1 | PowerShell | mit | 1,155 |
#
# Module manifest for module 'AzureRM.Consumption'
#
# Generated by: Microsoft Corporation
#
# Generated on: 4/25/2017
#
@{
# Script module or binary module file associated with this manifest.
# RootModule = ''
# Version number of this module.
ModuleVersion = '0.1.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'd72f2aef-79c8-4119-9fef-36710708712d'
# Author of this module
Author = 'Microsoft Corporation'
# Company or vendor of this module
CompanyName = 'Microsoft Corporation'
# Copyright statement for this module
Copyright = 'Microsoft Corporation. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Microsoft Azure PowerShell - Consumption service cmdlets for Azure Resource Manager'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows 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 = '4.0'
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
CLRVersion = '4.0'
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(@{ModuleName = 'AzureRM.Profile'; ModuleVersion = '2.8.0'; })
# 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 = '.\Microsoft.Azure.Commands.Consumption.Format.ps1xml'
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @('.\Microsoft.Azure.Commands.Consumption.dll')
# 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 = @()
# 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 = 'Get-AzureRmConsumptionUsageDetail'
# 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 = 'Azure','ResourceManager','ARM','Consumption'
# A URL to the license for this module.
LicenseUri = 'https://raw.githubusercontent.com/Azure/azure-powershell/dev/LICENSE.txt'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/Azure/azure-powershell'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'Updated for common code changes'
# 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 = ''
}
| krkhan/azure-powershell | src/ResourceManager/Consumption/AzureRM.Consumption.psd1 | PowerShell | apache-2.0 | 4,340 |
<#
.Synopsis
.\install-scaleiosvm.ps1
.DESCRIPTION
install-scaleiosvm is the a vmxtoolkit solutionpack for configuring and deploying scaleio 2.0 svm´s
Copyright 2014 Karsten Bott
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.
.LINK
http://labbuildr.readthedocs.io/en/master/Solutionpacks///install-scaleiosvm.ps1
.EXAMPLE
.\install-scaleiosvm.ps1 -Sourcedir d:\sources
.EXAMPLE
.\install-scaleiosvm.ps1 -configure -Defaults
This will Install and Configure a 3-Node ScaleIO with default Configuration
.EXAMPLE
.\install-scaleiosvm.ps1 -Defaults -configure -singlemdm
This will Configure a SIO Cluster with 3 Nodes and Single MDM
.EXAMPLE
.\install-scaleiosvm.ps1 -Disks 3 -sds
This will install a Single Node SDS
#>
[CmdletBinding(DefaultParametersetName = "import")]
Param(
### import parameters
<# for the Import, we specify the Path to the Sources.
Sources are the Root of the Extracted ScaleIO_VMware_SW_Download.zip
If not available, it will be downloaded from http://www.emc.com/scaleio
The extracte OVA will be dehydrated to a VMware Workstation Master #>
[Parameter(ParameterSetName = "import",Mandatory=$false)][String]
[ValidateScript({ Test-Path -Path $_ -ErrorAction SilentlyContinue })]$Sourcedir,
[Parameter(ParameterSetName = "import",Mandatory=$false)][switch]$forcedownload,
[Parameter(ParameterSetName = "import",Mandatory=$false)][switch]$noextract,
[Parameter(ParameterSetName = "import",Mandatory=$true)][switch]$import,
#### install parameters#
<# The ScaleIO Master created from -sourcedir #>
[Parameter(ParameterSetName = "defaults",Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$false)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)]
[String]$ScaleIOMaster = ".\ScaleIOVM_2*",
<# Number of Nodes, default to 3 #>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$false)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)][int32]$Nodes=3,
<# Starting Node #>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$false)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)][int32]$Startnode = 1,
<# Number of disks to add, default is 3#>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)]
[Parameter(ParameterSetName = "install",Mandatory=$False)][ValidateRange(1,3)][int32]$Disks = 3,
<# Specify your own Class-C Subnet in format xxx.xxx.xxx.xxx #>
[Parameter(ParameterSetName = "install",Mandatory=$true)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)][ValidateScript({$_ -match [IPAddress]$_ })][ipaddress]$subnet,
<# Name of the domain, .$Custom_DomainSuffix added#>
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)]
[Parameter(ParameterSetName = "install",Mandatory=$False)]
[ValidateLength(1,15)][ValidatePattern("^[a-zA-Z0-9][a-zA-Z0-9-]{1,15}[a-zA-Z0-9]+$")][string]$BuildDomain = "labbuildr",
<# VMnet to use#>
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)]
[Parameter(ParameterSetName = "install",Mandatory = $false)][ValidateSet('vmnet2','vmnet3','vmnet4','vmnet5','vmnet6','vmnet7','vmnet9','vmnet10','vmnet11','vmnet12','vmnet13','vmnet14','vmnet15','vmnet16','vmnet17','vmnet18','vmnet19')]$vmnet = "vmnet2",
<# SDS only#>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$true)][switch]$sds,
<# SDC only3#>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "sdsonly",Mandatory=$false)][switch]$sdc,
<# Configure automatically configures the ScaleIO Cluster and will always install 3 Nodes ! #>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$false)][switch]$configure = $true,
<# we use SingleMDM parameter with Configure for test and dev to Showcase ScaleIO und LowMem Machines #>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)]
[Parameter(ParameterSetName = "install",Mandatory=$False)][switch]$singlemdm,
<# Use labbuildr defaults.json #>
[Parameter(ParameterSetName = "defaults", Mandatory = $true)][switch]$Defaults,
<# Path to a defaults.json #>
[Parameter(ParameterSetName = "defaults", Mandatory = $false)][ValidateScript({ Test-Path -Path $_ })]$Defaultsfile=".\defaults.json"
)
#requires -version 3.0
#requires -module vmxtoolkit
#requires -module labtools
$ScaleIO_tag = "ScaleIOVM_2*"
switch ($PsCmdlet.ParameterSetName)
{
"import"
{
$Labdefaults = Get-LABDefaults
try
{
$Masterpath = $LabDefaults.Masterpath
}
catch
{
$Masterpath = $Builddir
}
Try
{
test-Path $Sourcedir
}
Catch
{
Write-Verbose $_
if (!($Sourcedir = $LabDefaults.Sourcedir))
{
exit
}
else
{
Write-Host -ForegroundColor Gray " ==>we will use $($labdefaults.Sourcedir)"
}
}
if (!($OVAPath = Get-ChildItem -Path "$Sourcedir\ScaleIO\$ScaleIO_Path" -recurse -Include "$ScaleIO_tag.ova" -ErrorAction SilentlyContinue) -or $forcedownload.IsPresent)
{
Write-Host -ForegroundColor Gray " ==>No ScaleIO OVA found, Checking for Downloaded Package"
$Downloadok = Receive-LABScaleIO -Destination $Sourcedir -arch VMware -unzip
}
$OVAPath = Get-ChildItem -Path "$Sourcedir\ScaleIO\$ScaleIO_Path" -Recurse -include "$ScaleIO_tag.ova" -Exclude ".*" | Sort-Object -Descending
$OVAPath = $OVApath[0]
$mastername = $($ovaPath.Basename)
if ($vmwareversion.Major -eq 14)
{
Write-Warning " running $($vmwareversion.ToString()),we try to avoid a OVF import Bug, trying a manual import"
Expand-LABpackage -Archive $ovaPath.FullName -filepattern *.vmdk -destination "$Masterpath/$mastername" -Verbose -force
Copy-Item "./template/ScaleIOVM_2nics.template" -Destination "$Masterpath/$mastername/$Mastername.vmx"
$Template_VMX = get-vmx -Path "$Masterpath/$mastername"
$Disk1_item = Get-Item "$Masterpath/$mastername/*disk1.vmdk"
$Disk1 = $Template_VMX | Add-VMXScsiDisk -Diskname $Disk1_item.Name -LUN 0 -Controller 0
}
else {
$Template = Import-VMXOVATemplate -OVA $ovaPath.FullName -destination $Masterpath -acceptAllEulas -Quiet -AllowExtraConfig
}
$MasterVMX = get-vmx -path "$Masterpath\$mastername"
if (!$MasterVMX.Template)
{
write-verbose "Templating Master VMX"
$Temolate = $MasterVMX | Set-VMXTemplate
}
Write-Host -ForegroundColor Gray "[Preparation of Template done"
write-host -ForegroundColor White ".\$($MyInvocation.MyCommand) -ScaleioMaster $MasterPath\$mastername -Defaults -configure"
}
default
{
If ($singlemdm.IsPresent)
{
[switch]$configure = $true
}
if ($configure.IsPresent)
{
[switch]$sds = $true
[switch]$sdc = $true
}
If ($Defaults.IsPresent)
{
$labdefaults = Get-labDefaults
$vmnet = $labdefaults.vmnet
$subnet = $labdefaults.MySubnet
$BuildDomain = $labdefaults.BuildDomain
$Sourcedir = $labdefaults.Sourcedir
$DefaultGateway = $labdefaults.DefaultGateway
$Sourcedir = $labdefaults.Sourcedir
}
if ($LabDefaults.custom_domainsuffix)
{
$custom_domainsuffix = $LabDefaults.custom_domainsuffix
}
else
{
$custom_domainsuffix = "local"
}
[System.Version]$subnet = $Subnet.ToString()
$Subnet = $Subnet.major.ToString() + "." + $Subnet.Minor + "." + $Subnet.Build
$rootuser = "root"
$old_rootpassword = "admin"
$MDMPassword = "Password123!"
$Guestpassword = $MDMPassword
[uint64]$Disksize = 100GB
$scsi = 0
$ScaleIO_OS = "VMware"
$ScaleIO_Path = "ScaleIO_$($ScaleIO_OS)_SW_Download"
$Devicename = "$Location"+"_Disk_$Driveletter"
$VolumeName = "Volume_$Location"
$ProtectionDomainName = "PD_$BuildDomain"
$StoragePoolName = "SP_$BuildDomain"
$SystemName = "ScaleIO@$BuildDomain"
$FaultSetName = "Rack_"
$mdm_ipa = "$subnet.191"
$mdm_ipb = "$subnet.192"
$tb_ip = "$subnet.193"
$mdm_name_a = "Manager_A"
$mdm_name_b = "Manager_B"
$tb_name = "TB"
if (!(Test-Path $SCALEIOMaster))
{
Write-Warning "!!!!! No ScaleIO Master found
please run .\install-scaleiosvm.ps1 -import to download / create Master
"
exit
}
if ($SCALEIOMaster -notmatch $ScaleIO_tag)
{
Write-Warning "Master must match $ScaleIO_tag"
exit
}
$Mastervmxlist = get-vmx -Path $SCALEIOMaster | Sort-Object -Descending
if (!($Mastervmxlist))
{
Write-Warning "!!!!! No ScaleIO Master found for $ScaleIO_tag
please run .\install-scaleiosvm.ps1 -import to download / create Master
"
exit
}
$MasterVMX = $Mastervmxlist[0]
$Nodeprefix = "ScaleIONode"
If ($configure.IsPresent -and $Nodes -lt 3)
{
Write-Warning "Configure Present, setting nodes to 3"
$Nodes = 3
}
if ($MasterVMX.VMXname -match '2.0.1')
{
$SIO_Major = '2.0.1'
Write-Host -ForegroundColor Magenta " ==> installing ScaleIO Branch 2.0.1 "
}
If ($singlemdm.IsPresent)
{
Write-Warning "Single MDM installations with MemoryTweaking are only for Test Deployments and Memory Contraints/Manager Laptops :-)"
$mdm_ip="$mdm_ipa"
}
else
{
$mdm_ip="$mdm_ipa,$mdm_ipb"
}
if (!$MasterVMX.Template)
{
write-verbose "Templating Master VMX"
$template = $MasterVMX | Set-VMXTemplate
}
$Basesnap = $MasterVMX | Get-VMXSnapshot -WarningAction SilentlyContinue | where Snapshot -Match "Base"
if (!$Basesnap)
{
Write-verbose "Base snap does not exist, creating now"
$Basesnap = $MasterVMX | New-VMXSnapshot -SnapshotName BASE
}
####Build Machines#
Write-Host -ForegroundColor Magenta "Starting Avalanche install For Scaleio Nodes..."
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
foreach ($Node in $Startnode..(($Startnode-1)+$Nodes))
{
Write-Host -ForegroundColor Gray " ==>Checking presence of $Nodeprefix$node"
if (!(get-vmx $Nodeprefix$node -WarningAction SilentlyContinue ))
{
$NodeClone = $MasterVMX | Get-VMXSnapshot | where Snapshot -Match "Base" | New-VMXLinkedClone -CloneName $Nodeprefix$Node
If ($Node -eq 1){$Primary = $NodeClone}
$Config = Get-VMXConfig -config $NodeClone.config
Write-Verbose "Tweaking Config"
$Config = $config | ForEach-Object { $_ -replace "lsilogic" , "pvscsi" }
$Config | set-Content -Path $NodeClone.Config
foreach ($LUN in (1..$Disks))
{
$Diskname = "SCSI$SCSI"+"_LUN$LUN.vmdk"
$Newdisk = New-VMXScsiDisk -NewDiskSize $Disksize -NewDiskname $Diskname -VMXName $NodeClone.VMXname -Path $NodeClone.Path
$NodeClone | Add-VMXScsiDisk -Diskname $Newdisk.Diskname -LUN $LUN -Controller $SCSI | Out-Null
}
$NodeClone | Set-VMXNetworkAdapter -Adapter 0 -ConnectionType hostonly -AdapterType vmxnet3 | out-null
if ($vmnet)
{
$NodeClone | Set-VMXNetworkAdapter -Adapter 0 -ConnectionType custom -AdapterType vmxnet3 -WarningAction SilentlyContinue | out-null
$NodeClone | Set-VMXVnet -Adapter 0 -vnet $vmnet -WarningAction SilentlyContinue | out-null
$NodeClone | Disconnect-VMXNetworkAdapter -Adapter 1 | out-null
$NodeClone | Disconnect-VMXNetworkAdapter -Adapter 2 | Out-Null
}
$Displayname = $NodeClone | Set-VMXDisplayName -DisplayName "$($NodeClone.CloneName)@$BuildDomain"
$MainMem = $NodeClone | Set-VMXMainMemory -usefile:$false
$Annotation = $NodeClone | Set-VMXAnnotation -Line1 "rootuser:$rootuser" -Line2 "rootpasswd:$Guestpassword" -Line3 "mdmuser:admin" -Line4 "mdmpassword:$MDMPassword" -Line5 "labbuildr by @sddc_guy" -builddate
$Scenario = $NodeClone |Set-VMXscenario -config $NodeClone.Config -Scenarioname Scaleio -Scenario 6
$ActivationPrefrence = $NodeClone |Set-VMXActivationPreference -config $NodeClone.Config -activationpreference $Node
if ($singlemdm.IsPresent -and $Node -notin (1,3))
{
$memorytweak = $NodeClone | Set-VMXmemory -MemoryMB 1536
}
# Set-VMXVnet -Adapter 0 -vnet vmnet2
start-vmx -Path $NodeClone.Path -VMXName $NodeClone.CloneName | out-null
# $NodeClone | Set-VMXSharedFolderState -enabled
}
else
{
Write-Warning "Node $Nodeprefix$node already exists"
if ($configure.IsPresent)
{
Write-Warning "Please Delete VM´s First, use
'get-vmx $Nodeprefix$Node | remove-vmx'
to remove the Machine or
'get-vmx $Nodeprefix | remove-vmx'
to remove all Nodes"
exit
}
}
}
$Logfile = "/tmp/install_sio.log"
Write-Host -ForegroundColor Magenta " ==>Starting configuration of Nodes, logging to $Logfile"
$Percentage = [math]::Round(100/$nodes)+1
if ($Percentage -lt 10)
{
$Percentage = 10
}
foreach ($Node in $Startnode..(($Startnode-1)+$Nodes))
{
Write-Host -ForegroundColor Gray " ==>waiting for Node $Nodeprefix$node"
$ip="$subnet.19$Node"
$NodeClone = get-vmx $Nodeprefix$node
do {
$ToolState = Get-VMXToolsState -config $NodeClone.config
Write-Verbose "VMware tools are in $($ToolState.State) state"
sleep 5
}
until ($ToolState.state -match "running")
If (!$DefaultGateway) {$DefaultGateway = $Ip}
$Scriptblock = "echo -e '$Guestpassword\n$Guestpassword' | (passwd --stdin root)"
$NodeClone | Invoke-VMXBash -Scriptblock $Scriptblock -Guestuser $rootuser -Guestpassword $old_rootpassword -logfile $Logfile | Out-Null
$Scriptblock = "/usr/bin/ssh-keygen -t rsa -N '' -f /root/.ssh/id_rsa"
Write-Verbose $Scriptblock
$Bashresult = $NodeClone | Invoke-VMXBash -Scriptblock $Scriptblock -Guestuser $Rootuser -Guestpassword $Guestpassword -logfile $Logfile
if ($labdefaults.Hostkey)
{
$Scriptblock = "echo '$($Labdefaults.Hostkey)' >> /root/.ssh/authorized_keys"
$NodeClone | Invoke-VMXBash -Scriptblock $Scriptblock -Guestuser $Rootuser -Guestpassword $Guestpassword | Out-Null
}
$NodeClone | Set-VMXLinuxNetwork -ipaddress $ip -network "$subnet.0" -netmask "255.255.255.0" -gateway $DefaultGateway -device eth0 -Peerdns -DNS1 "$subnet.10" -DNSDOMAIN "$BuildDomain.$Custom_DomainSuffix" -Hostname "$Nodeprefix$Node" -suse -rootuser $rootuser -rootpassword $Guestpassword | Out-Null
$NodeClone | Invoke-VMXBash -Scriptblock "rpm --import /root/install/RPM-GPG-KEY-ScaleIO" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
$NodeClone | Invoke-VMXBash -Scriptblock "rpm -Uhv /root/install/EMC-ScaleIO-openssl*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
if (!($PsCmdlet.ParameterSetName -eq "sdsonly"))
{
if (($Node -in 1..2 -and (!$singlemdm)) -or ($Node -eq 1))
{
Write-Host -ForegroundColor Gray " ==>trying MDM Install as manager"
$NodeClone | Invoke-VMXBash -Scriptblock "export MDM_ROLE_IS_MANAGER=1;rpm -Uhv /root/install/EMC-ScaleIO-mdm*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
}
if ($Node -eq 3)
{
$GatewayNode = $NodeClone
Write-Host -ForegroundColor Gray " ==>trying Gateway Install"
$NodeClone | Invoke-VMXBash -Scriptblock "rpm -Uhv /root/install/jre-*-linux-x64.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
$NodeClone | Invoke-VMXBash -Scriptblock "export SIO_GW_KEYTOOL=/usr/java/default/bin/;export GATEWAY_ADMIN_PASSWORD='Password123!';rpm -Uhv --nodeps /root/install/EMC-ScaleIO-gateway*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
if (!$singlemdm)
{
Write-Host -ForegroundColor Gray " ==>trying MDM Install as tiebreaker"
$NodeClone | Invoke-VMXBash -Scriptblock "export MDM_ROLE_IS_MANAGER=0;rpm -Uhv /root/install/EMC-ScaleIO-mdm*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==>adding MDM to Gateway Server Config File"
$sed = "sed -i 's\mdm.ip.addresses=.*\mdm.ip.addresses=$mdm_ipa;$mdm_ipb\' /opt/emc/scaleio/gateway/webapps/ROOT/WEB-INF/classes/gatewayUser.properties"
}
else
{
Write-Host -ForegroundColor Gray " ==>adding MDM's to Gateway Server Config File"
$sed = "sed -i 's\mdm.ip.addresses=.*\mdm.ip.addresses=$mdm_ipa;$mdm_ipa\' /opt/emc/scaleio/gateway/webapps/ROOT/WEB-INF/classes/gatewayUser.properties"
}
Write-Verbose $sed
$NodeClone | Invoke-VMXBash -Scriptblock $sed -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
$MY_CIPHERS="'ciphers='`"'TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_128_CBC_SHA256,TLS_RSA_WITH_AES_128_GCM_SHA256,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA256,TLS_RSA_WITH_AES_256_GCM_SHA384'`"''"
$Scriptblock = "MYCIPHERS=$MY_CIPHERS;sed -i '/ciphers=/s/.*/'`$MYCIPHERS'/' /opt/emc/scaleio/gateway/conf/server.xml"
$NodeClone | Invoke-VMXBash -Scriptblock $Scriptblock -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
$NodeClone | Invoke-VMXBash -Scriptblock "/etc/init.d/scaleio-gateway restart" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
}
Write-Host -ForegroundColor Gray " ==>trying LIA Install"
$NodeClone | Invoke-VMXBash -Scriptblock "rpm -Uhv /root/install/EMC-ScaleIO-lia*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
}
if ($sds.IsPresent)
{
Write-Host -ForegroundColor Gray " ==>trying SDS Install"
$NodeClone | Invoke-VMXBash -Scriptblock "rpm -Uhv /root/install/EMC-ScaleIO-sds-*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
}
if ($sdc.IsPresent)
{
Write-Host -ForegroundColor Gray " ==>trying SDC Install"
$NodeClone | Invoke-VMXBash -Scriptblock "export MDM_IP=$mdm_ip;rpm -Uhv /root/install/EMC-ScaleIO-sdc*.rpm" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
$Scriptlets = ("cat > /bin/emc/scaleio/scini_sync/driver_sync.conf <<EOF
repo_address = ftp://ftp.emc.com`
repo_user = QNzgdxXix`
repo_password = Aw3wFAwAq3`
local_dir = /bin/emc/scaleio/scini_sync/driver_cache/`
module_sigcheck = 0`
emc_public_gpg_key = /bin/emc/scaleio/scini_sync/RPM-GPG-KEY-ScaleIO`
repo_public_rsa_key = /bin/emc/scaleio/scini_sync/scini_repo_key.pub`
",
"/usr/bin/dos2unix /bin/emc/scaleio/scini_sync/driver_sync.conf;/etc/init.d/scini restart")
foreach ($Scriptblock in $Scriptlets)
{
Write-Verbose $Scriptblock
$NodeClone | Invoke-VMXBash -Scriptblock $Scriptblock -Guestuser $Rootuser -Guestpassword $Guestpassword | Out-Null
}
}
}
if ($configure.IsPresent)
{
Write-Host -ForegroundColor Magenta " ==> Now configuring ScaleIO"
$Logfile = "/tmp/configure_sio.log"
$mdmconnect = "scli --login --username admin --password $MDMPassword --mdm_ip $mdm_ip"
if ($Primary)
{
Write-Host -ForegroundColor Magenta "We are now creating the ScaleIO Cluster"
Write-Host -ForegroundColor Gray " ==>adding Primary MDM $mdm_ipa"
$sclicmd = "scli --create_mdm_cluster --master_mdm_ip $mdm_ipa --master_mdm_management_ip $mdm_ipa --master_mdm_name $mdm_name_a --approve_certificate --accept_license;sleep 3"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock $sclicmd -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==>Setting password"
$sclicmd = "scli --login --username admin --password admin --mdm_ip $mdm_ipa;scli --set_password --old_password admin --new_password $MDMPassword --mdm_ip $mdm_ipa"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock $sclicmd -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
if (!$singlemdm.IsPresent)
{
Write-Host -ForegroundColor Gray " ==>adding standby MDM $mdm_ipb"
$sclicmd = "$mdmconnect;scli --add_standby_mdm --mdm_role manager --new_mdm_ip $mdm_ipb --new_mdm_management_ip $mdm_ipb --new_mdm_name $mdm_name_b --mdm_ip $mdm_ipa"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock $sclicmd -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==>adding tiebreaker $tb_ip"
if ($SIO_Major -eq '2.0.1')
{
$sclicmd = "$mdmconnect; scli --add_standby_mdm --mdm_role tb --new_mdm_ip $tb_ip --mdm_ip $mdm_ipa"
}
else
{
$sclicmd = "$mdmconnect; scli --add_standby_mdm --mdm_role tb --new_mdm_ip $tb_ip --tb_name $tb_name --mdm_ip $mdm_ipa"
}
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock $sclicmd -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==>switching to cluster mode"
$sclicmd = "$mdmconnect;scli --switch_cluster_mode --cluster_mode 3_node --add_slave_mdm_ip $mdm_ipb --add_tb_ip $tb_ip --mdm_ip $mdm_ipa"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock $sclicmd -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
}
else
{
$mdm_ipb = $mdm_ipa
}
Write-Host -ForegroundColor Magenta "Storing SIO Confiuration locally"
Set-LABSIOConfig -mdm_ipa $mdm_ipa -mdm_ipb $mdm_ipb -gateway_ip $tb_ip -system_name $SystemName -pool_name $StoragePoolName -pd_name $ProtectionDomainName
Write-Host -ForegroundColor Gray " ==>adding protection domain $ProtectionDomainName"
$sclicmd = "scli --add_protection_domain --protection_domain_name $ProtectionDomainName --mdm_ip $mdm_ip"
$Primary | Invoke-VMXBash -Scriptblock "$mdmconnect;$sclicmd" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==>adding storagepool $StoragePoolName"
$sclicmd = "scli --add_storage_pool --storage_pool_name $StoragePoolName --protection_domain_name $ProtectionDomainName --mdm_ip $mdm_ip"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock "$mdmconnect;$sclicmd" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==>adding renaming system to $SystemName"
$sclicmd = "scli --rename_system --new_name $SystemName --mdm_ip $mdm_ip"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock "$mdmconnect;$sclicmd" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
Write-Host -ForegroundColor Gray " ==> approving mdm Certificates for gateway"
}#end Primary
foreach ($Node in $Startnode..(($Startnode-1)+$Nodes))
{
Write-Host -ForegroundColor Gray " ==>adding sds $subnet.19$Node with /dev/sdb"
$sclicmd = "scli --add_sds --sds_ip $subnet.19$Node --device_path /dev/sdb --device_name /dev/sdb --sds_name ScaleIONode$Node --protection_domain_name $ProtectionDomainName --storage_pool_name $StoragePoolName --no_test --mdm_ip $mdm_ip"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock "$mdmconnect;$sclicmd" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
}
Write-Host -ForegroundColor Gray " ==>adjusting spare policy"
$sclicmd = "scli --modify_spare_policy --protection_domain_name $ProtectionDomainName --storage_pool_name $StoragePoolName --spare_percentage $Percentage --i_am_sure --mdm_ip $mdm_ip"
Write-Verbose $sclicmd
$Primary | Invoke-VMXBash -Scriptblock "$mdmconnect;$sclicmd" -Guestuser $rootuser -Guestpassword $Guestpassword -logfile $Logfile | Out-Null
$scriptblock = "export TOKEN=`$(curl --silent --insecure --user 'admin:$($Guestpassword)' 'https://localhost/api/gatewayLogin' | sed 's:^.\(.*\).`$:\1:') \n`
curl --silent --show-error --insecure --user :`$TOKEN -X GET 'https://localhost/api/getHostCertificate/Mdm?host=$($mdm_ipa)' > '/tmp/mdm_a.cer' \n`
curl --silent --show-error --insecure --user :`$TOKEN -X POST -H 'Content-Type: multipart/form-data' -F 'file=@/tmp/mdm_a.cer' 'https://localhost/api/trustHostCertificate/Mdm' \n`
curl --silent --show-error --insecure --user :`$TOKEN -X GET 'https://localhost/api/getHostCertificate/Mdm?host=$($mdm_ipb)' > '/tmp/mdm_b.cer' \n`
curl --silent --show-error --insecure --user :`$TOKEN -X POST -H 'Content-Type: multipart/form-data' -F 'file=@/tmp/mdm_b.cer' 'https://localhost/api/trustHostCertificate/Mdm' "
$GatewayNode | Invoke-VMXBash -Scriptblock $Scriptblock -Guestuser $rootuser -Guestpassword $Guestpassword| Out-Null
write-host "Connect with ScaleIO UI to $mdm_ipa admin/Password123!"
}
write-host "Login to the VM´s with root/admin"
$StopWatch.Stop()
Write-host -ForegroundColor White "ScaleIO Deployment took $($StopWatch.Elapsed.ToString())"
} #end default
}#end switch | bottkars/labbuildr | labbuildr/install-scaleiosvm.ps1 | PowerShell | apache-2.0 | 27,956 |
$packageName = 'hub'
$url = 'https://github.com/github/hub/releases/download/v2.2.9/hub-windows-386-2.2.9.zip'
$checksum = 'afa3024091677269504c0196f546c548'
$checksumType = 'md5'
$url64 = 'https://github.com/github/hub/releases/download/v2.2.9/hub-windows-amd64-2.2.9.zip'
$checksum64 = '418a4aba5a9c7cb6d7b36e0afce4febf'
$checksumType64 = 'md5'
$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/hub/2.2.9/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 865 |
$packageName = 'awscli'
$installerType = 'msi'
$silentArgs = '/quiet /qn /norestart'
$url = 'https://s3.amazonaws.com/aws-cli/AWSCLI32-1.11.41.msi'
$checksum = 'f0d1c98a98368d52b557d910e57a79fa2b0a9e205fb19f534b84d06c844d9bd3'
$checksumType = 'sha256'
$url64 = 'https://s3.amazonaws.com/aws-cli/AWSCLI64-1.11.41.msi'
$checksum64 = 'cee6e11443ef3b8b4508f5a14ce9894f90d3ce4963fd233cec28450406b1f577'
$checksumType64 = 'sha256'
$validExitCodes = @(0)
Install-ChocolateyPackage -PackageName "$packageName" `
-FileType "$installerType" `
-SilentArgs "$silentArgs" `
-Url "$url" `
-Url64bit "$url64" `
-ValidExitCodes $validExitCodes `
-Checksum "$checksum" `
-ChecksumType "$checksumType" `
-Checksum64 "$checksum64" `
-ChecksumType64 "$checksumType64" | dtgm/chocolatey-packages | automatic/_output/awscli/1.11.41/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 985 |
function Get-TargetResource
{
[OutputType([Hashtable])]
param (
[ValidateSet("Present", "Absent")]
[string]$Ensure = "Present",
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$AgentName,
[ValidateSet("Started", "Stopped")]
[string]$State = "Started",
[string]$AgentHomeDirectory,
[string]$AgentWorkDirectory,
[string]$AgentHostname,
[int]$AgentPort,
[string]$ServerHostname,
[int]$ServerPort,
[string]$AgentBuildParameters
)
Write-Verbose "Checking if TeamCity Agent is installed"
$installLocation = (get-itemproperty -path "HKLM:\Software\ORACLE\KEY_XE" -ErrorAction SilentlyContinue).ORACLE_HOME
$present = Test-Path "$AgentHomeDirectory\bin\service.start.bat"
Write-Verbose "TeamCity Agent present: $present"
$currentEnsure = if ($present) { "Present" } else { "Absent" }
$serviceName = Get-TeamCityAgentServiceName -AgentName $AgentName
Write-Verbose "Checking for Windows Service: $serviceName"
$serviceInstance = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
$currentState = "Stopped"
if ($serviceInstance -ne $null)
{
Write-Verbose "Windows service: $($serviceInstance.Status)"
if ($serviceInstance.Status -eq "Running")
{
$currentState = "Started"
}
if ($currentEnsure -eq "Absent")
{
Write-Verbose "Since the Windows Service is still installed, the service is present"
$currentEnsure = "Present"
}
}
else
{
Write-Verbose "Windows service: Not installed"
$currentEnsure = "Absent"
}
return @{
AgentName = $AgentName;
Ensure = $currentEnsure;
State = $currentState;
};
}
function Set-TargetResource
{
param (
[ValidateSet("Present", "Absent")]
[string]$Ensure = "Present",
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$AgentName,
[ValidateSet("Started", "Stopped")]
[string]$State = "Started",
[string]$AgentHomeDirectory = "C:\TeamCity\Agent",
[string]$AgentWorkDirectory = "C:\TeamCity\Agent\work",
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$AgentHostname,
[Parameter(Mandatory)]
[int]$AgentPort,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ServerHostname,
[Parameter(Mandatory)]
[int]$ServerPort,
[string]$AgentBuildParameters
)
if ($Ensure -eq "Absent" -and $State -eq "Started")
{
throw "Invalid configuration: service cannot be both 'Absent' and 'Started'"
}
$currentResource = (Get-TargetResource -AgentName $AgentName -AgentHomeDirectory $AgentHomeDirectory)
Write-Verbose "Configuring TeamCity Agent ..."
$serviceName = Get-TeamCityAgentServiceName -AgentName $AgentName
if ($State -eq "Stopped" -and $currentResource["State"] -eq "Started")
{
Write-Verbose "Stopping TeamCity Agent service $serviceName"
Stop-Service -Name $serviceName -Force
}
if ($Ensure -eq "Absent" -and $currentResource["Ensure"] -eq "Present")
{
# Uninstall TeamCity Agent
throw "Removal of TeamCity Agent Currently not supported by this DSC Module!"
}
elseif ($Ensure -eq "Present" -and $currentResource["Ensure"] -eq "Absent")
{
Write-Verbose "Installing TeamCity Agent..."
Install-TeamCityAgent -AgentName $AgentName -AgentHomeDirectory $AgentHomeDirectory -AgentWorkDirectory $AgentWorkDirectory `
-AgentHostname $AgentHostname -AgentPort $AgentPort -ServerHostname $ServerHostname -ServerPort $ServerPort `
-AgentBuildParameters $AgentBuildParameters
Write-Verbose "TeamCity Agent installed!"
}
if ($State -eq "Started" -and $currentResource["State"] -eq "Stopped")
{
Write-Verbose "Starting TeamCity Agent service $serviceName"
Start-Service -Name $serviceName
}
Write-Verbose "Finished"
}
function Test-TargetResource
{
param (
[ValidateSet("Present", "Absent")]
[string]$Ensure = "Present",
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$AgentName,
[ValidateSet("Started", "Stopped")]
[string]$State = "Started",
[string]$AgentHomeDirectory,
[string]$AgentWorkDirectory,
[string]$AgentHostname,
[int]$AgentPort,
[string]$ServerHostname,
[int]$ServerPort,
[string]$AgentBuildParameters
)
$currentResource = (Get-TargetResource -AgentName $AgentName -AgentHomeDirectory $AgentHomeDirectory)
$ensureMatch = $currentResource["Ensure"] -eq $Ensure
Write-Verbose "Ensure: $($currentResource["Ensure"]) vs. $Ensure = $ensureMatch"
if (!$ensureMatch)
{
return $false
}
$stateMatch = $currentResource["State"] -eq $State
Write-Verbose "State: $($currentResource["State"]) vs. $State = $stateMatch"
if (!$stateMatch)
{
return $false
}
return $true
}
function Get-TeamCityAgentServiceName {
param (
[string]$AgentName
)
#For now just using default TeamCity Agent Service Name
return "TCBuildAgent"
}
function Request-File
{
param (
[string]$url,
[string]$saveAs
)
Write-Verbose "Downloading $url to $saveAs"
$downloader = new-object System.Net.WebClient
$downloader.DownloadFile($url, $saveAs)
}
function Expand-ZipFile
{
param (
[string]$file,
[string]$destination
)
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($file, $destination)
}
function Write-TokenReplacedFile {
param(
[parameter(Position=0)][string] $fileToTokenReplace,
[parameter(position=1)][string] $outFile,
[parameter(position=2)][hashtable] $tokenValues
)
$fileContents = Get-Content -Raw $fileToTokenReplace
foreach ($token in $tokenValues.GetEnumerator()) {
$fileContents = $fileContents -replace $token.Name, $token.Value
}
[io.file]::WriteAllText($outFile,$fileContents)
}
function Install-TeamCityAgent
{
param (
[Parameter(Mandatory)]
[string]$AgentName,
[Parameter(Mandatory=$True)]
[string]$AgentHomeDirectory,
[Parameter(Mandatory=$True)]
[string]$AgentWorkDirectory,
[Parameter(Mandatory=$True)]
[string]$AgentHostname,
[Parameter(Mandatory=$True)]
[int]$AgentPort,
[Parameter(Mandatory=$True)]
[string]$ServerHostname,
[Parameter(Mandatory=$True)]
[int]$ServerPort,
[string]$AgentBuildParameters
)
if ((test-path $AgentHomeDirectory) -ne $true) {
New-Item $AgentHomeDirectory -type directory
}
$installationZipFilePath = "$AgentHomeDirectory\TeamCityAgent.zip"
if ((test-path $installationZipFilePath) -ne $true)
{
$TeamCityAgentInstallationZipUrl = "http://$($ServerHostname):$($ServerPort)/update/buildAgent.zip"
Write-Verbose "Downloading TeamCity Agent installation zip from $TeamCityAgentInstallationZipUrl to $installationZipFilePath"
Request-File $TeamCityAgentInstallationZipUrl $installationZipFilePath
Write-Verbose "Downloaded TeamCity Agent installation zip to $installationZipFilePath"
}
Write-Verbose "Expanding TeamCity Agent installation zip $installationZipFilePath to directory $AgentHomeDirectory"
Expand-ZipFile $installationZipFilePath $AgentHomeDirectory
Write-Verbose "Expanded TeamCity Agent installation zip to directory $AgentHomeDirectory"
Write-Verbose "Configuring TeamCity Agent with name: $AgentName, ownAddress: $AgentHostname, ownPort: $AgentPort, server hostname: $ServerHostname, server port: $ServerPort."
$teamCityConfigFile = "$AgentHomeDirectory\\conf\\buildAgent.properties"
$AgentBuildParameterHashtable = convertfrom-stringdata -stringdata $AgentBuildParameters
$agentBuildParametersString = ''
$AgentBuildParameterHashtable.Keys | % { $agentBuildParametersString += "`n$($_)=$($AgentBuildParameterHashtable.Item($_))" }
Write-TokenReplacedFile "$AgentHomeDirectory\\conf\\buildAgent.dist.properties" $teamCityConfigFile @{
'serverUrl=http://localhost:8111/' = "serverUrl=http://$($ServerHostname):$($ServerPort)";
'name=' = "name=$AgentName";
'ownPort=9090' = "ownPort=$AgentPort";
'#ownAddress=<own IP address or server-accessible domain name>' = "ownAddress=$AgentHostname";
'workDir=../work' = "workDir=$AgentWorkDirectory";
'#env.exampleEnvVar=example Env Value' = $agentBuildParametersString;
}
Write-Verbose "Configured TeamCity Agent in file $teamCityConfigFile"
$serviceName = Get-TeamCityAgentServiceName -AgentName $AgentName
Write-Verbose "Installing TeamCity Agent Windows service with name $serviceName ..."
Push-Location -Path "$AgentHomeDirectory\bin"
.\service.install.bat
Pop-Location
Write-Verbose "Installed TeamCity Agent Windows service with name $serviceName."
}
| transcanada/teamcity-agent-dsc | TeamCityAgentDSC/DSCResources/cTeamCityAgent/cTeamCityAgent.psm1 | PowerShell | apache-2.0 | 9,269 |
function UrlExists($uri) {
try {
Get-WebHeaders $uri | Out-Null
}
catch {
if ($_ -match "unauthorized") { return $false }
throw $_
}
return $true;
}
function AddArchivePathToUrl($url) {
$newUrl = $url
$lix = $url.LastIndexOf("/")
if ($lix -ne -1) {
$newUrl = $url.SubString(0, $lix) + "/archives" + $url.SubString($lix)
}
return $newUrl
}
function GetDownloadInfo {
param(
[string]$downloadInfoFile,
$parameters
)
Write-Debug "Reading CSV file from $downloadInfoFile"
$downloadInfo = Get-Content -Encoding UTF8 -Path $downloadInfoFile | ConvertFrom-Csv -Delimiter '|' -Header 'Type','URL32','URL64','Checksum32','Checksum64'
if ($parameters.ThreadSafe) {
$downloadInfo | ? { $_.Type -eq 'threadsafe' } | select -first 1
} else {
$downloadInfo | ? { $_.Type -eq 'not-threadsafe' } | select -first 1
}
}
function GetInstallLocation {
param(
[string]$libDirectory
)
Write-Debug "Checking for uninstall text document in $libDirectory"
if (Test-Path "$libDirectory\*.txt") {
$txtContent = Get-Content -Encoding UTF8 "$libDirectory\*.txt" | select -first 1
$index = $txtContent.LastIndexOf('\')
if ($index -gt 0) {
return $txtContent.Substring(0, $index)
}
}
# If we got here, the text file doesn't exist or is empty
# we don't return anything as it may be already uninstalled
}
function GetNewInstallLocation {
param(
[string]$PackageName,
[string]$Version,
$pp
)
if ($pp -and $pp.InstallDir) {
return $pp.InstallDir
}
$toolsLocation = Get-BinRoot
return "$toolsLocation\{0}{1}" -f $PackageName, ($Version -replace '\.').Substring(0,2)
}
function UninstallPackage {
param(
[string]$libDirectory,
[string]$packageName
)
if (Test-Path "$libDirectory\*.txt") {
$txtFile = Resolve-Path "$libDirectory\*.txt" | select -first 1
$fileName = ($txtFile -split '\\' | select -last 1).TrimEnd('.txt')
Uninstall-ChocolateyZipPackage -PackageName $packageName -ZipFileName $fileName
}
}
if (!(Test-Path function:\Uninstall-ChocolateyPath)) {
function Uninstall-ChocolateyPath {
param(
[string]$pathToRemove,
[System.EnvironmentVariableTarget] $pathType = [System.EnvironmentVariableTarget]::User
)
Write-Debug "Running 'Uninstall-ChocolateyPath' with pathToRemove: `'$pathToRemove`'"
# get the PATH variable
Update-SessionEnvironment
$envPath = $env:PATH
if ($envPath.ToLower().Contains($pathToRemove.ToLower())) {
Write-Host "PATH environment variable do have $pathToRemove in it. Removing..."
$actualPath = Get-EnvironmentVariable -Name 'Path' -Scope $pathType -PreserveVariables
$newPath = $actualPath -replace [regex]::Escape($pathToRemove + ';'),'' -replace ';;',';'
if (($pathType -eq [System.EnvironmentVariableTarget]::Machine) -and !(Test-ProcessAdminRights)) {
Write-Warning "Removing path from machine environment variable is not supported when not running as an elevated user!"
} else {
Set-EnvironmentVariable -Name 'Path' -Value $newPath -Scope $pathType
}
$env:PATH = $newPath
}
}
}
| lennartb-/chocolatey-coreteampackages | automatic/php/tools/helpers.ps1 | PowerShell | apache-2.0 | 3,204 |
function Add-VSAppSyncGraphQLApiAdditionalAuthenticationProviders {
<#
.SYNOPSIS
Adds an AWS::AppSync::GraphQLApi.AdditionalAuthenticationProviders resource property to the template. A list of additional authentication providers for the GraphqlApi API.
.DESCRIPTION
Adds an AWS::AppSync::GraphQLApi.AdditionalAuthenticationProviders resource property to the template.
A list of additional authentication providers for the GraphqlApi API.
*Required*: No
*Type:* List of AdditionalAuthenticationProvider: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-graphqlapi-additionalauthenticationprovider.html
*Update requires:* No interruption
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-graphqlapi-additionalauthenticationproviders.html
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.AppSync.GraphQLApi.AdditionalAuthenticationProviders')]
[cmdletbinding()]
Param
(
)
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.AppSync.GraphQLApi.AdditionalAuthenticationProviders'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSAppSyncGraphQLApiAdditionalAuthenticationProviders.ps1 | PowerShell | apache-2.0 | 1,858 |
Function Get-UnitycifsFilesystemParameters {
<#
.SYNOPSIS
Settings for a SMB (also known as CIFS) file system.. <br/> <br/> This resource type is embedded in the storageResource resource type.
.DESCRIPTION
Settings for a SMB (also known as CIFS) file system.. <br/> <br/> This resource type is embedded in the storageResource resource type.
You need to have an active session with the array.
.NOTES
Written by Erwan Quelin under MIT licence - https://github.com/equelin/Unity-Powershell/blob/master/LICENSE
.LINK
https://github.com/equelin/Unity-Powershell
.PARAMETER Session
Specifies an UnitySession Object.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnitycifsFilesystemParameters
Retrieve information about all UnitycifsFilesystemParameters
.EXAMPLE
Get-UnitycifsFilesystemParameters -ID 'id01'
Retrieves information about a specific UnitycifsFilesystemParameters
#>
[CmdletBinding(DefaultParameterSetName='Name')]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName='ID',ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'UnitycifsFilesystemParameters ID')]
[String[]]$ID
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Executing function"
#Initialazing variables
$URI = '/api/types/cifsFilesystemParameters/instances' #URI
$TypeName = 'UnitycifsFilesystemParameters'
}
Process {
Foreach ($sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Session.Server) with SessionId: $($Session.SessionId)"
Get-UnityItemByKey -Session $Sess -URI $URI -Typename $Typename -Key $PsCmdlet.ParameterSetName -Value $PSBoundParameters[$PsCmdlet.ParameterSetName]
} # End Foreach ($sess in $session)
} # End Process
} # End Function
| equelin/Unity-Powershell | Tools/Functions/Result_UnityVSA_41/Get-UnitycifsFilesystemParameters.ps1 | PowerShell | mit | 2,062 |
<#
.EXAMPLE
This example adds a new user profile service application to the local farm
#>
Configuration Example
{
param(
[Parameter(Mandatory = $true)]
[PSCredential]
$SetupAccount,
[Parameter(Mandatory = $true)]
[PSCredential]
$FarmAccount
)
Import-DscResource -ModuleName SharePointDsc
node localhost {
SPUserProfileServiceApp UserProfileServiceApp
{
Name = "User Profile Service Application"
ApplicationPool = "SharePoint Service Applications"
MySiteHostLocation = "http://my.sharepoint.contoso.local"
MySiteManagedPath = "personal"
ProfileDBName = "SP_UserProfiles"
ProfileDBServer = "SQL.contoso.local\SQLINSTANCE"
SocialDBName = "SP_Social"
SocialDBServer = "SQL.contoso.local\SQLINSTANCE"
SyncDBName = "SP_ProfileSync"
SyncDBServer = "SQL.contoso.local\SQLINSTANCE"
EnableNetBIOS = $false
SiteNamingConflictResolution = "Domain_Username"
PsDscRunAsCredential = $SetupAccount
}
}
}
| ykuijs/xSharePoint | Modules/SharePointDsc/Examples/Resources/SPUserProfileServiceApp/3-SiteNamingConflictResolution.ps1 | PowerShell | mit | 1,436 |
[cmdletbinding()]
param()
<#
[CmdletBinding()]
param()
Trace-VstsEnteringInvocation $MyInvocation
try {
Import-VstsLocStrings "$PSScriptRoot\Task.json"
[string]$msBuildLocationMethod = Get-VstsInput -Name MSBuildLocationMethod
[string]$msBuildLocation = Get-VstsInput -Name MSBuildLocation
[string]$msBuildArguments = Get-VstsInput -Name MSBuildArguments
[string]$solution = Get-VstsInput -Name Solution -Require
[string]$platform = Get-VstsInput -Name Platform
[string]$configuration = Get-VstsInput -Name Configuration
[bool]$clean = Get-VstsInput -Name Clean -AsBool
[bool]$restoreNuGetPackages = Get-VstsInput -Name RestoreNuGetPackages -AsBool
[bool]$logProjectEvents = Get-VstsInput -Name LogProjectEvents -AsBool
[string]$msBuildVersion = Get-VstsInput -Name MSBuildVersion
[string]$msBuildArchitecture = Get-VstsInput -Name MSBuildArchitecture
. $PSScriptRoot\Select-MSBuildLocation_PS3.ps1
Import-Module -Name $PSScriptRoot\MSBuildHelpers\MSBuildHelpers.psm1
$solutionFiles = Get-SolutionFiles -Solution $solution
$msBuildArguments = Format-MSBuildArguments -MSBuildArguments $msBuildArguments -Platform $platform -Configuration $configuration
$msBuildLocation = Select-MSBuildLocation -Method $msBuildLocationMethod -Location $msBuildLocation -Version $msBuildVersion -Architecture $msBuildArchitecture
$ErrorActionPreference = 'Continue'
Invoke-BuildTools -NuGetRestore:$restoreNuGetPackages -SolutionFiles $solutionFiles -MSBuildLocation $msBuildLocation -MSBuildArguments $msBuildArguments -Clean:$clean -NoTimelineLogger:(!$logProjectEvents)
} finally {
Trace-VstsLeavingInvocation $MyInvocation
}
#>
# Arrange.
. $PSScriptRoot\..\..\lib\Initialize-Test.ps1
Register-Mock Trace-VstsEnteringInvocation
Register-Mock Trace-VstsLeavingInvocation
Register-Mock Import-VstsLocStrings
foreach ($clean in @($true, $false)) {
foreach ($restoreNuGetPackages in @($true, $false)) {
foreach ($logProjectEvents in @($true, $false)) {
Unregister-Mock Get-VstsInput
Unregister-Mock Get-SolutionFiles
Unregister-Mock Format-MSBuildArguments
Unregister-Mock Select-MSBuildLocation
Unregister-Mock Invoke-BuildTools
Register-Mock Get-VstsInput { 'Some input method' } -- -Name MSBuildLocationMethod
Register-Mock Get-VstsInput { 'Some input location' } -- -Name MSBuildLocation
Register-Mock Get-VstsInput { 'Some input arguments' } -- -Name MSBuildArguments
Register-Mock Get-VstsInput { 'Some input solution' } -- -Name Solution -Require
Register-Mock Get-VstsInput { 'Some input platform' } -- -Name Platform
Register-Mock Get-VstsInput { 'Some input configuration' } -- -Name Configuration
Register-Mock Get-VstsInput { $clean } -- -Name Clean -AsBool
Register-Mock Get-VstsInput { $restoreNuGetPackages } -- -Name RestoreNuGetPackages -AsBool
Register-Mock Get-VstsInput { $logProjectEvents } -- -Name LogProjectEvents -AsBool
Register-Mock Get-VstsInput { 'Some input version' } -- -Name MSBuildVersion
Register-Mock Get-VstsInput { 'Some input architecture' } -- -Name MSBuildArchitecture
Register-Mock Get-SolutionFiles { 'Some solution 1', 'Some solution 2' } -- -Solution 'Some input solution'
Register-Mock Format-MSBuildArguments { 'Some formatted arguments' } -- -MSBuildArguments 'Some input arguments' -Platform 'Some input platform' -Configuration 'Some input configuration'
Register-Mock Select-MSBuildLocation { 'Some location' } -- -Method 'Some input method' -Location 'Some input location' -Version 'Some input version' -Architecture 'Some input architecture'
Register-Mock Invoke-BuildTools { 'Some build output line 1', 'Some build output line 2' }
# Act.
$output = & $PSScriptRoot\..\..\..\Tasks\MSBuild\MSBuild_PS3.ps1
# Assert.
Assert-AreEqual ('Some build output line 1', 'Some build output line 2') $output
Assert-WasCalled Invoke-BuildTools -- -NuGetRestore: $restoreNuGetPackages -SolutionFiles @('Some solution 1', 'Some solution 2') -MSBuildLocation 'Some location' -MSBuildArguments 'Some formatted arguments' -Clean: $clean -NoTimelineLogger: $(!$logProjectEvents)
}
}
}
| vtbassmatt/vso-agent-tasks | Tests/L0/MSBuild/PassesArguments.ps1 | PowerShell | mit | 4,409 |
#Requires -Version 3.0
#Requires -Module AzureRM.Resources
#Requires -Module Azure.Storage
Param(
[string] [Parameter(Mandatory=$true)] $ResourceGroupLocation,
[string] $ResourceGroupName = 'ArmTemplates',
[switch] $UploadArtifacts,
[string] $StorageAccountName,
[string] $StorageAccountResourceGroupName,
[string] $StorageContainerName = $ResourceGroupName.ToLowerInvariant() + '-stageartifacts',
[string] $TemplateFile = '..\Templates\azuredeploy.json',
[string] $TemplateParametersFile = '..\Templates\azuredeploy.parameters.json',
[string] $ArtifactStagingDirectory = '..\bin\Debug\staging',
[string] $AzCopyPath = '..\Tools\AzCopy.exe',
[string] $DSCSourceFolder = '..\DSC'
)
Import-Module Azure -ErrorAction SilentlyContinue
try {
[Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent("VSAzureTools-$UI$($host.name)".replace(" ","_"), "2.8")
} catch { }
Set-StrictMode -Version 3
$OptionalParameters = New-Object -TypeName Hashtable
$TemplateFile = [System.IO.Path]::Combine($PSScriptRoot, $TemplateFile)
$TemplateParametersFile = [System.IO.Path]::Combine($PSScriptRoot, $TemplateParametersFile)
if ($UploadArtifacts) {
# Convert relative paths to absolute paths if needed
$AzCopyPath = [System.IO.Path]::Combine($PSScriptRoot, $AzCopyPath)
$ArtifactStagingDirectory = [System.IO.Path]::Combine($PSScriptRoot, $ArtifactStagingDirectory)
$DSCSourceFolder = [System.IO.Path]::Combine($PSScriptRoot, $DSCSourceFolder)
Set-Variable ArtifactsLocationName '_artifactsLocation' -Option ReadOnly -Force
Set-Variable ArtifactsLocationSasTokenName '_artifactsLocationSasToken' -Option ReadOnly -Force
$OptionalParameters.Add($ArtifactsLocationName, $null)
$OptionalParameters.Add($ArtifactsLocationSasTokenName, $null)
# Parse the parameter file and update the values of artifacts location and artifacts location SAS token if they are present
$JsonContent = Get-Content $TemplateParametersFile -Raw | ConvertFrom-Json
$JsonParameters = $JsonContent | Get-Member -Type NoteProperty | Where-Object {$_.Name -eq "parameters"}
if ($JsonParameters -eq $null) {
$JsonParameters = $JsonContent
}
else {
$JsonParameters = $JsonContent.parameters
}
$JsonParameters | Get-Member -Type NoteProperty | ForEach-Object {
$ParameterValue = $JsonParameters | Select-Object -ExpandProperty $_.Name
if ($_.Name -eq $ArtifactsLocationName -or $_.Name -eq $ArtifactsLocationSasTokenName) {
$OptionalParameters[$_.Name] = $ParameterValue.value
}
}
$StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $StorageAccountResourceGroupName -Name $StorageAccountName).Key1
$StorageAccountContext = (Get-AzureRmStorageAccount -ResourceGroupName $StorageAccountResourceGroupName -Name $StorageAccountName).Context
# Create DSC configuration archive
if (Test-Path $DSCSourceFolder) {
Add-Type -Assembly System.IO.Compression.FileSystem
$ArchiveFile = Join-Path $ArtifactStagingDirectory "dsc.zip"
Remove-Item -Path $ArchiveFile -ErrorAction SilentlyContinue
[System.IO.Compression.ZipFile]::CreateFromDirectory($DSCSourceFolder, $ArchiveFile)
}
# Generate the value for artifacts location if it is not provided in the parameter file
$ArtifactsLocation = $OptionalParameters[$ArtifactsLocationName]
if ($ArtifactsLocation -eq $null) {
$ArtifactsLocation = $StorageAccountContext.BlobEndPoint + $StorageContainerName
$OptionalParameters[$ArtifactsLocationName] = $ArtifactsLocation
}
# Use AzCopy to copy files from the local storage drop path to the storage account container
& $AzCopyPath """$ArtifactStagingDirectory""", $ArtifactsLocation, "/DestKey:$StorageAccountKey", "/S", "/Y", "/Z:$env:LocalAppData\Microsoft\Azure\AzCopy\$ResourceGroupName"
if ($LASTEXITCODE -ne 0) { return }
# Generate the value for artifacts location SAS token if it is not provided in the parameter file
$ArtifactsLocationSasToken = $OptionalParameters[$ArtifactsLocationSasTokenName]
if ($ArtifactsLocationSasToken -eq $null) {
# Create a SAS token for the storage container - this gives temporary read-only access to the container
$ArtifactsLocationSasToken = New-AzureStorageContainerSASToken -Container $StorageContainerName -Context $StorageAccountContext -Permission r -ExpiryTime (Get-Date).AddHours(4)
$ArtifactsLocationSasToken = ConvertTo-SecureString $ArtifactsLocationSasToken -AsPlainText -Force
$OptionalParameters[$ArtifactsLocationSasTokenName] = $ArtifactsLocationSasToken
}
}
# Create or update the resource group using the specified template file and template parameters file
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $ResourceGroupLocation -Verbose -Force -ErrorAction Stop
New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $TemplateFile).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) `
-ResourceGroupName $ResourceGroupName `
-TemplateFile $TemplateFile `
-TemplateParameterFile $TemplateParametersFile `
@OptionalParameters `
-Force -Verbose
| peterschen/ARM | old/04-Services/Scripts/Deploy-AzureResourceGroup.ps1 | PowerShell | mit | 5,416 |
function Get-DbaDbServiceBrokerService {
<#
.SYNOPSIS
Gets database service broker services
.DESCRIPTION
Gets database Sservice broker services
.PARAMETER SqlInstance
The target SQL Server instance or 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 service broker services from specific database(s)
.PARAMETER ExcludeDatabase
The database(s) to exclude - this list is auto populated from the server
.PARAMETER ExcludeSystemService
This switch removes all system objects from the queue collection
.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: Database, ServiceBroker, Service
Author: Ant Green (@ant_green)
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Get-DbaDbServiceBrokerService
.EXAMPLE
PS C:\> Get-DbaDbServiceBrokerService -SqlInstance sql2016
Gets all database service broker queues
.EXAMPLE
PS C:\> Get-DbaDbServiceBrokerService -SqlInstance Server1 -Database db1
Gets the service broker queues for the db1 database
.EXAMPLE
PS C:\> Get-DbaDbServiceBrokerService -SqlInstance Server1 -ExcludeDatabase db1
Gets the service broker queues for all databases except db1
.EXAMPLE
PS C:\> Get-DbaDbServiceBrokerService -SqlInstance Server1 -ExcludeSystemService
Gets the service broker queues for all databases that are not system objects
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[DbaInstanceParameter[]]$SqlInstance,
[PSCredential]$SqlCredential,
[object[]]$Database,
[object[]]$ExcludeDatabase,
[switch]$ExcludeSystemService,
[switch]$EnableException
)
process {
if (Test-Bound SqlInstance) {
$InputObject = Get-DbaDatabase -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
}
foreach ($db in $InputObject) {
if (!$db.IsAccessible) {
Write-Message -Level Warning -Message "Database $db is not accessible. Skipping."
continue
}
if ($db.ServiceBroker.Services.Count -eq 0) {
Write-Message -Message "No Service Broker Services exist in the $db database on $instance" -Target $db -Level Output
continue
}
foreach ($service in $db.ServiceBroker.Services) {
if ( (Test-Bound -ParameterName ExcludeSystemService) -and $service.IsSystemObject ) {
continue
}
Add-Member -Force -InputObject $service -MemberType NoteProperty -Name ComputerName -value $service.Parent.Parent.ComputerName
Add-Member -Force -InputObject $service -MemberType NoteProperty -Name InstanceName -value $service.Parent.Parent.InstanceName
Add-Member -Force -InputObject $service -MemberType NoteProperty -Name SqlInstance -value $service.Parent.Parent.SqlInstance
Add-Member -Force -InputObject $service -MemberType NoteProperty -Name Database -value $db.Name
$defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'Database', 'Owner', 'ID as ServiceID', 'Name', 'QueueSchema', 'QueueName'
Select-DefaultView -InputObject $service -Property $defaults
}
}
}
}
| wsmelton/dbatools | functions/Get-DbaDbServiceBrokerService.ps1 | PowerShell | mit | 4,281 |
param($installPath, $toolsPath, $package, $project)
# This is the MSBuild targets file to add
$targetsFile = [System.IO.Path]::Combine($toolsPath, $package.Id + '.targets')
# Need to load MSBuild assembly if it's not loaded yet.
Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
# Grab the loaded MSBuild project for the project
$msbuild = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1
# Make the path to the targets file relative.
$projectUri = new-object Uri('file://' + $project.FullName)
$targetUri = new-object Uri('file://' + $targetsFile)
$relativePath = $projectUri.MakeRelativeUri($targetUri).ToString().Replace([System.IO.Path]::AltDirectorySeparatorChar, [System.IO.Path]::DirectorySeparatorChar)
# Add the import and save the project
$msbuild.Xml.AddImport($relativePath) | out-null
$project.Save() | CslaGenFork/CslaGenFork | tags/Rules sample v.2.0.0/packages/Microsoft.Bcl.Build.1.0.0-rc/tools/Install.ps1 | PowerShell | mit | 1,032 |
# constants
if (Test-Path "$PSScriptRoot\constants.local.ps1") {
Write-Verbose "tests\constants.local.ps1 found."
. "$PSScriptRoot\constants.local.ps1"
} elseif ($env:CODESPACES -and ($env:TERM_PROGRAM -eq 'vscode' -and $env:REMOTE_CONTAINERS)) {
$script:instance1 = "dbatools1"
$script:instance2 = "dbatools2"
$script:instance3 = "dbatools3"
$script:instances = @($script:instance1, $script:instance2)
$SqlCred = [PSCredential]::new('sa', (ConvertTo-SecureString $env:SA_PASSWORD -AsPlainText -Force))
$PSDefaultParameterValues = @{
"*:SqlCredential" = $sqlCred
}
} elseif ($env:GITHUB_WORKSPACE) {
$script:dbatoolsci_computer = "localhost"
$script:instance1 = "localhost"
$script:instance2 = "localhost:14333"
$script:instance2SQLUserName = $null # placeholders for -SqlCredential testing
$script:instance2SQLPassword = $null
$script:instance3 = "localhost"
$script:instance2_detailed = "localhost,14333" #Just to make sure things parse a port properly
$script:appveyorlabrepo = "/tmp/appveyor-lab"
$instances = @($script:instance1, $script:instance2)
$ssisserver = "localhost\sql2016"
$script:azureblob = "https://dbatools.blob.core.windows.net/sql"
$script:azureblobaccount = "dbatools"
$script:azureserver = 'psdbatools.database.windows.net'
$script:azuresqldblogin = "appveyor@clemairegmail.onmicrosoft.com"
} else {
$script:dbatoolsci_computer = "localhost"
$script:instance1 = "localhost\sql2008r2sp2"
$script:instance2 = "localhost\sql2016"
$script:instance2SQLUserName = $null # placeholders for -SqlCredential testing
$script:instance2SQLPassword = $null
$script:instance3 = "localhost\sql2017"
$script:instance2_detailed = "localhost,14333\sql2016" #Just to make sure things parse a port properly
$script:appveyorlabrepo = "C:\github\appveyor-lab"
$instances = @($script:instance1, $script:instance2)
$ssisserver = "localhost\sql2016"
$script:azureblob = "https://dbatools.blob.core.windows.net/sql"
$script:azureblobaccount = "dbatools"
$script:azureserver = 'psdbatools.database.windows.net'
$script:azuresqldblogin = "appveyor@clemairegmail.onmicrosoft.com"
}
if ($env:appveyor) {
$PSDefaultParameterValues['*:WarningAction'] = 'SilentlyContinue'
}
| wsmelton/dbatools | tests/constants.ps1 | PowerShell | mit | 2,326 |
[cmdletbinding(SupportsShouldProcess=$true)]
param($publishProperties=@{}, $packOutput, $pubProfilePath)
# to learn more about this file visit https://go.microsoft.com/fwlink/?LinkId=524327
try{
if ($publishProperties['ProjectGuid'] -eq $null){
$publishProperties['ProjectGuid'] = '5a318bef-15a8-41d0-981e-2f9dbe025989'
}
$publishModulePath = Join-Path (Split-Path $MyInvocation.MyCommand.Path) 'publish-module.psm1'
Import-Module $publishModulePath -DisableNameChecking -Force
# call Publish-AspNet to perform the publish operation
Publish-AspNet -publishProperties $publishProperties -packOutput $packOutput -pubProfilePath $pubProfilePath
}
catch{
"An error occurred during publish.`n{0}" -f $_.Exception.Message | Write-Error
} | MMA2017/ObisoftWeb | src/ObisoftWebCore/Properties/PublishProfiles/Obisoft Server-publish.ps1 | PowerShell | apache-2.0 | 774 |
# powershell v2 compatibility
$psVer = $PSVersionTable.PSVersion.Major
if ($psver -ge 3) {
function Get-ChildItemDir {Get-ChildItem -Directory $args}
} else {
function Get-ChildItemDir {Get-ChildItem $args}
}
$packageName = 'keepass-plugin-keecloud'
$typName = 'KeeCloud.plgx'
$packageSearch = 'KeePass Password Safe'
try {
# search registry for installed KeePass
$regPath = Get-ItemProperty -Path @('HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',
'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*') `
-ErrorAction:SilentlyContinue `
| Where-Object {$_.DisplayName -like "$packageSearch*" `
-and `
$_.DisplayVersion -ge 2.0 `
-and `
$_.DisplayVersion -lt 3.0 } `
| ForEach-Object { $_.InstallLocation }
$installPath = $regPath
# search $env:ChocolateyBinRoot for portable install
if (! $installPath) {
Write-Host "$($packageSearch) not found in registry."
$binRoot = Get-BinRoot
$portPath = Join-Path $binRoot "keepass"
$installPath = Get-ChildItemDir $portPath* -ErrorAction SilentlyContinue
}
if (! $installPath) {
Write-Host "$($packageSearch) not found in $($env:ChocolateyBinRoot)"
throw "$($packageSearch) install location could not be found."
}
$pluginPath = (Get-ChildItemDir $installPath\Plugin*).FullName
if ($pluginPath.Count -eq 0) {
throw "Plugins directory not found."
}
$installFile = Join-Path $pluginPath "$($packageName).plgx"
Remove-Item -Path $installFile `
-Force
if ( Get-Process -Name "KeePass" `
-ErrorAction SilentlyContinue ) {
Write-Host "$($packageSearch) is running. $($packageName) will be removed at next restart of $($packageSearch)."
}
} catch {
throw $_.Exception
} | dtgm/chocolatey-packages | automatic/_output/keepass-plugin-keecloud/1.0.43/tools/chocolateyUninstall.ps1 | PowerShell | apache-2.0 | 1,985 |
$packageName = 'lsasecretsview'
$url = 'http://www.nirsoft.net/toolsdownload/lsasecretsview.zip'
$checksum = '62aa19e9aa4bbf6b1a0104d71ea2b4d450162287'
$checksumType = 'sha1'
$url64 = 'http://www.nirsoft.net/toolsdownload/lsasecretsview-x64.zip'
$checksum64 = 'cde2e9a0c8fdd9ede970fdf07bc8570426fe6107'
$checksumType64 = 'sha1'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$installFile = Join-Path $toolsDir "$($packageName).exe"
$chocTempDir = Join-Path $Env:Temp "chocolatey"
$tempDir = Join-Path $chocTempDir "$packageName"
if (![System.IO.Directory]::Exists($tempDir)) {[System.IO.Directory]::CreateDirectory($tempDir) | Out-Null}
$zipFile = Join-Path $tempDir "$($packageName).zip"
$url32bit = $url
$checksum32 = $checksum
$checksumType32 = $checksumType
$bitWidth = 32
if (Get-ProcessorBits 64) {
$bitWidth = 64
}
Write-Debug "CPU is $bitWidth bit"
$bitPackage = 32
if ($bitWidth -eq 64 -and $url64 -ne $null -and $url64 -ne '') {
Write-Debug "Setting url to '$url64' and bitPackage to $bitWidth"
$bitPackage = $bitWidth
$url = $url64
# only set if urls are different
if ($url32bit -ne $url64) {
$checksum = $checksum64
}
$checksumType = $checksumType64
}
$fileDirectory = $([System.IO.Path]::GetDirectoryName($zipFile))
if (!(Test-Path($fileDirectory))) {
[System.IO.Directory]::CreateDirectory($fileDirectory) | Out-Null
}
$forceX86 = $env:chocolateyForceX86
if ($forceX86) {
Write-Debug "User specified -x86 so forcing 32 bit"
$bitPackage = 32
$url = $url32bit
$checksum = $checksum32
$checksumType = $checksumType32
}
$referer = "http://www.nirsoft.net/utils/"
$wc = New-Object System.Net.WebClient
$wc.Headers.Add("Referer", $referer)
$wc.DownloadFile($url, $zipFile)
Get-ChecksumValid -File "$zipFile" `
-Checksum "$checksum" `
-ChecksumType "$checksumType"
Get-ChocolateyUnzip -FileFullPath "$zipFile" `
-Destination "$toolsDir" `
-PackageName "$packageName"
Set-Content -Path ("$installFile.gui") `
-Value $null | dtgm/chocolatey-packages | automatic/_output/lsasecretsview/1.21/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 2,084 |
param($global:RestartRequired=0,
$global:MoreUpdates=0,
$global:MaxCycles=5,
$MaxUpdatesPerCycle=500)
$Logfile = "C:\Windows\Temp\win-updates.log"
function LogWrite {
Param ([string]$logstring)
$now = Get-Date -format s
Add-Content $Logfile -value "$now $logstring"
Write-Host $logstring
}
function Check-ContinueRestartOrEnd() {
$RegistryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
$RegistryEntry = "InstallWindowsUpdates"
switch ($global:RestartRequired) {
0 {
$prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
if ($prop) {
LogWrite "Restart Registry Entry Exists - Removing It"
Remove-ItemProperty -Path $RegistryKey -Name $RegistryEntry -ErrorAction SilentlyContinue
}
LogWrite "No Restart Required"
Check-WindowsUpdates
if (($global:MoreUpdates -eq 1) -and ($script:Cycles -le $global:MaxCycles)) {
Install-WindowsUpdates
} elseif ($script:Cycles -gt $global:MaxCycles) {
LogWrite "Exceeded Cycle Count - Stopping"
Invoke-Expression "a:\openssh.ps1 -AutoStart"
} else {
LogWrite "Done Installing Windows Updates"
Invoke-Expression "a:\openssh.ps1 -AutoStart"
}
}
1 {
$prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
if (-not $prop) {
LogWrite "Restart Registry Entry Does Not Exist - Creating It"
Set-ItemProperty -Path $RegistryKey -Name $RegistryEntry -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File $($script:ScriptPath) -MaxUpdatesPerCycle $($MaxUpdatesPerCycle)"
} else {
LogWrite "Restart Registry Entry Exists Already"
}
LogWrite "Restart Required - Restarting..."
Restart-Computer
}
default {
LogWrite "Unsure If A Restart Is Required"
break
}
}
}
# Result code on downloading updates:
# 0 = not started
# 1 = in progress
# 2 = succeeded
# 3 = succeededwitherrors
# 4 = failed
# 5 = aborted
function Install-WindowsUpdates() {
$script:Cycles++
LogWrite "Evaluating Available Updates with limit of $($MaxUpdatesPerCycle):"
$UpdatesToDownload = New-Object -ComObject 'Microsoft.Update.UpdateColl'
$script:i = 0;
$CurrentUpdates = $SearchResult.Updates | Select-Object
while($script:i -lt $CurrentUpdates.Count -and $script:CycleUpdateCount -lt $MaxUpdatesPerCycle) {
$Update = $CurrentUpdates[$script:i]
if (($Update -ne $null) -and (!$Update.IsDownloaded)) {
[bool]$addThisUpdate = $false
if ($Update.InstallationBehavior.CanRequestUserInput) {
LogWrite "> Skipping: $($Update.Title) because it requires user input"
} else {
if (!($Update.EulaAccepted)) {
LogWrite "> Note: $($Update.Title) has a license agreement that must be accepted. Accepting the license."
$Update.AcceptEula()
[bool]$addThisUpdate = $true
$script:CycleUpdateCount++
} else {
[bool]$addThisUpdate = $true
$script:CycleUpdateCount++
}
}
if ([bool]$addThisUpdate) {
LogWrite "Adding: $($Update.Title)"
$UpdatesToDownload.Add($Update) |Out-Null
}
}
$script:i++
}
if ($UpdatesToDownload.Count -eq 0) {
LogWrite "No Updates To Download..."
} else {
LogWrite 'Downloading Updates...'
$ok = 0;
while (! $ok) {
try {
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Downloader.Download()
$ok = 1;
} catch {
LogWrite $_.Exception | Format-List -force
LogWrite "Error downloading updates. Retrying in 30s."
$script:attempts = $script:attempts + 1
Start-Sleep -s 30
}
}
}
$UpdatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl'
[bool]$rebootMayBeRequired = $false
LogWrite 'The following updates are downloaded and ready to be installed:'
foreach ($Update in $SearchResult.Updates) {
if (($Update.IsDownloaded)) {
LogWrite "> $($Update.Title)"
$UpdatesToInstall.Add($Update) |Out-Null
if ($Update.InstallationBehavior.RebootBehavior -gt 0){
[bool]$rebootMayBeRequired = $true
}
}
}
if ($UpdatesToInstall.Count -eq 0) {
LogWrite 'No updates available to install...'
$global:MoreUpdates=0
$global:RestartRequired=0
Invoke-Expression "a:\openssh.ps1 -AutoStart"
break
}
if ($rebootMayBeRequired) {
LogWrite 'These updates may require a reboot'
$global:RestartRequired=1
}
LogWrite "There are $($UpdatesToInstall.Count) updates currently queued."
LogWrite 'Installing updates...'
$Installer = $script:UpdateSession.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallationResult = $Installer.Install()
LogWrite "Installation Result: $($InstallationResult.ResultCode)"
LogWrite "Reboot Required: $($InstallationResult.RebootRequired)"
LogWrite 'Listing of updates installed and individual installation results:'
if ($InstallationResult.RebootRequired) {
$global:RestartRequired=1
} else {
$global:RestartRequired=0
}
for($i=0; $i -lt $UpdatesToInstall.Count; $i++) {
New-Object -TypeName PSObject -Property @{
Title = $UpdatesToInstall.Item($i).Title
Result = $InstallationResult.GetUpdateResult($i).ResultCode
}
}
Check-ContinueRestartOrEnd
}
function Check-WindowsUpdates() {
LogWrite "Checking For Windows Updates"
$Username = $env:USERDOMAIN + "\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName 'Windows Powershell' -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
LogWrite $Message
$script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
$script:successful = $FALSE
$script:attempts = 0
$script:maxAttempts = 12
while(-not $script:successful -and $script:attempts -lt $script:maxAttempts) {
try {
$script:SearchResult = $script:UpdateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
$script:successful = $TRUE
} catch {
LogWrite $_.Exception | Format-List -force
LogWrite "Search call to UpdateSearcher was unsuccessful. Retrying in 10s."
$script:attempts = $script:attempts + 1
Start-Sleep -s 10
}
}
if ($SearchResult.Updates.Count -ne 0) {
$Message = "There are " + $SearchResult.Updates.Count + " more updates."
LogWrite $Message
try {
$script:SearchResult.Updates |Select-Object -Property Title, Description, SupportUrl, UninstallationNotes, RebootRequired, EulaAccepted |Format-List
$global:MoreUpdates=1
} catch {
LogWrite $_.Exception | Format-List -force
LogWrite "Showing SearchResult was unsuccessful. Rebooting."
$global:RestartRequired=1
$global:MoreUpdates=0
Check-ContinueRestartOrEnd
LogWrite "Show never happen to see this text!"
Restart-Computer
}
} else {
LogWrite 'There are no applicable updates'
$global:RestartRequired=0
$global:MoreUpdates=0
}
}
$script:ScriptName = $MyInvocation.MyCommand.ToString()
$script:ScriptPath = $MyInvocation.MyCommand.Path
$script:UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
$script:UpdateSession.ClientApplicationID = 'Packer Windows Update Installer'
$script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
$script:SearchResult = New-Object -ComObject 'Microsoft.Update.UpdateColl'
$script:Cycles = 0
$script:CycleUpdateCount = 0
Check-WindowsUpdates
if ($global:MoreUpdates -eq 1) {
Install-WindowsUpdates
} else {
Check-ContinueRestartOrEnd
}
| tomswartz07/packer-windows | scripts/win-updates.ps1 | PowerShell | mit | 8,905 |
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"
. "$PSScriptRoot\..\internal\functions\Get-PasswordHash.ps1"
Describe "$CommandName Unit Tests" -Tag UnitTests, Get-DbaLogin {
Context "Validate parameters" {
[object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')}
[object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Login', 'Dictionary', '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
}
}
}
Describe "$commandname Integration Tests" -Tag "IntegrationTests" {
BeforeAll {
$server = Connect-DbaInstance -SqlInstance $script:instance1
$weaksauce = "dbatoolsci_testweak"
$weakpass = ConvertTo-SecureString $weaksauce -AsPlainText -Force
$newlogin = New-DbaLogin -SqlInstance $script:instance1 -Login $weaksauce -HashedPassword (Get-PasswordHash $weakpass $server.VersionMajor) -Force
}
AfterAll {
try {
$newlogin.Drop()
} catch {
# don't care
}
}
Context "making sure command works" {
It "finds the new weak password and supports piping" {
$results = Get-DbaLogin -SqlInstance $script:instance1 | Test-DbaLoginPassword
$results.SqlLogin | Should -Contain $weaksauce
}
It "returns just one login" {
$results = Test-DbaLoginPassword -SqlInstance $script:instance1 -Login $weaksauce
$results.SqlLogin | Should -Be $weaksauce
}
}
} | alevyinroc/dbatools | tests/Test-DbaLoginPassword.Tests.ps1 | PowerShell | mit | 1,893 |
#
# Swaggy Jenkins
# Jenkins API clients generated from Swagger / Open API specification
# Version: 1.1.2-pre.0
# Contact: blah@cliffano.com
# Generated by OpenAPI Generator: https://openapi-generator.tech
#
<#
.Synopsis
Helper function to format debug parameter output.
.Example
$PSBoundParameters | Out-DebugParameter | Write-Debug
#>
function Out-DebugParameter {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline = $true, Mandatory = $true)]
[AllowEmptyCollection()]
$InputObject
)
Begin {
$CommonParameters = Get-CommonParameters
}
Process {
$InputObject.GetEnumerator() | Where-Object {
$CommonParameters -notcontains $_.Key
} | Format-Table -AutoSize -Property (
@{
Name = 'Parameter'
Expression = {$_.Key}
},
@{
Name = 'Value'
Expression = {$_.Value}
}
) | Out-String -Stream | ForEach-Object {
if ($_.Trim()) {
$_
}
}
}
}
| cliffano/swaggy-jenkins | clients/powershell/generated/src/PSOpenAPITools/Private/Out-DebugParameter.ps1 | PowerShell | mit | 1,103 |
ConvertFrom-StringData -StringData @'
GettingActionMessage = Getting FSRM File Screen Template Action for {1} "{0}".
ActionExistsMessage = FSRM File Screen Template Action for {1} "{0}" exists.
ActionNotExistMessage = FSRM File Screen Template Action for {1} "{0}" does not exist.
SettingActionMessage = Setting FSRM File Screen Template Action for {1} "{0}".
EnsureActionExistsMessage = Ensuring FSRM File Screen Template Action for {1} "{0}" exists.
EnsureActionDoesNotExistMessage = Ensuring FSRM File Screen Template Action for {1} "{0}" does not exist.
ActionCreatedMessage = FSRM File Screen Template Action for {1} "{0}" has been created.
ActionUpdatedMessage = FSRM File Screen Template Action for {1} "{0}" has been updated.
ActionRemovedMessage = FSRM File Screen Template Action for {1} "{0}" has been removed.
ActionNoChangeMessage = FSRM File Screen Template Action for {1} "{0}" required not changes.
ActionWrittenMessage = FSRM File Screen Template Action for {1} "{0}" has been written.
TestingActionMessage = Testing FSRM File Screen Template Action for {1} "{0}".
ActionPropertyNeedsUpdateMessage = FSRM File Screen Template Action for {1} "{0}" {2} is different. Change required.
ActionDoesNotExistButShouldMessage = FSRM File Screen Template Action for {1} "{0}" does not exist but should. Change required.
ActionExistsAndShouldNotMessage = FSRM File Screen Template Action for {1} "{0}" exists but should not. Change required.
ActionDoesNotExistAndShouldNotMessage = FSRM File Screen Template Action for {1} "{0}" does not exist and should not. Change not required.
FileScreenTemplateNotFoundError = FSRM File Screen Template "{0}" not found.
FileScreenTemplateThresholdNotFoundError = FSRM File Screen Template "{0}" not found.
'@
| PlagueHO/cFSRM | DSCResources/DSR_FSRMFileScreenTemplateAction/en-US/DSR_FSRMFileScreenTemplateAction.strings.psd1 | PowerShell | mit | 1,825 |
function Add-AnnotatedContent
{
<#
.Synopsis
Concatenates files from a given folder into another file, annotating the
source folder and filenames in C# / SQL compatible comments.
.Description
Will accept a folder or list of folder via the pipeline. Always appends
to an existing file should it exist.
.Parameter Path
Complete folder path for a set of files. All files are read.
.Parameter Destination
The actual file to contactenate results to.
.Parameter Encoding
Optional parameter that specifies the Encoding to use for files.
Default is UTF8. Other options are Unicode, UTF7, UTF32, ASCII, Default,
OEM and BigEndianUnicode.
.Parameter Include
Optional parameter that can specify a filter for the files.
Uses the same syntax as the Get-ChildItem cmdlet.
Retrieves only the specified items. The value of this parameter
qualifies the Path parameter. Enter a path element or pattern,
such as "*.txt". Wildcards are permitted.
.Example
Add-AnnotatedContent -Path c:\test -Destination c:\bar\test.txt
Description
-----------
Finds all files in c:\test, and concatenates them to c:\bar\test.txt,
adding annotations for each directory and each file into the resulting
file. Uses default encoding of UTF8.
.Example
'c:\foo', 'c:\bar' | Add-AnnotatedContent -Destination c:\baz.txt
Description
-----------
Finds all files in c:\foo and c:\bar, and concatenates them to
c:\baz.txt, adding annotations for each directory and each file into the
resulting file. Uses default encoding of UTF8.
.Example
Add-AnnotatedContent -Path . -Include *.sql -Destination c:\s.sql
Description
-----------
Finds *.sql files in subdirs of current dir, and concatenates them to
c:\s.sql, adding annotations for each directory and each file into
the resulting file. Uses default encoding of UTF8.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
[ValidateScript({ (Test-Path $_) -and (Get-Item $_).PSIsContainer })]
$Path,
[Parameter(Mandatory=$true)]
[string]
$Destination,
[Parameter(Mandatory=$false)]
[string]
[ValidateSet('Unicode', 'UTF7', 'UTF8', 'UTF32', 'ASCII',
'BigEndianUnicode', 'Default', 'OEM')]
$Encoding = 'UTF8',
[Parameter(Mandatory=$false)]
[string[]]
$Include = $null
)
process
{
#handling both pipeline and non-pipeline calls
if ($_ -eq $null) { $_ = $Path }
$_ |
%{
$root = (Get-Item $_).FullName
$params = @{ Path = $_; Recurse = $true }
if ($include -ne $null) { $params.Include = $include }
$files = Get-ChildItem @params
$directories = $files |
Select -ExpandProperty DirectoryName -Unique |
Sort-Object
$directories |
% {
$dir = $_
Write-Verbose "Parsing $dir"
$dirName = $dir.Replace($root, '')
if ($dirName -eq '') { $dirName = '.' }
else { $dirName = $dirName.Substring(1) }
@"
/**************************************************
* Folder: $dirName
***************************************************/
"@ | Out-File $Destination -Append -Encoding $Encoding
$added = @()
$files |
? { $_.DirectoryName -eq $dir } |
% {
@"
--File Name: $($_.Name)
$([System.IO.File]::ReadAllText($_.FullName))
"@ | Out-File $Destination -Append -Encoding $Encoding
$added += $_.Name
}
"Added files $($added -join ' ') from $dirName to $Destination"
}
}
}
}
Export-ModuleMember -Function Add-AnnotatedContent
| Iristyle/Midori | tools/Files.psm1 | PowerShell | mit | 3,799 |
# Get the supplied parameters
$DACPACPackageStep = $OctopusParameters["DACPACPackageStep"]
$DACPACPackageName = $OctopusParameters["DACPACPackageName"]
$PublishProfile = $OctopusParameters["DACPACPublishProfile"]
$Report = Format-OctopusArgument -Value $OctopusParameters["Report"]
$Script = Format-OctopusArgument -Value $OctopusParameters["Script"]
$Deploy = Format-OctopusArgument -Value $OctopusParameters["Deploy"]
$TargetServer = $OctopusParameters["TargetServer"]
$TargetDatabase = $OctopusParameters["TargetDatabase"]
$UseIntegratedSecurity = Format-OctopusArgument -Value $OctopusParameters["UseIntegratedSecurity"]
$Username = $OctopusParameters["SQLUsername"]
$Password = $OctopusParameters["SQLPassword"]
$AdditionalDeploymentContributors = $OctopusParameters["AdditionalContributors"]
$AdditionalDeploymentContributorArguments = $OctopusParameters["AdditionalContributorArguments"]
$InstallPathKey = ("Octopus.Action[{0}].Output.Package.InstallationDirectoryPath" -f $DACPACPackageStep)
$InstallPath = $OctopusParameters[$InstallPathKey]
# Expand the publish dacpac filename
$DACPACPackageName = ($InstallPath + "\" + $DACPACPackageName)
# Expand the publish profile filename
$PublishProfile = ($InstallPath + "\" + $PublishProfile)
# Invoke the DacPac utility
Invoke-DacPacUtility -Report $Report -Script $Script -Deploy $Deploy -DacPacFilename $DACPACPackageName -TargetServer $TargetServer -TargetDatabase $TargetDatabase -UseIntegratedSecurity $UseIntegratedSecurity -Username $Username -Password $Password -PublishProfile $PublishProfile -AdditionalDeploymentContributors $AdditionalDeploymentContributors -AdditionalDeploymentContributorArguments $AdditionalDeploymentContributorArguments | kchenery/octopus | Octopus.PS/Step Templates/SSDT DacPac Command.ps1 | PowerShell | mit | 1,711 |
workflow Stop-LingeringSession {
param (
[Parameter(Mandatory)]
[Int] $ProcessId,
[Parameter(Mandatory)]
[String] $Server,
[Parameter(Mandatory)]
[PSCredential] $Credential
)
try {
$Null = inlinescript {
$CimSession = New-CimSession -ComputerName $using:Server -Authentication CredSsp -Credential $using:Credential
if ($process = Get-CimInstance -ClassName win32_process -CimSession $CimSession -Filter "ProcessId = '$using:ProcessId'") {
$process | Invoke-CimMethod -MethodName terminate | Out-Null
}
$CimSession | Remove-CimSession
}
}
catch {
# Do nothing
}
} | bgelens/Presentations | 052015_DUPSUG/WAPack-Integration/Stop-LingeringSession.ps1 | PowerShell | mit | 728 |
function Export-DbaUser {
<#
.SYNOPSIS
Exports users creation and its permissions to a T-SQL file or host.
.DESCRIPTION
Exports users creation and its permissions to a T-SQL file or host. Export includes user, create and add to role(s), database level permissions, object level permissions.
.PARAMETER SqlInstance
The target SQL Server instance or instances. SQL Server 2000 and above supported.
.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
The database(s) to process - this list is auto-populated from the server. If unspecified, all InputObject will be processed.
.PARAMETER ExcludeDatabase
The database(s) to exclude - this list is auto-populated from the server
.PARAMETER User
Export only the specified database user(s). If not specified will export all users from the database(s)
.PARAMETER DestinationVersion
To say to which version the script should be generated. If not specified will use database compatibility level
.PARAMETER Path
Specifies the directory where the file or files will be exported.
.PARAMETER FilePath
Specifies the full file path of the output file.
.PARAMETER InputObject
Allows database objects to be piped in from Get-DbaDatabase
.PARAMETER NoClobber
Do not overwrite file
.PARAMETER Append
Append to file
.PARAMETER Passthru
Output script to console, useful with | clip
.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed.
.PARAMETER Confirm
Prompts you for confirmation before executing any changing operations within the command.
.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.
.PARAMETER ScriptingOptionsObject
A Microsoft.SqlServer.Management.Smo.ScriptingOptions object with the options that you want to use to generate the t-sql script.
You can use the NEw-DbaScriptingOption to generate it.
.PARAMETER ExcludeGoBatchSeparator
If specified, will NOT script the 'GO' batch separator.
.NOTES
Tags: User, Export
Author: Claudio Silva (@ClaudioESSilva)
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Export-DbaUser
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sql2005 -FilePath C:\temp\sql2005-users.sql
Exports SQL for the users in server "sql2005" and writes them to the file "C:\temp\sql2005-users.sql"
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sqlserver2014a $scred -FilePath C:\temp\users.sql -Append
Authenticates to sqlserver2014a using SQL Authentication. Exports all users to C:\temp\users.sql, and appends to the file if it exists. If not, the file will be created.
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -FilePath C:\temp\users.sql
Exports ONLY users User1 and User2 from sqlserver2014a to the file C:\temp\users.sql
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sqlserver2014a -User User1, User2 -Path C:\temp
Exports ONLY users User1 and User2 from sqlserver2014a to the folder C:\temp. One file per user will be generated
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -User User1 -FilePath C:\temp\users.sql -DestinationVersion SQLServer2016
Exports user User1 from sqlserver2008 to the file C:\temp\users.sql with syntax to run on SQL Server 2016
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\temp\users.sql
Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\temp\users.sql file.
.EXAMPLE
PS C:\> $options = New-DbaScriptingOption
PS C:\> $options.ScriptDrops = $false
PS C:\> $options.WithDependencies = $true
PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\temp\users.sql -ScriptingOptionsObject $options
Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\temp\users.sql file.
It will not script drops but will script dependencies.
.EXAMPLE
PS C:\> Export-DbaUser -SqlInstance sqlserver2008 -Database db1,db2 -FilePath C:\temp\users.sql -ExcludeGoBatchSeparator
Exports ONLY users from db1 and db2 database on sqlserver2008 server, to the C:\temp\users.sql file without the 'GO' batch separator.
#>
[CmdletBinding(DefaultParameterSetName = "Default")]
[OutputType([String])]
param (
[parameter(ValueFromPipeline)]
[DbaInstanceParameter[]]$SqlInstance,
[parameter(ValueFromPipeline)]
[Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
[PSCredential]$SqlCredential,
[string[]]$Database,
[string[]]$ExcludeDatabase,
[string[]]$User,
[ValidateSet('SQLServer2000', 'SQLServer2005', 'SQLServer2008/2008R2', 'SQLServer2012', 'SQLServer2014', 'SQLServer2016', 'SQLServer2017')]
[string]$DestinationVersion,
[string]$Path = (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport'),
[Alias("OutFile", "FileName")]
[string]$FilePath,
[Alias("NoOverwrite")]
[switch]$NoClobber,
[switch]$Append,
[switch]$Passthru,
[switch]$EnableException,
[Microsoft.SqlServer.Management.Smo.ScriptingOptions]$ScriptingOptionsObject = $null,
[switch]$ExcludeGoBatchSeparator
)
begin {
$null = Test-ExportDirectory -Path $Path
$outsql = $script:pathcollection = @()
$GenerateFilePerUser = $false
$versions = @{
'SQLServer2000' = 'Version80'
'SQLServer2005' = 'Version90'
'SQLServer2008/2008R2' = 'Version100'
'SQLServer2012' = 'Version110'
'SQLServer2014' = 'Version120'
'SQLServer2016' = 'Version130'
'SQLServer2017' = 'Version140'
}
$versionName = @{
'Version80' = 'SQLServer2000'
'Version90' = 'SQLServer2005'
'Version100' = 'SQLServer2008/2008R2'
'Version110' = 'SQLServer2012'
'Version120' = 'SQLServer2014'
'Version130' = 'SQLServer2016'
'Version140' = 'SQLServer2017'
}
}
process {
if (Test-FunctionInterrupt) { return }
foreach ($instance in $SqlInstance) {
$InputObject += Get-DbaDatabase -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase
}
# To keep the filenames generated and re-use (appedn) if needed
$usersProcessed = @{ }
foreach ($db in $InputObject) {
if ([string]::IsNullOrEmpty($destinationVersion)) {
#Get compatibility level for scripting the objects
$scriptVersion = $db.CompatibilityLevel
} else {
$scriptVersion = $versions[$destinationVersion]
}
$versionNameDesc = $versionName[$scriptVersion.ToString()]
#If not passed create new ScriptingOption. Otherwise use the one that was passed
if ($null -eq $ScriptingOptionsObject) {
$ScriptingOptionsObject = New-DbaScriptingOption
$ScriptingOptionsObject.TargetServerVersion = [Microsoft.SqlServer.Management.Smo.SqlServerVersion]::$scriptVersion
$ScriptingOptionsObject.AllowSystemObjects = $false
$ScriptingOptionsObject.IncludeDatabaseRoleMemberships = $true
$ScriptingOptionsObject.ContinueScriptingOnError = $false
$ScriptingOptionsObject.IncludeDatabaseContext = $false
$ScriptingOptionsObject.IncludeIfNotExists = $true
}
Write-Message -Level Verbose -Message "Validating users on database $db"
if ($User) {
$users = $db.Users | Where-Object { $User -contains $_.Name -and $_.IsSystemObject -eq $false -and $_.Name -notlike "##*" }
} else {
$users = $db.Users
}
# Generate the file path
if (Test-Bound -ParameterName FilePath -Not) {
$GenerateFilePerUser = $true
} else {
# Generate a new file name with passed/default path
$FilePath = Get-ExportFilePath -Path $PSBoundParameters.Path -FilePath $PSBoundParameters.FilePath -Type sql -ServerName $db.Parent.Name -Unique
# Force append to have everything on same file
$Append = $true
}
# Store roles between users so if we hit the same one we don't create it again
$roles = @()
$stepCounter = 0
foreach ($dbuser in $users) {
if ($GenerateFilePerUser) {
if ($null -eq $usersProcessed[$dbuser.Name]) {
# If user and not specific output file, create file name without database name.
$FilePath = Get-ExportFilePath -Path $PSBoundParameters.Path -FilePath $PSBoundParameters.FilePath -Type sql -ServerName $("$($db.Parent.Name)-$($dbuser.Name)") -Unique
$usersProcessed[$dbuser.Name] = $FilePath
} else {
$Append = $true
$FilePath = $usersProcessed[$dbuser.Name]
}
}
Write-ProgressHelper -TotalSteps $users.Count -Activity "Exporting from $($db.Name)" -StepNumber ($stepCounter++) -Message "Generating script ($FilePath) for user $dbuser"
#setting database
if (((Test-Bound ScriptingOptionsObject) -and $ScriptingOptionsObject.IncludeDatabaseContext) -or - (Test-Bound ScriptingOptionsObject -Not)) {
$useDatabase = "USE [" + $db.Name + "]"
}
try {
#Fixed Roles #Dependency Issue. Create Role, before add to role.
foreach ($rolePermission in ($db.Roles | Where-Object { $_.IsFixedRole -eq $false })) {
foreach ($rolePermissionScript in $rolePermission.Script($ScriptingOptionsObject)) {
if ($rolePermission.ToString() -notin $roles) {
$roles += , $rolePermission.ToString()
$outsql += "$($rolePermissionScript.ToString())"
}
}
}
#Database Create User(s) and add to Role(s)
foreach ($dbUserPermissionScript in $dbuser.Script($ScriptingOptionsObject)) {
if ($dbuserPermissionScript.Contains("sp_addrolemember")) {
$execute = "EXEC "
} else {
$execute = ""
}
$outsql += "$execute$($dbUserPermissionScript.ToString())"
}
#Database Permissions
foreach ($databasePermission in $db.EnumDatabasePermissions() | Where-Object { @("sa", "dbo", "information_schema", "sys") -notcontains $_.Grantee -and $_.Grantee -notlike "##*" -and ($dbuser.Name -contains $_.Grantee) }) {
if ($databasePermission.PermissionState -eq "GrantWithGrant") {
$withGrant = " WITH GRANT OPTION"
$grantDatabasePermission = 'GRANT'
} else {
$withGrant = " "
$grantDatabasePermission = $databasePermission.PermissionState.ToString().ToUpper()
}
$outsql += "$($grantDatabasePermission) $($databasePermission.PermissionType) TO [$($databasePermission.Grantee)]$withGrant AS [$($databasePermission.Grantor)];"
}
#Database Object Permissions
# NB: This is a bit of a mess for a couple of reasons
# 1. $db.EnumObjectPermissions() doesn't enumerate all object types
# 2. Some (x)Collection types can have EnumObjectPermissions() called
# on them directly (e.g. AssemblyCollection); others can't (e.g.
# ApplicationRoleCollection). Those that can't we iterate the
# collection explicitly and add each object's permission.
$perms = New-Object System.Collections.ArrayList
$null = $perms.AddRange($db.EnumObjectPermissions($dbuser.Name))
foreach ($item in $db.ApplicationRoles) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.Assemblies) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.Certificates) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.DatabaseRoles) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.FullTextCatalogs) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.FullTextStopLists) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.SearchPropertyLists) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.ServiceBroker.MessageTypes) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.RemoteServiceBindings) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.ServiceBroker.Routes) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.ServiceBroker.ServiceContracts) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.ServiceBroker.Services) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
if ($scriptVersion -ne "Version80") {
foreach ($item in $db.AsymmetricKeys) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
}
foreach ($item in $db.SymmetricKeys) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($item in $db.XmlSchemaCollections) {
$null = $perms.AddRange($item.EnumObjectPermissions($dbuser.Name))
}
foreach ($objectPermission in $perms | Where-Object { @("sa", "dbo", "information_schema", "sys") -notcontains $_.Grantee -and $_.Grantee -notlike "##*" -and $_.Grantee -eq $dbuser.Name }) {
switch ($objectPermission.ObjectClass) {
'ApplicationRole' {
$object = 'APPLICATION ROLE::[{0}]' -f $objectPermission.ObjectName
}
'AsymmetricKey' {
$object = 'ASYMMETRIC KEY::[{0}]' -f $objectPermission.ObjectName
}
'Certificate' {
$object = 'CERTIFICATE::[{0}]' -f $objectPermission.ObjectName
}
'DatabaseRole' {
$object = 'ROLE::[{0}]' -f $objectPermission.ObjectName
}
'FullTextCatalog' {
$object = 'FULLTEXT CATALOG::[{0}]' -f $objectPermission.ObjectName
}
'FullTextStopList' {
$object = 'FULLTEXT STOPLIST::[{0}]' -f $objectPermission.ObjectName
}
'MessageType' {
$object = 'Message Type::[{0}]' -f $objectPermission.ObjectName
}
'ObjectOrColumn' {
if ($scriptVersion -ne "Version80") {
$object = 'OBJECT::[{0}].[{1}]' -f $objectPermission.ObjectSchema, $objectPermission.ObjectName
if ($null -ne $objectPermission.ColumnName) {
$object += '([{0}])' -f $objectPermission.ColumnName
}
}
#At SQL Server 2000 OBJECT did not exists
else {
$object = '[{0}].[{1}]' -f $objectPermission.ObjectSchema, $objectPermission.ObjectName
}
}
'RemoteServiceBinding' {
$object = 'REMOTE SERVICE BINDING::[{0}]' -f $objectPermission.ObjectName
}
'Schema' {
$object = 'SCHEMA::[{0}]' -f $objectPermission.ObjectName
}
'SearchPropertyList' {
$object = 'SEARCH PROPERTY LIST::[{0}]' -f $objectPermission.ObjectName
}
'Service' {
$object = 'SERVICE::[{0}]' -f $objectPermission.ObjectName
}
'ServiceContract' {
$object = 'CONTRACT::[{0}]' -f $objectPermission.ObjectName
}
'ServiceRoute' {
$object = 'ROUTE::[{0}]' -f $objectPermission.ObjectName
}
'SqlAssembly' {
$object = 'ASSEMBLY::[{0}]' -f $objectPermission.ObjectName
}
'SymmetricKey' {
$object = 'SYMMETRIC KEY::[{0}]' -f $objectPermission.ObjectName
}
'User' {
$object = 'USER::[{0}]' -f $objectPermission.ObjectName
}
'UserDefinedType' {
$object = 'TYPE::[{0}].[{1}]' -f $objectPermission.ObjectSchema, $objectPermission.ObjectName
}
'XmlNamespace' {
$object = 'XML SCHEMA COLLECTION::[{0}]' -f $objectPermission.ObjectName
}
}
if ($objectPermission.PermissionState -eq "GrantWithGrant") {
$withGrant = " WITH GRANT OPTION"
$grantObjectPermission = 'GRANT'
} else {
$withGrant = " "
$grantObjectPermission = $objectPermission.PermissionState.ToString().ToUpper()
}
$outsql += "$grantObjectPermission $($objectPermission.PermissionType) ON $object TO [$($objectPermission.Grantee)]$withGrant AS [$($objectPermission.Grantor)];"
}
} catch {
Stop-Function -Message "This user may be using functionality from $($versionName[$db.CompatibilityLevel.ToString()]) that does not exist on the destination version ($versionNameDesc)." -Continue -InnerErrorRecord $_ -Target $db
}
if (@($outsql.Count) -gt 0) {
if ($ExcludeGoBatchSeparator) {
$sql = "$useDatabase $outsql"
} else {
if ($useDatabase) {
$sql = "$useDatabase`r`nGO`r`n" + ($outsql -join "`r`nGO`r`n")
} else {
$sql = $outsql -join "`r`nGO`r`n"
}
#add the final GO
$sql += "`r`nGO"
}
}
if (-not $Passthru) {
# If generate a file per user, clean the collection to populate with next one
if ($GenerateFilePerUser) {
if (-not [string]::IsNullOrEmpty($sql)) {
$sql | Out-File -Encoding UTF8 -FilePath $FilePath -Append:$Append -NoClobber:$NoClobber
Get-ChildItem -Path $FilePath
}
} else {
$sql | Out-File -Encoding UTF8 -FilePath $FilePath -Append:$Append -NoClobber:$NoClobber
}
# Clear variables for next user
$outsql = @()
$sql = ""
} else {
$sql
}
}
}
# Just a single file, output path once here
if (-Not $GenerateFilePerUser) {
Get-ChildItem -Path $FilePath
}
}
} | alevyinroc/dbatools | functions/Export-DbaUser.ps1 | PowerShell | mit | 23,037 |
# AD Module Check
Write-Host "Checking if the Active Directory Module is installed"
if ((Get-Module -name ActiveDirectory -ErrorAction SilentlyContinue | foreach { $_.Name }) -ne "ActiveDirectory")
{
Write-Host Active Directory Management has not been added to this session, adding it now...
Import-Module ActiveDirectory
}
else
{
Write-Host Active Directory Module is ready for commands. -backgroundcolor green -foregroundcolor yellow
Start-Sleep -s 1
}
$cred = Get-Credential $env:userdomain\$env:username
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://(URL)/PowerShell/ -Authentication Kerbeross -Credential $cred
Import-PSSession $Session
$timestamp = Get-Date -Format 'MM/dd/yyyy - h:mm:ss tt'
$dnsroot = '@' + (Get-ADDomain).dnsroot
# Groups not pulled from the template account
# $AdditionalGroups = ('','','','','','')
$filePath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$importCSV = $filePath + '\accounts_to_make.csv'
$CSVdata = Import-CSV $importCSV
foreach ($cell in $CSVdata)
{
$TicketNumber = $cell.'Ticket Number'.trim()
$template_sAMAccountName = $cell.'Template Account'.trim()
$new_FirstName = $cell.'First Name'.trim()
$new_LastName = $cell.'Last Name'.trim()
$new_sAMAccountName = $cell.'User_Logon'.trim()
if ($new_sAMAccountName.length -gt 20)
{
$new_sAMAccountName = $new_sAMAccountName.substring(0,20)
}
$new_DisplayName = $new_FirstName + ' ' + $new_LastName
$new_Name = $new_FirstName + ' ' + $new_LastName
$new_UserPrincipalName = $new_sAMAccountName + $dnsroot
$new_primaryEmailAddress = $new_FirstName.replace(" ", "") + "." + $new_LastName.replace("'", "") + "@domain.com"
$new_secondaryEmailAddress = $new_FirstName.replace(" ", "") + "." + $new_LastName.replace("'", "") + "@domain.net"
$new_thirdEmailAddress = $new_FirstName.replace(" ", "") + "_" + $new_LastName.replace("'", "") + "@domain.net"
$new_Password = 'Abc1234'
$new_Office = $cell.'Office'.trim()
$new_DriveLetter = 'U:'
$new_HomeDir = $cell.'Home Drive Path'.trim() + $new_sAMAccountName
$new_Manager = $cell.Manager.trim()
$mgr = Get-ADUser -Identity $new_Manager
$mgrOU = ($mgr.DistinguishedName -split ",", 2)[1]
$new_Title = $cell.'Title / Position'.trim()
$new_Department = $cell.Department.trim()
$new_Description = 'AA/B//CCCCC/' + $new_Department + ' - ' + $timestamp
$new_Notes = $cell.Notes.trim()
$enable_afterCreation = $true
$change_passAtLogon = $true
$accountExpires = ([DateTime]($cell.'Account Expiration')).AddDays(1)
$cloneADInstance = Get-Aduser $template_sAMAccountName -Properties city,company,country,postalCode,ScriptPath,State,StreetAddress,MemberOf
$params = @{'SamAccountName' = $new_sAMAccountName;
'Instance' = $cloneADInstance;
'DisplayName' = $new_DisplayName;
'GivenName' = $new_FirstName;
'Surname' = $new_LastName;
'ChangePasswordAtLogon' = $change_passAtLogon;
'Description' = $new_Description;
'Title' = $new_Title;
'Department' = $new_Department;
'Office' = $new_Office;
'Manager' = $new_Manager;
'Enabled' = $enable_afterCreation;
'UserPrincipalName' = $new_UserPrincipalName;
'AccountPassword' = (ConvertTo-SecureString -AsPlainText $new_Password -Force);
'OtherAttributes' = @{'info'=$TicketNumber + ' - ' + $timestamp + ' - ' + $new_Notes};
}
# Create the new user account using template account
Get-ADUser -Filter {SamAccountName -eq $template_sAMAccountName} -Properties city,company,country,postalCode,ScriptPath,State,StreetAddress | New-ADUser -Name $new_Name @params
# Mirror template Security Groups
$cloneADInstance.MemberOf |
ForEach-Object {
$_ | Add-ADGroupMember -Members $new_sAMAccountName
}
# Additional Groups to add
# $AdditionalGroups | Add-ADGroupMember -Members $new_sAMAccountName
# Move the new user to Manager's OU
Get-ADUser $new_sAMAccountName | Move-ADObject -TargetPath $mgrOU
New-Item $new_HomeDir -type Directory -Force
$ACL = Get-Acl "$new_HomeDir"
$ACL.Access | ForEach { [Void]$ACL.RemoveAccessRule($_) }
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\$new_sAMAccountName","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\Domain Admins","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("DOMAIN\Administrator","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
$ACL.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")))
Set-Acl "$new_HomeDir" $ACL
Set-ADUser -Identity $new_sAMAccountName -HomeDrive "$new_DriveLetter" -HomeDirectory "$new_HomeDir"
Set-ADAccountExpiration $new_sAMAccountName -DateTime $accountExpires -Server (Get-ADDomain).PDCEmulator
Enable-Mailbox -Identity $new_sAMAccountName
Set-Mailbox -Identity $new_sAMAccountName -EmailAddresses $new_primaryEmailAddress,$new_secondaryEmailAddress,$new_thirdEmailAddress -Alias $new_sAMAccountName
}
| HMcC-Tek/ActiveDirectory | massCreator.ps1 | PowerShell | mit | 5,827 |
using module PSNativeAutomation
class MainWindow : Window
{
[ListBox]$ListBoxGames
[ListView]$ListViewGames
[Menu]$PopupMenu
[UIObject]$TextFilter
[UIObject]$ButtonInstall
[UIObject]$ButtonMore
[UIObject]$ButtonSetupProgress
[UIObject]$ButtonPlay
[UIObject]$HyperlinkStore
[UIObject]$HyperlinkForum
[UIObject]$HyperlinkWiki
[Menu]$MenuMainMenu
[Menu]$MenuViewSettings
[Menu]$MenuViewMode
[UIObject]$FilterSelector
[UIObject]$GridGamesView
[UIObject]$ImagesGamesView
[UIObject]$ListGamesView
[UIObject]$SearchBoxFilter
[UIObject]$CheckFilterView
[UIObject]$ImageLogo
[UIObject]$ProgressControl
[UIObject]$TabControlView
[UIObject]$TextView
[UIObject]$TextGroup
MainWindow() : base({Get-UIWindow -ProcessName "PlayniteUI" -AutomationId "WindowMain"}, "MainWindow")
{
$this.ListBoxGames = [ListBox]::New($this.GetChildReference({Get-UIListBox -AutomationId "ListGames" -First}), "ListBoxGames");
$this.ListViewGames = [ListView]::New($this.GetChildReference({Get-UIListView -AutomationId "GridGames" -First}), "ListViewGames");
$this.PopupMenu = [Menu]::New($this.GetChildReference({Get-UIControl -Class "Popup" -First}), "PopupMenu");
$this.TextFilter = [UIObject]::New($this.GetChildReference({Get-UITextBox -AutomationId "TextFilter" -First}), "TextFilter");
$this.ButtonInstall = [UIObject]::New($this.GetChildReference({Get-UIButton -AutomationId "ButtonInstall" -First}), "ButtonInstall")
$this.ButtonMore = [UIObject]::New($this.GetChildReference({Get-UIButton -AutomationId "ButtonMore" -First}), "ButtonMore")
$this.ButtonSetupProgress = [UIObject]::New($this.GetChildReference({Get-UIButton -AutomationId "ButtonSetupProgress" -First}), "ButtonSetupProgress")
$this.ButtonPlay = [UIObject]::New($this.GetChildReference({Get-UIButton -AutomationId "ButtonPlay" -First}), "ButtonPlay")
$this.HyperlinkStore = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "HyperlinkStore" -First}), "HyperlinkStore")
$this.HyperlinkForum = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "HyperlinkForum" -First}), "HyperlinkForum")
$this.HyperlinkWiki = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "HyperlinkWiki" -First}), "HyperlinkWiki")
$this.MenuMainMenu = [Menu]::New($this.GetChildReference({Get-UIContextMenu -AutomationId "MenuMainMenu" -First}), "MenuMainMenu")
$this.MenuViewSettings = [Menu]::New($this.GetChildReference({Get-UIContextMenu -AutomationId "MenuViewSettings" -First}), "MenuViewSettings")
$this.MenuViewMode = [Menu]::New($this.GetChildReference({Get-UIContextMenu -AutomationId "MenuViewMode" -First}), "MenuViewMode")
$this.FilterSelector = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "FilterSelector" -First}), "FilterSelector")
$this.GridGamesView = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "GridGamesView" -First}), "GridGamesView")
$this.ImagesGamesView = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "ImagesGamesView" -First}), "ImagesGamesView")
$this.ListGamesView = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "ListGamesView" -First}), "ListGamesView")
$this.SearchBoxFilter = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "SearchBoxFilter" -First}), "SearchBoxFilter")
$this.CheckFilterView = [UIObject]::New($this.GetChildReference({Get-UICheckBox -AutomationId "CheckFilterView" -First}), "CheckFilterView")
$this.ImageLogo = [UIObject]::New($this.GetChildReference({Get-UIImage -AutomationId "ImageLogo" -First}), "ImageLogo")
$this.ProgressControl = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "ProgressControl" -First}), "ProgressControl")
$this.TabControlView = [UIObject]::New($this.GetChildReference({Get-UIControl -AutomationId "TabControlView" -First}), "TabControlView")
$this.TextView = [UIObject]::New($this.GetChildReference({Get-UITextBlock -AutomationId "TextView" -First}), "TextView")
$this.TextGroup = [UIObject]::New($this.GetChildReference({Get-UITextBlock -AutomationId "TextGroup" -First}), "TextGroup")
}
}
return [MainWindow]::New() | JosefNemec/Playnite | tests/Mapping/MainWindow.ps1 | PowerShell | mit | 4,593 |
$error.clear();
Set-StrictMode -Version:Latest
$GLOBAL:ErrorActionPreference = "Stop"
."$PSCommandPath.vars.ps1"
import-module -force -DisableNameChecking "$($SCRIPT:DIRECTORY_PATH_OF_pratom_ATOM_NUCLEUS_PROTONS)\protons.psm1"
import-module -force -DisableNameChecking "$($SCRIPT:DIRECTORY_PATH_OF_pratom_ATOM_NUCLEUS_NEUTRONS)\neutrons.psm1"
Export-ModuleMember -Function * | pratom/master | nucleus/nucleus.psm1 | PowerShell | mit | 391 |
# Launch a console for the project.
param(
[switch]$Quick,
[switch]$Verbose
)
$project_root = Split-Path $PSScriptRoot
. $PSScriptRoot\Write-Status.ps1
Write-Status "Plush console"
# Set a global variable to indicate we want to set and update some useful console functions
$Global:plush_functions = $true
$venv = Join-Path $project_root "venv\scripts\Activate.ps1"
if (Test-Path $venv) {
if (-Not($Quick)) {
. $PSScriptRoot\Update.ps1 -Verbose:$Verbose
}
}
else {
if ($Quick) {
Write-Warning "No virtual env detected, -Quick will be ignored"
}
. $PSScriptRoot\Setup.ps1
}
. $PSScriptRoot\Ensure-Venv.ps1 | Out-Null
Write-Status "Plush ready"
| kbarnes3/Plush | scripts/Console.ps1 | PowerShell | mit | 720 |
Function Import-MDTModule {
$MDTModuleInstallLocation = "C:\Program Files\Microsoft Deployment Toolkit\Bin\MicrosoftDeploymentToolkit.psd1"
if (!(Get-Module MicrosoftDeploymentToolkit)) {
if (Test-Path $MDTModuleInstallLocation) {
Import-Module $MDTModuleInstallLocation
} else {
Write-Error "MDT module not working. Microsoft Deployment Toolkit may need to be installed."
}
}
$return = Get-Module MicrosoftDeploymentToolkit
return $return
}
Function Get-MDTDrive {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$Name
)
PROCESS{
if(Import-MDTModule) {
$drive = Get-PSDrive -Name $Name -PSProvider MDTProvider
return $drive
}
}
}
Function Set-MDTDrive {
[cmdletbinding(
SupportsShouldProcess=$true
)]
param(
[Parameter(Mandatory=$true)]
$Name,
[Parameter(Mandatory=$true)]
$Path,
[Parameter()]
[switch]$Force
)
BEGIN {
$mdtdrive = Get-MDTDrive -Name $Name -ErrorAction:SilentlyContinue
if (Import-MDTModule) {
if ($mdtdrive) {
Write-Verbose "$Name already exists"
if ($Force) {
if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Creating MDT drive $Name with path $Path")) {
Write-Verbose "Force switch specified. Overwriting drive $Name"
New-PSDrive -Name $Name -PSProvider MDTProvider -Root $Path -NetworkPath $Path -Scope Global
}
}
} elseif (!($mdtdrive)) {
if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Creating MDT drive $Name with path $Path")) {
Write-Verbose "Creating new drive: $Name : $Path"
New-PSDrive -Name $Name -PSProvider MDTProvider -Root $Path -NetworkPath $Path -Scope Global
}
}
}
}
}
Function Get-MDTApplication {
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NoFilter')]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$ShareName,
[Parameter(ParameterSetName='NoFilter')]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$Location,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameFilter')]
$Name,
[Parameter(
Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='GUIDFilter')]
$GUID
)
BEGIN {
$mdtdriveworking = Get-MDTDrive -Name $ShareName
if ($mdtdriveworking) {
if ($null -eq $location) {
$getchilditemquery = Get-ChildItem -Path $ShareName`:\Applications -Recurse | Where-Object {$_.NodeType -eq "Application"}
} else {
$getchilditemquery = Get-ChildItem -Path $ShareName`:\Applications\$location -Recurse | Where-Object {$_.NodeType -eq "Application"}
}
}
}
PROCESS {
if ($mdtdriveworking) {
switch ($PSCmdlet.ParameterSetName) {
"NameFilter" {
$appobject = $getchilditemquery | Where-Object {$_.Name -like $Name}
Write-Output $appobject
}
"GUIDFilter" {
if($GUID -notmatch "{*}") {
$GUID = ("{" + $GUID + "}")
}
$appobject = $getchilditemquery | Where-Object {$_.GUID -like $GUID}
Write-Output $appobject
}
"NoFilter" {
Write-Output $getchilditemquery
}
}
}
}
}
Function Get-MDTApplicationDependency {
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$ShareName,
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
[ValidateSet("ReturnParent","ReturnChild")]
$DependencyType = "ReturnParent",
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
[switch]$Recurse,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameFilter')]
$Name,
[Parameter(
Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='GUIDFilter')]
$GUID
)
BEGIN {
switch ($PSCmdlet.ParameterSetName) {
"NameFilter" {
$sourceapp = Get-MDTApplication -ShareName $ShareName -Name $Name
}
"GUIDFilter" {
if($GUID -notmatch "{*}") {
$GUID = ("{" + $GUID + "}")
}
$sourceapp = Get-MDTApplication -ShareName $ShareName -GUID $GUID
}
}
if ($DependencyType -eq "ReturnChild") {
$allapplications = Get-MDTApplication -ShareName $ShareName
}
}
PROCESS {
switch ($DependencyType) {
"ReturnParent" {
foreach ($app in $sourceapp.dependency) {
$appobject = Get-MDTApplication -ShareName $ShareName -GUID $app | Add-Member NoteProperty ParentDependency($sourceapp.Name) -PassThru
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.ApplicationDependency.ParentDependency')
Write-Output $appobject
if ($Recurse -and $appobject.dependency) {
Get-MDTApplicationDependency -ShareName $ShareName -GUID $app -DependencyType ReturnParent -Recurse
}
}
}
"ReturnChild" {
foreach ($app in $allapplications) {
if ($app.Dependency -contains $sourceapp.guid) {
$appobject = Get-MDTApplication -ShareName $ShareName -GUID $app.guid | Add-Member NoteProperty ChildDependency($sourceapp.Name) -PassThru
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.ApplicationDependency.ChildDependency')
Write-Output $appobject
if ($Recurse -and $appobject.dependency) {
Get-MDTApplicationDependency -ShareName $ShareName -GUID $app.guid -DependencyType ReturnChild -Recurse
}
}
}
}
}
}
}
Function Get-MDTApplicationSupportedPlatform {
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NoFilter')]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$ShareName,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameFilter')]
$Name,
[Parameter(
Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='GUIDFilter')]
$GUID,
[ValidateSet("Yes", "No", "All")]
$SupportedPlatformSet = "All"
)
PROCESS {
switch ($PSCmdlet.ParameterSetName) {
"NoFilter" {
$basequery = Get-MDTApplication -ShareName $ShareName
switch ($SupportedPlatformSet) {
"Yes" {$appobject = $basequery | Where-Object {$_.SupportedPlatform -like "*"}}
"No" {$appobject = $basequery | Where-Object {[string]$_.SupportedPlatform -like ""}}
"All" {$appobject = $basequery}
}
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.SupportedPlatform')
Write-Output $appobject
}
"NameFilter" {
$basequery = Get-MDTApplication -ShareName $ShareName -Name $Name
switch ($SupportedPlatformSet) {
"Yes" {$appobject = $basequery | Where-Object {$_.SupportedPlatform -like "*"}}
"No" {$appobject = $basequery | Where-Object {[string]$_.SupportedPlatform -like ""}}
"All" {$appobject = $basequery}
}
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.SupportedPlatform')
Write-Output $appobject
}
"GUIDFilter" {
if($GUID -notmatch "{*}") {
$GUID = ("{" + $GUID + "}")
}
$basequery = Get-MDTApplication -ShareName $ShareName -GUID $GUID
switch ($SupportedPlatformSet) {
"Yes" {$appobject = $basequery | Where-Object {$_.SupportedPlatform -like "*"}}
"No" {$appobject = $basequery | Where-Object {[string]$_.SupportedPlatform -like ""}}
"All" {$appobject = $basequery}
}
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.SupportedPlatform')
Write-Output $appobject
}
}
}
}
Function Set-MDTApplicationSupportedPlatform {
[cmdletbinding(
SupportsShouldProcess=$true,
ConfirmImpact="High"
)]
param(
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NoFilter')]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$ShareName,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameFilter')]
$Name,
[Parameter(
Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='GUIDFilter')]
$GUID,
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NoFilter')]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
[ValidateSet("Null", "Windows7Only", "Windows8Only", "Windows8.1Only", "Windows10Only")]
$SetSupportedPlatformTo
)
BEGIN {
Switch ($SetSupportedPlatformTo) {
"Null" {$code = @()}
"Windows7Only" {$code = @('All x86 Windows 7 Client', 'All x64 Windows 7 Client')}
"Windows8Only" {$code = @('All x86 Windows 8 Client', 'All x64 Windows 8 Client')}
"Windows8.1Only" {$code = @('All x86 Windows 8.1 Client', 'All x64 Windows 8.1 Client') }
"Windows10Only" {$code = @('All x86 Windows 10 Client', 'All x64 Windows 10 Client') }
}
}
PROCESS {
switch ($PSCmdlet.ParameterSetName) {
"NoFilter" {
$app = Get-MDTApplication -ShareName $ShareName
if ($PSCmdlet.ShouldProcess($ShareName,"Setting Supported Platform to $SetSupportedPlatformTo on all applications")) {
$appobject = $app | ForEach-Object {Set-ItemProperty -Path ([string]$_.PsPath -replace 'MicrosoftDeploymentToolkit\\MDTProvider::',"") -Name SupportedPlatform -Value $code}
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.SupportedPlatform')
Write-Output $appobject
}
}
"NameFilter" {
$app = Get-MDTApplication -ShareName $ShareName -Name $Name
$appname = $app.Name
if ($PSCmdlet.ShouldProcess($ShareName,"Setting Supported Platform to $SetSupportedPlatformTo on $appname")) {
$appobject = $app | ForEach-Object {Set-ItemProperty -Path ([string]$_.PsPath -replace 'MicrosoftDeploymentToolkit\\MDTProvider::',"") -Name SupportedPlatform -Value $code}
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.SupportedPlatform')
Write-Output $appobject
}
}
"GUIDFilter" {
if($GUID -notmatch "{*}") {
$GUID = ("{" + $GUID + "}")
}
$app = Get-MDTApplication -ShareName $ShareName -GUID $GUID
$appname = $app.Name
if ($PSCmdlet.ShouldProcess($ShareName,"Setting Supported Platform to $SetSupportedPlatformTo on $appname")) {
$appobject = $app | ForEach-Object {Set-ItemProperty -Path ([string]$_.PsPath -replace 'MicrosoftDeploymentToolkit\\MDTProvider::',"") -Name SupportedPlatform -Value $code}
$appobject.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.SupportedPlatform')
Write-Output $appobject
}
}
}
}
}
Function Find-MDTApplicationContent {
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
$ShareName,
$String,
[switch]$ParseScript
)
BEGIN {
$apps = Get-MDTApplication -ShareName $ShareName
$filetypes = @(".bat",".cmd",".vbs",".wsf",".ps1",".psm1",".psd1")
$sharepath = (Get-PSDrive -Name $ShareName).Root
}
PROCESS {
if($ParseScript) {
foreach ($app in $apps) { #goes through all apps in share
if ($app.Source -notlike $null) { #makes sure app has files to search for
$apppath = ($app.Source.ToString()).substring(1)
$apppath = "$sharepath$apppath"
if (Test-Path $apppath) { #makes sure apppath exists
$appcontents = Get-ChildItem -Path $apppath #gets list of files in $apppath
foreach ($item in $appcontents) { #goes through each item in $apppath
$itemfound = $false
$lineobj = @()
foreach ($filetype in $filetypes) {
if ($item -like "*$filetype*") { #selects only items with filetype defined in $filetypes
$itemcontent = Get-Content -Path $item.FullName #gets content of item
foreach ($line in $itemcontent) { #goes through each line in item content,
if ($line -like $String) { #and outputs if string matches
$itemfound = $true
$line = $line.ReadCount.ToString() + ': ' + $line.Trim() #prepends the line number to the beginning of the found string
$lineobj += $line
}
}
if ($itemfound) {
$app.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.ApplicationContent.ParseScript')
$app = $app | Add-Member NoteProperty Script($item) -PassThru| Add-Member NoteProperty LinesFound($lineobj) -PassThru
Write-Output $app
}
}
}
}
}
}
}
} else {
$app = Get-MDTApplication -ShareName $ShareName | Where-Object {$_.CommandLine -like "$String"}
$app.PSObject.TypeNames.Insert(0,'Microsoft.BDD.PSSnapIn.MDTObject.MDTApplicationTools.ApplicationContent.InstallCmd')
Write-Output $app
}
}
}
function Rename-MDTApplication {
[cmdletbinding(
SupportsShouldProcess=$true,
ConfirmImpact="High"
)]
param(
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$ShareName,
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameFilter')]
$Name,
[Parameter(
Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='GUIDFilter')]
$GUID,
[Parameter(Mandatory=$true)]
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
$NewName,
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
[switch]$RenameSource,
[Parameter(ParameterSetName='NameFilter')]
[Parameter(ParameterSetName='GUIDFilter')]
[switch]$Force
)
PROCESS {
$prevappcheck = Get-MDTApplication -ShareName $ShareName -Name $NewName
if(!$prevappcheck -or $Force) {
switch ($PSCmdlet.ParameterSetName) {
"NameFilter" {
$app = Get-MDTApplication -ShareName $ShareName -Name $Name
}
"GUIDFilter" {
if($GUID -notmatch "{*}") {
$GUID = ("{" + $GUID + "}")
}
$app = Get-MDTApplication -ShareName $ShareName -GUID $GUID
}
}
if($app -or $Force){
$appname = $app.Name #variable needed to display name in shouldprocess statements
$apppath = ([string]$app.PsPath -split "::")[1] #path used for set-itemproperty statements
if ($app.CommandLine -notlike "") {
if ($app.Source -notlike "") {
$apptype = "APPSOURCE"
} else {
$apptype = "APPNOSOURCE"
}
} else {
$apptype = "APPBUNDLE"
}
if ($RenameSource -eq $false -or $apptype -eq "APPBUNDLE" -or $apptype -eq "APPNOSOURCE") {
if ($PSCmdlet.ShouldProcess($ShareName,"Renaming $appname to $NewName")) {
Set-ItemProperty -Path $apppath -Name ShortName -Value $NewName
Set-ItemProperty -Path $apppath -Name Name -Value $NewName
}
} else {
$mdtdriveroot = Get-PSDrive -Name $ShareName | Select-Object -ExpandProperty Root
$origfullpath = $mdtdriveroot + $app.Source.TrimStart(".")
$oldsourcename = $app.Source.split("\") | Select-Object -Last 1
$newsourcepath = $app.Source.Replace($oldsourcename,$NewName) #path used when changing source path property
if ($PSCmdlet.ShouldProcess($ShareName,"Renaming $appname to $NewName, and renaming source directory from $oldsourcename to $NewName")) {
try {
Rename-Item -Path $origfullpath -NewName $NewName -ErrorAction Stop
Set-ItemProperty -Path $apppath -Name Source -Value $newsourcepath
Set-ItemProperty -Path $apppath -Name WorkingDirectory -Value $newsourcepath
Set-ItemProperty -Path $apppath -Name ShortName -Value $NewName
Set-ItemProperty -Path $apppath -Name Name -Value $NewName
} catch {
Write-Error "issue renaming directory. no changes have been made."
}
}
}
} else {
switch ($PSCmdlet.ParameterSetName) {
"NameFilter" {
Write-Error "no app with Name $Name exists"
}
"GUIDFilter" {
if($GUID -notmatch "{*}") {
$GUID = ("{" + $GUID + "}")
}
Write-Error "no app with GUID $GUID exists"
}
}
}
} else {
Write-Error "An app with the name $NewName already exists"
}
}
} | JohnForet/MDTApplicationTools | MDTApplicationTools.psm1 | PowerShell | mit | 20,875 |
Param (
[string]$OwnerTagName = "Owner"
)
#This section will be removed once Functions support modern PowerShell and Azure modules properly
#it's to a workaround inconsistent behaviour of auto load from 'modules' folder
Import-Module "D:\home\site\wwwroot\azuremodules\AzureRM.Profile.psd1" -Global;
Import-Module "D:\home\site\wwwroot\azuremodules\AzureRM.Resources.psd1" -Global;
Import-Module "D:\home\site\wwwroot\azuremodules\AzureRM.Tags.psd1" -Global;
#login
$user = $env:azureGcUser
$password = $env:azureGcPass
$tenant = $env:azureGcTenant
$securedPass = ConvertTo-SecureString -AsPlainText -String $password -Force
$creds = New-Object System.Management.Automation.PSCredential($user,$securedPass)
Add-AzureRmAccount -ServicePrincipal -TenantId $tenant -Credential $creds
Set-AzureRmContext -SubscriptionId $env:azureGcSubscription
#get all resource groups in the subscription (including tags information)
$resourceGroups = Get-AzureRmResourceGroup
#Find resource groups with no owner and no expire -> queue them for deletion
$rgsToDelete = $resourceGroups | Where-Object {(!$_.Tags.$OwnerTagName)}
$deletionMessages = $rgsToDelete | ForEach-Object { $_.ResourceId } #foreach instead of select because we need array of string, not of PSCustomObject. easier on the queue processor side
$deletionMessages | ConvertTo-Json | Out-File -Encoding UTF8 $outputQueueItem | itaysk/AzureGC | functions/noOwner/noOwner.ps1 | PowerShell | mit | 1,388 |
#region HEADER
$script:DSCModuleName = 'xExchange'
$script:DSCResourceName = 'MSFT_xExchJetstress'
# Unit Test Template Version: 1.2.4
$script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath 'DscResource.Tests'))
}
Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'DSCResource.Tests' -ChildPath 'TestHelper.psm1')) -Force
Import-Module -Name (Join-Path -Path $script:moduleRoot -ChildPath (Join-Path -Path 'Tests' -ChildPath (Join-Path -Path 'TestHelpers' -ChildPath 'xExchangeTestHelper.psm1'))) -Global -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:DSCModuleName `
-DSCResourceName $script:DSCResourceName `
-ResourceType 'Mof' `
-TestType Unit
#endregion HEADER
function Invoke-TestSetup
{
}
function Invoke-TestCleanup
{
Restore-TestEnvironment -TestEnvironment $TestEnvironment
}
# Begin Testing
try
{
Invoke-TestSetup
InModuleScope $script:DSCResourceName {
Describe 'MSFT_xExchJetstress\Get-TargetResource' -Tag 'Get' {
AfterEach {
Assert-VerifiableMock
}
$getTargetResourceParams = @{
Type = 'Performance'
JetstressPath = 'C:\Program Files\Exchange Jetstress'
JetstressParams = '/c "C:\Program Files\Exchange Jetstress\JetstressConfig.xml"'
}
Context 'When Get-TargetResource is called' {
Mock -CommandName Write-FunctionEntry -Verifiable
Test-CommonGetTargetResourceFunctionality -GetTargetResourceParams $getTargetResourceParams
}
}
}
}
finally
{
Invoke-TestCleanup
}
| IngoGege/xExchange | Tests/Unit/MSFT_xExchJetstress.tests.ps1 | PowerShell | mit | 2,054 |
<#
.SYNOPSIS
Builds all assets in this repository.
.PARAMETER Configuration
The project configuration to build.
#>
[CmdletBinding(SupportsShouldProcess)]
Param(
[Parameter()]
[ValidateSet('Debug', 'Release')]
[string]$Configuration,
[Parameter()]
[ValidateSet('minimal', 'normal', 'detailed', 'diagnostic')]
[string]$MsBuildVerbosity = 'minimal'
)
$msbuildCommandLine = "dotnet build `"$PSScriptRoot\src\Nerdbank.GitVersioning.sln`" /m /verbosity:$MsBuildVerbosity /nologo /p:Platform=`"Any CPU`" /t:build,pack"
if (Test-Path "C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll") {
$msbuildCommandLine += " /logger:`"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll`""
}
if ($Configuration) {
$msbuildCommandLine += " /p:Configuration=$Configuration"
}
Push-Location .
try {
if ($PSCmdlet.ShouldProcess("$PSScriptRoot\src\Nerdbank.GitVersioning.sln", "msbuild")) {
Invoke-Expression $msbuildCommandLine
if ($LASTEXITCODE -ne 0) {
throw "dotnet build failed"
}
}
if ($PSCmdlet.ShouldProcess("$PSScriptRoot\src\nerdbank-gitversioning.npm", "gulp")) {
cd "$PSScriptRoot\src\nerdbank-gitversioning.npm"
yarn install
yarn run build
if ($LASTEXITCODE -ne 0) {
throw "Node build failed"
}
}
} catch {
Write-Error "Build failure"
# we have the try so that PS fails when we get failure exit codes from build steps.
throw;
} finally {
Pop-Location
}
| AArnott/Nerdbank.GitVersioning | build.ps1 | PowerShell | mit | 1,526 |
function Get-Config ([string]$path) {
return (Get-Content -Path $path | Where { $_ -notmatch "^[\s]*//" }) -join ' ' | ConvertFrom-Json
}
function Build-Packages
{
param (
[Parameter(Mandatory=$false)]
[string]$Project
)
$config = Get-Config "NugetMaker.json"
$projects = $config.projects
# Remove previously built packages.
Remove-Item *.nupkg
# Get solution directory.
$solutionDir = Split-Path $dte.Solution.FileName -Parent
$currentDir = "$solutionDir"
# Get NuGet handle.
$nuget = "$solutionDir\.nuget\NuGet.exe"
# Clean solution
$dte.Solution.SolutionBuild.Clean($true)
foreach ($project in $projects | where {$_ -like "*$Project*"})
{
Write-Host "`r`nBuilding '$project' package..." -ForegroundColor 'green' -BackgroundColor 'black'
$projectDir = "$solutionDir\$project"
$projectFullName = "$projectDir\$project.csproj"
# Make sure .nuspec file exists.
cd $projectDir
&$nuget spec -Verbosity quiet
cd $currentDir
# Build project
$dte.Solution.SolutionBuild.BuildProject("Release", $projectFullName, $true)
# Build package.
&$nuget pack $projectFullName `
-OutputDirectory "$currentDir" `
-Symbols `
-Properties Configuration=Release
}
}
function Push-Packages
{
param (
[Parameter(Mandatory=$false)]
[string]$ApiKey,
[Parameter(Mandatory=$false)]
[switch]$Local
)
$solutionDir = Split-Path $dte.Solution.FileName -Parent
$packagesDir = "$solutionDir"
# Get NuGet handle.
$nuget = "$solutionDir\.nuget\NuGet.exe"
$packages = Get-ChildItem -Path "$packagesDir\*.nupkg" -Exclude '*.symbols.nupkg'
# Get config file.
$configFile = if ($Local) { "NugetMaker.Local.json" } else { "NugetMaker.json" }
$config = Get-Config $configFile
# Get push target.
$destination = $config.target
foreach ($package in $packages)
{
$packageName = [System.IO.Path]::GetFileName($package)
Write-Host "`r`nPushing '$packageName' to '$destination'..." -ForegroundColor 'green' -BackgroundColor 'black'
if ($ApiKey)
{
&$nuget push $package -source $destination -ApiKey $ApiKey
}
else
{
&$nuget push $package -source $destination
}
}
}
Export-ModuleMember Build-Packages
Export-ModuleMember Push-Packages
| niaher/NugetMaker | package/tools/NugetMaker.psm1 | PowerShell | mit | 2,206 |
@{
AllNodes = @(
@{
NodeName = 'localhost'
}
);
Versions = @{
Kubectl = '1.8.0'
MiniKube = '0.22.3'
Kd = '0.4.0'
}
Paths = @{
Base = 'c:\winikube'
Bin = 'c:\winikube\bin'
Tmp = 'c:\winikube\tmp'
}
NATNetworkName = 'WiniKubeNAT'
NATSwitchName = 'WiniKubeNATSwitch'
NATGatewayIP = '172.16.76.1/24'
NATNetworkPrefix = '172.16.76.0/24'
} | CivicaDigital/winikube | config.psd1 | PowerShell | mit | 389 |
# Copyright (c) 2018-2020 Tigera, Inc. 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.
# This script is run from the main Calico directory.
. .\config.ps1
ipmo .\libs\calico\calico.psm1 -Force
# Autoconfigure the IPAM block mode.
if ($env:CNI_IPAM_TYPE -EQ "host-local") {
$env:USE_POD_CIDR = "true"
} else {
$env:USE_POD_CIDR = "false"
}
if($env:CALICO_NETWORKING_BACKEND = "windows-bgp")
{
Wait-ForCalicoInit
Write-Host "Windows BGP is enabled, running confd..."
cd "$PSScriptRoot"
# Remove the old peerings and blocks so that confd will always trigger
# reconfiguration at start of day. This ensures that stopping and starting the service
# reliably recovers from previous failures.
rm peerings.ps1 -ErrorAction SilentlyContinue
rm blocks.ps1 -ErrorAction SilentlyContinue
# Run the calico-confd binary.
& ..\calico-node.exe -confd -confd-confdir="$PSScriptRoot"
} else {
Write-Host "Windows BGP is disabled, not running confd."
while($True) {
Start-Sleep 10
}
}
| projectcalico/calico | node/windows-packaging/CalicoWindows/confd/confd-service.ps1 | PowerShell | apache-2.0 | 1,527 |
function Push-Migration
{
Update-StoredProcedure -SchemaName 'rivet' -Name 'InsertMigration' -Definition @'
@ID bigint,
@Name nvarchar(241),
@Who nvarchar(50),
@ComputerName nvarchar(50)
as
begin
declare @AtUtc datetime2(7)
select @AtUtc = getutcdate()
insert into [rivet].[Migrations] ([ID],[Name],[Who],[ComputerName],[AtUtc]) values (@ID,@Name,@Who,@ComputerName,@AtUtc)
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Push',@ID,@Name,@Who,@ComputerName,@AtUtc)
end
'@
Update-StoredProcedure -SchemaName 'rivet' -Name 'RemoveMigration' -Definition @'
@ID bigint,
@Name nvarchar(241),
@Who nvarchar(50),
@ComputerName nvarchar(50)
as
begin
delete from [rivet].[Migrations] where [ID] = @ID
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Pop',@ID,@Name,@Who,@ComputerName,getutcdate())
end
'@
}
function Pop-Migration
{
Update-StoredProcedure -SchemaName 'rivet' -Name 'InsertMigration' -Definition @'
@ID bigint,
@Name varchar(241),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
declare @AtUtc datetime2(7)
select @AtUtc = getutcdate()
insert into [rivet].[Migrations] ([ID],[Name],[Who],[ComputerName],[AtUtc]) values (@ID,@Name,@Who,@ComputerName,@AtUtc)
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Push',@ID,@Name,@Who,@ComputerName,@AtUtc)
end
'@
Update-StoredProcedure -SchemaName 'rivet' -Name 'RemoveMigration' -Definition @'
@ID bigint,
@Name varchar(241),
@Who varchar(50),
@ComputerName varchar(50)
as
begin
delete from [rivet].[Migrations] where [ID] = @ID
insert into [rivet].[Activity] ([Operation],[MigrationID],[Name],[Who],[ComputerName],[AtUtc]) values ('Pop',@ID,@Name,@Who,@ComputerName,getutcdate())
end
'@
} | RivetDB/Rivet | Rivet/Migrations/00000000000003_RivetChangeStoredProcedureVarcharParametersToNVarchar.ps1 | PowerShell | apache-2.0 | 1,936 |
# - - - - - - - - - - - - - - - - - - - - - - - -
# Helper function
# Assigns Constructor script to Class
# - - - - - - - - - - - - - - - - - - - - - - - -
function Attach-PSClassConstructor {
param (
[psobject]$Class
, [scriptblock]$scriptblock = $(Throw "Constuctor scriptblock is required.")
)
if ($Class.__ConstructorScript -ne $null) {
Throw "Only one Constructor is allowed"
}
$Class.__ConstructorScript = $scriptblock
} | ghostsquad/AetherClass | functions/Attach-PSClassConstructor.ps1 | PowerShell | apache-2.0 | 487 |
$packageName = 'kvrt'
$url = 'http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe'
$checksum = 'a363dee56a2b4263125590ee1bb5ced07963c684032d8ff228bff4f20b14debe'
$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.03.24.0815/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 960 |
# The msi must remove all components.
# But the msi uninstall log may contain
# disallowing uninstallation of component: ...... since another client exists
# After msi uninstall, run this to remove
#
# https://stackoverflow.com/questions/26739524/wix-toolset-complete-cleanup-after-disallowing-uninstallation-of-component-sin
# S-1-5-18 Local System A service account that is used by the operating system.
$components = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\
$removed = 0
$unremoved = 0
$each50 = 0
foreach ($c in $components) {
foreach($p in $c.Property) {
$propValue = (Get-ItemProperty "Registry::$($c.Name)" -Name "$($p)")."$($p)"
if ($propValue -match '^C:\\salt\\') {
if ($each50++ -eq 50) {
Write-Output $propValue
$each50 = 0
}
Remove-Item "Registry::$($c.Name)" -Recurse
$removed++
} else {
$unremoved++
}
}
}
Write-Host "$($removed) Local System component(s) pointed to (manually removed) C:\salt files and removed, left $($unremoved) unremoved"
| markuskramerIgitt/salt-windows-msi | remove_orpahned_salt_components.ps1 | PowerShell | apache-2.0 | 1,180 |
$packageName = 'adinsight'
$url = 'https://download.sysinternals.com/files/AdInsight.zip'
$checksum = '11e664c627c83808f7355d2e0d146b65faf9b6b3'
$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" | dtgm/chocolatey-packages | automatic/_output/adinsight/1.20/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 757 |
$projectRootPath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent
$moduleRootPath = Join-Path -Path $projectRootPath -ChildPath 'DscResource.DocumentationHelper'
$modulePath = Join-Path -Path $moduleRootPath -ChildPath 'MofHelper.psm1'
Import-Module -Name $modulePath -Force
InModuleScope -ModuleName 'MofHelper' {
$script:className = 'MSFT_MofHelperTest'
$script:fileName = '{0}.schema.mof' -f $script:ClassName
$script:tempFileName = '{0}.tmp' -f $script:fileName
$script:filePath = 'TestDrive:\{0}' -f $script:fileName
$script:tempFilePath = 'TestDrive:\{0}' -f $script:tempFileName
Describe Get-MofSchemaObject {
Mock -CommandName Resolve-Path -MockWith {
[pscustomobject]@{
Path = $script:filePath
}
} -ParameterFilter {$Path -eq $script:fileName}
Mock -CommandName Join-Path -MockWith {
$script:tempFilePath
}
$fileContent = @"
[ClassVersion("1.0.0"), FriendlyName("MofHelperTest")]
class MSFT_MofHelperTest : OMI_BaseResource
{
[Key, Description("Test key string property")] String Name;
[Required, Description("Test required property"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] String Needed;
[Write, Description("Test writeable string array")] String MultipleValues[];
[Write, Description("Test writeable boolean")] Boolean Switch;
[Write, Description("Test writeable datetime")] DateTime ExecuteOn;
[Write, Description("Test credential"), EmbeddedInstance("MSFT_Credential")] String Credential;
[Read, Description("Test readonly integer")] Uint32 NoWrite;
};
"@
Set-Content -Path $script:filePath -Value $fileContent
It 'Should import the class from the schema file without throwing' {
{ Get-MofSchemaObject -FileName $script:filePath } | Should -Not -Throw
}
$schema = Get-MofSchemaObject -FileName $script:filePath
It "Should import class with ClassName $script:className" {
$schema.ClassName | Should -Be $script:className
}
It 'Should get class version' {
$schema.ClassVersion | Should -Be '1.0.0'
}
It 'Should get class FriendlyName' {
$schema.FriendlyName | Should -Be 'MofHelperTest'
}
It 'Should get property <PropertyName> with all correct properties' {
[CmdletBinding()]
param (
[Parameter()]
[System.String]
$PropertyName,
[Parameter()]
[System.String]
$State,
[Parameter()]
[System.String]
$DataType,
[Parameter()]
[System.Boolean]
$IsArray,
[Parameter()]
[System.String]
$Description
)
$property = $schema.Attributes.Where({$_.Name -eq $PropertyName})
$property.State | Should -Be $State
$property.DataType | Should -Be $DataType
$property.Description | Should -Be $Description
$property.IsArray | Should -Be $IsArray
} -TestCases @(
@{
PropertyName = 'Name'
State = 'Key'
DataType = 'String'
Description = 'Test key string property'
IsArray = $false
}
@{
PropertyName = 'Needed'
State = 'Required'
DataType = 'String'
Description = 'Test required property'
IsArray = $false
}
@{
PropertyName = 'MultipleValues'
State = 'Write'
DataType = 'StringArray'
Description = 'Test writeable string array'
IsArray = $true
}
@{
PropertyName = 'Switch'
State = 'Write'
DataType = 'Boolean'
Description = 'Test writeable boolean'
IsArray = $false
}
@{
PropertyName = 'ExecuteOn'
State = 'Write'
DataType = 'DateTime'
Description = 'Test writeable datetime'
IsArray = $false
}
@{
PropertyName = 'Credential'
State = 'Write'
DataType = 'Instance'
Description = 'Test credential'
IsArray = $false
}
@{
PropertyName = 'NoWrite'
State = 'Read'
DataType = 'Uint32'
Description = 'Test readonly integer'
IsArray = $false
}
)
It 'Should return the proper ValueMap' {
$property = $schema.Attributes.Where({$_.Name -eq 'Needed'})
$property.ValueMap | Should -HaveCount 2
$property.ValueMap | Should -Contain 'Absent'
$property.ValueMap | Should -Contain 'Present'
}
It 'Should return the proper EmbeddedInstance for Credential' {
$property = $schema.Attributes.Where({$_.Name -eq 'Credential'})
$property.EmbeddedInstance | Should -Be 'MSFT_Credential'
}
}
}
| PlagueHO/DscResource.Tests | Tests/Unit/MofHelper.Tests.ps1 | PowerShell | mit | 5,396 |
UnInstall-ChocolateyZipPackage wfn 'wfnInstall.zip' | dtgm/chocolatey-packages | manual/wfn/tools/chocolateyUninstall.ps1 | PowerShell | apache-2.0 | 54 |
if ($IsLinux -or $IsMacOS) {
if (-not (Get-Command 'Get-Service' -ErrorAction SilentlyContinue)) {
function Get-Service {
Import-Clixml -Path (Join-Path $PSScriptRoot Get-Service.xml)
}
}
if (-not (Get-Command 'Get-CimInstance' -ErrorAction SilentlyContinue)) {
function Get-CimInstance {
param (
$ClassName,
$Namespace,
$class
)
if ($ClassName -eq 'win32_logicaldisk') {
Import-Clixml -Path (Join-Path $PSScriptRoot Get-CimInstanceDisk.xml)
}
elseif ($class -eq 'MSFT_NetAdapter') {
Import-Clixml -Path (Join-Path $PSScriptRoot Get-CimInstanceNetAdapter.xml)
}
}
}
function Get-Process {
param (
$Name,
$Id
)
if (-not $Name) {
if ($Id) {
(Import-Clixml -Path (Join-Path $PSScriptRoot Get-Process.xml))[0]
}
else {
Import-Clixml -Path (Join-Path $PSScriptRoot Get-Process.xml)
}
}
}
}
<# Creating the samples
Get-Service | Select-Object -First 30 | Export-Clixml -Path Get-Service.xml
$Disk = Get-CimInstance -ClassName win32_logicaldisk | Select-Object -Property DeviceId,VolumeName, Size,Freespace
$Disk | Export-Clixml -Path Get-CimInstanceDisk.xml
$NetAdapter = Get-CimInstance -Namespace root/StandardCimv2 -class MSFT_NetAdapter | Select-Object -Property Name, InterfaceDescription, MacAddress, LinkSpeed
$NetAdapter | Export-Clixml -Path Get-CimInstanceNetAdapter.xml
$Process = Get-Process | Where-Object { $_.StartTime -and $_.StartInfo -and $_.Modules -and $_.Company -notlike '*Microsoft*' } | Select-Object -first 20
$Process | Export-Clixml -Path $Path
$Process = Import-Clixml -Path $Path
$Process | foreach {$_.Threads = 'System.Diagnostics.ProcessThreadCollection'}
$Process | foreach {$_.Modules = 'System.Diagnostics.ProcessThreadCollection'}
$Process | Export-Clixml -Path $Path
#> | dfinke/ImportExcel | __tests__/Samples/Samples.ps1 | PowerShell | apache-2.0 | 2,060 |
function Enable-BoxstarterVM {
<#
.SYNOPSIS
Opens WMI ports and LocalAccountTokenFilterPolicy for Workgroup Hyper-V VMs
.DESCRIPTION
Prepares a Hyper-V VM for Boxstarter Installation. Opening WMI
ports if remoting is not enabled and enabling
LocalAccountTokenFilterPolicy if the VM is not in a domain so
that Boxstarter can later enable PowerShell Remoting.
Enable-BoxstarterVM will also restore the VM to a specified
checkpoint or create a new checkpoint if the given checkpoint
does not exist.
.Parameter Provider
The VM Provider to use.
.PARAMETER VMName
The name of the VM to enable.
.PARAMETER Credential
The Credential to use to test PSRemoting.
.PARAMETER CheckpointName
If a Checkpoint exists by this name, it will be restored. Otherwise one will be created.
.NOTES
PSRemoting must be enabled in order for Boxstarter to install to a remote machine. Bare
Metal machines require a manual step of enabling it before remote Boxstarter installs
will work. However, on a Hyper-V VM, Boxstarter can manage this by mounting and
manipulating the VM's VHD. Boxstarter can open the WMI ports which enable it to create a
Scheduled Task that will enable PSRemoting. For VMs that are not domain joined,
Boxstarter will also enable LocalAccountTokenFilterPolicy so that local accounts can
authenticate remotely.
For Non-HyperV VMs, use Enable-BoxstarterVHD to perform these adjustments on the VHD of
the VM. The VM must be powered off and accessible.
.OUTPUTS
A BoxstarterConnectionConfig that contains the ConnectionURI of the VM Computer and
the PSCredential needed to authenticate.
.EXAMPLE
$cred=Get-Credential domain\username
Enable-BoxstarterVM -Provider HyperV -VMName MyVM $cred
Prepares MyVM for a Boxstarter Installation
.EXAMPLE
Enable-BoxstarterVM -Provider HyperV -VMName MyVM $cred | Install-BoxstarterPackage MyPackage
Prepares MyVM and then installs MyPackage
.EXAMPLE
Enable-BoxstarterVM -Provider HyperV -VMName MyVM $cred ExistingSnapshot | Install-BoxstarterPackage MyPackage
Prepares MyVM, Restores ExistingSnapshot and then installs MyPackage
.EXAMPLE
Enable-BoxstarterVM -Provider HyperV -VMName MyVM $cred NewSnapshot | Install-BoxstarterPackage MyPackage
Prepares MyVM, Creates a new snapshot named NewSnapshot and then installs MyPackage
.LINK
http://boxstarter.org
Enable-BoxstarterVHD
Install-BoxstarterPackage
#>
[CmdletBinding()]
[OutputType([BoxstarterConnectionConfig])]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$True, Position=0)]
[string[]]$VMName,
[parameter(Mandatory=$true, Position=1)]
[Management.Automation.PsCredential]$Credential,
[parameter(Mandatory=$false, Position=2)]
[string]$CheckpointName
)
Begin {
##Cannot run remotely unelevated. Look into self elevating
if(!(Test-Admin)) {
Write-Error "You must be running as an administrator. Please open a PowerShell console as Administrator and rerun Install-BoxstarperPackage."
return
}
if(!(Get-Command -Name Get-VM -ErrorAction SilentlyContinue)){
Write-Error "Boxstarter could not find the Hyper-V PowerShell Module installed. This is required for use with Boxstarter.HyperV. Run Install-windowsfeature -name hyper-v -IncludeManagementTools."
return
}
$CurrentVerbosity=$global:VerbosePreference
if($PSBoundParameters["Verbose"] -eq $true) {
$global:VerbosePreference="Continue"
}
}
Process {
$VMName | % {
$vm=Get-VM $_ -ErrorAction SilentlyContinue
if($vm -eq $null){
throw New-Object -TypeName InvalidOperationException -ArgumentList "Could not find VM: $_"
}
if($CheckpointName -ne $null -and $CheckpointName.Length -gt 0){
$point = Get-VMSnapshot -VMName $_ -Name $CheckpointName -ErrorAction SilentlyContinue
$origState=$vm.State
if($point -ne $null) {
Restore-VMSnapshot -VMName $_ -Name $CheckpointName -Confirm:$false
Write-BoxstarterMessage "$checkpointName restored on $_ waiting to complete..."
$restored=$true
}
}
if($vm.State -eq "saved"){
Remove-VMSavedState $_
}
if($vm.State -ne "running"){
Start-VM $_ -ErrorAction SilentlyContinue
Wait-HeartBeat $_
}
do {
Start-Sleep -milliseconds 100
$ComputerName=Get-VMGuestComputerName $_
}
until ($ComputerName -ne $null)
$clientRemoting = Enable-BoxstarterClientRemoting $ComputerName
Write-BoxstarterMessage "Testing remoting access on $ComputerName..."
$remotingTest = Invoke-Command $ComputerName { Get-WmiObject Win32_ComputerSystem } -Credential $Credential -ErrorAction SilentlyContinue
$params=@{}
if(!$remotingTest) {
Log-BoxstarterMessage "PowerShell remoting connection failed:"
if($global:Error.Count -gt 0) { Log-BoxstarterMessage $global:Error[0] }
write-BoxstarterMessage "Testing WSMAN..."
$WSManResponse = Test-WSMan $ComputerName -ErrorAction SilentlyContinue
if($WSManResponse) {
Write-BoxstarterMessage "WSMAN responded. Will not enable WMI." -verbose
$params["IgnoreWMI"]=$true
}
else {
Log-BoxstarterMessage "WSMan connection failed:"
if($global:Error.Count -gt 0) { Log-BoxstarterMessage $global:Error[0] }
write-BoxstarterMessage "Testing WMI..."
$wmiTest=try { Invoke-WmiMethod -ComputerName $ComputerName -Credential $Credential Win32_Process Create -Args "cmd.exe" -ErrorAction SilentlyContinue } catch {$ex=$_}
if($wmiTest -or ($ex -ne $null -and $ex.CategoryInfo.Reason -eq "UnauthorizedAccessException")) {
Write-BoxstarterMessage "WMI responded. Will not enable WMI." -verbose
$params["IgnoreWMI"]=$true
}
else {
Log-BoxstarterMessage "WMI connection failed:"
if($global:Error.Count -gt 0) { Log-BoxstarterMessage $global:Error[0] }
}
}
$credParts = $Credential.UserName.Split("\\")
if(($credParts.Count -eq 1 -and $credParts[0] -eq "administrator") -or `
($credParts.Count -eq 2 -and $credParts[0] -eq $ComputerName -and $credParts[1] -eq "administrator") -or`
($credParts.Count -eq 2 -and $credParts[0] -ne $ComputerName)){
$params["IgnoreLocalAccountTokenFilterPolicy"]=$true
}
if($credParts.Count -eq 2 -and $credParts[0] -eq $ComputerName -and $credParts[1] -eq "administrator"){
$params["IgnoreLocalAccountTokenFilterPolicy"]=$true
}
}
if(!$remotingTest -and ($params.Count -lt 2)) {
Write-BoxstarterMessage "Stopping $_"
Stop-VM $_ -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
$vhd=Get-VMHardDiskDrive -VMName $_
Enable-BoxstarterVHD $vhd.Path @params | Out-Null
Start-VM $_
Write-BoxstarterMessage "Started $_. Waiting for Heartbeat..."
Wait-HeartBeat $_
}
if(!$restored -and $CheckpointName -ne $null -and $CheckpointName.Length -gt 0) {
Write-BoxstarterMessage "Creating Checkpoint $CheckpointName"
Checkpoint-VM -Name $_ -SnapshotName $CheckpointName
}
$res=new-Object -TypeName BoxstarterConnectionConfig -ArgumentList "http://$($computerName):5985/wsman",$Credential,$null
return $res
}
}
End {
$global:VerbosePreference=$CurrentVerbosity
}
}
function Get-VMGuestComputerName($vmName) {
$vm = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter "ElementName='$vmName'"
$vm.GetRelated("Msvm_KvpExchangeComponent").GuestIntrinsicExchangeItems | % {
if(([XML]$_) -ne $null){
$GuestExchangeItemXml = ([XML]$_).SelectSingleNode("/INSTANCE/PROPERTY[@NAME='Name']/VALUE[child::text()='FullyQualifiedDomainName']")
if ($GuestExchangeItemXml -ne $null) {
$GuestExchangeItemXml.SelectSingleNode("/INSTANCE/PROPERTY[@NAME='Data']/VALUE/child::text()").Value
}
}
}
}
function Wait-HeartBeat($vmName) {
do {Start-Sleep -milliseconds 100}
until ((Get-VMIntegrationService -VMName $vmName | ?{$_.id.endswith("\\84EAAE65-2F2E-45F5-9BB5-0E857DC8EB47") -or ($_.name -eq "Heartbeat")}).PrimaryStatusDescription -eq "OK")
} | fhchina/boxstarter | Boxstarter.HyperV/Enable-BoxstarterVM.ps1 | PowerShell | apache-2.0 | 9,087 |
[CmdletBinding()]
param()
# Arrange.
. $PSScriptRoot\..\..\lib\Initialize-Test.ps1
. $PSScriptRoot\..\..\..\Tasks\PublishSymbols\IndexHelpers\SrcSrvIniContentFunctions.ps1
$provider = New-Object psobject -Property @{
CollectionUrl = 'Some collection URL'
CommitId = 'Some commit ID'
RepoId = 'Some repo ID'
TeamProjectId = 'Some team project ID'
SourcesRootPath = 'SomeDrive:\SomeRoot\\\' # Function should handle trimming trailing slashes.
}
$sourceFiles = @(
'SomeDrive:\SomeRoot\SomeSolution\SomeProject\SomeSource.cs'
'SomeDrive:\SomeRoot\AnotherSolution\AnotherProject\AnotherSource.cs'
)
$script:now = Get-Date
Register-Mock Get-Date { $script:now }
# Act.
$actual = New-TfsGitSrcSrvIniContent -Provider $provider -SourceFilePaths $sourceFiles
# Assert.
$expected = @(
'SRCSRV: ini ------------------------------------------------'
'VERSION=3'
'INDEXVERSION=2'
'VERCTRL=Team Foundation Server'
[string]::Format(
[System.Globalization.CultureInfo]::InvariantCulture,
'DATETIME={0:ddd MMM dd HH:mm:ss yyyy}',
($now))
'INDEXER=TFSTB'
'SRCSRV: variables ------------------------------------------'
"TFS_EXTRACT_TARGET=%targ%\%var5%\%fnvar%(%var6%)%fnbksl%(%var7%)"
"TFS_EXTRACT_CMD=tf.exe git view /collection:%fnvar%(%var2%) /teamproject:""%fnvar%(%var3%)"" /repository:""%fnvar%(%var4%)"" /commitId:%fnvar%(%var5%) /path:""%var7%"" /output:%SRCSRVTRG% %fnvar%(%var8%)"
"TFS_COLLECTION=Some collection URL"
"TFS_TEAM_PROJECT=Some team project ID"
"TFS_REPO=Some repo ID"
"TFS_COMMIT=Some commit ID"
"TFS_SHORT_COMMIT=Some com"
"TFS_APPLY_FILTERS=/applyfilters"
'SRCSRVVERCTRL=git'
'SRCSRVERRDESC=access'
'SRCSRVERRVAR=var2'
'SRCSRVTRG=%TFS_EXTRACT_TARGET%'
'SRCSRVCMD=%TFS_EXTRACT_CMD%'
'SRCSRV: source files ---------------------------------------'
"SomeDrive:\SomeRoot\SomeSolution\SomeProject\SomeSource.cs*TFS_COLLECTION*TFS_TEAM_PROJECT*TFS_REPO*TFS_COMMIT*TFS_SHORT_COMMIT*/SomeSolution/SomeProject/SomeSource.cs*TFS_APPLY_FILTERS"
"SomeDrive:\SomeRoot\AnotherSolution\AnotherProject\AnotherSource.cs*TFS_COLLECTION*TFS_TEAM_PROJECT*TFS_REPO*TFS_COMMIT*TFS_SHORT_COMMIT*/AnotherSolution/AnotherProject/AnotherSource.cs*TFS_APPLY_FILTERS"
'SRCSRV: end ------------------------------------------------'
)
Assert-AreEqual $expected $actual
| cwoolum/vso-agent-tasks | Tests/L0/PublishSymbols/New-TfsGitSrcSrvIniContent.FormatsContent.ps1 | PowerShell | mit | 2,421 |
# 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
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
}
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
}
catch {
Write-Host 'Exception caught in script:'
Write-Host $_.InvocationInfo.PositionMessage
Write-Host "Kubernetes Windows node setup failed: $($_.Exception.Message)"
exit 1
}
| Miciah/origin | vendor/k8s.io/kubernetes/cluster/gce/windows/configure.ps1 | PowerShell | apache-2.0 | 5,775 |
$env:JAVA_HOME_PARENT = if ($env:JAVA_HOME_PARENT) {
$env:JAVA_HOME_PARENT
} elseif ($IsWindows) {
"$env:ProgramFiles\Java"
} else {
'/usr/lib/jvm/'
}
$env:JDK_HOME = if ($env:JDK_HOME) {
$env:JDK_HOME
} else {
(Get-ChildItem $env:JAVA_HOME_PARENT -Filter jdk* | Sort-Object @{ Expression = { ($_.Name -replace 'jdk(.*)_(.*)','$1.$2') -as [version] } } -Bottom 1).FullName
}
$env:JAVA_HOME = if ($env:JAVA_HOME) {
$env:JAVA_HOME
} else {
$env:JDK_HOME
}
$env:Path = @(
"$env:JDK_HOME\bin"
$env:Path
) -join [System.IO.Path]::PathSeparator
| matt9ucci/PSProfiles | PSModules/Java/Java.psm1 | PowerShell | mit | 550 |
<#
.EXAMPLE
This example will enable TCP/IP protocol and set the custom static port to 4509.
When RestartService is set to $true the resource will also restart the SQL service.
#>
Configuration Example
{
param
(
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$SysAdminAccount
)
Import-DscResource -ModuleName xSqlServer
node localhost
{
xSQLServerNetwork 'ChangeTcpIpOnDefaultInstance'
{
InstanceName = 'MSSQLSERVER'
ProtocolName = 'Tcp'
IsEnabled = $true
TCPDynamicPort = $true
RestartService = $true
}
}
}
| PaulFeaser/xSQLServer | Examples/Resources/xSQLServerNetwork/2-EnableTcpIpWithDynamicPort.ps1 | PowerShell | mit | 743 |
<#PSScriptInfo
.VERSION 1.0.0
.GUID b5646852-132f-4f84-8057-b8e9e91e29b8
.AUTHOR DSC Community
.COMPANYNAME DSC Community
.COPYRIGHT DSC Community contributors. All rights reserved.
.TAGS DSCConfiguration
.LICENSEURI https://github.com/dsccommunity/xFailOverCluster/blob/main/LICENSE
.PROJECTURI https://github.com/dsccommunity/xFailOverCluster
.ICONURI https://dsccommunity.org/images/DSC_Logo_300p.png
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
First version.
.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core
#>
#Requires -Module xFailOverCluster
<#
.DESCRIPTION
This example shows how to add two failover over cluster disk resources to the
failover cluster.
.NOTES
This example assumes the failover cluster is already present.
#>
Configuration xClusterDisk_AddClusterDiskConfig
{
Import-DscResource -ModuleName xFailOverCluster
Node localhost
{
xClusterDisk 'AddClusterDisk-SQL2017-DATA'
{
Number = 1
Ensure = 'Present'
Label = 'SQL2016-DATA'
}
xClusterDisk 'AddClusterDisk-SQL2017-LOG'
{
Number = 2
Ensure = 'Present'
Label = 'SQL2016-LOG'
}
}
}
| PowerShell/xFailOverCluster | source/Examples/Resources/xClusterDisk/1-xClusterDisk_AddClusterDiskConfig.ps1 | PowerShell | mit | 1,293 |
function Get-PASAccountCredentials {
<#
.SYNOPSIS
Returns password for an account.
.DESCRIPTION
Returns password for an account identified by its AccountID.
Will not return SSH Keys.
Cannot be used if a reason for password access must be specified.
.PARAMETER AccountID
The ID of the account whose password will be retrieved.
.PARAMETER sessionToken
Hashtable containing the session token returned from New-PASSession
.PARAMETER WebSession
WebRequestSession object returned from New-PASSession
.PARAMETER BaseURI
PVWA Web Address
Do not include "/PasswordVault/"
.PARAMETER PVWAAppName
The name of the CyberArk PVWA Virtual Directory.
Defaults to PasswordVault
.EXAMPLE
$token | Get-PASAccount -Keywords root -Safe Prod_Safe | Get-PASAccountCredentials
Will return the password value of the account fond by Get-PASAccount:
Password
--------
Ra^D0MwM666*&U
.INPUTS
All parameters can be piped by property name
Accepts pipeline input from other Get-PASAccount
.OUTPUTS
Outputs Object of Custom Type psPAS.CyberArk.Vault.Credential
SessionToken, WebSession, BaseURI are passed through and
contained in output object for inclusion in subsequent
pipeline operations.
Output format is defined via psPAS.Format.ps1xml.
To force all output to be shown, pipe to Select-Object *
.NOTES
.LINK
#>
[CmdletBinding()]
param(
[parameter(
Mandatory = $true,
ValueFromPipelinebyPropertyName = $true
)]
[string]$AccountID,
[parameter(
Mandatory = $true,
ValueFromPipelinebyPropertyName = $true
)]
[ValidateNotNullOrEmpty()]
[hashtable]$sessionToken,
[parameter(
ValueFromPipelinebyPropertyName = $true
)]
[Microsoft.PowerShell.Commands.WebRequestSession]$WebSession,
[parameter(
Mandatory = $true,
ValueFromPipelinebyPropertyName = $true
)]
[string]$BaseURI,
[parameter(
Mandatory = $false,
ValueFromPipelinebyPropertyName = $true
)]
[string]$PVWAAppName = "PasswordVault"
)
BEGIN {}#begin
PROCESS {
#Create request URL
$URI = "$baseURI/$PVWAAppName/WebServices/PIMServices.svc/Accounts/$($AccountID |
Get-EscapedString)/Credentials"
#Send request to web service
$result = Invoke-PASRestMethod -Uri $URI -Method GET -Headers $sessionToken -WebSession $WebSession
}#process
END {
If($result) {
[PSCustomObject] @{"Password" = $result} |
Add-ObjectDetail -typename psPAS.CyberArk.Vault.Credential -PropertyToAdd @{
"sessionToken" = $sessionToken
"WebSession" = $WebSession
"BaseURI" = $BaseURI
"PVWAAppName" = $PVWAAppName
}
}
}#end
} | zshehri/CTU | psPAS/Functions/Accounts/Get-PASAccountCredentials.ps1 | PowerShell | mit | 2,889 |
#Requires -RunAsAdministrator
# Install the provider
$myPath = Get-Location
$myDll = 'privacyIDEA-ADFSProvider.dll'
$myDllFullName = (get-item $myDll).FullName
function Gac-Util
{
param (
[parameter(Mandatory = $true)][string] $assembly
)
try
{
$Error.Clear()
[Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") | Out-Null
[System.EnterpriseServices.Internal.Publish] $publish = New-Object System.EnterpriseServices.Internal.Publish
if (!(Test-Path $assembly -type Leaf) )
{ throw "The assembly $assembly does not exist" }
if ([System.Reflection.Assembly]::LoadFile($assembly).GetName().GetPublicKey().Length -eq 0 )
{ throw "The assembly $assembly must be strongly signed" }
$publish.GacInstall($assembly)
Write-Host "`t`t$($MyInvocation.InvocationName): Assembly $assembly gacced"
}
catch
{
Write-Host "`t`t$($MyInvocation.InvocationName): $_"
}
}
# check event source
if (!([System.Diagnostics.EventLog]::SourceExists("privacyIDEAProvider")))
{
New-EventLog -LogName "AD FS/Admin" -Source "privacyIDEAProvider"
Write-Host "Log source created"
}
Gac-Util $myDllFullName
$appFullName = ([system.reflection.assembly]::loadfile($myDllFullName)).FullName
$typeName = "privacyIDEAADFSProvider.Adapter, "+$appFullName
Register-AdfsAuthenticationProvider -TypeName $typeName -Name "privacyIDEA-ADFSProvider" -ConfigurationFilePath $myPath"\config.xml" -Verbose
Restart-Service adfssrv | sbidy/privacyIDEA-ADFSProvider | privacyIDEAADFSProvider/Install/Install-ADFSProvider.ps1 | PowerShell | mit | 1,550 |
function Export-DbaXESessionTemplate {
<#
.SYNOPSIS
Exports an XESession XML Template.
.DESCRIPTION
Exports an XESession XML Template either from the dbatools repository or a file you specify. Exports to "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates" by default
.PARAMETER SqlInstance
Target SQL Server. You must have sysadmin access and server version must be SQL Server version 2008 or higher.
.PARAMETER SqlCredential
Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
.PARAMETER Session
The Name of the session(s) to export.
.PARAMETER Path
The path to export the file into. Can be .xml or directory.
.PARAMETER InputObject
Specifies an XE Session output by Get-DbaXESession.
.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
Website: https://dbatools.io
Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Export-DbaXESessionTemplate
.EXAMPLE
Export-DbaXESessionTemplate -SqlInstance sql2017 -Path C:\temp\xe
Exports XE Session Template to the C:\temp\xe folder.
.EXAMPLE
Get-DbaXESession -SqlInstance sql2017 -Session session_health | Export-DbaXESessionTemplate -Path C:\temp
Returns a new XE Session object from sql2017 then adds an event, an action then creates it.
#>
[CmdletBinding()]
param (
[Alias("ServerInstance", "SqlServer")]
[DbaInstanceParameter[]]$SqlInstance,
[PSCredential]$SqlCredential,
[object[]]$Session,
[string]$Path = "$home\Documents\SQL Server Management Studio\Templates\XEventTemplates",
[Parameter(ValueFromPipeline)]
[Microsoft.SqlServer.Management.XEvent.Session[]]$InputObject,
[switch]$EnableException
)
process {
foreach ($instance in $SqlInstance) {
try {
Write-Message -Level Verbose -Message "Connecting to $instance."
$InputObject += Get-DbaXESession -SqlInstance $instance -SqlCredential $SqlCredential -Session $Session -EnableException
}
catch {
Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
}
}
foreach ($xes in $InputObject) {
$xesname = Remove-InvalidFileNameChars -Name $xes.Name
if (-not (Test-Path -Path $Path)) {
Stop-Function -Message "$Path does not exist." -Target $Path
}
if ($path.EndsWith(".xml")) {
$filename = $path
}
else {
$filename = "$path\$xesname.xml"
}
Write-Message -Level Verbose -Message "Wrote $xesname to $filename"
[Microsoft.SqlServer.Management.XEvent.XEStore]::SaveSessionToTemplate($xes, $filename, $true)
Get-ChildItem -Path $filename
}
}
} | SirCaptainMitch/dbatools | functions/Export-DbaXESessionTemplate.ps1 | PowerShell | mit | 3,636 |
Function New-AGMLibGCVEfailover ([string]$filename,[int]$phase)
{
<#
.SYNOPSIS
Uses a pre-prepared CSV list of VMware VM Names to run mount jobs in phases
.EXAMPLE
New-AGMLibGCVEfailover -filename recoverylist.csv -vcenterid XXXXXX
This will load the contents of the file recoverylist.csv and use it to run multiple New-AGMLibVM jobs
.DESCRIPTION
This routine needs a well formatted CSV file. Here is an example of such a file:
phase,sourcevmname,targetvmname,label,targetnetworkname,poweronvm,targetmacaddress
1,WinSrv2019-2,WinSrv2019-2-rec,phase1,avtest,true,
1,WinSrv2019-3,WinSrv2019-3-rec,phase1,avtest,false,01:50:56:81:11:6b
2,Centos1,centos1-rec,phase2,avtest,true,
2,Centos2,centos2-red,phase2,avtest,false
#>
if ( (!($AGMSESSIONID)) -or (!($AGMIP)) )
{
Get-AGMErrorMessage -messagetoprint "Not logged in or session expired. Please login using Connect-AGM"
return
}
$sessiontest = Get-AGMVersion
if ($sessiontest.errormessage)
{
Get-AGMErrorMessage -messagetoprint "AGM session has expired. Please login again using Connect-AGM"
return
}
if (!($filename))
{
Get-AGMErrorMessage -messagetoprint "Please supply a csv file correctly formatted as per the help for this function using: -filename xxxx.csv"
return;
}
if ( Test-Path $filename )
{
$recoverylist = Import-Csv -Path $filename
if (!($recoverylist.phase)) { Get-AGMErrorMessage -messagetoprint "Could not find the phase column in the CSV file, which is mandatory"; return }
if (!($recoverylist.sourcevmname)) { Get-AGMErrorMessage -messagetoprint "Could not find the sourcevmname column in the CSV file, which is mandatory"; return }
}
else
{
Get-AGMErrorMessage -messagetoprint "VM list: $filename could not be opened."
return;
}
# The user can give us a vcenter ID, but given this is GCVE, we expect we will have only one vCenter. If we find more than one then we need to know which one
if (!($vcenterid))
{
$vcentergrab = Get-AGMHost -filtervalue isvcenterhost=true
if ($vcentergrab.count -lt 1)
{
Get-AGMErrorMessage -messagetoprint "Could not find any vCenters"
return;
}
if ($vcentergrab.counts -gt 1)
{
Get-AGMErrorMessage -messagetoprint "Found too many vCenters, please learn the correct ID and specify it wiht -vcenterid"
return;
}
$vcenterid = $vcentergrab.id
$srcid = $vcentergrab.srcid
$vcentername = $vcentergrab.name
write-host ""
write-host "Using the following vCenter:"
write-host "Name: $vcentername vCenterID: $vcenterid"
}
# we now create a round robin list of ESX hosts. We are going to treat them equally
# firstly we need a srcid from our vcenter
if (!($srcid))
{
$vcentergrab = Get-AGMHost $vcenterid
if ($vcentergrab.srcid)
{
$srcid = $vcentergrab.srcid
$vcentername = $vcentergrab.name
write-host ""
write-host "Using vCenter named $vcentername with vCenterID $vcenterid"
}
else
{
Get-AGMErrorMessage -messagetoprint "Could not find vCenters with ID $vcenterid"
return;
}
}
$esxgrab = Get-AGMHost -filtervalue "vcenterhostid=$srcid&isesxhost=true&originalhostid=0"
if ($esxgrab.count -lt 1)
{
Get-AGMErrorMessage -messagetoprint "Could not find ESX hosts for vCenter with ID $vcenterid"
return;
}
# we count the number of ESX hosts
$esxhostcount = $esxgrab.id.count
# we start with ESX host index 0
$esxroundrobin = 0
write-host ""
write-host "Using the following ESXi hosts"
$esxtable = $esxgrab | Select-Object id,name | Format-Table
$esxtable
# Our assumption is that GCVE has one datastore and that all ESX hosts have access to that datastore
$datastoregrab = (((Get-AGMHost $esxgrab.id[0]).sources.datastorelist) | select-object name| sort-object name | Get-Unique -asstring).name
if ($datastoregrab.count -lt 1)
{
Get-AGMErrorMessage -messagetoprint "Could not find any datastores"
return;
}
if ($datastoregrab.count -gt 1)
{
Get-AGMErrorMessage -messagetoprint "Found too many datastores"
return;
}
$datastore = $datastoregrab
write-host ""
write-host "Using the following Datastore:"
write-host "$datastore"
write-host ""
write-host "Starting Mounts now for phase $phase"
# we are now ready to go through our list
foreach ($app in $recoverylist)
{
if ($app.phase -eq $phase)
{
# so this is the our esxhostid. Starting with index 0
$esxhostid = $esxgrab.id[$esxroundrobin]
if ($app.targetvmname.length -gt 0)
{
$mountvmname = $app.targetvmname
}
else {
$mountvmname = $app.sourcevmname
}
$mountcommand = 'New-AGMLibVM -appname ' +$app.sourcevmname +' -vmname ' +$mountvmname +' -datastore ' +$datastore +' -vcenterid ' +$vcenterid +' -esxhostid ' +$esxhostid +' -mountmode nfs -onvault true'
if ($app.label) { $mountcommand = $mountcommand + ' -label "' +$app.Label +'"' }
# if user asked for a MAC address, then we better keep power off the VM
if ($app.targetmacaddress.length -gt 0) { $mountcommand = $mountcommand + ' -poweronvm "false"' }
elseif ($app.poweronvm.length -gt 0) { $mountcommand = $mountcommand + ' -poweronvm "' +$app.poweronvm +'"' }
write-host "Running $mountcommand"
Invoke-Expression $mountcommand
# we add one to our ESX round robin. If we hit the hostcount we have gone too far, so 3 hosts means index 0,1,2 so when we get to 3 then we go back to 0
$esxroundrobin += 1
if ($esxroundrobin -eq $esxhostcount )
{
$esxroundrobin = 0
}
}
}
} | Actifio/AGMPowerLib | Public/New-AGMLibGCVEfailover.ps1 | PowerShell | mit | 6,207 |
function Get-IMSecurityGroup
{
<#
.Synopsis
Get a Security Group object from Identity Manager.
.DESCRIPTION
You can filter on DisplayName or ObjectID
.EXAMPLE
Get-IMSecurityGroup
Will output all security groups from Identity Manager
.EXAMPLE
Get-IMSecurityGroup -Displayname "Domain*"
Will ouput all security groups that have Domain in their displayname
.EXAMPLE
Get-IMPerson -ObjectID 0e64a52c-3696-4edc-b836-caf54888fbb7
Will output the security group with id '0e64a52c-3696-4edc-b836-caf54888fbb7'
.OUTPUTS
It outpus a PSCustomObject with the attribute bindings that is defined for the Person Object
.COMPONENT
Identity Manager
.FUNCTIONALITY
Identity Manager
#>
[OutputType([System.Management.Automation.PSCustomObject])]
[cmdletbinding()]
Param(
[string]$DisplayName
,
[Parameter(ParameterSetName='ByObjectID')]
[string]$ObjectID
,
[pscredential]$Credential
,
[string]$uri = "http://localhost:5725/ResourceManagementService"
,
[switch]$AllRelated
)
BEGIN
{
$f = $MyInvocation.InvocationName
Write-Verbose -Message "$f - START"
$splat = @{
uri = $uri
ResourceType = "Group"
ErrorAction = [System.Management.Automation.ActionPreference]::SilentlyContinue
}
}
PROCESS
{
if($PSBoundParameters.ContainsKey("DisplayName"))
{
$null = $splat.Add("Attribute", "DisplayName")
$null = $splat.Add("AttributeValue","$DisplayName")
}
if($PSBoundParameters.ContainsKey("ObjectID"))
{
$null = $splat.Add("Attribute", "ObjectID")
$null = $splat.Add("AttributeValue","$ObjectID")
}
if($PSBoundParameters.ContainsKey("Credential"))
{
Write-Verbose -Message "$f - Credentials provided, adding to splat"
$null = $splat.Add("Credential",$Credential)
}
if ($PSBoundParameters.ContainsKey("AllRelated"))
{
Write-Verbose -Message "$f - AllRelated specified, adding to splat"
$null = $splat.Add("AllRelated",$true)
}
$FIMobject = Get-IMobject @splat
if(-not $FIMobject)
{
Write-Verbose "$f - Get-IMobject returned null objects of resourcetype $($splat.ResourceType)"
}
$FIMobject
}
END
{
Write-Verbose -Message "$f - END"
}
} | torgro/IdentityManager | Functions/Get-IMSecurityGroup.ps1 | PowerShell | mit | 2,336 |
Start-AutoRestCodeGeneration -ResourceProvider "recoveryservicesbackup/resource-manager" -AutoRestVersion "v2" -SdkGenerationDirectory "$PSScriptRoot\recoveryservicesbackup\Generated" -ConfigFileTag "package-2021-12" -Namespace "Microsoft.Azure.Management.RecoveryServices.Backup"
Start-AutoRestCodeGeneration -ResourceProvider "recoveryservicesbackup/resource-manager" -AutoRestVersion "v2" -SdkGenerationDirectory "$PSScriptRoot\recoveryservicesbackupCrossregionRestore\Generated" -ConfigFileTag "package-passivestamp-2021-11-15" -Namespace "Microsoft.Azure.Management.RecoveryServices.Backup.CrossRegionRestore" -ClearMetadataLog $false
| Azure/azure-sdk-for-net | sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/generate.ps1 | PowerShell | mit | 641 |
function Remove-TVDevice
{
<#
#>
[OutputType([bool])]
[CmdletBinding(
SupportsShouldProcess = $true
)]
param(
[Parameter(
Mandatory = $true
)]
[string] $Token,
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true,
ParameterSetName = 'ByInputObject'
)]
[ValidateNotNull()]
[TVDevice] $InputObject,
[Parameter(
Mandatory = $true,
HelpMessage = 'The DeviceID of the Device to delete.',
ParameterSetName = 'ByID'
)]
[string] $DeviceID
)
process
{
if ( $PSCmdlet.ParameterSetName -ne 'ByInputObject')
{
$InputObject = Get-TVDevice -Token $Token | Where-Object { $_.DeviceID -eq $DeviceID }
}
if (!($InputObject))
{
throw 'Invalid groupname received.'
}
if ( $PSCmdlet.ShouldProcess($InputObject.Alias, 'Remove Device') )
{
Try
{
$Param = @{
Token = $Token
Method = 'Delete'
Resource = 'devices'
PrincipalID = $InputObject.DeviceID
}
Invoke-TVApiRequest @Param
# return ( $null -eq (Get-TVGroup -Token $Token -Name $InputObject.Name) )
}
catch
{
$_.Exception.Message
#$ErrJson = $_ | convertFrom-json
Write-Error -Message ("err: {0}" -f $ErrJson.message )
return $false
}
}
}
} | Marcuzzo/PSTeamViewer | PSTeamViewer/public/Remove-TVDevice.ps1 | PowerShell | mit | 1,689 |
Describe $($PSCommandPath -Replace ".Tests.ps1") {
BeforeAll {
#Get Current Directory
$Here = Split-Path -Parent $PSCommandPath
#Assume ModuleName from Repository Root folder
$ModuleName = Split-Path (Split-Path $Here -Parent) -Leaf
#Resolve Path to Module Directory
$ModulePath = Resolve-Path "$Here\..\$ModuleName"
#Define Path to Module Manifest
$ManifestPath = Join-Path "$ModulePath" "$ModuleName.psd1"
if ( -not (Get-Module -Name $ModuleName -All)) {
Import-Module -Name "$ManifestPath" -ArgumentList $true -Force -ErrorAction Stop
}
$Script:RequestBody = $null
$Script:BaseURI = "https://SomeURL/SomeApp"
$Script:ExternalVersion = "0.0"
$Script:WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
}
AfterAll {
$Script:RequestBody = $null
}
InModuleScope $(Split-Path (Split-Path (Split-Path -Parent $PSCommandPath) -Parent) -Leaf ) {
It 'outputs a string' {
"+ & %" | Get-EscapedString | Should -BeOfType System.String
}
It 'outputs an escaped string' {
"+ & %" | Get-EscapedString | Should -BeExactly "%2B%20%26%20%25"
}
}
} | pspete/psPAS | Tests/Get-EscapedString.Tests.ps1 | PowerShell | mit | 1,127 |
<#
.Description
Migrate Azure IaaS VM from one subscripiton to another subscription
.Example
.\Migrate-AzureVM.ps1 -SourceSubscriptionName "foo" -DestSubscritpionName "bar" -SourceCloudServiceName "foocs" -SourceVMName "foovm" -DestCloudServiceName "barcs" -DestStorageAccountName "barstorage" -DestLocationName "China East" -DestVNetName "foovnet"
#>
Param
(
[string] $SourceSubscriptionName,
[string] $DestSubscritpionName,
[string] $SourceCloudServiceName,
[string] $SourceVMName,
[string] $DestCloudServiceName,
[string] $DestStorageAccountName,
[string] $DestLocationName,
[string] $DestVNetName
)
#Check the Azure PowerShell module version
Write-Host "Checking Azure PowerShell module verion" -ForegroundColor Green
$APSMajor =(Get-Module azure).version.Major
$APSMinor =(Get-Module azure).version.Minor
$APSBuild =(Get-Module azure).version.Build
$APSVersion =("$PSMajor.$PSMinor.$PSBuild")
If ($APSVersion -ge 0.8.14)
{
Write-Host "Powershell version check success" -ForegroundColor Green
}
Else
{
Write-Host "[ERROR] - Azure PowerShell module must be version 0.8.14 or higher. Exiting." -ForegroundColor Red
Exit
}
Write-Host "`t================= Migration Setting =======================" -ForegroundColor Green
Write-Host "`t Source Subscription Name = $SourceSubscriptionName " -ForegroundColor Green
Write-Host "`t Source Cloud Service Name = $SourceCloudServiceName " -ForegroundColor Green
Write-Host "`t Source VM Name = $SourceVMName " -ForegroundColor Green
Write-Host "`t Dest Subscription Name = $DestSubscritpionName " -ForegroundColor Green
Write-Host "`t Dest Cloud Service Name = $DestCloudServiceName " -ForegroundColor Green
Write-Host "`t Dest Storage Account Name = $DestStorageAccountName " -ForegroundColor Green
Write-Host "`t Dest Location = $DestLocationName " -ForegroundColor Green
Write-Host "`t Dest VNET = $DestVNetName " -ForegroundColor Green
Write-Host "`t===========================================================" -ForegroundColor Green
$ErrorActionPreference = "Stop"
try{ stop-transcript|out-null }
catch [System.InvalidOperationException] { }
$workingDir = (Get-Location).Path
$log = $workingDir + "\VM-" + $SourceCloudServiceName + "-" + $SourceVMName + ".log"
Start-Transcript -Path $log -Append -Force
Select-AzureSubscription -SubscriptionName $SourceSubscriptionName
#######################################################################
# Check if the VM is shut down
# Stopping the VM is a required step so that the file system is consistent when you do the copy operation.
# Azure does not support live migration at this time..
#######################################################################
$sourceVM = Get-AzureVM –ServiceName $SourceCloudServiceName –Name $SourceVMName
if ( $sourceVM -eq $null )
{
Write-Host "[ERROR] - The source VM doesn't exist. Exiting." -ForegroundColor Red
Exit
}
# check if VM is shut down
if ( $sourceVM.Status -notmatch "Stopped" )
{
Write-Host "[Warning] - Stopping the VM is a required step so that the file system is consistent when you do the copy operation. Azure does not support live migration at this time. If you’d like to create a VM from a generalized image, sys-prep the Virtual Machine before stopping it." -ForegroundColor Yellow
$ContinueAnswer = Read-Host "`n`tDo you wish to stop $SourceVMName now? (Y/N)"
If ($ContinueAnswer -ne "Y") { Write-Host "`n Exiting." -ForegroundColor Red; Exit }
$sourceVM | Stop-AzureVM
# wait until the VM is shut down
$sourceVMStatus = (Get-AzureVM –ServiceName $SourceCloudServiceName –Name $SourceVMName).Status
while ($sourceVMStatus -notmatch "Stopped")
{
Write-Host "Waiting VM $vmName to shut down, current status is $sourceVMStatus" -ForegroundColor Green
Sleep -Seconds 5
$sourceVMStatus = (Get-AzureVM –ServiceName $SourceCloudServiceName –Name $SourceVMName).Status
}
}
# exporting the sourve vm to a configuration file, you can restore the original VM by importing this config file
# see more information for Import-AzureVM
$vmConfigurationPath = $workingDir + "\ExportedVMConfig-" + $SourceCloudServiceName + "-" + $SourceVMName +".xml"
Write-Host "Exporting VM configuration to $vmConfigurationPath" -ForegroundColor Green
$sourceVM | Export-AzureVM -Path $vmConfigurationPath
#######################################################################
# Copy the vhds of the source vm
# You can choose to copy all disks including os and data disks by specifying the
# parameter -DataDiskOnly to be $false. The default is to copy only data disk vhds
# and the new VM will boot from the original os disk.
#######################################################################
$sourceOSDisk = $sourceVM.VM.OSVirtualHardDisk
$sourceDataDisks = $sourceVM.VM.DataVirtualHardDisks
# Get source storage account information, not considering the data disks and os disks are in different accounts
$sourceStorageAccountName = $sourceOSDisk.MediaLink.Host -split "\." | select -First 1
$sourceStorageAccount = Get-AzureStorageAccount –StorageAccountName $sourceStorageAccountName
$sourceStorageKey = (Get-AzureStorageKey -StorageAccountName $sourceStorageAccountName).Primary
Select-AzureSubscription -SubscriptionName $DestSubscritpionName
# Create destination context
$destStorageAccount = Get-AzureStorageAccount | ? {$_.StorageAccountName -eq $DestStorageAccountName} | select -first 1
if ($destStorageAccount -eq $null)
{
New-AzureStorageAccount -StorageAccountName $DestStorageAccountName -Location $DestLocationName
$destStorageAccount = Get-AzureStorageAccount -StorageAccountName $DestStorageAccountName
}
$DestStorageAccountName = $destStorageAccount.StorageAccountName
$destStorageKey = (Get-AzureStorageKey -StorageAccountName $DestStorageAccountName).Primary
$sourceContext = New-AzureStorageContext –StorageAccountName $sourceStorageAccountName -StorageAccountKey $sourceStorageKey -Environment AzureChinaCloud
$destContext = New-AzureStorageContext –StorageAccountName $DestStorageAccountName -StorageAccountKey $destStorageKey
# Create a container of vhds if it doesn't exist
if ((Get-AzureStorageContainer -Context $destContext -Name vhds -ErrorAction SilentlyContinue) -eq $null)
{
Write-Host "Creating a container vhds in the destination storage account." -ForegroundColor Green
New-AzureStorageContainer -Context $destContext -Name vhds
}
$allDisks = @($sourceOSDisk) + $sourceDataDisks
$destDataDisks = @()
# Copy all data disk vhds
# Start all async copy requests in parallel.
foreach($disk in $allDisks)
{
$blobName = $disk.MediaLink.Segments[2]
# copy all data disks
Write-Host "Starting copying data disk $($disk.DiskName) at $(get-date)." -ForegroundColor Green
$sourceBlob = "https://" + $disk.MediaLink.Host + "/vhds/"
$targetBlob = $destStorageAccount.Endpoints[0] + "vhds/"
$azcopylog = "azcopy-" + $SourceCloudServiceName + "-" + $SourceVMName +".log"
Write-Host "Start copy vhd to destination storage account" -ForegroundColor Green
Write-Host .\Tools\AzCopy.exe /Source:$sourceBlob /Dest:$targetBlob /SourceKey:$sourceStorageKey /DestKey:$destStorageKey /Pattern:$blobName /SyncCopy /v:$azcopylog -ForegroundColor Green
.\Tools\AzCopy.exe /Source:$sourceBlob /Dest:$targetBlob /SourceKey:$sourceStorageKey /DestKey:$destStorageKey /Pattern:$blobName /SyncCopy /v:$azcopylog
if ($disk –eq $sourceOSDisk)
{
$destOSDisk = $targetBlob + $blobName
}
else
{
$destDataDisks += $targetBlob + $blobName
}
}
# Create OS and data disks
Write-Host "Add VM OS Disk " $destOSDisk.MediaLink -ForegroundColor Green
Add-AzureDisk -OS $sourceOSDisk.OS -DiskName $sourceOSDisk.DiskName -MediaLocation $destOSDisk
# Attached the copied data disks to the new VM
foreach($currenDataDisk in $destDataDisks)
{
$diskName = ($sourceDataDisks | ? {$currenDataDisk.EndsWith($_.MediaLink.Segments[2])}).DiskName
Write-Host "Add VM Data Disk $diskName" -ForegroundColor Green
Add-AzureDisk -DiskName $diskName -MediaLocation $currenDataDisk
}
Write-Host "Import VM from " $vmConfigurationPath -ForegroundColor Green
Set-AzureSubscription -SubscriptionName $DestSubscritpionName -CurrentStorageAccountName $DestStorageAccountName
# Import VM from previous exported configuration plus vnet info
if (( Get-AzureService | Where { $_.ServiceName -eq $DestCloudServiceName } ).Count -eq 0 )
{
New-AzureService -ServiceName $DestCloudServiceName -Location $DestLocationName
}
Import-AzureVM -Path $vmConfigurationPath | New-AzureVM -ServiceName $DestCloudServiceName -VNetName $DestVNetName -WaitForBoot
| blrchen/AzureAutomationScripts | Migrate-AzureVM/Migrate-AzureVM.ps1 | PowerShell | mit | 9,037 |
# Simulate processes of analysis, sandbox and VM software that some malware will try to evade.
# This just spawns ping.exe with different names (wireshark.exe, vboxtray.exe, ...)
#
# This is the updated version with no system load at all. I might also add some more fake processes in future updates.
# Maintained by Phoenix1747, get updates and fixes on https://github.com/phoenix1747/fake-sandbox/
#
# Usage (CMD): Powershell -executionpolicy remotesigned -F "C:\Full\Path\To\File\fsp.ps1"
$action = read-host " What do you want to do? (start/stop)"
# Your processes come here:
$fakeProcesses = @('WinDbg.exe','idaq.exe','wireshark.exe','vmacthlp.exe','VBoxService.exe','VBoxTray.exe','procmon.exe','ollydbg.exe','vmware-tray.exe','idag.exe','ImmunityDebugger.exe')
# If you type in "start" it will run this:
if ($action -ceq "start") {
# We will store our renamed binaries into a temp folder
$tmpdir = [System.Guid]::NewGuid().ToString()
$binloc = Join-path $env:temp $tmpdir
# Creating temp folder
New-Item -Type Directory -Path $binloc
$oldpwd = $pwd
Set-Location $binloc
foreach ($proc in $fakeProcesses) {
# Copy ping.exe and rename binary to fake one
Copy-Item c:\windows\system32\ping.exe "$binloc\$proc"
# Start infinite ping process (invalid ip) that pings every 3600000 ms (1 hour)
Start-Process ".\$proc" -WindowStyle Hidden -ArgumentList "-t -w 3600000 -4 1.1.1.1"
write-host "[+] Spawned $proc"
}
Set-Location $oldpwd
write-host ""
write-host "Press any key to close..."
cmd /c pause | out-null
}
# If you type in "stop" it will run this:
elseif ($action -ceq "stop") {
write-host ""
foreach ($proc in $fakeProcesses) {
Stop-Process -processname "$proc".Split(".")[0]
write-host "[+] Killed $proc"
}
write-host ""
write-host "Press any key to close..."
cmd /c pause | out-null
}
# Else print this:
else {
write-host ""
write-host "Bad usage: You need to use either 'start' or 'stop' for this to work!" -foregroundcolor Red
write-host "Press any key to close..."
cmd /c pause | out-null
}
| Aperture-Diversion/fake-sandbox | fsp.ps1 | PowerShell | mit | 2,128 |
properties {
$base_dir = resolve-path .
$parent_dir = resolve-path ..
$build_dir = "$base_dir\_build"
$tools_dir = "$parent_dir\tools"
$sln_file = "$base_dir\ServiceLogs.sln"
$run_tests = $false
$msbuild = "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe"
}
Framework "4.0"
task default -depends Package
task Clean {
remove-item -force -recurse $build_dir -ErrorAction SilentlyContinue
}
task Init -depends Clean {
new-item $build_dir -itemType directory
}
task Compile -depends Init {
& $msbuild $sln_file /target:Rebuild /p:"OutDir=$build_dir\3.5;Configuration=Release;TargetFrameworkVersion=v3.5" /m
& $msbuild $sln_file /target:Rebuild /p:"OutDir=$build_dir\4.0;Configuration=Release;TargetFrameworkVersion=v4.0" /m
& $msbuild $sln_file /target:Rebuild /p:"OutDir=$build_dir\4.5;Configuration=Release;TargetFrameworkVersion=v4.5;TargetFrameworkProfile=" /m
& $msbuild $sln_file /target:Rebuild /p:"OutDir=$build_dir\4.6.1;Configuration=Release;TargetFrameworkVersion=v4.6.1;TargetFrameworkProfile=" /m
}
task Test -depends Compile -precondition { return $run_tests } {
}
task Dependency -precondition { return $true } {
$package_files = @(Get-ChildItem $base_dir -include *packages.config -recurse)
foreach ($package in $package_files)
{
& $tools_dir\NuGet.exe install $package.FullName -o packages
}
}
task Package -depends Dependency, Compile, Test {
$spec_files = @(Get-ChildItem $base_dir -include *.nuspec -recurse)
foreach ($spec in $spec_files)
{
& $tools_dir\NuGet.exe pack $spec.FullName -o $build_dir -Symbols -BasePath $base_dir
}
& $tools_dir\NuGet.exe locals all -clear
}
task Push -depends Package {
$spec_files = @(Get-ChildItem $build_dir -include *.nupkg -recurse)
foreach ($spec in $spec_files)
{
& $tools_dir\NuGet.exe push $spec.FullName -source "https://www.nuget.org"
}
}
| BclEx/System.Abstract | src.servicelogs/default.ps1 | PowerShell | mit | 1,950 |
#Create test AD accounts for lab/testing purposes
#
#preset variables for the script:
#
$date = Get-date -format M.d.yyyy
$ou="OU=LANDING,DC=DEFAULTDOMAIN,DC=COM"
$principlename = "@DEFAULT.com"
$description = "Test Account Generate $date"
$Number_of_users = "5000"
$company = "Test Company"
#Supported Nationalities: AU, BR, CA, CH, DE, DK, ES, FI, FR, GB, IE, IR, NL, NZ, TR, US
#Comma seperated values for multiple ie:
#$nationalities ="US,DK,FR"
$nationalities ="US"
#
#end of preset variables for script:
#
function find_ad_id($first,$last) {
$first = $first -Replace "\s*"
$last = $last -Replace "\s*"
$not_found = $true
for($i = 1; $i -le $first.length; $i++) {
$Sam_account =""
$letters_first = ""
for($l = 0; $l -ne $i; $l++){
$letters_first += $first[$l]
}
$sam_account = $letters_first+$last
if(-not (Get-aduser -Filter {SamaccountName -eq $sam_account})) {
$not_found = $false
return $sam_account
}
}
if($not_found -eq $true) {
return "ERROR:FAIL"
}
}
function generate() {
$character = @("!","$","%","^","&","*","(",")","?")
$letters_low=@("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
$letters_cap=@("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z")
$numbers=@("1","2","3","4","5","6","7","8","9","0")
$itterations = get-random -minimum 8 -maximum 10
[string]$pass_value = ""
for($i = 0; $i -ne $itterations+1;$i++) {
$character_type = Get-random -minimum 1 -maximum 9
switch ($character_type) {
1 { $letter = Get-random -minimum 0 -maximum 26
$pass_value = $pass_value+$character[$letter]
}
2 { $letter = Get-random -minimum 0 -maximum 26
$pass_value = $pass_value+$letters_low[$letter] }
3 { $letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$letters_low[$letter] }
4 { $letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$letters_cap[$letter] }
5 { $letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$character[$letter] }
6 { $letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$numbers[$letter] }
7 { $letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$letters_cap[$letter] }
8 { $letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$letters_cap[$letter]}
}
$letter = Get-random -minimum 0 -maximum 26
$pass_value = $pass_value+$character[$letter]
$letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$letters_cap[$letter]
$letter = Get-random -minimum 0 -maximum 11
$pass_value = $pass_value+$numbers[$letter]
}
return $pass_value
}
echo "Status,Date,SamAccountName,Password,FirstName,LastName,DisplayName,City,Phone" >> create_output.csv
$user_data_json_list = invoke-restmethod "https://www.randomuser.me/api/?results=$Number_of_users&nat=$nationalities" | select -expandproperty results
foreach($user_data_json in $user_data_json_list) {
$aduser_Given = $user_data_json.name.first
$aduser_Surname = $user_data_json.name.last
$aduser_password = generate
$aduser_display = $user_data_json.name.last + ", " + $user_data_json.name.first
$aduser_phone = $user_data_json.phone
$aduser_city = $user_data_json.location.city
$aduser_samaccountname = find_ad_id $aduser_Given $aduser_Surname
if($aduser_samaccountname -eq "ERROR:FAIL") {
echo "Failure $aduser_Surname sam account in use"
echo "Error Samaccount,""$date"",""$aduser_samaccountname"",""$aduser_password"",""$aduser_Given"",""$aduser_Surname"",""$aduser_display"",""$aduser_city"",""$aduser_phone""" >> create_output.csv
} else {
New-ADUser -AccountPassword (ConvertTo-SecureString “$aduser_password” -AsPlainText -Force) -ChangePasswordAtLogon $false -City $aduser_city -company “$company_name” -DisplayName “$aduser_display” -Enabled $true -MobilePhone “$aduser_phone” -Name “$aduser_display” -SamAccountName $aduser_samaccountname -Path “$ou" -givenname $aduser_Given -surname $aduser_Surname -userprincipalname (“$aduser_samaccountname” + “$principlename”) -description “$description”
clear
Write-Host "`r Generating user: $aduser_Given $aduser_Surname" -NoNewLine
echo "Success,""$date"",""$aduser_samaccountname"",""$aduser_password"",""$aduser_Given"",""$aduser_Surname"",""$aduser_display"",""$aduser_city"",""$aduser_phone""" >> create_output.csv
}
} | schm2055/PowerShell | AD_Generate_TestLab_Accounts.ps1 | PowerShell | cc0-1.0 | 4,755 |
Update-SessionEnvironment
$version = '0.16.1'
python -m pip install mkdocs==$version
| lennartb-/chocolatey-coreteampackages | automatic/mkdocs/tools/ChocolateyInstall.ps1 | PowerShell | apache-2.0 | 90 |
function Add-VSWAFByteMatchSetFieldToMatch {
<#
.SYNOPSIS
Adds an AWS::WAF::ByteMatchSet.FieldToMatch resource property to the template. **Note**
.DESCRIPTION
Adds an AWS::WAF::ByteMatchSet.FieldToMatch resource property to the template.
**Note**
This is **AWS WAF Classic** documentation. For more information, see AWS WAF Classic: https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html in the developer guide.
**For the latest version of AWS WAF**, use the AWS WAFV2 API and see the AWS WAF Developer Guide: https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html. With the latest version, AWS WAF has a single set of endpoints for regional and global use.
Specifies where in a web request to look for TargetString.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html
.PARAMETER Data
When the value of Type is HEADER, enter the name of the header that you want AWS WAF to search, for example, User-Agent or Referer. The name of the header is not case sensitive.
When the value of Type is SINGLE_QUERY_ARG, enter the name of the parameter that you want AWS WAF to search, for example, UserName or SalesRegion. The parameter name is not case sensitive.
If the value of Type is any other value, omit Data.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html#cfn-waf-bytematchset-bytematchtuples-fieldtomatch-data
PrimitiveType: String
UpdateType: Mutable
.PARAMETER Type
The part of the web request that you want AWS WAF to search for a specified string. Parts of a request that you can search include the following:
+ HEADER: A specified request header, for example, the value of the User-Agent or Referer header. If you choose HEADER for the type, specify the name of the header in Data.
+ METHOD: The HTTP method, which indicated the type of operation that the request is asking the origin to perform. Amazon CloudFront supports the following methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, and PUT.
+ QUERY_STRING: A query string, which is the part of a URL that appears after a ? character, if any.
+ URI: The part of a web request that identifies a resource, for example, /images/daily-ad.jpg.
+ BODY: The part of a request that contains any additional data that you want to send to your web server as the HTTP request body, such as data from a form. The request body immediately follows the request headers. Note that only the first 8192 bytes of the request body are forwarded to AWS WAF for inspection. To allow or block requests based on the length of the body, you can create a size constraint set.
+ SINGLE_QUERY_ARG: The parameter in the query string that you will inspect, such as *UserName* or *SalesRegion*. The maximum length for SINGLE_QUERY_ARG is 30 characters.
+ ALL_QUERY_ARGS: Similar to SINGLE_QUERY_ARG, but rather than inspecting a single parameter, AWS WAF will inspect all parameters within the query for the value or regex pattern that you specify in TargetString.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html#cfn-waf-bytematchset-bytematchtuples-fieldtomatch-type
PrimitiveType: String
UpdateType: Mutable
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.WAF.ByteMatchSet.FieldToMatch')]
[cmdletbinding()]
Param
(
[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 ", ")."))
}
})]
$Data,
[parameter(Mandatory = $true)]
[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 ", ")."))
}
})]
$Type
)
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.WAF.ByteMatchSet.FieldToMatch'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSWAFByteMatchSetFieldToMatch.ps1 | PowerShell | apache-2.0 | 5,670 |
<#
.SYNOPSIS
Tests DataLakeStore Account trusted identity provider Lifecycle (Create, Update, Get, List, Delete).
#>
function Test-DataLakeStoreTrustedIdProvider
{
param
(
$location = "West US"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
# Test to make sure the account doesn't exist
Assert-False {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
# Test it without specifying a resource group
Assert-False {Test-AzureRMDataLakeStoreAccount -Name $accountName}
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location -Encryption ServiceManaged
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
# In loop to check if account exists
for ($i = 0; $i -le 60; $i++)
{
[array]$accountGet = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName
if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
{
Assert-AreEqual $accountName $accountGet[0].Name
Assert-AreEqual $location $accountGet[0].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
break
}
Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
}
# Test to make sure the account does exist
Assert-True {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
$trustedIdName = getAssetName
$trustedIdEndpoint = "https://sts.windows.net/6b04908c-b91f-40ce-8024-7ee8a4fd6150"
# Add a provider
Add-AzureRmDataLakeStoreTrustedIdProvider -AccountName $accountName -Name $trustedIdName -ProviderEndpoint $trustedIdEndpoint
# Get the provider
$result = Get-AzureRmDataLakeStoreTrustedIdProvider -AccountName $accountName -Name $trustedIdName
Assert-AreEqual $trustedIdName $result.Name
Assert-AreEqual $trustedIdEndpoint $result.IdProvider
# remove the provider
Remove-AzureRmDataLakeStoreTrustedIdProvider -AccountName $accountName -Name $trustedIdName
# Make sure get throws.
Assert-Throws {Get-AzureRmDataLakeStoreTrustedIdProvider -AccountName $accountName -Name $trustedIdName}
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
}
<#
.SYNOPSIS
Tests DataLakeStore Account firewall rules Lifecycle (Create, Update, Get, List, Delete).
#>
function Test-DataLakeStoreFirewall
{
param
(
$location = "West US"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
# Test to make sure the account doesn't exist
Assert-False {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
# Test it without specifying a resource group
Assert-False {Test-AzureRMDataLakeStoreAccount -Name $accountName}
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location -Encryption ServiceManaged
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
# In loop to check if account exists
for ($i = 0; $i -le 60; $i++)
{
[array]$accountGet = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName
if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
{
Assert-AreEqual $accountName $accountGet[0].Name
Assert-AreEqual $location $accountGet[0].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
break
}
Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
}
# Test to make sure the account does exist
Assert-True {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
$firewallRuleName = getAssetName
$startIp = "127.0.0.1"
$endIp = "127.0.0.2"
# Add a firewall rule
Add-AzureRmDataLakeStoreFirewallRule -AccountName $accountName -Name $firewallRuleName -StartIpAddress $startIp -EndIpAddress $endIp
# Get the firewall rule
$result = Get-AzureRmDataLakeStoreFirewallRule -AccountName $accountName -Name $firewallRuleName
Assert-AreEqual $firewallRuleName $result.Name
Assert-AreEqual $startIp $result.StartIpAddress
Assert-AreEqual $endIp $result.EndIpAddress
# remove the firewall rule
Remove-AzureRmDataLakeStoreFirewallRule -AccountName $accountName -Name $firewallRuleName
# Make sure get throws.
Assert-Throws {Get-AzureRmDataLakeStoreFirewallRule -AccountName $accountName -Name $firewallRuleName}
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
}
<#
.SYNOPSIS
Tests DataLakeStore Account Commitment tiers (in Create and Update).
#>
function Test-DataLakeStoreAccountTiers
{
param
(
$location = "West US"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
$secondAccountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
# Test to make sure the account doesn't exist
Assert-False {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
# Test it without specifying a resource group
Assert-False {Test-AzureRMDataLakeStoreAccount -Name $accountName}
# Test 1: create without a tier specified verify that it defaults to "consumption"
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
Assert-AreEqual "Consumption" $accountCreated.CurrentTier
Assert-AreEqual "Consumption" $accountCreated.NewTier
# Test 2: update this account to use a different tier
$accountUpdated = Set-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Tier Commitment1TB
Assert-AreEqual "Consumption" $accountUpdated.CurrentTier
Assert-AreEqual "Commitment1TB" $accountUpdated.NewTier
# Test 3: create a new account with a specific tier.
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $secondAccountName -Location $location -Tier Commitment1TB
Assert-AreEqual "Commitment1TB" $accountCreated.CurrentTier
Assert-AreEqual "Commitment1TB" $accountCreated.NewTier
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $secondAccountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
}
<#
.SYNOPSIS
Tests DataLakeStore Account Lifecycle (Create, Update, Get, List, Delete).
#>
function Test-DataLakeStoreAccount
{
param
(
$location = "West US"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
# Test to make sure the account doesn't exist
Assert-False {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
# Test it without specifying a resource group
Assert-False {Test-AzureRMDataLakeStoreAccount -Name $accountName}
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location -Encryption ServiceManaged
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
# In loop to check if account exists
for ($i = 0; $i -le 60; $i++)
{
[array]$accountGet = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName
if ($accountGet[0].ProvisioningState -like "Succeeded")
{
Assert-AreEqual $accountName $accountGet[0].Name
Assert-AreEqual $location $accountGet[0].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
Assert-True {$accountGet[0].Identity -ne $null}
Assert-True {$accountGet[0].EncryptionConfig -ne $null}
break
}
Write-Host "account not yet provisioned. current state: $($accountGet[0].ProvisioningState)"
[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
}
# Test to make sure the account does exist
Assert-True {Test-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
# Test it without specifying a resource group
Assert-True {Test-AzureRMDataLakeStoreAccount -Name $accountName}
# Updating Account
$tagsToUpdate = @{"TestTag" = "TestUpdate"}
$accountUpdated = Set-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Tags $tagsToUpdate
Assert-AreEqual $accountName $accountUpdated.Name
Assert-AreEqual $location $accountUpdated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountUpdated.Type
Assert-True {$accountUpdated.Id -like "*$resourceGroupName*"}
Assert-NotNull $accountUpdated.Tags "Tags do not exists"
Assert-NotNull $accountUpdated.Tags["TestTag"] "The updated tag 'TestTag' does not exist"
# List all accounts in resource group
[array]$accountsInResourceGroup = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName
Assert-True {$accountsInResourceGroup.Count -ge 1}
$found = 0
for ($i = 0; $i -lt $accountsInResourceGroup.Count; $i++)
{
if ($accountsInResourceGroup[$i].Name -eq $accountName)
{
$found = 1
Assert-AreEqual $location $accountsInResourceGroup[$i].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountsInResourceGroup[$i].Type
Assert-True {$accountsInResourceGroup[$i].Id -like "*$resourceGroupName*"}
break
}
}
Assert-True {$found -eq 1} "Account created earlier is not found when listing all in resource group: $resourceGroupName."
# List all Data Lake accounts in subscription
[array]$accountsInSubscription = Get-AzureRMDataLakeStoreAccount
Assert-True {$accountsInSubscription.Count -ge 1}
Assert-True {$accountsInSubscription.Count -ge $accountsInResourceGroup.Count}
$found = 0
for ($i = 0; $i -lt $accountsInSubscription.Count; $i++)
{
if ($accountsInSubscription[$i].Name -eq $accountName)
{
$found = 1
Assert-AreEqual $location $accountsInSubscription[$i].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountsInSubscription[$i].Type
Assert-True {$accountsInSubscription[$i].Id -like "*$resourceGroupName*"}
break
}
}
Assert-True {$found -eq 1} "Account created earlier is not found when listing all in subscription."
# Test creation of a new account without specifying encryption and ensure it is still ServiceManaged.
$secondAccountName = Get-DataLakeStoreAccountName
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $secondAccountName -Location $location
Assert-True {$accountCreated.EncryptionConfig -ne $null}
Assert-AreEqual "ServiceManaged" $accountCreated.EncryptionConfig.Type
# Create an account with no encryption explicitly.
$thirdAccountName = Get-DataLakeStoreAccountName
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $thirdAccountName -Location $location -DisableEncryption
Assert-True {[string]::IsNullOrEmpty(($accountCreated.EncryptionConfig.Type))}
Assert-AreEqual "Disabled" $accountCreated.EncryptionState
# Delete Data Lake account
Assert-True {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."
# Verify that it is gone by trying to get it again
Assert-Throws {Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $secondAccountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $thirdAccountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
}
<#
.SYNOPSIS
Tests DataLakeStore filesystem operations (Create, append, get, delete, read, etc.).
#>
function Test-DataLakeStoreFileSystem
{
param
(
$fileToCopy,
$location = "West US"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
# In loop to check if account exists
for ($i = 0; $i -le 60; $i++)
{
[array]$accountGet = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName
if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
{
Assert-AreEqual $accountName $accountGet[0].Name
Assert-AreEqual $location $accountGet[0].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
break
}
Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
}
# define all the files and folders to create
$folderToCreate = "/adlspstestfolder"
$emptyFilePath = "$folderToCreate\emptyfile.txt" # have one where the slash is in the wrong direction to make sure they get fixed.
$contentFilePath = "$folderToCreate/contentfile.txt"
$concatFile = "$folderToCreate/concatfile.txt"
$moveFile = "$folderToCreate/movefile.txt"
$movefolder = "/adlspstestmovefolder"
$importFile = "$folderToCreate/importfile.txt"
$content = "Test file content! @ Azure PsTest01?"
# Create and get Empty folder
$result = New-AzureRMDataLakeStoreItem -Account $accountName -path $folderToCreate -Folder
Assert-NotNull $result "No value was returned on folder creation"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $folderToCreate
Assert-NotNull $result "No value was returned on folder get"
Assert-AreEqual "Directory" $result.Type
# Create and get Empty File
$result = New-AzureRMDataLakeStoreItem -Account $accountName -path $emptyFilePath
Assert-NotNull $result "No value was returned on empty file creation"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $emptyFilePath
Assert-NotNull $result "No value was returned on empty file get"
Assert-AreEqual "File" $result.Type
Assert-AreEqual 0 $result.Length
# Create and get file with content
$result = New-AzureRMDataLakeStoreItem -Account $accountName -path $contentFilePath -Value $content
Assert-NotNull $result "No value was returned on content file creation"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $contentFilePath
Assert-NotNull $result "No value was returned on content file get"
Assert-AreEqual "File" $result.Type
Assert-AreEqual $content.length $result.Length
# set and validate expiration for a file
Assert-True {253402300800000 -ge $result.ExpirationTime -or 0 -le $result.ExpirationTime} # validate that expiration is currently max value
[DateTimeOffset]$timeToUse = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::GetVariable("absoluteTime", [DateTimeOffset]::UtcNow.AddSeconds(120))
$result = Set-AzureRmDataLakeStoreItemExpiry -Account $accountName -path $contentFilePath -Expiration $timeToUse
Assert-AreEqual $timeToUse.UtcTicks $result.Expiration.UtcTicks
# set it back to "never expire"
$result = Set-AzureRmDataLakeStoreItemExpiry -Account $accountName -path $contentFilePath
Assert-True {253402300800000 -ge $result.ExpirationTime -or 0 -le $result.ExpirationTime} # validate that expiration is currently max value
# list files
$result = Get-AzureRMDataLakeStoreChildItem -Account $accountName -path $folderToCreate
Assert-NotNull $result "No value was returned on folder list"
Assert-AreEqual 2 $result.length
# add content to empty file
Add-AzureRMDataLakeStoreItemContent -Account $accountName -Path $emptyFilePath -Value $content
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $emptyFilePath
Assert-NotNull $result "No value was returned on empty file get with content added"
Assert-AreEqual "File" $result.Type
Assert-AreEqual $content.length $result.Length
# concat files
$result = Join-AzureRMDataLakeStoreItem -Account $accountName -Paths $emptyFilePath,$contentFilePath -Destination $concatFile
Assert-NotNull $result "No value was returned on concat file"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $concatFile
Assert-NotNull $result "No value was returned on concat file get"
Assert-AreEqual "File" $result.Type
Assert-AreEqual $($content.length*2) $result.Length
# Preview content from the file
$previewContent = Get-AzureRMDataLakeStoreItemContent -Account $accountName -Path $concatFile
Assert-AreEqual $($content.length*2) $previewContent.Length
# Preview a subset of the content
$previewContent = Get-AzureRMDataLakeStoreItemContent -Account $accountName -Path $concatFile -Offset 2
Assert-AreEqual $(($content.length*2) - 2) $previewContent.Length
# Preview a subset with a specific length
$previewContent = Get-AzureRMDataLakeStoreItemContent -Account $accountName -Path $concatFile -Offset 2 -Length $content.Length
Assert-AreEqual $content.length $previewContent.Length
# Import and get file
$localFileInfo = Get-ChildItem $fileToCopy
$result = Import-AzureRMDataLakeStoreItem -Account $accountName -Path $fileToCopy -Destination $importFile
Assert-NotNull $result "No value was returned on import file"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $importFile
Assert-NotNull $result "No value was returned on import file get"
Assert-AreEqual "File" $result.Type
Assert-AreEqual $localFileInfo.length $result.Length
# download file
$currentDir = Split-Path $fileToCopy
$targetFile = Join-Path $currentDir "adlspstestdownload.txt"
if(Test-Path $targetFile)
{
Remove-Item -path $targetFile -force -confirm:$false
}
Export-AzureRMDataLakeStoreItem -Account $accountName -Path $concatFile -Destination $targetFile
$downloadedFileInfo = Get-ChildItem $targetFile
Assert-AreEqual $($content.length*2) $downloadedFileInfo.length
Remove-Item -path $targetFile -force -confirm:$false
# move a file
$result = Move-AzureRMDataLakeStoreItem -Account $accountName -Path $concatFile -Destination $moveFile
Assert-NotNull $result "No value was returned on move file"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $moveFile
Assert-NotNull $result "No value was returned on move file get"
Assert-AreEqual "File" $result.Type
Assert-AreEqual $($content.length*2) $result.Length
Assert-Throws {Get-AzureRMDataLakeStoreItem -Account $accountName -path $concatFile}
# move a folder
$result = Move-AzureRMDataLakeStoreItem -Account $accountName -Path $folderToCreate -Destination $moveFolder
Assert-NotNull $result "No value was returned on move folder"
$result = Get-AzureRMDataLakeStoreItem -Account $accountName -path $moveFolder
Assert-NotNull $result "No value was returned on move folder get"
Assert-AreEqual "Directory" $result.Type
Assert-AreEqual 0 $result.Length
Assert-Throws {Get-AzureRMDataLakeStoreItem -Account $accountName -path $folderToCreate}
# delete a file
Assert-True {Remove-AzureRMDataLakeStoreItem -Account $accountName -paths "$moveFolder/movefile.txt" -force -passthru } "Remove File Failed"
Assert-Throws {Get-AzureRMDataLakeStoreItem -Account $accountName -path $moveFile}
# delete a folder
Assert-True {Remove-AzureRMDataLakeStoreItem -Account $accountName -paths $moveFolder -force -recurse -passthru} "Remove folder failed"
Assert-Throws {Get-AzureRMDataLakeStoreItem -Account $accountName -path $moveFolder}
# Delete Data Lake account
Assert-True {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."
# Verify that it is gone by trying to get it again
Assert-Throws {Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
}
<#
.SYNOPSIS
Tests DataLakeStore filesystem permissions operations (Create, Update, Get, List, Delete).
#>
function Test-DataLakeStoreFileSystemPermissions
{
param
(
$location = "West US"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
# In loop to check if account exists
for ($i = 0; $i -le 60; $i++)
{
[array]$accountGet = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName
if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
{
Assert-AreEqual $accountName $accountGet[0].Name
Assert-AreEqual $location $accountGet[0].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
break
}
Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
Assert-False {$i -eq 60} " Data Lake Store account is not in succeeded state even after 30 min."
}
# define the permissions to add/remove
$aceUserId = "027c28d5-c91d-49f0-98c5-d10134b169b3"
# Set and get all the permissions
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-NotNull $result "Did not get any result from ACL get"
Assert-True {$result.Count -ge 0} "UserAces is negative or null"
$currentCount = $result.Count
$result.Add("user:$aceUserId`:rwx")
$toRemove = $result[$result.Count -1]
Assert-AreEqual $aceUserId $toRemove.Id
Set-AzureRMDataLakeStoreItemAcl -Account $accountName -path "/" -Acl $result
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
# it is +2 because the mask gets computed when the first user is added.
Assert-AreEqual $($currentCount+2) $result.Count
$found = $false
for($i = 0; $i -lt $result.Count; $i++)
{
if($result[$i].Id -like $aceUserId)
{
$found = $true
$result.RemoveAt($i)
break
}
}
Assert-True { $found } "Failed to remove the element: $($toRemove.Entry)"
# remove the account
Set-AzureRMDataLakeStoreItemAcl -Account $accountName -path "/" -Acl $result
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
# mask does not get removed when removing the user
Assert-AreEqual $($currentCount+1) $result.Count
# Set and get a specific permission with friendly sets
Set-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/" -AceType User -Id $aceUserId -Permissions All
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-AreEqual $($currentCount+2) $result.Count
# remove a specific permission with friendly remove
Remove-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/" -AceType User -Id $aceUserId
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-AreEqual $($currentCount+1) $result.Count
# set and get a specific permission with the ACE string
Set-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/" -Acl $([string]::Format("user:{0}:rwx", $aceUserId))
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-AreEqual $($currentCount+2) $result.Count
# remove a specific permission with the ACE string
Remove-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/" -Acl $([string]::Format("user:{0}:---", $aceUserId))
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-AreEqual $($currentCount+1) $result.Count
# Validate full ACL removal
Remove-AzureRMDataLakeStoreItemAcl -Account $accountName -Path "/" -Force -Default
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-AreEqual 4 $result.Count
Remove-AzureRMDataLakeStoreItemAcl -Account $accountName -Path "/" -Force
$result = Get-AzureRMDataLakeStoreItemAclEntry -Account $accountName -path "/"
Assert-AreEqual 3 $result.Count
# validate permissions
$permission = Get-AzureRMDataLakeStoreItemPermission -Account $accountName -path "/"
Assert-AreEqual 770 $permission
Set-AzureRMDataLakeStoreItemPermission -Account $accountName -path "/" -Permission 777 | Out-Null
$permission = Get-AzureRMDataLakeStoreItemPermission -Account $accountName -path "/"
Assert-AreEqual 777 $permission
# Delete Data Lake account
Assert-True {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."
# Verify that it is gone by trying to get it again
Assert-Throws {Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
}
<#
.SYNOPSIS
Tests DataLakeStore Account Lifecycle Failure scenarios (Create, Update, Get, Delete).
#>
function Test-NegativeDataLakeStoreAccount
{
param
(
$location = "West US",
$fakeaccountName = "psfakedataLakeaccounttest"
)
try
{
# Creating Account
$resourceGroupName = Get-ResourceGroupName
$accountName = Get-DataLakeStoreAccountName
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location
$accountCreated = New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location
Assert-AreEqual $accountName $accountCreated.Name
Assert-AreEqual $location $accountCreated.Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountCreated.Type
Assert-True {$accountCreated.Id -like "*$resourceGroupName*"}
# In loop to check if account exists
for ($i = 0; $i -le 60; $i++)
{
[array]$accountGet = Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName
if ($accountGet[0].Properties.ProvisioningState -like "Succeeded")
{
Assert-AreEqual $accountName $accountGet[0].Name
Assert-AreEqual $location $accountGet[0].Location
Assert-AreEqual "Microsoft.DataLakeStore/accounts" $accountGet[0].Type
Assert-True {$accountGet[0].Id -like "*$resourceGroupName*"}
break
}
Write-Host "account not yet provisioned. current state: $($accountGet[0].Properties.ProvisioningState)"
[Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport]::Delay(30000)
Assert-False {$i -eq 60} " Data Lake Store account not in succeeded state even after 30 min."
}
# attempt to recreate the already created account
Assert-Throws {New-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Location $location}
# attempt to update a non-existent account
$tagsToUpdate = @{"TestTag" = "TestUpdate"}
Assert-Throws {Set-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $fakeaccountName -Tags $tagsToUpdate}
# attempt to get a non-existent account
Assert-Throws {Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $fakeaccountName}
# Delete Data Lake account
Assert-True {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru} "Remove Account failed."
# Delete Data Lake account again should throw.
Assert-Throws {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -PassThru}
# Verify that it is gone by trying to get it again
Assert-Throws {Get-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName}
}
finally
{
# cleanup the resource group that was used in case it still exists. This is a best effort task, we ignore failures here.
Invoke-HandledCmdlet -Command {Remove-AzureRMDataLakeStoreAccount -ResourceGroupName $resourceGroupName -Name $accountName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
Invoke-HandledCmdlet -Command {Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction SilentlyContinue} -IgnoreFailures
}
} | seanbamsft/azure-powershell | src/ResourceManager/DataLakeStore/Commands.DataLakeStore.Test/ScenarioTests/AdlsTests.ps1 | PowerShell | apache-2.0 | 33,403 |
function Add-VSAppMeshRouteTcpRoute {
<#
.SYNOPSIS
Adds an AWS::AppMesh::Route.TcpRoute resource property to the template. An object that represents a TCP route type.
.DESCRIPTION
Adds an AWS::AppMesh::Route.TcpRoute resource property to the template.
An object that represents a TCP route type.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appmesh-route-tcproute.html
.PARAMETER Action
The action to take if a match is determined.
Type: TcpRouteAction
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appmesh-route-tcproute.html#cfn-appmesh-route-tcproute-action
UpdateType: Mutable
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.AppMesh.Route.TcpRoute')]
[cmdletbinding()]
Param
(
[parameter(Mandatory = $true)]
$Action
)
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.AppMesh.Route.TcpRoute'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSAppMeshRouteTcpRoute.ps1 | PowerShell | apache-2.0 | 1,739 |
Import-Module "$PSScriptRoot\..\..\Publish\PSPlus\PSPlus.psd1" -Force
Describe "Windows.Diagnostics.ProcessControl" {
Context "When trying to do process related operations" {
It "Should be able to check if other process is 64 bits." {
$notepadNativePath = "$env:WINDIR\system32\notepad.exe"
if ((Test-Is64BitsOS) -and (Test-Is32BitsPowershell)) {
$notepadNativePath = "$env:WINDIR\sysnative\notepad.exe"
}
$notepad = Start-Process $notepadNativePath -PassThru
$is32BitsProcess = Test-Is32BitsProcess $notepad
$is64BitsProcess = Test-Is64BitsProcess $notepad
$is32BitsProcess -xor $is64BitsProcess | Should Be $true
if (Test-Is32BitsOS) {
$is64BitsProcess | Should Be $false
} else {
$is64BitsProcess | Should Be $true
}
$notepad.Kill()
}
It "Should be able to get the process command line in the same arch" {
$testProgram = "$env:WINDIR\system32\cmd.exe"
$testArguments = "/?"
$testProcess = Start-Process $testProgram -ArgumentList $testArguments -PassThru
Get-ProcessCommandLine $testProcess | Should Be """C:\WINDOWS\system32\cmd.exe"" /? "
$testProcess.Kill()
$testProcess.Close()
}
It "Should be able to get the process command line of wow64 process." {
if (-not (Test-Is64BitsOS)) {
return
}
$testProgram = "$env:WINDIR\SysWOW64\cmd.exe"
$testArguments = "/?"
$testProcess = Start-Process $testProgram -ArgumentList $testArguments -PassThru
Get-ProcessCommandLine $testProcess | Should Be """C:\WINDOWS\SysWOW64\cmd.exe"" /? "
$testProcess.Kill()
$testProcess.Close()
}
It "Should be unable to get the process command line of amd64 process from x86 process." {
if (-not (Test-Is64BitsOS)) {
return
}
if (-not (Test-Is32BitsPowershell)) {
return
}
$testProgram = "$env:WINDIR\sysnative\cmd.exe"
$testArguments = "/?"
$testProcess = Start-Process $testProgram -ArgumentList $testArguments -PassThru
$exceptionThrown = $false
try
{
Get-ProcessCommandLine $testProcess
}
catch
{
$exceptionThrown = $true
}
$exceptionThrown | Should Be $true
$testProcess.Kill()
$testProcess.Close()
}
}
} | r12f/PSPlus | PSPlus.Tests/Windows/PSPlus.Modules.Windows.Diagnostics.ProcessControl.tests.ps1 | PowerShell | bsd-2-clause | 2,713 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.