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 |
|---|---|---|---|---|---|
$networkDomainName = "Test API network"
$location = "NASH_PCS01_N2_VMWARE_1"
$osImageName = "RedHat 6 64-bit 2 CPU"
$administratorPassword= "password123"
$vlanName = "testV1"
#import Caas Module
Import-Module CaaS
#capture the Caas credentials and create a new Caas conneciton
$login = Get-Credential
New-CaasConnection -ApiCredentials $login -Region NorthAmerica_NA
#Get the network with a specific name
$networkDomain = Get-CaasNetworkDomain -NetworkDomainName $networkDomainName
#Get a OS image with a specific name
$os=Get-CaasOsImages -Location $location -Name $osImageName
#create a new server details configuration
$vlan = get-CaasVlan -Name $vlanName -NetworkDomain $networkDomain
new-CaasServerOnNetworkDomain -Name "MyTestServer" -Description "Server Created using PS" -NetworkDomain $networkDomain -ServerImage $os -IsStarted $True -AdminPassword $administratorPassword -PrimaryNetwork $vlan
| DimensionDataCBUSydney/DimensionData.ComputeClient | PowerShell Examples/Mcp2DeployServer.ps1 | PowerShell | mit | 914 |
<#
Sample DSC Configuration for a DNS/DHCP Server
DNS is configured to house addresses for a server pool and a sql server
DHCP is configured for reservations to the server pool
Script was tested in a DSC push configuration.
Tested using Server 2012 R2 DC Core running PowerShell v4.
Server is not joined to a domain.
Test Server has two virtual network interfaces with one configured as "TestInt".
Before testing, please run the following on the test server:
winrm qc
winrm s winrm/config/client '@{TrustedHosts="*"}'
Also be sure to download the DSC Resource kit at:
https://github.com/PowerShell/xPSDesiredStateConfiguration
and install it at $env:programfiles\windowspowershell\modules.
Also, be sure to have KB2883200 installed.
DNS Record entries are created using Round Robin rotation.
Network Config:
Network ID: 192.168.0.0
Broadcast: 192.168.0.15
Gateway: 192.168.0.1
SubMask: 28
DNS Config:
Zone Name: internal.contoso.org
Web Pool A Record: webpool1
Host Name IP Address Role MAC Address
------------------------------------------------------------
TestNode 192.168.0.2 DNS/DHCP 07-3D-D3-29-39-32
Web1 192.168.0.3 Web Server FF-CA-2D-36-B6-4A
Web2 192.168.0.4 " 5A-62-17-7D-87-FA
Web3 192.168.0.5 " AE-6B-C3-DE-39-1B
SQL1 192.168.0.6 DB 59-72-C2-C4-76-79
Cache1 192.168.0.7 Cache A2-A1-AC-4D-06-8F
#>
$serverip = "192.168.0.2"
$machinename = "TestNode"
$scopeid = "192.168.0.0"
Configuration TestNodeConfig{
Param(
$Machinename,
$ServerIP,
$ScopeID
)
Import-DscResource -Module xNetworking
Import-DscResource -Module xDHCPServer
node ($Machinename){
LocalConfigurationManager{
RebootNodeIfNeeded = $true
}
xIPAddress ServerIP
{
IPAddress = $ServerIP
InterfaceAlias = "TestInt"
DefaultGateway = "192.168.0.1"
SubnetMask = 28
AddressFamily = "IPv4"
}
xDNSServerAddress ServerDNS
{
Address = $ServerIP
InterfaceAlias = "Ethernet"
AddressFamily = "IPv4"
}
WindowsFeature DHCP
{
Ensure = "Present"
Name = "DHCP"
DependsOn = "[xIPAddress]ServerIP","[xDNSServerAddress]ServerDNS"
}
WindowsFeature DNS
{
Ensure = "Present"
Name = "DNS"
DependsOn = "[xIPAddress]ServerIP","[xDNSServerAddress]ServerDNS"
}
xDhcpServerScope ServerScope
{
IPStartRange = "192.168.0.3"
IPEndRange = "192.168.0.7"
Name = "TestScope1"
SubnetMask = "255.255.255.240"
State = "Active"
Ensure = "Present"
LeaseDuration = "7:00:00"
DependsOn = "[WindowsFeature]DHCP"
}
xDhcpServerOption ServerOpt
{
ScopeID = $ScopeID
DnsServerIPAddress = $ServerIP
DnsDomain = "TestDomain"
AddressFamily = "IPv4"
Ensure = "Present"
DependsOn = "[xDhcpServerScope]ServerScope"
}
xDhcpServerReservation Web1Res
{
ScopeID = $ScopeID
IPAddress = "192.168.0.3"
ClientMACAddress = "FF-CA-2D-36-B6-4A"
Name = "Web1"
AddressFamily = "IPv4"
Ensure = "Present"
DependsOn = "[xDhcpServerScope]ServerScope"
}
xDhcpServerReservation Web2Res
{
ScopeID = $ScopeID
IPAddress = "192.168.0.4"
ClientMACAddress = "5A-62-17-7D-87-FA"
Name = "Web2"
AddressFamily = "IPv4"
Ensure = "Present"
DependsOn = "[xDhcpServerScope]ServerScope"
}
xDhcpServerReservation Web3Res
{
ScopeID = $ScopeID
IPAddress = "192.168.0.5"
ClientMACAddress = "AE-6B-C3-DE-39-1B"
Name = "Web3"
AddressFamily = "IPv4"
Ensure = "Present"
DependsOn = "[xDhcpServerScope]ServerScope"
}
xDhcpServerReservation SQL1Res
{
ScopeID = $ScopeID
IPAddress = "192.168.0.6"
ClientMACAddress = "59-72-C2-C4-76-79"
Name = "SQL1"
AddressFamily = "IPv4"
Ensure = "Present"
DependsOn = "[xDhcpServerScope]ServerScope"
}
xDhcpServerReservation Cache1Res
{
ScopeID = $ScopeID
IPAddress = "192.168.0.7"
ClientMACAddress = "A2-A1-AC-4D-06-8F"
Name = "Cache1"
AddressFamily = "IPv4"
Ensure = "Present"
DependsOn = "[xDhcpServerScope]ServerScope"
}
Script DNSConfig{
SetScript = {
Add-DnsServerPrimaryZone -Name "internal.contoso.org" -ZoneFile "internal.contoso.org.dns"
Add-DnsServerPrimaryZone -NetworkID 192.168.0.0/28 -ZoneFile "0.168.192.in-addr.arpa.dns"
Add-DnsServerForwarder -IPAddress 8.8.8.8 -PassThru
Add-DnsServerForwarder -IPAddress 4.2.2.2 –PassThru
dnscmd.exe localhost /config /roundrobin 1
Add-DnsServerResourceRecordA -Name "WebPool1" -ZoneName "Internal.contoso.org" `
-ipaddress 192.168.0.3,192.168.0.4,192.168.0.5
Add-DnsServerResourceRecordA -Name "sql1" -ZoneName "Internal.contoso.org" `
-ipaddress 192.168.0.6
Add-DnsServerResourceRecordA -Name "cache1" -ZoneName "Internal.contoso.org" `
-ipaddress 192.168.0.7
Add-DnsServerResourceRecord -name "3" -Ptr -ZoneName "0.0.168.192.in-addr.arpa" `
-PtrDomainName "webpool1.internal.contoso.org"
Add-DnsServerResourceRecord -name "4" -Ptr -ZoneName "0.0.168.192.in-addr.arpa" `
-PtrDomainName "webpool1.internal.contoso.org"
Add-DnsServerResourceRecord -name "5" -Ptr -ZoneName "0.0.168.192.in-addr.arpa" `
-PtrDomainName "webpool1.internal.contoso.org"
Add-DnsServerResourceRecord -name "6" -Ptr -ZoneName "0.0.168.192.in-addr.arpa" `
-PtrDomainName "sql1.internal.contoso.org"
Add-DnsServerResourceRecord -name "7" -Ptr -ZoneName "0.0.168.192.in-addr.arpa" `
-PtrDomainName "cache1.internal.contoso.org"
}
TestScript = { if((get-dnsserverzone).zonename -ccontains "0.0.168.192.in-addr.arpa" -and "internal.contoso.org") `
{return (Get-DnsServerResourceRecord -zoneName "internal.contoso.org" -name "webpool1" `
| select-object -expandproperty recorddata).ipv4address.ipaddresstostring -ccontains `
"192.168.0.3" -and "192.168.0.4" -and "192.168.0.5"}
else{
return $false
}
}
GetScript = { return @{ DNSZone = ((get-dnsserverzone).zonename | where-object {$_ -eq "internal.contoso.org"})
ARPZone = ((get-dnsserverzone).zonename | where-object {$_ -eq "0.0.168.192.in-addr.arpa"})
Web1ARec = ((get-dnsserverresourcerecord -zonename "internal.contoso.org" -name "webpool1" `
| select-object -expandproperty recorddata).ipv4address.ipaddresstostring | `
where-object {$_ -eq "192.168.0.3"})
Web2ARec = ((get-dnsserverresourcerecord -zonename "internal.contoso.org" -name "webpool1" `
| select-object -expandproperty recorddata).ipv4address.ipaddresstostring | `
where-object {$_ -eq "192.168.0.4"})
Web3ARec = ((get-dnsserverresourcerecord -zonename "internal.contoso.org" -name "webpool1" `
| select-object -expandproperty recorddata).ipv4address.ipaddresstostring | `
where-object {$_ -eq "192.168.0.5"})
SQL1ARec = ((get-dnsserverresourcerecord -zonename "internal.contoso.org" -name "sql1" `
| select-object -expandproperty recorddata).ipv4address.ipaddresstostring | `
where-object {$_ -eq "192.168.0.6"})
Cache1ARec = ((get-dnsserverresourcerecord -zonename "internal.contoso.org" -name "cache1" `
| select-object -expandproperty recorddata).ipv4address.ipaddresstostring | `
where-object {$_ -eq "192.168.0.7"})
RoundRobin = ((get-dnsserver | select-object -expandproperty serversettings).roundrobin)
Fwdr1 = ((get-dnsserver | select-object -expandproperty serversettings).ipaddress.ipaddresstostring `
| where-object {$_ -eq "8.8.8.8"})
Fwdr2 = ((get-dnsserver | select-object -expandproperty serversettings).ipaddress.ipaddresstostring `
| where-object {$_ -eq "4.2.2.2"})
}
}
DependsOn = "[WindowsFeature]DNS"
}
}
}
Set-Location c:
# Push the DSC configuration to the Test server
TestNodeConfig -machinename "TestNode" -serverIP "192.168.0.2" -scopeid "192.168.0.0"
start-dscconfiguration -computername "TestNode" -path "c:\testnodeconfig"
| jonathanelbailey/PowerShell-Code-Samples | DSC/SamplePushConfig.ps1 | PowerShell | mit | 10,007 |
#
# .SYNOPSIS
#
# Complete the -Counter argument to Get-Counter cmdlet
#
function CounterParameterCompletion
{
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$optionalCn = @{}
$cn = $fakeBoundParameter["ComputerName"]
if($cn)
{
$optionalCn.ComputerName = $cn
}
(Get-Counter -ListSet * @optionalCn).Counter |
Where-Object { $_ -like "$wordToComplete*" } |
Sort-Object |
ForEach-Object {
# TODO: need a tooltip
New-CompletionResult $_
}
}
#
# .SYNOPSIS
#
# Complete the -ListSet argument to Get-Counter cmdlet
#
function ListSetParameterCompletion
{
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$optionalCn = @{}
$cn = $fakeBoundParameter["ComputerName"]
if($cn)
{
$optionalCn.ComputerName = $cn
}
Get-Counter -ListSet "$wordToComplete*" @optionalCn |
Sort-Object CounterSetName |
ForEach-Object {
$tooltip = $_.Description
New-CompletionResult $_.CounterSetName $tooltip
}
}
#
# .SYNOPSIS
#
# Completes names of the logs for Get-WinEvent cmdlet.
#
function GetWinEvent_LogNameCompleter
{
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
$optionalCn = @{}
$cn = $fakeBoundParameter['ComputerName']
if ($cn)
{
$optionalCn.ComputerName = $cn
}
Get-WinEvent -ListLog "$wordToComplete*" -Force @optionalCn |
where { $_.IsEnabled } |
Sort-Object -Property LogName |
ForEach-Object {
$toolTip = "Log $($_.LogName): $($_.RecordCount) entries"
New-CompletionResult $_.LogName $toolTip
}
}
#
# .SYNOPSIS
#
# Completes names of the logs for Get-WinEvent cmdlet.
#
function GetWinEvent_ListLogCompleter
{
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
[System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.GetLogNames() | Where-Object {$_ -like "*$wordToComplete*"} | Sort-Object | ForEach-Object {
New-CompletionResult $_ $_
}
}
#
# .SYNOPSIS
#
# Completes providers names for Get-WinEvent cmdlet.
#
function GetWinEvent_ListProviderCompleter
{
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
[System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.GetProviderNames() | Where-Object {$_ -like "*$wordToComplete*"} | Sort-Object | ForEach-Object {
New-CompletionResult $_ $_
}
}
Register-ArgumentCompleter `
-Command 'Get-Counter' `
-Parameter 'Counter' `
-Description @'
Complete counter for the Get-Counter cmdlet, optionally on a remote machine. For example:
Get-Counter -Counter <TAB>
Get-Counter -cn 127.0.0.1 -Counter <TAB>
'@ `
-ScriptBlock $function:CounterParameterCompletion
Register-ArgumentCompleter `
-Command 'Get-Counter' `
-Parameter 'ListSet' `
-Description @'
Complete counter sets for the Get-Counter cmdlet, optionally on a remote machine. For example:
Get-Counter -ListSet <TAB>
Get-Counter -cn 127.0.0.1 -ListSet <TAB>
'@ `
-ScriptBlock $function:ListSetParameterCompletion
Register-ArgumentCompleter `
-Command 'Get-WinEvent' `
-Parameter 'LogName' `
-Description 'Completes names for the logs, for example: Get-WinEvent -LogName <TAB>' `
-ScriptBlock $function:GetWinEvent_LogNameCompleter
Register-ArgumentCompleter `
-Command 'Get-WinEvent' `
-Parameter 'ListLog' `
-Description 'Completes names for the logs, for example: Get-WinEvent -ListLog <TAB>' `
-ScriptBlock $function:GetWinEvent_ListLogCompleter
Register-ArgumentCompleter `
-Command 'Get-WinEvent' `
-Parameter 'ListProvider' `
-Description 'Completes names of the providers, for example: Get-WinEvent -ListProvider <TAB>' `
-ScriptBlock $function:GetWinEvent_ListProviderCompleter
| lzybkr/TabExpansionPlusPlus | Microsoft.PowerShell.Diagnostics.ArgumentCompleters.ps1 | PowerShell | bsd-2-clause | 4,033 |
function Join-DbaPath {
<#
.SYNOPSIS
Performs multisegment path joins.
.DESCRIPTION
Performs multisegment path joins.
.PARAMETER Path
The basepath to join on.
.PARAMETER Child
Any number of child paths to add.
.EXAMPLE
PS C:\> Join-DbaPath -Path 'C:\temp' 'Foo' 'Bar'
Returns 'C:\temp\Foo\Bar' on windows.
Returns 'C:/temp/Foo/Bar' on non-windows.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]
$Path,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]
$Child
)
return @($path) + $Child -join
[IO.Path]::DirectorySeparatorChar -replace
'\\|/', [IO.Path]::DirectorySeparatorChar
$resultingPath = $Path
if (($PSVersionTable.PSVersion.Major -ge 6) -and (-not $script:isWindows)) {
$resultingPath = $resultingPath.Replace("\", "/")
} else { $resultingPath = $resultingPath.Replace("/", "\") }
foreach ($childItem in $Child) {
$resultingPath = Join-Path -Path $resultingPath -ChildPath $childItem
}
$resultingPath
} | alevyinroc/dbatools | internal/functions/utility/Join-DbaPath.ps1 | PowerShell | mit | 1,161 |
function Stop-DbaProcess {
<#
.SYNOPSIS
This command finds and kills SQL Server processes.
.DESCRIPTION
This command kills all spids associated with a spid, login, host, program or database.
If you are attempting to kill your own login sessions, the process performing the kills will be skipped.
.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 Spid
Specifies one or more spids to be killed. Options for this parameter are auto-populated from the server.
.PARAMETER Login
Specifies one or more login names whose processes will be killed. Options for this parameter are auto-populated from the server and only login names that have active processes are offered.
.PARAMETER Hostname
Specifies one or more client hostnames whose processes will be killed. Options for this parameter are auto-populated from the server and only hostnames that have active processes are offered.
.PARAMETER Program
Specifies one or more client programs whose processes will be killed. Options for this parameter are auto-populated from the server and only programs that have active processes are offered.
.PARAMETER Database
Specifies one or more databases whose processes will be killed. Options for this parameter are auto-populated from the server and only databases that have active processes are offered.
This parameter is auto-populated from -SqlInstance and allows only database names that have active processes. You can specify one or more Databases whose processes will be killed.
.PARAMETER ExcludeSpid
Specifies one or more spids which will not be killed. Options for this parameter are auto-populated from the server.
Exclude is the last filter to run, so even if a spid matches (for example) Hosts, if it's listed in Exclude it wil be excluded.
.PARAMETER InputObject
This is the process object passed by Get-DbaProcess if using a pipeline.
.PARAMETER WhatIf
If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
.PARAMETER Confirm
If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
.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: Processes
Author: Chrissy LeMaire (@cl), netnerds.net
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Stop-DbaProcess
.EXAMPLE
PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -Login base\ctrlb, sa
Finds all processes for base\ctrlb and sa on sqlserver2014a, then kills them. Uses Windows Authentication to login to sqlserver2014a.
.EXAMPLE
PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -SqlCredential $credential -Spid 56, 77
Finds processes for spid 56 and 57, then kills them. Uses alternative (SQL or Windows) credentials to login to sqlserver2014a.
.EXAMPLE
PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -Program 'Microsoft SQL Server Management Studio'
Finds processes that were created in Microsoft SQL Server Management Studio, then kills them.
.EXAMPLE
PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014a -Hostname workstationx, server100
Finds processes that were initiated (computers/clients) workstationx and server 1000, then kills them.
.EXAMPLE
PS C:\> Stop-DbaProcess -SqlInstance sqlserver2014 -Database tempdb -WhatIf
Shows what would happen if the command were executed.
.EXAMPLE
PS C:\> Get-DbaProcess -SqlInstance sql2016 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess
Finds processes that were created with dbatools, then kills them.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess)]
param (
[parameter(Mandatory, ParameterSetName = "Server")]
[DbaInstanceParameter]$SqlInstance,
[PSCredential]$SqlCredential,
[int[]]$Spid,
[int[]]$ExcludeSpid,
[string[]]$Database,
[string[]]$Login,
[string[]]$Hostname,
[string[]]$Program,
[parameter(ValueFromPipeline, Mandatory, ParameterSetName = "Process")]
[object[]]$InputObject,
[switch]$EnableException
)
process {
if (Test-FunctionInterrupt) { return }
if (-not $InputObject) {
$bound = $PSBoundParameters
$null = $bound.Remove("WhatIf")
$null = $bound.Remove("Confirm")
$InputObject = Get-DbaProcess @bound
}
foreach ($session in $InputObject) {
$sourceserver = $session.Parent
if (!$sourceserver) {
Stop-Function -Message "Only process objects can be passed through the pipeline." -Category InvalidData -Target $session
return
}
$currentspid = $session.spid
if ($sourceserver.ConnectionContext.ProcessID -eq $currentspid) {
Write-Message -Level Warning -Message "Skipping spid $currentspid because you cannot use KILL to kill your own process." -Target $session
Continue
}
if ($Pscmdlet.ShouldProcess($sourceserver, "Killing spid $currentspid")) {
try {
$sourceserver.KillProcess($currentspid)
[pscustomobject]@{
SqlInstance = $sourceserver.name
Spid = $session.Spid
Login = $session.Login
Host = $session.Host
Database = $session.Database
Program = $session.Program
Status = 'Killed'
}
} catch {
Stop-Function -Message "Couldn't kill spid $currentspid." -Target $session -ErrorRecord $_ -Continue
}
}
}
}
} | alevyinroc/dbatools | functions/Stop-DbaProcess.ps1 | PowerShell | mit | 6,979 |
$InstallPath = Join-Path $($env:ChocolateyInstall) 'lib\\TfsCmdlets'
$ToolsDir = Join-Path $InstallPath 'Tools'
if ($env:PSModulePath -like "*$ToolsDir*")
{
Write-Output "TfsCmdlets: Removing installation directory from PSModulePath environment variable"
$NewModulePath = $Env:PSModulePath.Replace($ToolsDir, '').Replace(';;', ';')
SETX @('PSModulePath', $NewModulePath, '/M')
}
$ShortcutTargetDir = "$Env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs"
$ShortcutName = 'Azure DevOps Shell'
$ShortcutFilePath = "$ShortcutTargetDir\\$ShortcutName.lnk"
if (Test-Path $ShortcutFilePath)
{
Write-Output "TfsCmdlets: Removing Start Menu shortcut file"
Remove-Item $ShortcutFilePath
} | igoravl/tfscmdlets | PS/chocolateyUninstall.ps1 | PowerShell | mit | 708 |
param($installPath, $toolsPath, $package, $project)
$analyzerPath = join-path $toolsPath "analyzers"
$analyzerFilePath = join-path $analyzerPath "AsyncAwaitAnalyzer.dll"
$project.Object.AnalyzerReferences.Remove("$analyzerFilePath") | olohmann/AsyncAwaitAnalyzer | src/AsyncAwaitAnalyzer/AsyncAwaitAnalyzer/tools/uninstall.ps1 | PowerShell | mit | 237 |
# Initialize variables if they aren't already defined.
# These may be defined as parameters of the importing script, or set after importing this script.
# CI mode - set to true on CI server for PR validation build or official build.
[bool]$ci = if (Test-Path variable:ci) { $ci } else { $false }
# Build configuration. Common values include 'Debug' and 'Release', but the repository may use other names.
[string]$configuration = if (Test-Path variable:configuration) { $configuration } else { 'Debug' }
# Set to true to opt out of outputting binary log while running in CI
[bool]$excludeCIBinarylog = if (Test-Path variable:excludeCIBinarylog) { $excludeCIBinarylog } else { $false }
# Set to true to output binary log from msbuild. Note that emitting binary log slows down the build.
[bool]$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $ci -and !$excludeCIBinarylog }
# Set to true to use the pipelines logger which will enable Azure logging output.
# https://github.com/Microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md
# This flag is meant as a temporary opt-opt for the feature while validate it across
# our consumers. It will be deleted in the future.
[bool]$pipelinesLog = if (Test-Path variable:pipelinesLog) { $pipelinesLog } else { $ci }
# Turns on machine preparation/clean up code that changes the machine state (e.g. kills build processes).
[bool]$prepareMachine = if (Test-Path variable:prepareMachine) { $prepareMachine } else { $false }
# True to restore toolsets and dependencies.
[bool]$restore = if (Test-Path variable:restore) { $restore } else { $true }
# Adjusts msbuild verbosity level.
[string]$verbosity = if (Test-Path variable:verbosity) { $verbosity } else { 'minimal' }
# Set to true to reuse msbuild nodes. Recommended to not reuse on CI.
[bool]$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { !$ci }
# Configures warning treatment in msbuild.
[bool]$warnAsError = if (Test-Path variable:warnAsError) { $warnAsError } else { $true }
# Specifies which msbuild engine to use for build: 'vs', 'dotnet' or unspecified (determined based on presence of tools.vs in global.json).
[string]$msbuildEngine = if (Test-Path variable:msbuildEngine) { $msbuildEngine } else { $null }
# True to attempt using .NET Core already that meets requirements specified in global.json
# installed on the machine instead of downloading one.
[bool]$useInstalledDotNetCli = if (Test-Path variable:useInstalledDotNetCli) { $useInstalledDotNetCli } else { $true }
# Enable repos to use a particular version of the on-line dotnet-install scripts.
# default URL: https://dot.net/v1/dotnet-install.ps1
[string]$dotnetInstallScriptVersion = if (Test-Path variable:dotnetInstallScriptVersion) { $dotnetInstallScriptVersion } else { 'v1' }
# True to use global NuGet cache instead of restoring packages to repository-local directory.
[bool]$useGlobalNuGetCache = if (Test-Path variable:useGlobalNuGetCache) { $useGlobalNuGetCache } else { !$ci }
# True to exclude prerelease versions Visual Studio during build
[bool]$excludePrereleaseVS = if (Test-Path variable:excludePrereleaseVS) { $excludePrereleaseVS } else { $false }
# An array of names of processes to stop on script exit if prepareMachine is true.
$processesToStopOnExit = if (Test-Path variable:processesToStopOnExit) { $processesToStopOnExit } else { @('msbuild', 'dotnet', 'vbcscompiler') }
$disableConfigureToolsetImport = if (Test-Path variable:disableConfigureToolsetImport) { $disableConfigureToolsetImport } else { $null }
set-strictmode -version 2.0
$ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# If specifies, provides an alternate path for getting .NET Core SDKs and Runtimes. This script will still try public sources first.
[string]$runtimeSourceFeed = if (Test-Path variable:runtimeSourceFeed) { $runtimeSourceFeed } else { $null }
# Base-64 encoded SAS token that has permission to storage container described by $runtimeSourceFeed
[string]$runtimeSourceFeedKey = if (Test-Path variable:runtimeSourceFeedKey) { $runtimeSourceFeedKey } else { $null }
function Create-Directory ([string[]] $path) {
New-Item -Path $path -Force -ItemType 'Directory' | Out-Null
}
function Unzip([string]$zipfile, [string]$outpath) {
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}
# This will exec a process using the console and return it's exit code.
# This will not throw when the process fails.
# Returns process exit code.
function Exec-Process([string]$command, [string]$commandArgs) {
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = $command
$startInfo.Arguments = $commandArgs
$startInfo.UseShellExecute = $false
$startInfo.WorkingDirectory = Get-Location
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$finished = $false
try {
while (-not $process.WaitForExit(100)) {
# Non-blocking loop done to allow ctr-c interrupts
}
$finished = $true
return $global:LASTEXITCODE = $process.ExitCode
}
finally {
# If we didn't finish then an error occurred or the user hit ctrl-c. Either
# way kill the process
if (-not $finished) {
$process.Kill()
}
}
}
# createSdkLocationFile parameter enables a file being generated under the toolset directory
# which writes the sdk's location into. This is only necessary for cmd --> powershell invocations
# as dot sourcing isn't possible.
function InitializeDotNetCli([bool]$install, [bool]$createSdkLocationFile) {
if (Test-Path variable:global:_DotNetInstallDir) {
return $global:_DotNetInstallDir
}
# Don't resolve runtime, shared framework, or SDK from other locations to ensure build determinism
$env:DOTNET_MULTILEVEL_LOOKUP=0
# Disable first run since we do not need all ASP.NET packages restored.
$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
# Disable telemetry on CI.
if ($ci) {
$env:DOTNET_CLI_TELEMETRY_OPTOUT=1
}
# Source Build uses DotNetCoreSdkDir variable
if ($env:DotNetCoreSdkDir -ne $null) {
$env:DOTNET_INSTALL_DIR = $env:DotNetCoreSdkDir
}
# Find the first path on %PATH% that contains the dotnet.exe
if ($useInstalledDotNetCli -and (-not $globalJsonHasRuntimes) -and ($env:DOTNET_INSTALL_DIR -eq $null)) {
$dotnetExecutable = GetExecutableFileName 'dotnet'
$dotnetCmd = Get-Command $dotnetExecutable -ErrorAction SilentlyContinue
if ($dotnetCmd -ne $null) {
$env:DOTNET_INSTALL_DIR = Split-Path $dotnetCmd.Path -Parent
}
}
$dotnetSdkVersion = $GlobalJson.tools.dotnet
# Use dotnet installation specified in DOTNET_INSTALL_DIR if it contains the required SDK version,
# otherwise install the dotnet CLI and SDK to repo local .dotnet directory to avoid potential permission issues.
if ((-not $globalJsonHasRuntimes) -and (-not [string]::IsNullOrEmpty($env:DOTNET_INSTALL_DIR)) -and (Test-Path(Join-Path $env:DOTNET_INSTALL_DIR "sdk\$dotnetSdkVersion"))) {
$dotnetRoot = $env:DOTNET_INSTALL_DIR
} else {
$dotnetRoot = Join-Path $RepoRoot '.dotnet'
if (-not (Test-Path(Join-Path $dotnetRoot "sdk\$dotnetSdkVersion"))) {
if ($install) {
InstallDotNetSdk $dotnetRoot $dotnetSdkVersion
} else {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to find dotnet with SDK version '$dotnetSdkVersion'"
ExitWithExitCode 1
}
}
$env:DOTNET_INSTALL_DIR = $dotnetRoot
}
# Creates a temporary file under the toolset dir.
# The following code block is protecting against concurrent access so that this function can
# be called in parallel.
if ($createSdkLocationFile) {
do {
$sdkCacheFileTemp = Join-Path $ToolsetDir $([System.IO.Path]::GetRandomFileName())
}
until (!(Test-Path $sdkCacheFileTemp))
Set-Content -Path $sdkCacheFileTemp -Value $dotnetRoot
try {
Move-Item -Force $sdkCacheFileTemp (Join-Path $ToolsetDir 'sdk.txt')
} catch {
# Somebody beat us
Remove-Item -Path $sdkCacheFileTemp
}
}
# Add dotnet to PATH. This prevents any bare invocation of dotnet in custom
# build steps from using anything other than what we've downloaded.
# It also ensures that VS msbuild will use the downloaded sdk targets.
$env:PATH = "$dotnetRoot;$env:PATH"
# Make Sure that our bootstrapped dotnet cli is available in future steps of the Azure Pipelines build
Write-PipelinePrependPath -Path $dotnetRoot
Write-PipelineSetVariable -Name 'DOTNET_MULTILEVEL_LOOKUP' -Value '0'
Write-PipelineSetVariable -Name 'DOTNET_SKIP_FIRST_TIME_EXPERIENCE' -Value '1'
return $global:_DotNetInstallDir = $dotnetRoot
}
function Retry($downloadBlock, $maxRetries = 5) {
$retries = 1
while($true) {
try {
& $downloadBlock
break
}
catch {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_
}
if (++$retries -le $maxRetries) {
$delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff
Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)."
Start-Sleep -Seconds $delayInSeconds
}
else {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unable to download file in $maxRetries attempts."
break
}
}
}
function GetDotNetInstallScript([string] $dotnetRoot) {
$installScript = Join-Path $dotnetRoot 'dotnet-install.ps1'
if (!(Test-Path $installScript)) {
Create-Directory $dotnetRoot
$ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit
$uri = "https://dot.net/$dotnetInstallScriptVersion/dotnet-install.ps1"
Retry({
Write-Host "GET $uri"
Invoke-WebRequest $uri -OutFile $installScript
})
}
return $installScript
}
function InstallDotNetSdk([string] $dotnetRoot, [string] $version, [string] $architecture = '', [switch] $noPath) {
InstallDotNet $dotnetRoot $version $architecture '' $false $runtimeSourceFeed $runtimeSourceFeedKey -noPath:$noPath
}
function InstallDotNet([string] $dotnetRoot,
[string] $version,
[string] $architecture = '',
[string] $runtime = '',
[bool] $skipNonVersionedFiles = $false,
[string] $runtimeSourceFeed = '',
[string] $runtimeSourceFeedKey = '',
[switch] $noPath) {
$installScript = GetDotNetInstallScript $dotnetRoot
$installParameters = @{
Version = $version
InstallDir = $dotnetRoot
}
if ($architecture) { $installParameters.Architecture = $architecture }
if ($runtime) { $installParameters.Runtime = $runtime }
if ($skipNonVersionedFiles) { $installParameters.SkipNonVersionedFiles = $skipNonVersionedFiles }
if ($noPath) { $installParameters.NoPath = $True }
try {
& $installScript @installParameters
}
catch {
if ($runtimeSourceFeed -or $runtimeSourceFeedKey) {
Write-Host "Failed to install dotnet from public location. Trying from '$runtimeSourceFeed'"
if ($runtimeSourceFeed) { $installParameters.AzureFeed = $runtimeSourceFeed }
if ($runtimeSourceFeedKey) {
$decodedBytes = [System.Convert]::FromBase64String($runtimeSourceFeedKey)
$decodedString = [System.Text.Encoding]::UTF8.GetString($decodedBytes)
$installParameters.FeedCredential = $decodedString
}
try {
& $installScript @installParameters
}
catch {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from custom location '$runtimeSourceFeed'."
ExitWithExitCode 1
}
} else {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Failed to install dotnet from public location."
ExitWithExitCode 1
}
}
}
#
# Locates Visual Studio MSBuild installation.
# The preference order for MSBuild to use is as follows:
#
# 1. MSBuild from an active VS command prompt
# 2. MSBuild from a compatible VS installation
# 3. MSBuild from the xcopy tool package
#
# Returns full path to msbuild.exe.
# Throws on failure.
#
function InitializeVisualStudioMSBuild([bool]$install, [object]$vsRequirements = $null) {
if (-not (IsWindowsPlatform)) {
throw "Cannot initialize Visual Studio on non-Windows"
}
if (Test-Path variable:global:_MSBuildExe) {
return $global:_MSBuildExe
}
# Minimum VS version to require.
$vsMinVersionReqdStr = '16.8'
$vsMinVersionReqd = [Version]::new($vsMinVersionReqdStr)
# If the version of msbuild is going to be xcopied,
# use this version. Version matches a package here:
# https://dev.azure.com/dnceng/public/_packaging?_a=package&feed=dotnet-eng&package=RoslynTools.MSBuild&protocolType=NuGet&version=16.10.0-preview2&view=overview
$defaultXCopyMSBuildVersion = '16.10.0-preview2'
if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs }
$vsMinVersionStr = if ($vsRequirements.version) { $vsRequirements.version } else { $vsMinVersionReqdStr }
$vsMinVersion = [Version]::new($vsMinVersionStr)
# Try msbuild command available in the environment.
if ($env:VSINSTALLDIR -ne $null) {
$msbuildCmd = Get-Command 'msbuild.exe' -ErrorAction SilentlyContinue
if ($msbuildCmd -ne $null) {
# Workaround for https://github.com/dotnet/roslyn/issues/35793
# Due to this issue $msbuildCmd.Version returns 0.0.0.0 for msbuild.exe 16.2+
$msbuildVersion = [Version]::new((Get-Item $msbuildCmd.Path).VersionInfo.ProductVersion.Split([char[]]@('-', '+'))[0])
if ($msbuildVersion -ge $vsMinVersion) {
return $global:_MSBuildExe = $msbuildCmd.Path
}
# Report error - the developer environment is initialized with incompatible VS version.
throw "Developer Command Prompt for VS $($env:VisualStudioVersion) is not recent enough. Please upgrade to $vsMinVersionStr or build from a plain CMD window"
}
}
# Locate Visual Studio installation or download x-copy msbuild.
$vsInfo = LocateVisualStudio $vsRequirements
if ($vsInfo -ne $null) {
$vsInstallDir = $vsInfo.installationPath
$vsMajorVersion = $vsInfo.installationVersion.Split('.')[0]
InitializeVisualStudioEnvironmentVariables $vsInstallDir $vsMajorVersion
} else {
if (Get-Member -InputObject $GlobalJson.tools -Name 'xcopy-msbuild') {
$xcopyMSBuildVersion = $GlobalJson.tools.'xcopy-msbuild'
$vsMajorVersion = $xcopyMSBuildVersion.Split('.')[0]
} else {
#if vs version provided in global.json is incompatible (too low) then use the default version for xcopy msbuild download
if($vsMinVersion -lt $vsMinVersionReqd){
Write-Host "Using xcopy-msbuild version of $defaultXCopyMSBuildVersion since VS version $vsMinVersionStr provided in global.json is not compatible"
$xcopyMSBuildVersion = $defaultXCopyMSBuildVersion
}
else{
# If the VS version IS compatible, look for an xcopy msbuild package
# with a version matching VS.
# Note: If this version does not exist, then an explicit version of xcopy msbuild
# can be specified in global.json. This will be required for pre-release versions of msbuild.
$vsMajorVersion = $vsMinVersion.Major
$vsMinorVersion = $vsMinVersion.Minor
$xcopyMSBuildVersion = "$vsMajorVersion.$vsMinorVersion.0"
}
}
$vsInstallDir = $null
if ($xcopyMSBuildVersion.Trim() -ine "none") {
$vsInstallDir = InitializeXCopyMSBuild $xcopyMSBuildVersion $install
if ($vsInstallDir -eq $null) {
throw "Could not xcopy msbuild. Please check that package 'RoslynTools.MSBuild @ $xcopyMSBuildVersion' exists on feed 'dotnet-eng'."
}
}
if ($vsInstallDir -eq $null) {
throw 'Unable to find Visual Studio that has required version and components installed'
}
}
$msbuildVersionDir = if ([int]$vsMajorVersion -lt 16) { "$vsMajorVersion.0" } else { "Current" }
$local:BinFolder = Join-Path $vsInstallDir "MSBuild\$msbuildVersionDir\Bin"
$local:Prefer64bit = if ($vsRequirements.Prefer64bit) { $vsRequirements.Prefer64bit } else { $false }
if ($local:Prefer64bit -and (Test-Path(Join-Path $local:BinFolder "amd64"))) {
$global:_MSBuildExe = Join-Path $local:BinFolder "amd64\msbuild.exe"
} else {
$global:_MSBuildExe = Join-Path $local:BinFolder "msbuild.exe"
}
return $global:_MSBuildExe
}
function InitializeVisualStudioEnvironmentVariables([string] $vsInstallDir, [string] $vsMajorVersion) {
$env:VSINSTALLDIR = $vsInstallDir
Set-Item "env:VS$($vsMajorVersion)0COMNTOOLS" (Join-Path $vsInstallDir "Common7\Tools\")
$vsSdkInstallDir = Join-Path $vsInstallDir "VSSDK\"
if (Test-Path $vsSdkInstallDir) {
Set-Item "env:VSSDK$($vsMajorVersion)0Install" $vsSdkInstallDir
$env:VSSDKInstall = $vsSdkInstallDir
}
}
function InstallXCopyMSBuild([string]$packageVersion) {
return InitializeXCopyMSBuild $packageVersion -install $true
}
function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install) {
$packageName = 'RoslynTools.MSBuild'
$packageDir = Join-Path $ToolsDir "msbuild\$packageVersion"
$packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg"
if (!(Test-Path $packageDir)) {
if (!$install) {
return $null
}
Create-Directory $packageDir
Write-Host "Downloading $packageName $packageVersion"
$ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit
Retry({
Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath
})
Unzip $packagePath $packageDir
}
return Join-Path $packageDir 'tools'
}
#
# Locates Visual Studio instance that meets the minimal requirements specified by tools.vs object in global.json.
#
# The following properties of tools.vs are recognized:
# "version": "{major}.{minor}"
# Two part minimal VS version, e.g. "15.9", "16.0", etc.
# "components": ["componentId1", "componentId2", ...]
# Array of ids of workload components that must be available in the VS instance.
# See e.g. https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-enterprise?view=vs-2017
#
# Returns JSON describing the located VS instance (same format as returned by vswhere),
# or $null if no instance meeting the requirements is found on the machine.
#
function LocateVisualStudio([object]$vsRequirements = $null){
if (-not (IsWindowsPlatform)) {
throw "Cannot run vswhere on non-Windows platforms."
}
if (Get-Member -InputObject $GlobalJson.tools -Name 'vswhere') {
$vswhereVersion = $GlobalJson.tools.vswhere
} else {
$vswhereVersion = '2.5.2'
}
$vsWhereDir = Join-Path $ToolsDir "vswhere\$vswhereVersion"
$vsWhereExe = Join-Path $vsWhereDir 'vswhere.exe'
if (!(Test-Path $vsWhereExe)) {
Create-Directory $vsWhereDir
Write-Host 'Downloading vswhere'
Retry({
Invoke-WebRequest "https://netcorenativeassets.blob.core.windows.net/resource-packages/external/windows/vswhere/$vswhereVersion/vswhere.exe" -OutFile $vswhereExe
})
}
if (!$vsRequirements) { $vsRequirements = $GlobalJson.tools.vs }
$args = @('-latest', '-format', 'json', '-requires', 'Microsoft.Component.MSBuild', '-products', '*')
if (!$excludePrereleaseVS) {
$args += '-prerelease'
}
if (Get-Member -InputObject $vsRequirements -Name 'version') {
$args += '-version'
$args += $vsRequirements.version
}
if (Get-Member -InputObject $vsRequirements -Name 'components') {
foreach ($component in $vsRequirements.components) {
$args += '-requires'
$args += $component
}
}
$vsInfo =& $vsWhereExe $args | ConvertFrom-Json
if ($lastExitCode -ne 0) {
return $null
}
# use first matching instance
return $vsInfo[0]
}
function InitializeBuildTool() {
if (Test-Path variable:global:_BuildTool) {
# If the requested msbuild parameters do not match, clear the cached variables.
if($global:_BuildTool.Contains('ExcludePrereleaseVS') -and $global:_BuildTool.ExcludePrereleaseVS -ne $excludePrereleaseVS) {
Remove-Item variable:global:_BuildTool
Remove-Item variable:global:_MSBuildExe
} else {
return $global:_BuildTool
}
}
if (-not $msbuildEngine) {
$msbuildEngine = GetDefaultMSBuildEngine
}
# Initialize dotnet cli if listed in 'tools'
$dotnetRoot = $null
if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') {
$dotnetRoot = InitializeDotNetCli -install:$restore
}
if ($msbuildEngine -eq 'dotnet') {
if (!$dotnetRoot) {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "/global.json must specify 'tools.dotnet'."
ExitWithExitCode 1
}
$dotnetPath = Join-Path $dotnetRoot (GetExecutableFileName 'dotnet')
$buildTool = @{ Path = $dotnetPath; Command = 'msbuild'; Tool = 'dotnet'; Framework = 'netcoreapp3.1' }
} elseif ($msbuildEngine -eq "vs") {
try {
$msbuildPath = InitializeVisualStudioMSBuild -install:$restore
} catch {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message $_
ExitWithExitCode 1
}
$buildTool = @{ Path = $msbuildPath; Command = ""; Tool = "vs"; Framework = "net472"; ExcludePrereleaseVS = $excludePrereleaseVS }
} else {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Unexpected value of -msbuildEngine: '$msbuildEngine'."
ExitWithExitCode 1
}
return $global:_BuildTool = $buildTool
}
function GetDefaultMSBuildEngine() {
# Presence of tools.vs indicates the repo needs to build using VS msbuild on Windows.
if (Get-Member -InputObject $GlobalJson.tools -Name 'vs') {
return 'vs'
}
if (Get-Member -InputObject $GlobalJson.tools -Name 'dotnet') {
return 'dotnet'
}
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "-msbuildEngine must be specified, or /global.json must specify 'tools.dotnet' or 'tools.vs'."
ExitWithExitCode 1
}
function GetNuGetPackageCachePath() {
if ($env:NUGET_PACKAGES -eq $null) {
# Use local cache on CI to ensure deterministic build.
# Avoid using the http cache as workaround for https://github.com/NuGet/Home/issues/3116
# use global cache in dev builds to avoid cost of downloading packages.
# For directory normalization, see also: https://github.com/NuGet/Home/issues/7968
if ($useGlobalNuGetCache) {
$env:NUGET_PACKAGES = Join-Path $env:UserProfile '.nuget\packages\'
} else {
$env:NUGET_PACKAGES = Join-Path $RepoRoot '.packages\'
$env:RESTORENOCACHE = $true
}
}
return $env:NUGET_PACKAGES
}
# Returns a full path to an Arcade SDK task project file.
function GetSdkTaskProject([string]$taskName) {
return Join-Path (Split-Path (InitializeToolset) -Parent) "SdkTasks\$taskName.proj"
}
function InitializeNativeTools() {
if (-Not (Test-Path variable:DisableNativeToolsetInstalls) -And (Get-Member -InputObject $GlobalJson -Name "native-tools")) {
$nativeArgs= @{}
if ($ci) {
$nativeArgs = @{
InstallDirectory = "$ToolsDir"
}
}
& "$PSScriptRoot/init-tools-native.ps1" @nativeArgs
}
}
function InitializeToolset() {
if (Test-Path variable:global:_ToolsetBuildProj) {
return $global:_ToolsetBuildProj
}
$nugetCache = GetNuGetPackageCachePath
$toolsetVersion = $GlobalJson.'msbuild-sdks'.'Microsoft.DotNet.Arcade.Sdk'
$toolsetLocationFile = Join-Path $ToolsetDir "$toolsetVersion.txt"
if (Test-Path $toolsetLocationFile) {
$path = Get-Content $toolsetLocationFile -TotalCount 1
if (Test-Path $path) {
return $global:_ToolsetBuildProj = $path
}
}
if (-not $restore) {
Write-PipelineTelemetryError -Category 'InitializeToolset' -Message "Toolset version $toolsetVersion has not been restored."
ExitWithExitCode 1
}
$buildTool = InitializeBuildTool
$proj = Join-Path $ToolsetDir 'restore.proj'
$bl = if ($binaryLog) { '/bl:' + (Join-Path $LogDir 'ToolsetRestore.binlog') } else { '' }
'<Project Sdk="Microsoft.DotNet.Arcade.Sdk"/>' | Set-Content $proj
MSBuild-Core $proj $bl /t:__WriteToolsetLocation /clp:ErrorsOnly`;NoSummary /p:__ToolsetLocationOutputFile=$toolsetLocationFile
$path = Get-Content $toolsetLocationFile -Encoding UTF8 -TotalCount 1
if (!(Test-Path $path)) {
throw "Invalid toolset path: $path"
}
return $global:_ToolsetBuildProj = $path
}
function ExitWithExitCode([int] $exitCode) {
if ($ci -and $prepareMachine) {
Stop-Processes
}
exit $exitCode
}
function Stop-Processes() {
Write-Host 'Killing running build processes...'
foreach ($processName in $processesToStopOnExit) {
Get-Process -Name $processName -ErrorAction SilentlyContinue | Stop-Process
}
}
#
# Executes msbuild (or 'dotnet msbuild') with arguments passed to the function.
# The arguments are automatically quoted.
# Terminates the script if the build fails.
#
function MSBuild() {
if ($pipelinesLog) {
$buildTool = InitializeBuildTool
if ($ci -and $buildTool.Tool -eq 'dotnet') {
$env:NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS = 20
$env:NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS = 20
Write-PipelineSetVariable -Name 'NUGET_PLUGIN_HANDSHAKE_TIMEOUT_IN_SECONDS' -Value '20'
Write-PipelineSetVariable -Name 'NUGET_PLUGIN_REQUEST_TIMEOUT_IN_SECONDS' -Value '20'
}
$toolsetBuildProject = InitializeToolset
$basePath = Split-Path -parent $toolsetBuildProject
$possiblePaths = @(
# new scripts need to work with old packages, so we need to look for the old names/versions
(Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.ArcadeLogging.dll')),
(Join-Path $basePath (Join-Path $buildTool.Framework 'Microsoft.DotNet.Arcade.Sdk.dll')),
(Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.ArcadeLogging.dll')),
(Join-Path $basePath (Join-Path netcoreapp2.1 'Microsoft.DotNet.Arcade.Sdk.dll'))
)
$selectedPath = $null
foreach ($path in $possiblePaths) {
if (Test-Path $path -PathType Leaf) {
$selectedPath = $path
break
}
}
if (-not $selectedPath) {
Write-PipelineTelemetryError -Category 'Build' -Message 'Unable to find arcade sdk logger assembly.'
ExitWithExitCode 1
}
$args += "/logger:$selectedPath"
}
MSBuild-Core @args
}
#
# Executes msbuild (or 'dotnet msbuild') with arguments passed to the function.
# The arguments are automatically quoted.
# Terminates the script if the build fails.
#
function MSBuild-Core() {
if ($ci) {
if (!$binaryLog -and !$excludeCIBinarylog) {
Write-PipelineTelemetryError -Category 'Build' -Message 'Binary log must be enabled in CI build, or explicitly opted-out from with the -excludeCIBinarylog switch.'
ExitWithExitCode 1
}
if ($nodeReuse) {
Write-PipelineTelemetryError -Category 'Build' -Message 'Node reuse must be disabled in CI build.'
ExitWithExitCode 1
}
}
$buildTool = InitializeBuildTool
$cmdArgs = "$($buildTool.Command) /m /nologo /clp:Summary /v:$verbosity /nr:$nodeReuse /p:ContinuousIntegrationBuild=$ci"
if ($warnAsError) {
$cmdArgs += ' /warnaserror /p:TreatWarningsAsErrors=true'
}
else {
$cmdArgs += ' /p:TreatWarningsAsErrors=false'
}
foreach ($arg in $args) {
if ($null -ne $arg -and $arg.Trim() -ne "") {
if ($arg.EndsWith('\')) {
$arg = $arg + "\"
}
$cmdArgs += " `"$arg`""
}
}
$env:ARCADE_BUILD_TOOL_COMMAND = "$($buildTool.Path) $cmdArgs"
$exitCode = Exec-Process $buildTool.Path $cmdArgs
if ($exitCode -ne 0) {
# We should not Write-PipelineTaskError here because that message shows up in the build summary
# The build already logged an error, that's the reason it failed. Producing an error here only adds noise.
Write-Host "Build failed with exit code $exitCode. Check errors above." -ForegroundColor Red
$buildLog = GetMSBuildBinaryLogCommandLineArgument $args
if ($null -ne $buildLog) {
Write-Host "See log: $buildLog" -ForegroundColor DarkGray
}
if ($ci) {
Write-PipelineSetResult -Result "Failed" -Message "msbuild execution failed."
# Exiting with an exit code causes the azure pipelines task to log yet another "noise" error
# The above Write-PipelineSetResult will cause the task to be marked as failure without adding yet another error
ExitWithExitCode 0
} else {
ExitWithExitCode $exitCode
}
}
}
function GetMSBuildBinaryLogCommandLineArgument($arguments) {
foreach ($argument in $arguments) {
if ($argument -ne $null) {
$arg = $argument.Trim()
if ($arg.StartsWith('/bl:', "OrdinalIgnoreCase")) {
return $arg.Substring('/bl:'.Length)
}
if ($arg.StartsWith('/binaryLogger:', 'OrdinalIgnoreCase')) {
return $arg.Substring('/binaryLogger:'.Length)
}
}
}
return $null
}
function GetExecutableFileName($baseName) {
if (IsWindowsPlatform) {
return "$baseName.exe"
}
else {
return $baseName
}
}
function IsWindowsPlatform() {
return [environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
}
function Get-Darc($version) {
$darcPath = "$TempDir\darc\$(New-Guid)"
if ($version -ne $null) {
& $PSScriptRoot\darc-init.ps1 -toolpath $darcPath -darcVersion $version | Out-Host
} else {
& $PSScriptRoot\darc-init.ps1 -toolpath $darcPath | Out-Host
}
return "$darcPath\darc.exe"
}
. $PSScriptRoot\pipeline-logging-functions.ps1
$RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\..\')
$EngRoot = Resolve-Path (Join-Path $PSScriptRoot '..')
$ArtifactsDir = Join-Path $RepoRoot 'artifacts'
$ToolsetDir = Join-Path $ArtifactsDir 'toolset'
$ToolsDir = Join-Path $RepoRoot '.tools'
$LogDir = Join-Path (Join-Path $ArtifactsDir 'log') $configuration
$TempDir = Join-Path (Join-Path $ArtifactsDir 'tmp') $configuration
$GlobalJson = Get-Content -Raw -Path (Join-Path $RepoRoot 'global.json') | ConvertFrom-Json
# true if global.json contains a "runtimes" section
$globalJsonHasRuntimes = if ($GlobalJson.tools.PSObject.Properties.Name -Match 'runtimes') { $true } else { $false }
Create-Directory $ToolsetDir
Create-Directory $TempDir
Create-Directory $LogDir
Write-PipelineSetVariable -Name 'Artifacts' -Value $ArtifactsDir
Write-PipelineSetVariable -Name 'Artifacts.Toolset' -Value $ToolsetDir
Write-PipelineSetVariable -Name 'Artifacts.Log' -Value $LogDir
Write-PipelineSetVariable -Name 'TEMP' -Value $TempDir
Write-PipelineSetVariable -Name 'TMP' -Value $TempDir
# Import custom tools configuration, if present in the repo.
# Note: Import in global scope so that the script set top-level variables without qualification.
if (!$disableConfigureToolsetImport) {
$configureToolsetScript = Join-Path $EngRoot 'configure-toolset.ps1'
if (Test-Path $configureToolsetScript) {
. $configureToolsetScript
if ((Test-Path variable:failOnConfigureToolsetError) -And $failOnConfigureToolsetError) {
if ((Test-Path variable:LastExitCode) -And ($LastExitCode -ne 0)) {
Write-PipelineTelemetryError -Category 'Build' -Message 'configure-toolset.ps1 returned a non-zero exit code'
ExitWithExitCode $LastExitCode
}
}
}
}
| cshung/clrmd | eng/common/tools.ps1 | PowerShell | mit | 31,527 |
jekyll serve -c "_config.yml,_config.local.yml" | mvsouza/mvsouza.github.io | runServerLocal.ps1 | PowerShell | mit | 47 |
#!/usr/bin/env powershell
function Send-TeamsCard
{
<#
.SYNOPSIS
Sends an actioncard to a MS Teams channel
.DESCRIPTION
Sends an actioncard to a MS Teams channel. Please note that you may have to enable developer preview.
.EXAMPLE
PS C:\> <example usage>
Explanation of what the example does
.INPUTS
ActionCard as hashtable.
.OUTPUTS
$true or $false
Refers to whether or not the post was successful.
.NOTES
This cmdlet does not create cards, it only sends a card you have already created. See New-Card for card creation.
#>
[CmdletBinding()]
[OutputType('Bool')]
param(
[Parameter()]
[ValidateScript({ $_ -match '^https://outlook.office.com/webhook*' })]
[string]
$Webhook,
[Parameter()] [PSCustomObject] $Card
)
$parameter = @{
Headers = @{ accept = 'application/json' }
Body = $Card | ConvertTo-Json -Compress -Depth 10
Method = 'POST'
URI = $Webhook
}
try
{
$apiResponse = Invoke-RestMethod @parameter
if ($apiResponse -eq 1) { $true }
else
{
$false
"Got response: $apiResponse" | Write-Error
}
}
catch [WebException]
{
Throw "API did not accept request."
}
catch
{
throw "Could not post to Teams. $($Error[0])"
}
}
| dizzi90/PoSh-MSTeams | Function/Send-TeamsCard.ps1 | PowerShell | mit | 1,204 |
$script:ErrorActionPreference = "Stop"
$adminDomain = $ptfpropDomain
$adminName = $ptfpropUser1Name
$adminPassword = $ptfpropUser1Password
$sutVersion = $ptfpropSutVersion
$adminAccount = $adminDomain + "\" + $adminName
if($sutVersion -ge "ExchangeServer2010")
{
$securePassword = ConvertTo-SecureString $adminPassword -AsPlainText -Force
$credential = new-object Management.Automation.PSCredential($adminAccount,$securePassword)
#Invoke function remotely
$ret = invoke-command -computer $serverComputerName -Credential $credential -scriptblock {
param(
[string]$userEmail,
[System.Object]$credential,
[string]$serverComputerName,
[string]$deviceType
)
$connectUri = "http://" + $serverComputerName + "/PowerShell"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectUri -Credential $credential -Authentication Kerberos
Import-PSSession $session -AllowClobber -DisableNameChecking
#Request a remote wipe to the device
$devices = Get-MobileDevice -Mailbox $userEmail
foreach($device in $devices)
{
if($device.DeviceType -eq $deviceType)
{
Clear-MobileDevice -AccountOnly -Identity $device.Identity -NotificationEmailAddresses $userEmail -Confirm:$false
}
}
return $true
}-ArgumentList $userEmail,$credential,$serverComputerName,$deviceType
return $ret
}
else
{
cmd /c "winrs -r:$serverComputerName -u:$adminAccount -p:$adminPassword Powershell Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin;`$devices = Get-ActiveSyncDeviceStatistics -Mailbox $userEmail;foreach(`$device in `$devices){if(`$device.DeviceType -eq '$deviceType'){ Clear-ActiveSyncDevice -Identity `$device.Identity -Confirm:`$false }}"
return $true
} | OfficeDev/Interop-TestSuites | ExchangeActiveSync/Source/MS-ASPROV/Adapter/SUTControlAdapter/Implementation/AccountOnlyWipeData.ps1 | PowerShell | mit | 1,757 |
$errorActionPreference = 'Stop'
Set-StrictMode -Version 'Latest'
<#
.SYNOPSIS
Tests if the package with the given Id is installed.
.PARAMETER ProductId
The ID of the package to test for.
#>
function Test-PackageInstalledById
{
[OutputType([Boolean])]
[CmdletBinding()]
param
(
[String]
$ProductId
)
$uninstallRegistryKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
$uninstallRegistryKeyWow64 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$productEntry = $null
if (-not [String]::IsNullOrEmpty($ProductId))
{
$productEntryKeyLocation = Join-Path -Path $uninstallRegistryKey -ChildPath $ProductId
$productEntry = Get-Item -Path $productEntryKeyLocation -ErrorAction 'SilentlyContinue'
if ($null -eq $productEntry)
{
$productEntryKeyLocation = Join-Path -Path $uninstallRegistryKeyWow64 -ChildPath $ProductId
$productEntry = Get-Item $productEntryKeyLocation -ErrorAction 'SilentlyContinue'
}
}
return ($null -ne $productEntry)
}
<#
.SYNOPSIS
Starts a simple mock http or https file server. Server will stay on and continue to be able
to receive requests until the client calls Stop-Server. The server returns the job object
and an EventWaitHandle object that the client will need to dispose of (by calling Stop-Server)
once it is done sending requests.
.PARAMETER FilePath
The path to the file to add on to the mock file server. Should be an MSI file.
.PARAMETER LogPath
The path to the log file to write output to. This is important for debugging since
most of the work of this function is done within a separate process. Default value
will be in PSScriptRoot.
.PARAMETER Https
Indicates whether the server should use Https. If True then the file server will use Https
and listen on port 'https://localhost:1243'. Otherwise the file server will use Http and
listen on port 'http://localhost:1242'
Default value is False (Http).
#>
function Start-Server
{
[OutputType([Hashtable])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$FilePath,
[String]
$LogPath = (Join-Path -Path $PSScriptRoot -ChildPath 'PackageTestLogFile.txt'),
[System.Boolean]
$Https = $false
)
# Create an event object to let the client know when the server is ready to begin receiving requests.
$fileServerStarted = New-Object -TypeName 'System.Threading.EventWaitHandle' -ArgumentList @($false, [System.Threading.EventResetMode]::ManualReset,
'HttpIntegrationTest.FileServerStarted')
$null = $fileServerStarted.Reset()
<#
The server is run on a separate process so that it can receive requests
while the tests continue to run. It takes in the same parameterss that are passed
in to this function. All helper functions that the server uses have to be
defined within the scope of this script.
#>
$server =
{
param($FilePath, $LogPath, $Https)
<#
.SYNOPSIS
Stops the listener, removes the SSL binding if applicable, and closes the listener.
.PARAMETER HttpListener
The listner to stop and close.
.PARAMETER Https
Indicates whether https was used and if so, removes the SSL binding.
#>
function Stop-Listener
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Net.HttpListener]
$HttpListener,
[Parameter(Mandatory = $true)]
[System.Boolean]
$Https
)
Write-Log -LogFile $LogPath -Message 'Finished listening for requests. Shutting down HTTP server.'
$ipPort = '0.0.0.0:1243'
if ($null -eq $HttpListener)
{
$errorMessage = 'HttpListener was null when trying to close'
Write-Log -LogFile $LogPath -Message $errorMessage
if ($Https)
{
Invoke-ConsoleCommand -Target $ipPort -Action 'removing SSL certificate binding' -ScriptBlock {
netsh http delete sslcert ipPort="$ipPort"
}
}
throw $errorMessage
}
if ($HttpListener.IsListening)
{
Write-Log -LogFile $LogPath -Message 'HttpListener is about to be stopped'
$HttpListener.Stop()
}
if ($Https)
{
Write-Log -LogFile $LogPath -Message 'Removing SSL binding'
# Remove SSL Binding
Invoke-ConsoleCommand -Target $ipPort -Action 'removing SSL certificate binding' -ScriptBlock {
netsh http delete sslcert ipPort="$ipPort"
}
}
Write-Log -LogFile $LogPath -Message 'Closing listener'
$HttpListener.Close()
$null = netsh advfirewall set allprofiles state on
}
<#
.SYNOPSIS
Creates and registers an SSL certificate for Https connections.
#>
function Register-Ssl
{
[CmdletBinding()]
param()
# Create certificate
$certificate = New-SelfSignedCertificate -CertStoreLocation 'Cert:\LocalMachine\My' -DnsName localhost
Write-Log -LogFile $LogPath -Message 'Created certificate'
$hash = $certificate.Thumbprint
$certPassword = ConvertTo-SecureString -String 'password12345' -AsPlainText -Force
$tempPath = 'C:\certForTesting'
$null = Export-PfxCertificate -Cert $certificate -FilePath $tempPath -Password $certPassword
$null = Import-PfxCertificate -CertStoreLocation 'Cert:\LocalMachine\Root' -FilePath 'C:\certForTesting' -Password $certPassword
Remove-Item -Path $tempPath
Write-Log -LogFile $LogPath -Message 'Finished importing certificate into root. About to bind it to port.'
# Use net shell command to directly bind certificate to designated testing port
$null = netsh http add sslcert ipport=0.0.0.0:1243 certhash=$hash appid='{833f13c2-319a-4799-9d1a-5b267a0c3593}' clientcertnegotiation=enable
}
<#
.SYNOPSIS
Defines the callback function required for BeginGetContext.
.PARAMETER Callback
The callback script - in this case the requestListener script defined below.
#>
function New-ScriptBlockCallback
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ScriptBlock]
$Callback
)
# Add the CallbackEventBridge type if it's not already defined
if (-not ('CallbackEventBridge' -as [Type]))
{
Add-Type @'
using System;
public sealed class CallbackEventBridge {
public event AsyncCallback CallbackComplete = delegate { };
private CallbackEventBridge() {}
private void CallbackInternal(IAsyncResult result)
{
CallbackComplete(result);
}
public AsyncCallback Callback
{
get { return new AsyncCallback(CallbackInternal); }
}
public static CallbackEventBridge Create()
{
return new CallbackEventBridge();
}
}
'@
}
$bridge = [CallbackEventBridge]::Create()
Register-ObjectEvent -InputObject $bridge -EventName 'CallbackComplete' -Action $Callback -MessageData $args > $null
$bridge.Callback
Write-Log -LogFile $LogPath -Message 'Finished callback function'
}
<#
.SYNOPSIS
Invokes a console command and captures the exit code.
.PARAMETER Target
Where the command is being executed.
.PARAMETER Action
A description of the action being performed.
.PARAMETER ScriptBlock
The code to execute.
#>
function Invoke-ConsoleCommand
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[String]
$Target,
[Parameter(Mandatory = $true)]
[String]
$Action,
[Parameter(Mandatory = $true)]
[ScriptBlock]
$ScriptBlock
)
$output = Invoke-Command -ScriptBlock $ScriptBlock
if ($LASTEXITCODE)
{
$output = $output -join [Environment]::NewLine
$message = ('Failed action ''{0}'' on target ''{1}'' (exit code {2}): {3}' -f $Action,$Target,$LASTEXITCODE,$output)
Write-Error -Message $message
Write-Log -LogFile $LogPath -Message "Error from Invoke-ConsoleCommand: $message"
}
else
{
$nonNullOutput = $output | Where-Object { $_ -ne $null }
Write-Log -LogFile $LogPath -Message "Output from Invoke-ConsoleCommand: $nonNullOutput"
}
}
<#
.SYNOPSIS
Writes the specified message to the specified log file.
Does NOT overwrite what is already written there.
.PARAMETER LogFile
The path to the file to write to.
.PARAMETER Message
The message to write to the file.
#>
function Write-Log
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[String]
$LogFile,
[Parameter(Mandatory = $true)]
[String]
$Message
)
$Message >> $LogFile
}
# End of function declarations - Beginning of function execution
if ($null -eq (Get-NetFirewallRule -DisplayName 'UnitTestRule' -ErrorAction 'SilentlyContinue'))
{
$null = New-NetFirewallRule -DisplayName 'UnitTestRule' -Direction 'Inbound' -Program "$PSHome\powershell.exe" -Authentication 'NotRequired' -Action 'Allow'
}
$null = netsh advfirewall set allprofiles state off
Write-Log -LogFile $LogPath -Message (Get-Date)
$HttpListener = New-Object 'System.Net.HttpListener'
$fileServerStarted = $null
try
{
# Set up the listener
if ($Https)
{
$HttpListener.Prefixes.Add([Uri]'https://localhost:1243')
try
{
Register-SSL
}
catch
{
$errorMessage = "Unable to bind SSL certificate to port. Error: $_"
Write-Log -LogFile $LogPath -Message $errorMessage
throw $errorMessage
}
Write-Log -LogFile $LogPath -Message 'Certificate is registered'
}
else
{
$HttpListener.Prefixes.Add([Uri]'http://localhost:1242')
}
Write-Log -LogFile $LogPath -Message 'Finished listener setup - about to start listener'
$HttpListener.Start()
# Cue the tests that the listener is started and can begin receiving requests
$fileServerStarted = New-Object -TypeName 'System.Threading.EventWaitHandle' `
-ArgumentList @($false,
[System.Threading.EventResetMode]::AutoReset,
'HttpIntegrationTest.FileServerStarted'
)
$fileServerStarted.Set()
Write-Log -LogFile $LogPath -Message 'Listener is started'
<#
.SYNOPSIS
Script block called by the callback function for BeginGetContext.
Ends the current BeginGetContext, copies the response, and calls BeginGetContext again
to continue receiving requests.
.PARAMETER Result
th IAsyncResult containing the listener object and path to the MSI file.
#>
$requestListener =
{
[CmdletBinding()]
param
(
[IAsyncResult]
$Result
)
Write-Log -LogFile $LogPath -Message 'Starting request listener'
$asyncState = $Result.AsyncState
[System.Net.HttpListener]$listener = $asyncState.Listener
$filepath = $asyncState.FilePath
Write-Log -LogFile $LogPath -Message (ConvertTo-Json $asyncState)
# Call EndGetContext to complete the asynchronous operation.
$context = $listener.EndGetContext($Result)
$response = $null
try
{
# Prepare binary buffer for http/https response
$fileInfo = New-Object -TypeName 'System.IO.FileInfo' -ArgumentList @( $filePath )
$numBytes = $fileInfo.Length
$fileStream = New-Object -TypeName 'System.IO.FileStream' -ArgumentList @( $filePath, 'Open' )
$binaryReader = New-Object -TypeName 'System.IO.BinaryReader' -ArgumentList @( $fileStream )
[Byte[]] $buf = $binaryReader.ReadBytes($numBytes)
$fileStream.Close()
Write-Log -LogFile $LogPath -Message 'Buffer prepared for response'
$response = $context.Response
$response.ContentType = 'application/octet-stream'
$response.ContentLength64 = $buf.Length
$response.OutputStream.Write($buf, 0, $buf.Length)
Write-Log -LogFile $LogPath -Message 'Response written'
$response.OutputStream.Flush()
# Open the response stream again to receive more requests
$listener.BeginGetContext((New-ScriptBlockCallback -Callback $requestListener), $asyncState)
}
catch
{
$errorMessage = "error writing response: $_"
Write-Log -LogFile $LogPath -Message $errorMessage
throw $errorMessage
}
finally
{
if ($null -ne $response)
{
$response.Dispose()
}
}
}
# Register the request listener scriptblock as the async callback
$HttpListener.BeginGetContext((New-ScriptBlockCallback -Callback $requestListener), @{ Listener = $Httplistener; FilePath = $FilePath }) | Out-Null
Write-Log -LogFile $LogPath -Message 'First BeginGetContext called'
# Ensure that the request listener stays on until the server is done receiving responses - client is responsible for stopping the server.
while ($true)
{
Start-Sleep -Milliseconds 100
}
}
catch
{
$errorMessage = "There were problems setting up the HTTP(s) listener. Error: $_"
Write-Log -LogFile $LogPath -Message $errorMessage
throw $errorMessage
}
finally
{
if ($fileServerStarted)
{
$fileServerStarted.Dispose()
}
Write-Log -LogFile $LogPath -Message 'Stopping the Server'
Stop-Listener -HttpListener $HttpListener -Https $Https
}
}
$job = Start-Job -ScriptBlock $server -ArgumentList @( $FilePath, $LogPath, $Https )
<#
Return the event object so that client knows when it can start sending requests and
the job object so that the client can stop the job once it is done sending requests.
#>
return @{
FileServerStarted = $fileServerStarted
Job = $job
}
}
<#
.SYNOPSIS
Disposes the EventWaitHandle object and stops and removes the job to ensure that proper
cleanup is done for the listener. If this function is not called after Start-Server then
the listening port will remain open until the job is stopped or the machine is rebooted.
.PARAMETER FileServerStarted
The EventWaitHandle object returned by Start-Server to let the client know that it is ready
to receive requests. The client is responsible for calling this function to ensure that
this object is disposed of once the client is done sending requests.
.PARAMETER Job
The job object returned by Start-Server that needs to be stopped so that the server will
close the listening port.
#>
function Stop-Server
{
[CmdletBinding()]
param
(
[System.Threading.EventWaitHandle]
$FileServerStarted,
[System.Management.Automation.Job]
$Job
)
if ($null -ne $FileServerStarted)
{
$FileServerStarted.Dispose()
}
if ($null -ne $Job)
{
Stop-Job -Job $Job
Remove-Job -Job $Job
}
}
<#
.SYNOPSIS
Creates a new MSI package for testing.
.PARAMETER DestinationPath
The path at which to create the test msi file.
#>
function New-TestMsi
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$DestinationPath
)
#region msiContentInBase64
$msiContentInBase64 = '0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgAEAP7/DAAGAAAAAAAAAAEAAAABAAAAAQA' + `
'AAAAAAAAAEAAAAgAAAAEAAAD+////AAAAAAAAAAD/////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'////////////////////8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP3////+/////v///wYAAAD+////BAAAAP7////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'////////////////////////////////////////////////////////////9SAG8AbwB0ACAARQBuAHQAcgB' + `
'5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgAFAP//////////CQAAAIQQ' + `
'DAAAAAAAwAAAAAAAAEYAAAAAAAAAAAAAAADwRqG1qh/OAQMAAAAAEwAAAAAAAA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
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + `
'AA////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQA' + `
'AAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAD+////CgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEA' + `
'AAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAACAAAAAhA' + `
'AAAIgAAACMAAAAkAAAAJQAAAP7////+/////v////7////+/////v////7////+////LgAAAP7////+/////v' + `
'////7////+/////v////7///82AAAANwAAADgAAAA5AAAAOgAAADsAAAA8AAAAPQAAAD4AAAD+////QAAAAEE' + `
'AAABCAAAAQwAAAEQAAABFAAAARgAAAEcAAABIAAAASQAAAEoAAABLAAAA/v//////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'/////////////////////////////////////////////////////////////////////////////////////' + `
'///////////////////7/AAAGAQIAAAAAAAAAAAAAAAAAAAAAAAEAAADghZ/y+U9oEKuRCAArJ7PZMAAAAAwC' + `
'AAAOAAAAAQAAAHgAAAACAAAAgAAAAAMAAACgAAAABAAAAMQAAAAFAAAA9AAAAAYAAAAIAQAABwAAAGwBAAAJA' + `
'AAAgAEAAAwAAACwAQAADQAAALwBAAAOAAAAyAEAAA8AAADQAQAAEgAAANgBAAATAAAABAIAAAIAAADkBAAAHg' + `
'AAABYAAABJbnN0YWxsYXRpb24gRGF0YWJhc2UAAAAeAAAAGwAAAEEgcGFja2FnZSBmb3IgdW5pdCB0ZXN0aW5' + `
'nAAAeAAAAKAAAAE1pY3Jvc29mdCBVbml0IFRlc3RpbmcgR3VpbGQgb2YgQW1lcmljYQAeAAAACgAAAEluc3Rh' + `
'bGxlcgAAAB4AAABcAAAAVGhpcyBpbnN0YWxsZXIgZGF0YWJhc2UgY29udGFpbnMgdGhlIGxvZ2ljIGFuZCBkY' + `
'XRhIHJlcXVpcmVkIHRvIGluc3RhbGwgRFNDVW5pdFRlc3RQYWNrYWdlLgAeAAAACwAAAEludGVsOzEwMzMAAB' + `
'4AAAAnAAAAe0YxN0FGREExLUREMEItNDRFNi1CNDczLTlFQkUyREJEOUVBOX0AAEAAAAAAAOO0qh/OAUAAAAA' + `
'AAOO0qh/OAQMAAADIAAAAAwAAAAIAAAAeAAAAIwAAAFdpbmRvd3MgSW5zdGFsbGVyIFhNTCAoMy43LjEyMDQu' + `
'MCkAAAMAAAACAAAAAAAAAAYABgAGAAYABgAGAAYABgAGAAYACgAKACIAIgAiACkAKQApACoAKgAqACsAKwArA' + `
'CsAKwArADEAMQAxAD4APgA+AD4APgA+AD4APgBNAE0AUgBSAFIAUgBSAFIAUgBSAGAAYABgAGEAYQBhAGIAYg' + `
'BmAGYAZgBmAGYAZgByAHIAdg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VzICh3aXRoIHRoZSBkZWNpbWFsIHZhbHVlIG9mIGVhY2ggYml0IHBvc2l0aW9uIGluIHB' + `
'hcmVudGhlc2VzKVNlcXVlbmNlIHdpdGggcmVzcGVjdCB0byB0aGUgbWVkaWEgaW1hZ2VzOyBvcmRlciBtdXN0' + `
'IHRyYWNrIGNhYmluZXQgb3JkZXIuSW5zdGFsbEV4ZWN1dGVTZXF1ZW5jZUluc3RhbGxVSVNlcXVlbmNlTGF1b' + `
'mNoQ29uZGl0aW9uRXhwcmVzc2lvbiB3aGljaCBtdXN0IGV2YWx1YXRlIHRvIFRSVUUgaW4gb3JkZXIgZm9yIG' + `
'luc3RhbGwgdG8gY29tbWVuY2UuRm9ybWF0dGVkTG9jYWxpemFibGUgdGV4dCB0byBkaXNwbGF5IHdoZW4gY29' + `
'uZGl0aW9uIGZhaWxzIGFuZCBpbnN0YWxsIG11c3QgYWJvcnQuTWVkaWFEaXNrSWRQcmltYXJ5IGtleSwgaQgA' + `
'AgAIAAIACAACAAoAFgANAAEADgABAAMAAQAeAAEAAQAnABUAAQAVAAEANgABACQAAQD1AAEADwABAAQACQAgA' + `
'AEAFQABABQABwAGAAoAQgAFAAkAFQCfAAUACAAMAG8ABQAPAAcAEwAHAAkAEgA7AAEACwACAAQAAgA+AAEACg' + `
'AEAAkADADSAAEACgAIACcAAQDoAAEABwACABwAAQDjAAEAhgABABAAAgCmAAEACgADACkAAQAHABUAOQABAA4' + `
'AAgCUAAEABQACAC4AAQA6AAEABwACAD4AAQAFAAIAgQABAAkAAgBrAAEAUQABABIAAQARAAUACAACAB8AAQAK' + `
'AAYAIQABAAQAFABzAAEAOQABAAgAAgAIAAEAYwABAAgAAgAlAAEABwADAEEAAQAIAAYAPwABAHYAAQBKAAEAF' + `
'gAHABEABwAPAAUASAABAAkABABIAAEABQANAAYAAgA3AAEADAACADYAAQAKAAIAhAABAAcAAwBmAAEACwACAC' + `
'MAAQAGAAIACAAIADcAAQA+AAEAMAABAAgADwAhAAEABA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+ `
'AAAAAAAAAAAAAAAAAAA='
#endregion
$msiContentInBytes = [System.Convert]::FromBase64String($msiContentInBase64)
Set-Content -Path $DestinationPath -Value $msiContentInBytes -Encoding 'Byte' | Out-Null
}
<#
.SYNOPSIS
Clears the Package cache where files are downloaded from the file server when applicable.
#>
function Clear-PackageCache
{
[CmdletBinding()]
param ()
$packageCacheLocation = "$env:ProgramData\Microsoft\Windows\PowerShell\Configuration\" + `
'BuiltinProvCache\MSFT_xPackageResource'
Remove-Item -Path $packageCacheLocation -ErrorAction 'SilentlyContinue' -Recurse
}
<#
.SYNOPSIS
Tests if the package with the given name is installed.
.PARAMETER Name
The name of the package to test for.
#>
function Test-PackageInstalledByName
{
[OutputType([Boolean])]
[CmdletBinding()]
param
(
[String]
$Name
)
$uninstallRegistryKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
$uninstallRegistryKeyWow64 = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$productEntry = $null
foreach ($registryKeyEntry in (Get-ChildItem -Path @( $uninstallRegistryKey, $uninstallRegistryKeyWow64) -ErrorAction 'Ignore' ))
{
if ($Name -eq (Get-LocalizedRegistryKeyValue -RegistryKey $registryKeyEntry -ValueName 'DisplayName'))
{
$productEntry = $registryKeyEntry
break
}
}
return ($null -ne $productEntry)
}
<#
.SYNOPSIS
Retrieves a localized registry key value.
.PARAMETER RegistryKey
The registry key to retrieve the value from.
.PARAMETER ValueName
The name of the value to retrieve.
#>
function Get-LocalizedRegistryKeyValue
{
[CmdletBinding()]
param
(
[Object]
$RegistryKey,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$ValueName
)
$localizedRegistryKeyValue = $RegistryKey.GetValue('{0}_Localized' -f $ValueName)
if ($null -eq $localizedRegistryKeyValue)
{
$localizedRegistryKeyValue = $RegistryKey.GetValue($ValueName)
}
return $localizedRegistryKeyValue
}
<#
.SYNOPSIS
Mimics a simple http or https file server.
Used only by the xPackage resource - xMsiPackage uses Start-Server instead
.PARAMETER FilePath
The path to the file to add on the mock file server.
.PARAMETER Https
Indicates that the new file server should use https.
Otherwise the new file server will use http.
Https functionality is not currently implemented in
this function - Start-Server should be used instead.
#>
function New-MockFileServer
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$FilePath,
[Switch]
$Https
)
if ($null -eq (Get-NetFirewallRule -DisplayName 'UnitTestRule' -ErrorAction 'SilentlyContinue'))
{
$null = New-NetFirewallRule -DisplayName 'UnitTestRule' -Direction 'Inbound' -Program "$PSHome\powershell.exe" -Authentication 'NotRequired' -Action 'Allow'
}
netsh advfirewall set allprofiles state off
Start-Job -ArgumentList @( $FilePath ) -ScriptBlock {
# Create certificate
$certificate = Get-ChildItem -Path 'Cert:\LocalMachine\My' -Recurse | Where-Object { $_.EnhancedKeyUsageList.FriendlyName -eq 'Server Authentication' }
if ($certificate.Count -gt 1)
{
# Just use the first one
$certificate = $certificate[0]
}
elseif ($certificate.count -eq 0)
{
# Create a self-signed one
$certificate = New-SelfSignedCertificate -CertStoreLocation 'Cert:\LocalMachine\My' -DnsName $env:computerName
}
$hash = $certificate.Thumbprint
# Use net shell command to directly bind certificate to designated testing port
netsh http add sslcert ipport=0.0.0.0:1243 certhash=$hash appid='{833f13c2-319a-4799-9d1a-5b267a0c3593}' clientcertnegotiation=enable
# Start listening endpoints
$httpListener = New-Object -TypeName 'System.Net.HttpListener'
if ($Https)
{
$httpListener.Prefixes.Add([Uri]'https://localhost:1243')
}
else
{
$httpListener.Prefixes.Add([Uri]'http://localhost:1242')
}
$httpListener.AuthenticationSchemes = [System.Net.AuthenticationSchemes]::Negotiate
$httpListener.Start()
# Create a pipe to flag http/https client
$pipe = New-Object -TypeName 'System.IO.Pipes.NamedPipeClientStream' -ArgumentList @( '\\.\pipe\dsctest1' )
$pipe.Connect()
$pipe.Dispose()
# Prepare binary buffer for http/https response
$fileInfo = New-Object -TypeName 'System.IO.FileInfo' -ArgumentList @( $args[0] )
$numBytes = $fileInfo.Length
$fileStream = New-Object -TypeName 'System.IO.FileStream' -ArgumentList @( $args[0], 'Open' )
$binaryReader = New-Object -TypeName 'System.IO.BinaryReader' -ArgumentList @( $fileStream )
[Byte[]] $buf = $binaryReader.ReadBytes($numBytes)
$fileStream.Close()
# Send response
$response = ($httpListener.GetContext()).Response
$response.ContentType = 'application/octet-stream'
$response.ContentLength64 = $buf.Length
$response.OutputStream.Write($buf, 0, $buf.Length)
$response.OutputStream.Flush()
# Wait for client to finish downloading
$pipe = New-Object -TypeName 'System.IO.Pipes.NamedPipeServerStream' -ArgumentList @( '\\.\pipe\dsctest2' )
$pipe.WaitForConnection()
$pipe.Dispose()
$response.Dispose()
$httpListener.Stop()
$httpListener.Close()
# Close pipe
# Use net shell command to clean up the certificate binding
netsh http delete sslcert ipport=0.0.0.0:1243
}
netsh advfirewall set allprofiles state on
}
<#
.SYNOPSIS
Creates a new test executable.
.PARAMETER DestinationPath
The path at which to create the test executable.
#>
function New-TestExecutable
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$DestinationPath
)
if (Test-Path -Path $DestinationPath)
{
Write-Verbose -Message "Removing old executable at $DestinationPath..."
Remove-Item -Path $DestinationPath -Force
}
$testExecutableCode = @'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Runtime.InteropServices;
namespace Providers.Package.UnitTests.MySuite
{
class ExeTestClass
{
public static void Main(string[] args)
{
string cmdline = System.Environment.CommandLine;
Console.WriteLine("Cmdline was " + cmdline);
int endIndex = cmdline.IndexOf("\"", 1);
string self = cmdline.Substring(0, endIndex);
string other = cmdline.Substring(self.Length + 1);
string msiexecpath = System.IO.Path.Combine(System.Environment.SystemDirectory, "msiexec.exe");
self = self.Replace("\"", "");
string packagePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(self), "DSCSetupProject.msi");
string msiexecargs = String.Format("/i {0} {1}", packagePath, other);
System.Diagnostics.Process.Start(msiexecpath, msiexecargs).WaitForExit();
}
}
}
'@
Add-Type -TypeDefinition $testExecutableCode -OutputAssembly $DestinationPath -OutputType 'ConsoleApplication'
}
Export-ModuleMember -Function `
New-TestMsi, `
Clear-PackageCache, `
New-TestExecutable, `
New-MockFileServer, `
Start-Server, `
Stop-Server, `
Test-PackageInstalledByName, `
Test-PackageInstalledById
| mgreenegit/xPSDesiredStateConfiguration | Tests/MSFT_xPackageResource.TestHelper.psm1 | PowerShell | mit | 78,440 |
[CmdletBinding()]
Param
(
[switch] $Preview,
[ValidateSet('2017', '2019', '2022')] [string] $VisualStudioYear = '2017'
)
Set-StrictMode -Version 5
#Requires -Version 5
$ErrorActionPreference = 'Stop'
$InformationPreference = 'Continue'
$repoRoot = Split-Path -Parent -Path (Split-Path -Parent -Path $PSScriptRoot)
if ((Get-Module -Name AU -ErrorAction SilentlyContinue | Measure-Object).Count -eq 0)
{
Import-Module -Name "$repoRoot\au\AU\AU.psm1" -Alias @() -Function *
}
# Wraps Get-RemoteChecksum from AU, with different progress indication
# (progress shown by Invoke-WebRequest slows it down tremendously).
# Note that we cannot simply call Get-RemoteChecksum because preference variables
# do not flow into module functions by default.
function Get-RemoteChecksumFast([string] $Url, $Algorithm='sha256', $Headers)
{
$ProgressPreference = 'SilentlyContinue'
& (Get-Command -Name Get-RemoteChecksum -Module AU).ScriptBlock.GetNewClosure() @PSBoundParameters
}
function Invoke-WebRequestAcceptingAllStatusCodes
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory = $true)] [Uri] $Uri,
[switch] $UseBasicParsing,
[int] $MaximumRedirection
)
try
{
# There is a subtle difference in behavior between $ErrorActionPreference and -ErrorAction.
# We want to suppress errors returned by Invoke-WebRequest in Win PS for 3xx responses
# (so pass -ErrorAction SilentlyContinue), but still detect and throw more serious errors
# such as DNS resolution failures (those would be suppressed if $ErrorActionPreference was
# more lax, such as when _our caller_ passed -ErrorAction SilentlyContinue).
# More info: https://github.com/MicrosoftDocs/PowerShell-Docs/issues/1583
$iwrArgs = $PSBoundParameters.PSObject.Copy()
[void]$iwrArgs.Remove('ErrorAction')
$ea = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try
{
$res = Microsoft.PowerShell.Utility\Invoke-WebRequest @iwrArgs -ErrorAction SilentlyContinue
}
finally
{
$ErrorActionPreference = $ea
}
}
catch
{
$x = $_.Exception
# duck typing FTW: in PS Core x is HttpResponseException, in Win PS x is WebException
if ($null -ne $x.PSObject.Properties['Response'] -and $null -ne $x.Response)
{
$res = $x.Response
}
else
{
# respect user preference, so that if we are called with -ErrorAction SilentlyContinue no error is raised
Write-Error $_
return $null
}
}
return $res
}
function global:au_SearchReplace
{
@{
"tools\ChocolateyInstall.ps1" = @{
"(^\s*-Url\s+)('.*')" = "`$1'$($Latest.BootstrapperUrl)'"
"(^\s*-Checksum\s+)('.*')" = "`$1'$($Latest.BootstrapperChecksum)'"
}
"$($Latest.PackageName).nuspec" = @{
"^\d+\.\d+\.\d+\.\d+(-[a-z]+\d*)?\:$" = "$($Latest.Version):"
"(?:(?:(?:Package\smetadata\supdated)|(?:Initial\spackage\srelease))\sfor\sVisual\sStudio\s(\d+)\sversion\s)(?:[^(]+)" = "Package metadata updated for Visual Studio `${1} version $($Latest.ProductDisplayVersion) "
}
}
}
function global:au_BeforeUpdate() {
$Latest.BootstrapperChecksum = (Get-RemoteChecksumFast -Url $Latest.BootstrapperUrl).ToUpperInvariant()
}
function global:au_AfterUpdate() {
# fix BOM stripped by AU
$c = Get-Content -Path "$($Latest.PackageName).nuspec" -Encoding UTF8
$c | Set-Content -Path "$($Latest.PackageName).nuspec" -Encoding (@{ Core = 'utf8BOM'; Desktop = 'UTF8' }[$PSVersionTable.PSEdition])
}
function global:au_GetLatest
{
$product = ((Split-Path -Leaf -Path (Get-Location)) -replace "visualstudio${VisualStudioYear}", '') -replace '-preview', ''
$akaUrl = 'https://aka.ms/vs/{0}/{1}/vs_{2}.exe' -f $script:vsMajorVersion, $script:channelUrlToken, $product
$res = Invoke-WebRequestAcceptingAllStatusCodes -Uri $akaUrl -UseBasicParsing -MaximumRedirection 0
if ($res.StatusCode -ne 301 -and $res.StatusCode -ne 302)
{
$res | Format-List -Property * | Out-String | Write-Warning
Write-Error "Unable to resolve url $akaUrl"
}
else
{
$url = $res.Headers.Location
if ($url -eq 'https://www.microsoft.com')
{
throw "File '$akaUrl' redirects to www.microsoft.com"
}
}
$version = $script:visualStudioProductVersion
$displayVersion = $script:visualStudioProductDisplayVersion
# Packages which always install the latest VS version get major version = 100 + VS major version,
# to leave the VS major version free for use by packages which install the exact VS version.
# Since this is a rather major change of the versioning philosophy (pun not intended),
# it is done only for VS 2022+ for now.
if ($script:vsMajorVersion -ge 17)
{
$packageVersionThreeParts = [version]::new(100 + $script:visualStudioProductVersion.Major, $script:visualStudioProductVersion.Minor, $script:visualStudioProductVersion.Build)
$packageVersion = "${packageVersionThreeParts}${script:packageVersionSuffix}"
}
else
{
$packageVersion = "${version}${script:packageVersionSuffix}"
}
return @{ Version = $packageVersion; Product = $product; ProductVersion = $version; ProductDisplayVersion = $displayVersion; BootstrapperUrl = $url; BootstrapperChecksum = '' }
}
function Get-VSVersion
{
$channelUri = 'https://aka.ms/vs/{0}/{1}/channel' -f $script:vsMajorVersion, $script:channelUrlToken
$res = Invoke-WebRequest -Uri $channelUri -UseBasicParsing
$channelManifest = ConvertFrom-Json ([Text.Encoding]::UTF8.GetString($res.Content))
$productDisplayVersion = $channelManifest.info.productDisplayVersion
$version = [version](($productDisplayVersion -split ' ')[0])
if ($null -ne $channelManifest.info.PSObject.Properties['productReleaseNameSuffix'])
{
$productReleaseNameSuffix = $channelManifest.info.productReleaseNameSuffix
}
else
{
$productReleaseNameSuffix = $null
}
Write-Output $version
Write-Output $productDisplayVersion
Write-Output ([version]$channelManifest.info.productPreReleaseMilestoneSuffix)
Write-Output $productReleaseNameSuffix
}
$dirSuffix = @{ $true = '-preview'; $false = '' }[$Preview.ToBool()]
$channelUrlToken = @{ $true = 'pre'; $false = 'release' }[$Preview.ToBool()]
$vsMajorVersion = @{ '2017' = 15; '2019' = 16; '2022' = 17 }[$VisualStudioYear]
$mainProducts = @('BuildTools','Community','Enterprise','FeedbackClient','Professional','SQL','TeamExplorer','TestAgent','TestController','TestProfessional')
$visualStudioProductVersion, $visualStudioProductDisplayVersion, $productPreReleaseMilestoneSuffix, $productReleaseNameSuffix = Get-VSVersion
Write-Information "Current published Visual Studio version: $visualStudioProductVersion ('$visualStudioProductDisplayVersion', milestone: $productPreReleaseMilestoneSuffix, release name suffix: $productReleaseNameSuffix)"
if ($Preview)
{
$packageVersionSuffix = ('.{0}-preview1' -f ($productPreReleaseMilestoneSuffix.Major * 10000 + $productPreReleaseMilestoneSuffix.Minor * 100))
}
else
{
if ($null -eq $productReleaseNameSuffix -or $productReleaseNameSuffix -notmatch '^RC')
{
$packageVersionSuffix = '.0'
}
else
{
if ($productReleaseNameSuffix -match '^RC(\.?(?<rcn>\d+))?(\s+SVC(?<svcn>\d+))?')
{
$rcn = [int]$matches['rcn']
$svcn = [int]$matches['svcn']
$packageVersionSuffix = ('.0-rc{0}' -f ($rcn * 10000 + $svcn * 100))
}
else
{
throw "Unable to match RC productReleaseNameSuffix: [$productReleaseNameSuffix]"
}
}
}
foreach ($product in $mainProducts)
{
$dirPath = "$repoRoot\visualstudio${VisualStudioYear}$($product.ToLowerInvariant())$dirSuffix"
if ((Test-Path -Path $dirPath) -and (-not (Test-Path -Path "$dirPath\disabled.marker")))
{
Write-Information "Processing package for product: $product"
Push-Location -Path $dirPath
try
{
AU\Update-Package -ChecksumFor none
}
finally
{
Pop-Location
}
}
}
| jberezanski/ChocolateyPackages | tools/VS2017/Update-VisualStudio2017Packages.ps1 | PowerShell | mit | 8,365 |
function Get-ADSIFsmo
{
<#
.SYNOPSIS
This function will query Active Directory for all the Flexible Single Master Operation (FSMO) role owner.
.PARAMETER Credential
Specify the Credential to use
.PARAMETER DomainDistinguishedName
Specify the DistinguishedName of the Domain to query
.PARAMETER SizeLimit
Specify the number of item(s) to output.
Default is 100.
.NOTES
Francois-Xavier Cat
LazyWinAdmin.com
@lazywinadm
#>
[CmdletBinding()]
PARAM (
[Parameter()]
[Alias("Domain", "DomainDN")]
[String]$DomainDistinguishedName = $(([adsisearcher]"").Searchroot.path),
[Alias("RunAs")]
[System.Management.Automation.Credential()]
$Credential = [System.Management.Automation.PSCredential]::Empty,
[Alias("ResultLimit", "Limit")]
[int]$SizeLimit = '100'
)
BEGIN { }
PROCESS
{
TRY
{
# Building the basic search object with some parameters
$Search = New-Object -TypeName System.DirectoryServices.DirectorySearcher -ErrorAction 'Stop'
$Search.SizeLimit = $SizeLimit
$Search.Filter = "((fSMORoleOwner=*))"
IF ($PSBoundParameters['DomainDistinguishedName'])
{
IF ($DomainDistinguishedName -notlike "LDAP://*") { $DomainDistinguishedName = "LDAP://$DomainDistinguishedName" }#IF
Write-Verbose -Message "[PROCESS] Different Domain specified: $DomainDistinguishedName"
$Search.SearchRoot = $DomainDistinguishedName
}
IF ($PSBoundParameters['Credential'])
{
Write-Verbose -Message "[PROCESS] Different Credential specified: $($credential.username)"
$Cred = New-Object -TypeName System.DirectoryServices.DirectoryEntry -ArgumentList $DomainDistinguishedName, $($Credential.UserName), $($Credential.GetNetworkCredential().password)
$Search.SearchRoot = $Cred
}
If (-not $PSBoundParameters["SizeLimit"])
{
Write-Warning -Message "Default SizeLimit: 100 Results"
}
foreach ($FSMO in $($Search.FindAll()))
{
# Define the properties
# The properties need to be lowercase!!!!!!!!
$FSMO.properties
# Output the info
#New-Object -TypeName PSObject -Property $Properties
<#
#'PDC FSMO
(&(objectClass=domainDNS)(fSMORoleOwner=*))
#'Rid FSMO
(&(objectClass=rIDManager)(fSMORoleOwner=*))
#'Infrastructure FSMO
(&(objectClass=infrastructureUpdate)(fSMORoleOwner=*))
#'Schema FSMO
(&(objectClass=dMD)(fSMORoleOwner=*))
OR [DirectoryServices.ActiveDirectory.ActiveDirectorySchema]::GetCurrentSchema().SchemaRoleOwner
'Domain Naming FSMO
(&(objectClass=crossRefContainer)(fSMORoleOwner=*))
#>
}
}#TRY
CATCH
{
$pscmdlet.ThrowTerminatingError($_)
}
}#PROCESS
END
{
Write-Verbose -Message "[END] Function Get-ADSIFsmo End."
}
} | lazywinadmin/AdsiPS | Archives/Get-ADSIFsmo.ps1 | PowerShell | mit | 3,102 |
function Get-CPowershellPath
{
<#
.SYNOPSIS
Gets the path to powershell.exe.
.DESCRIPTION
Returns the path to the powershell.exe binary for the machine's default architecture (i.e. x86 or x64). If you're on a x64 machine and want to get the path to x86 PowerShell, set the `x86` switch.
Here are the possible combinations of operating system, PowerShell, and desired path architectures, and the path they map to.
+-----+-----+------+--------------------------------------------------------------+
| OS | PS | Path | Result |
+-----+-----+------+--------------------------------------------------------------+
| x64 | x64 | x64 | $env:windir\System32\Windows PowerShell\v1.0\powershell.exe |
| x64 | x64 | x86 | $env:windir\SysWOW64\Windows PowerShell\v1.0\powershell.exe |
| x64 | x86 | x64 | $env:windir\sysnative\Windows PowerShell\v1.0\powershell.exe |
| x64 | x86 | x86 | $env:windir\SysWOW64\Windows PowerShell\v1.0\powershell.exe |
| x86 | x86 | x64 | $env:windir\System32\Windows PowerShell\v1.0\powershell.exe |
| x86 | x86 | x86 | $env:windir\System32\Windows PowerShell\v1.0\powershell.exe |
+-----+-----+------+--------------------------------------------------------------+
.EXAMPLE
Get-CPowerShellPath
Returns the path to the version of PowerShell that matches the computer's architecture (i.e. x86 or x64).
.EXAMPLE
Get-CPowerShellPath -x86
Returns the path to the x86 version of PowerShell.
#>
[CmdletBinding()]
param(
# Gets the path to 32-bit PowerShell.
[switch]$x86,
[switch]$NoWarn
)
Set-StrictMode -Version 'Latest'
Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState
if( -not $NoWarn )
{
Write-CRefactoredCommandWarning -CommandName $MyInvocation.MyCommand.Name -ModuleName 'Carbon.Core'
}
$psPath = $PSHOME
if( (Test-COSIs64Bit -NoWarn) )
{
if( (Test-CPowerShellIs64Bit -NoWarn) )
{
if( $x86 )
{
# x64 OS, x64 PS, want x86 path
$psPath = $PSHOME -replace 'System32','SysWOW64'
}
}
else
{
if( -not $x86 )
{
# x64 OS, x32 PS, want x64 path
$psPath = $PSHome -replace 'SysWOW64','sysnative'
}
}
}
else
{
# x86 OS, no SysWOW64, everything is in $PSHOME
$psPath = $PSHOME
}
Join-Path $psPath powershell.exe
}
| pshdo/Carbon | Carbon/Functions/Get-PowershellPath.ps1 | PowerShell | apache-2.0 | 2,762 |
$packageName = 'dolphin'
$url = 'http://dl.dolphin-emu.org/builds/dolphin-master-5.0-1605-x64.7z'
$checksum = 'ae1b33ee7e3377370e7db43da5823efac4204f5184f0771067869a677a84e2cc'
$checksumType = 'sha256'
$url64 = $url
$checksum64 = $checksum
$checksumType64 = $checksumType
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
Install-ChocolateyZipPackage -PackageName "$packageName" `
-Url "$url" `
-UnzipLocation "$toolsDir" `
-Url64bit "$url64" `
-Checksum "$checksum" `
-ChecksumType "$checksumType" `
-Checksum64 "$checksum64" `
-ChecksumType64 "$checksumType64" | dtgm/chocolatey-packages | automatic/_output/dolphin/5.0.1605/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 790 |
function Set-WindowsExplorerOptions {
<#
.SYNOPSIS
Sets options on the Windows Explorer shell
.PARAMETER EnableShowHiddenFilesFoldersDrives
If this flag is set, hidden files will be shown in Windows Explorer
.PARAMETER DisableShowHiddenFilesFoldersDrives
Disables the showing on hidden files in Windows Explorer, see EnableShowHiddenFilesFoldersDrives
.PARAMETER EnableShowProtectedOSFiles
If this flag is set, hidden Operating System files will be shown in Windows Explorer
.PARAMETER DisableShowProtectedOSFiles
Disables the showing of hidden Operating System Files in Windows Explorer, see EnableShowProtectedOSFiles
.PARAMETER EnableShowFileExtensions
Setting this switch will cause Windows Explorer to include the file extension in file names
.PARAMETER DisableShowFileExtensions
Disables the showing of file extension in file names, see EnableShowFileExtensions
.PARAMETER EnableShowFullPathInTitleBar
Setting this switch will cause Windows Explorer to show the full folder path in the Title Bar
.PARAMETER DisableShowFullPathInTitleBar
Disables the showing of the full path in Windows Explorer Title Bar, see EnableShowFullPathInTitleBar
.PARAMETER EnableExpandToOpenFolder
Setting this switch will cause Windows Explorer to expand the navigation pane to the current open folder
.PARAMETER DisableExpandToOpenFolder
Disables the expanding of the navigation page to the current open folder in Windows Explorer, see EnableExpandToOpenFolder
.PARAMETER EnableOpenFileExplorerToQuickAccess
Setting this switch will cause Windows Explorer to open itself to the Computer view, rather than the Quick Access view
.PARAMETER DisableOpenFileExplorerToQuickAccess
Disables the Quick Access location and shows Computer view when opening Windows Explorer, see EnableOpenFileExplorerToQuickAccess
.PARAMETER EnableShowRecentFilesInQuickAccess
Setting this switch will cause Windows Explorer to show recently used files in the Quick Access pane
.PARAMETER DisableShowRecentFilesInQuickAccess
Disables the showing of recently used files in the Quick Access pane, see EnableShowRecentFilesInQuickAccess
.PARAMETER EnableShowFrequentFoldersInQuickAccess
Setting this switch will cause Windows Explorer to show frequently used directories in the Quick Access pane
.PARAMETER DisableShowFrequentFoldersInQuickAccess
Disables the showing of frequently used directories in the Quick Access pane, see EnableShowFrequentFoldersInQuickAccess
.LINK
http://boxstarter.org
#>
[CmdletBinding()]
param(
[switch]$EnableShowHiddenFilesFoldersDrives,
[switch]$DisableShowHiddenFilesFoldersDrives,
[switch]$EnableShowProtectedOSFiles,
[switch]$DisableShowProtectedOSFiles,
[switch]$EnableShowFileExtensions,
[switch]$DisableShowFileExtensions,
[switch]$EnableShowFullPathInTitleBar,
[switch]$DisableShowFullPathInTitleBar,
[switch]$EnableExpandToOpenFolder,
[switch]$DisableExpandToOpenFolder,
[switch]$EnableOpenFileExplorerToQuickAccess,
[switch]$DisableOpenFileExplorerToQuickAccess,
[switch]$EnableShowRecentFilesInQuickAccess,
[switch]$DisableShowRecentFilesInQuickAccess,
[switch]$EnableShowFrequentFoldersInQuickAccess,
[switch]$DisableShowFrequentFoldersInQuickAccess
)
$PSBoundParameters.Keys | % {
if($_-like "En*"){ $other="Dis" + $_.Substring(2)}
if($_-like "Dis*"){ $other="En" + $_.Substring(3)}
if($PSBoundParameters[$_] -and $PSBoundParameters[$other]) {
throw new-Object -TypeName ArgumentException "You may not set both $_ and $other. You can only set one."
}
}
$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer'
$advancedKey = "$key\Advanced"
$cabinetStateKey = "$key\CabinetState"
Write-BoxstarterMessage "Setting Windows Explorer options..."
if(Test-Path -Path $key) {
if($EnableShowRecentFilesInQuickAccess) {Set-ItemProperty $key ShowRecent 1}
if($DisableShowRecentFilesInQuickAccess) {Set-ItemProperty $key ShowRecent 0}
if($EnableShowFrequentFoldersInQuickAccess) {Set-ItemProperty $key ShowFrequent 1}
if($DisableShowFrequentFoldersInQuickAccess) {Set-ItemProperty $key ShowFrequent 0}
}
if(Test-Path -Path $advancedKey) {
if($EnableShowHiddenFilesFoldersDrives) {Set-ItemProperty $advancedKey Hidden 1}
if($DisableShowHiddenFilesFoldersDrives) {Set-ItemProperty $advancedKey Hidden 0}
if($EnableShowFileExtensions) {Set-ItemProperty $advancedKey HideFileExt 0}
if($DisableShowFileExtensions) {Set-ItemProperty $advancedKey HideFileExt 1}
if($EnableShowProtectedOSFiles) {Set-ItemProperty $advancedKey ShowSuperHidden 1}
if($DisableShowProtectedOSFiles) {Set-ItemProperty $advancedKey ShowSuperHidden 0}
if($EnableExpandToOpenFolder) {Set-ItemProperty $advancedKey NavPaneExpandToCurrentFolder 1}
if($DisableExpandToOpenFolder) {Set-ItemProperty $advancedKey NavPaneExpandToCurrentFolder 0}
if($EnableOpenFileExplorerToQuickAccess) {Set-ItemProperty $advancedKey LaunchTo 2}
if($DisableOpenFileExplorerToQuickAccess) {Set-ItemProperty $advancedKey LaunchTo 1}
}
if(Test-Path -Path $cabinetStateKey) {
if($EnableShowFullPathInTitleBar) {Set-ItemProperty $cabinetStateKey FullPath 1}
if($DisableShowFullPathInTitleBar) {Set-ItemProperty $cabinetStateKey FullPath 0}
}
Restart-Explorer
}
| smaglio81/boxstarter | Boxstarter.WinConfig/Set-WindowsExplorerOptions.ps1 | PowerShell | apache-2.0 | 5,507 |
$packageName = '{{PackageName}}'
$url = '{{DownloadUrl}}'
$checksum = '{{Checksum}}'
$checksumType = 'sha1'
$url64 = "$url"
$checksum64 = "$checksum"
$checksumType64 = "checksumType"
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
Install-ChocolateyZipPackage -PackageName "$packageName" `
-Url "$url" `
-UnzipLocation "$toolsDir" `
-Url64bit "$url64" `
-Checksum "$checksum" `
-ChecksumType "$checksumType" `
-Checksum64 "$checksum64" `
-ChecksumType64 "$checksumType64"
Write-Verbose "Accepting license..."
$regRoot = 'HKCU:\Software\Sysinternals'
$regPkg = 'Desktops'
$regPath = Join-Path $regRoot $regPkg
if (! Test-Path $regRoot) {New-Item -Path "$regRoot"}
if (! Test-Path $regPath) {New-Item -Path "$regRoot" -Name "$regPkg"}
Set-ItemProperty -Path "$regPath" -Name EulaAccepted -Value 1
if ((Get-ItemProperty -Path "$regPath").EulaAccepted -ne 1) {
throw "Failed setting registry value."
} | maharishi/chocolatey-packages | automatic/desktops/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 1,128 |
#
# Module manifest for module 'PSGet_Azure.Storage'
#
# Generated by: Microsoft Corporation
#
# Generated on: 10/31/2016
#
@{
# Script module or binary module file associated with this manifest.
# RootModule = ''
# Version number of this module.
ModuleVersion = '2.4.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '00612bca-fa22-401d-a671-9cc48b010e3b'
# 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 - Storage service cmdlets. Manages blobs, queues, tables and files in Microsoft Azure storage accounts'
# 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.4.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 = '.\Microsoft.WindowsAzure.Commands.Storage.Types.ps1xml'
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = '.\Microsoft.WindowsAzure.Commands.Storage.format.ps1xml'
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @('.\Microsoft.WindowsAzure.Commands.Storage.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-AzureStorageTable', 'New-AzureStorageTableSASToken',
'New-AzureStorageTableStoredAccessPolicy', 'New-AzureStorageTable',
'Remove-AzureStorageTableStoredAccessPolicy',
'Remove-AzureStorageTable',
'Get-AzureStorageTableStoredAccessPolicy',
'Set-AzureStorageTableStoredAccessPolicy', 'Get-AzureStorageQueue',
'New-AzureStorageQueue', 'Remove-AzureStorageQueue',
'Get-AzureStorageQueueStoredAccessPolicy',
'New-AzureStorageQueueSASToken',
'New-AzureStorageQueueStoredAccessPolicy',
'Remove-AzureStorageQueueStoredAccessPolicy',
'Set-AzureStorageQueueStoredAccessPolicy', 'Get-AzureStorageFile',
'Get-AzureStorageFileContent', 'Get-AzureStorageFileCopyState',
'Get-AzureStorageShare', 'Get-AzureStorageShareStoredAccessPolicy',
'New-AzureStorageDirectory', 'New-AzureStorageFileSASToken',
'New-AzureStorageShare', 'New-AzureStorageShareSASToken',
'New-AzureStorageShareStoredAccessPolicy',
'Remove-AzureStorageDirectory', 'Remove-AzureStorageFile',
'Remove-AzureStorageShare',
'Remove-AzureStorageShareStoredAccessPolicy',
'Set-AzureStorageFileContent', 'Set-AzureStorageShareQuota',
'Set-AzureStorageShareStoredAccessPolicy',
'Start-AzureStorageFileCopy', 'Stop-AzureStorageFileCopy',
'New-AzureStorageAccountSASToken', 'Set-AzureStorageCORSRule',
'Get-AzureStorageCORSRule',
'Get-AzureStorageServiceLoggingProperty',
'Get-AzureStorageServiceMetricsProperty',
'Remove-AzureStorageCORSRule',
'Set-AzureStorageServiceLoggingProperty',
'Set-AzureStorageServiceMetricsProperty', 'New-AzureStorageContext',
'Set-AzureStorageContainerAcl', 'Remove-AzureStorageBlob',
'Set-AzureStorageBlobContent', 'Get-AzureStorageBlob',
'Get-AzureStorageBlobContent', 'Get-AzureStorageBlobCopyState',
'Get-AzureStorageContainer',
'Get-AzureStorageContainerStoredAccessPolicy',
'New-AzureStorageBlobSASToken', 'New-AzureStorageContainer',
'New-AzureStorageContainerSASToken',
'New-AzureStorageContainerStoredAccessPolicy',
'Remove-AzureStorageContainer',
'Remove-AzureStorageContainerStoredAccessPolicy',
'Set-AzureStorageContainerStoredAccessPolicy',
'Start-AzureStorageBlobCopy', 'Stop-AzureStorageBlobCopy'
# 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 = 'Get-AzureStorageContainerAcl', 'Start-CopyAzureStorageBlob',
'Stop-CopyAzureStorageBlob'
# 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','Storage','Blob','Queue','Table'
# 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 = ''
}
| alfantp/azure-powershell | src/Storage/Azure.Storage.psd1 | PowerShell | apache-2.0 | 7,253 |
$packageName = 'kvrt'
$url = 'http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe'
$checksum = '1b6ef621fe47b99aa2ded0d1f55e0fddb209022d'
$checksumType = 'sha1'
$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/2016.04.23.1700/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 931 |
#
# Module manifest for module 'Microsoft.Azure.Commands.NotificationHubs'
#
# Generated by: Microsoft Corporation
#
# Generated on: 9/19/2015
#
@{
# Version number of this module.
ModuleVersion = '0.10.1'
# ID used to uniquely identify this module
GUID = 'f875725d-8ce4-423f-a6af-ea880bc63f13'
# 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 - NotificationHubs'
# 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 the .NET Framework required by this module
DotNetFrameworkVersion = '4.0'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion='4.0'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'None'
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @( @{ ModuleName = 'AzureRM.Profile'; ModuleVersion = '0.10.1' })
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in ModuleToProcess
NestedModules = @(
'.\Microsoft.Azure.Commands.NotificationHubs.dll'
)
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = @()
# 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 ModuleToProcess
PrivateData = ''
}
| pomortaz/azure-powershell | src/ResourceManager/NotificationHubs/AzureRM.NotificationHubs.psd1 | PowerShell | apache-2.0 | 2,587 |
# copies file to the solution directory
# creates ".Settings" solution folder
# adds shipped files to the solution
function Init
{
param($installPath, $toolsPath, $package, $project)
# Checks if a partical file already added to a solution/project as project item
function CheckIfFileExistsInProject
{
param($projectItems, [string]$fileName)
write-Host "Prepare the project and copy necessary files"
for([int]$i = 1; $i -le $projectItems.Count; $i++)
{
$item = $projectItems.Item($i)
if($item.FileNames(1).Equals($fileName)){return $true;}
}
return $false
}
# Copies a file to solution dir, if not already there
# Creates a solution folder, if not already there
# Adds files to solution, if not already there
function AddFileToSettings
{
param([string]$filename, [string]$newFilename, [string]$installPath, [string]$policyFolderName, [string]$settingsFolderName, $solution)
$solutionDir = [System.IO.Path]::GetDirectoryName($solution.FullName)
$oldpath = [System.IO.Path]::Combine($installPath, $policyFolderName, $fileName)
$newPath = [System.IO.Path]::Combine($solutionDir, $newFilename)
# checks whether file exists in package
if(Test-Path $oldpath)
{
Copy-Item $oldpath $newPath
# look up for solution folder
$settingsFolder = $solution.Projects | Where-Object {$_.Name.Equals($settingsFolderName, [StringComparison]::OrdinalIgnoreCase)} | Select-Object -First 1
# if not there, create new one
if ($settingsFolder -eq $null)
{
$settingsFolder = $solution.AddSolutionFolder($settingsFolderName) #solution change!!!!!!
}
# check if added already
if(!(CheckIfFileExistsInProject $settingsFolder.ProjectItems $newPath))
{
$settingsFolder.ProjectItems.AddFromFile($newPath)
}
}
}
$solution = Get-Interface $dte.Solution ([EnvDTE80.Solution2])
$solutionFile = $solution.FullName
$solutionDir = [System.IO.Path]::GetDirectoryName($solutionFile)
$settingsFolder = $null
$settingsFolderName = ".Settings"
[string]$policyFilePath = [System.IO.Path]::Combine($installPath, "CompanyPolicy", "CompanyPolicy.config")
# no config file
if(!(Test-Path $policyFilePath))
{
write-Host $policyFilePath
return;
}
# while loop, read file names
$fileNameList = New-Object 'System.Collections.Generic.List[string]'
[xml]$xmlContent = [xml](Get-Content -Path $policyFilePath)
[System.Xml.XmlElement] $root = $xmlContent.get_DocumentElement()
[System.Xml.XmlElement] $staticCodeAnalysis = $root.StaticCodeAnalysis
if($staticCodeAnalysis -ne $null)
{
[System.Xml.XmlElement] $configuration = $null
foreach($configuration in $staticCodeAnalysis.ChildNodes)
{
if($configuration.Attributes["ruleSet"] -ne $null)
{
[string]$ruleSet = $configuration.Attributes["ruleSet"].Value
# add file name to list, only if not added yet
if($fileNameList.Contains($ruleSet) -eq $false)
{
$fileNameList.Add($ruleSet)
}
}
}
}
# iterate file names collection and copy them to solution directory
foreach($fileName in $fileNameList)
{
AddFileToSettings $filename $filename $installPath "CompanyPolicy\StaticCodeAnalysis" $settingsFolderName $solution
}
## Signing
[System.Xml.XmlElement] $signing = $root.Signing
if($signing -ne $null)
{
[System.Xml.XmlElement] $configuration = $signing.ChildNodes | Select-Object -First 1
if(($configuration.Attributes["enabled"] -ne $null) -and ($configuration.Attributes["enabled"].Value -eq "true"))
{
if($configuration.Attributes["keyFile"] -ne $null)
{
[string]$keyFile = $configuration.Attributes["keyFile"].Value
AddFileToSettings $keyFile $keyFile $installPath "CompanyPolicy\Signing" $settingsFolderName $solution
}
}
}
[System.Xml.XmlElement] $codeAnalysisDictionary = $root.CodeAnalysisDictionary
if($codeAnalysisDictionary -ne $null)
{
[System.Xml.XmlElement] $configuration = $codeAnalysisDictionary.ChildNodes | Select-Object -First 1
if($configuration.Attributes["dictionary"] -ne $null)
{
[string]$dictionary = $configuration.Attributes["dictionary"].Value
AddFileToSettings $dictionary $dictionary $installPath "CompanyPolicy\CodeAnalysisDictionary" $settingsFolderName $solution
}
}
[System.Xml.XmlElement] $styleCop = $root.StyleCop
if($styleCop -ne $null)
{
[System.Xml.XmlElement] $configuration = $styleCop.ChildNodes | Select-Object -First 1
if($configuration.Attributes["settings"] -ne $null)
{
[string]$styleCopFileName = $configuration.Attributes["settings"].Value
AddFileToSettings $styleCopFileName $styleCopFileName $installPath "CompanyPolicy\StyleCop" $settingsFolderName $solution
}
}
## Resharper
[System.Xml.XmlElement] $resharperSettings = $root.Resharper
if($resharperSettings -ne $null)
{
[System.Xml.XmlElement] $configuration = $resharperSettings.ChildNodes | Select-Object -First 1
if($configuration.Attributes["settings"] -ne $null)
{
[string]$resharperSettingsFile = $configuration.Attributes["settings"].Value
if($resharperSettingsFile -ne $null)
{
$resharperSettingsFilePath = [System.IO.Path]::Combine($installPath, "CompanyPolicy\Resharper", $resharperSettingsFile)
$solutionFileName = [System.IO.Path]::GetFileName($solutionFile)
$resharperSettingsNewFile = $solutionFileName + '.DotSettings'
AddFileToSettings $resharperSettingsFile $resharperSettingsNewFile $installPath "CompanyPolicy\Resharper" $settingsFolderName $solution
}
}
}
if($solution.IsDirty)
{
$solution.SaveAs($solutionFile)
}
write-Host "Finished Copying"
}
| AITGmbH/ApplyCompanyPolicy.Template | src/ApplyCompanyPolicy/tools/scripts/PrepareProject.ps1 | PowerShell | mit | 5,824 |
# Global Variables
$localCredDemo = new-object -typename System.Management.Automation.PSCredential `
-argumentlist "Demo", (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force)
$localCred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist "Administrator", (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force)
$domainCred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist "Ignite\Administrator", (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force)
$VMPath = "C:\VMs"
$DomainControllerVMName = "Domain Controller"
$DomainControllerGuestName = "DC"
$VirtualSwitchName = "Virtual Switch"
$VLANID = 7
function waitForPSDirect([string]$VMName, $cred){
Write-Output "[$($VMName)]:: Waiting for PowerShell Direct (using $($cred.username))"
while ((icm -VMName $VMName -Credential $cred {"Test"} -ea SilentlyContinue) -ne "Test") {Sleep -Seconds 1}}
function rebootVM([string]$VMName){Write-Output "[$($VMName)]:: Rebooting"; stop-vm $VMName; start-vm $VMName}
function CreateBaseVM([string]$VMName, `
[string]$GuestOSName, `
[string]$IPAddress, `
[switch]$domainJoined, `
[switch]$Desktop, `
[switch]$enableHyperV, `
[switch]$enableClustering, `
[switch]$DomainController, `
[switch]$SOFSnode) {
# Throw away old VM
Write-Output "[$($VMName)]:: Removing old VM"
get-vm $VMName -ErrorAction SilentlyContinue | stop-vm -TurnOff -Force -Passthru | remove-vm -Force
if (test-path "$($VMPath)\$($GuestOSName).vhdx") {remove-item "$($VMPath)\$($GuestOSName).vhdx" -Force}
# Clean up old domain entries
if ($domainJoined) {
Write-Output "[$($VMName)]:: Cleaning out old virtual machine domain entry"
icm -VMName $DomainControllerVMName -Credential $domainCred {
param($GuestOSName)
Get-ADComputer -Filter * | ? Name -eq "$($GuestOSName)" | Remove-ADObject -Recursive -Confirm:$false
} -ArgumentList $GuestOSName}
# Make new VM
Write-Output "[$($VMName)]:: Creating new differencing disk"
if ($Desktop) {New-VHD -Path "$($VMPath)\$($GuestOSName).vhdx" -ParentPath "$($VMPath)\VMDesktopBase.vhdx" -Differencing | Out-Null}
else {New-VHD -Path "$($VMPath)\$($GuestOSName).vhdx" -ParentPath "$($VMPath)\VMServerBase.vhdx" -Differencing | Out-Null}
Write-Output "[$($VMName)]:: Creating virtual machine"
new-vm -Name $VMName -MemoryStartupBytes 768mb -SwitchName $VirtualSwitchName `
-VHDPath "$($VMPath)\$($GuestOSName).vhdx" -Generation 2 | Set-VM -ProcessorCount 2 -StaticMemory
Write-Output "[$($VMName)]:: Setting VLAN on network adapter"
Get-VMNetworkAdapter -VMName $VMName | Set-VMNetworkAdapterVlan -access -VlanId $VLANID
Write-Output "[$($VMName)]:: Starting virtual machine"
start-vm $VMName
waitForPSDirect $VMName -cred $localCred
# Set IP address & name
icm -VMName $VMName -Credential $localCred {
param($IPAddress, $GuestOSName, $domainJoined, $domainCred, $enableHyperV, $enableClustering, $DomainController, $VMName, $SOFSnode)
Write-Output "[$($VMName)]:: Setting IP Address to $($IPAddress)"
New-NetIPAddress -IPAddress $IPAddress -InterfaceAlias "Ethernet" -PrefixLength 24 | Out-Null
Write-Output "[$($VMName)]:: Setting DNS Address"
Get-DnsClientServerAddress | %{Set-DnsClientServerAddress -InterfaceIndex $_.InterfaceIndex -ServerAddresses 10.100.7.1}
Write-Output "[$($VMName)]:: Renaming OS to `"$($GuestOSName)`""
Rename-Computer $GuestOSName
if ($enableHyperV) {
Write-Output "[$($VMName)]:: Enabling Hyper-V"
Install-WindowsFeature RSAT-Hyper-V-Tools | out-null
dism.exe /Online /Enable-Feature:Microsoft-Hyper-V /All /NoRestart | out-null}
if ($enableClustering) {
Write-Output "[$($VMName)]:: Enabling Clustering"
Install-WindowsFeature Failover-Clustering –IncludeManagementTools | out-null}
if ($DomainController) {
Write-Output "[$($VMName)]:: Enabling iSCSI, AD and DHCP"
Add-WindowsFeature -Name FS-iSCSITarget-Server | out-null
Install-WindowsFeature AD-Domain-Services, DHCP –IncludeManagementTools | out-null}
if ($SOFSnode) {
Write-Output "[$($VMName)]:: Enabling file services"
Install-WindowsFeature File-Services, FS-FileServer –IncludeManagementTools | Out-Null}
Write-Output "[$($VMName)]:: Configuring WSMAN Trusted hosts"
Set-Item WSMan:\localhost\Client\TrustedHosts "*.ignite.demo" -Force
Set-Item WSMan:\localhost\client\trustedhosts "10.100.7.*" -force -concatenate
} -ArgumentList $IPAddress, $GuestOSName, $domainJoined, $domainCred, $enableHyperV, $enableClustering, $DomainController, $VMName, $SOFSnode
if ($domainJoined) {
# Reboot
rebootVM $VMName; waitForPSDirect $VMName -cred $localCred
icm -VMName $VMName -Credential $localCred {
param($VMName, $domainCred)
Write-Output "[$($VMName)]:: Joining domain as `"$($env:computername)`""
while (!(Test-Connection -Computername 10.100.7.1 -BufferSize 16 -Count 1 -Quiet -ea SilentlyContinue)) {sleep -seconds 1}
Add-Computer -DomainName Ignite.demo -Credential $domainCred
} -ArgumentList $VMName, $domainCred
# Reboot
rebootVM $VMName; waitForPSDirect $VMName -cred $domainCred
}
# Setup domain controller
if ($DomainController) {
# Reboot
rebootVM $VMName; waitForPSDirect $VMName -cred $localCred
icm -VMName $VMName -Credential $localCred {
param($VMName)
Write-Output "[$($VMName)]:: Configuring DHCP Server"
Set-DhcpServerv4Binding -BindingState $true -InterfaceAlias Ethernet
Add-DhcpServerv4Scope -Name "IPv4 Network" -StartRange 10.100.7.100 -EndRange 10.100.7.200 -SubnetMask 255.255.255.0
Write-Output "[$($VMName)]:: Installing Active Directory and promoting to domain controller"
Install-ADDSForest -DomainName Ignite.demo -InstallDNS -NoDNSonNetwork -NoRebootOnCompletion `
-SafeModeAdministratorPassword (ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force) -confirm:$false
} -ArgumentList $VMName
# Reboot
rebootVM $VMName; waitForPSDirect $VMName -cred $domainCred
icm -VMName $VMName -Credential $domainCred {
param($VMName)
Write-Output "[$($VMName)]:: Creating VHDXs for iSCSI targets"
New-IscsiVirtualDisk C:\iSCSITargetDisks\Quorum.vhdx –size 10GB | Out-Null
New-IscsiVirtualDisk C:\iSCSITargetDisks\Data.vhdx –size 120GB | Out-Null
Write-Output "[$($VMName)]:: Creating iSCSI targets"
New-IscsiServerTarget ISCSIQuorum –InitiatorIds "Iqn:iqn.1991-05.com.microsoft:sofs-n1.ignite.demo" | Out-Null
New-IscsiServerTarget ISCSIData –InitiatorIds "Iqn:iqn.1991-05.com.microsoft:sofs-n1.ignite.demo" | Out-Null
Write-Output "[$($VMName)]:: Mapping VHDX files to iSCSI targets"
Add-IscsiVirtualDiskTargetMapping ISCSIQuorum C:\iSCSITargetDisks\Quorum.vhdx -lun 0
Add-IscsiVirtualDiskTargetMapping ISCSIData C:\iSCSITargetDisks\Data.vhdx -lun 0
Write-Output "[$($VMName)]:: Setting DNS option on DHCP server"
Set-DhcpServerV4OptionValue -DnsDomain Ignite.demo -DnsServer 10.100.7.1
} -ArgumentList $VMName
# Reboot
rebootVM $VMName; waitForPSDirect $VMName -cred $domainCred
icm -VMName $VMName -Credential $domainCred {
param($VMName)
Write-Output "[$($VMName)]:: Registering DHCP with AD"
sleep -Seconds 60
Add-DhcpServerInDC -DnsName "DC.Ignite.demo" -IPAddress "10.100.7.1"
} -ArgumentList $VMName
}
if ($SOFSnode) {
icm -VMName $VMName -Credential $domainCred {
Set-Service MSiSCSI -StartupType automatic
Start-Service MSiSCSI
New-iSCSITargetPortal -TargetPortalAddress dc.ignite.demo
Get-iSCSITarget | Connect-iSCSITarget
Get-iSCSISession | Register-iSCSISession
Get-Disk | ?{$_.BusType -eq "iSCSI"} | %{
$d = “WXYZ”[$_.Number]
Set-Disk -Number $_.Number -IsReadOnly 0
Set-Disk -Number $_.Number -IsOffline 0
Initialize-Disk -Number $_.Number -PartitionStyle MBR
New-Partition -DiskNumber $_.Number -UseMaximumSize | Set-Partition -NewDriveLetter $d
Initialize-Volume -DriveLetter $d -FileSystem NTFS -Confirm:$false}
New-Cluster –Name SOFS -Node $env:COMPUTERNAME -StaticAddress 10.100.7.3
Get-Disk | ?{$_.BusType -eq "iSCSI"} | Add-ClusterDisk
Get-ClusterResource | ? Name -eq "Cluster Disk 1" | %{Set-ClusterQuorum -DiskWitness $_}
Get-ClusterResource | ? Name -eq "Cluster Disk 2" | Add-ClusterSharedVolume
Add-ClusterScaleOutFileServerRole -Name SOFS-FS
MD C:\ClusterStorage\Volume1\VHDX
New-SmbShare -Name VHDX -Path C:\ClusterStorage\Volume1\VHDX -FullAccess Ignite.demo\administrator
Set-SmbPathAcl –ShareName VHDX
MD C:\ClusterStorage\Volume1\ClusQuorum
New-SmbShare -Name ClusQuorum -Path C:\ClusterStorage\Volume1\ClusQuorum -FullAccess Ignite.demo\administrator
Set-SmbPathAcl –ShareName ClusQuorum
MD C:\ClusterStorage\Volume1\ClusData
New-SmbShare -Name ClusData -Path C:\ClusterStorage\Volume1\ClusData -FullAccess Ignite.demo\administrator
Set-SmbPathAcl –ShareName ClusData}
}
if ($domainJoined -or $DomainController) {waitForPSDirect $VMName -cred $domainCred}
else {waitForPSDirect $VMName -cred $localCred}
}
Function BuildBaseImages {
$ServerWim = "D:\Build\Builds\FBL_IMPRESSIVE10074.0.150424-1350\10074.0.150424-1350.FBL_IMPRESSIVE_SERVER_OEMRET_X64FRE_EN-US.WIM"
$DesktopWim = "D:\Build\Builds\FBL_IMPRESSIVE10074.0.150424-1350\10074.0.150424-1350.FBL_IMPRESSIVE_CLIENTPRO-CORE_OEMRET_X64FRE_EN-US.wim"
D:\Build\Scripts\Convert-WindowsImage.ps1 -SourcePath $DesktopWim -VHDPath "$($VMPath)\VMDesktopBase.vhdx" `
-SizeBytes 40GB -VHDFormat VHDX -UnattendPath D:\Build\Unattends\unattendDesktopFull.xml `
-Edition "Windows 10 Pro Technical Preview" -VHDPartitionStyle GPT
D:\Build\Scripts\Convert-WindowsImage.ps1 -SourcePath $ServerWim -VHDPath "$($VMPath)\VMServerBase.vhdx" `
-SizeBytes 40GB -VHDFormat VHDX -UnattendPath D:\Build\Unattends\unattendServerFull.xml `
-Edition "ServerDataCenter" -VHDPartitionStyle GPT
}
Function BuildVMsForLaptop2 {
CreateBaseVM -VMName $DomainControllerVMName -GuestOSName $DomainControllerGuestName -IPAddress "10.100.7.1" -DomainController
CreateBaseVM -VMName "SOFS Cluster Node 1" -GuestOSName "SOFS-N1" -IPAddress "10.100.7.2" -domainJoined -SOFSnode -enableClustering
CreateBaseVM -VMName "Workload" -GuestOSName "Workload" -IPAddress "10.100.7.13"
CreateBaseVM -VMName "Cluster Node 1" -GuestOSName "ClusNode1" -IPAddress "10.100.7.4" -enableHyperV -enableClustering -domainJoined
CreateBaseVM -VMName "Cluster Node 2" -GuestOSName "ClusNode2" -IPAddress "10.100.7.5" -enableHyperV -enableClustering -domainJoined
CreateBaseVM -VMName "Replica Target" -GuestOSName "Replica" -IPAddress "10.100.7.8" -enableHyperV -domainJoined
CreateBaseVM -VMName "Protected Workload" -GuestOSName "vTPM" -IPAddress "10.100.7.12" -Desktop
invoke-command -VMName "Cluster Node 1" -Credential $domainCred {
new-cluster -name "Demo-Cluster" -Node ClusNode1, ClusNode2 -NoStorage -staticAddress 10.100.7.6
Set-ClusterQuorum -Cluster ClusNode1 -NodeAndFileShareMajority \\sofs-fs.ignite.demo\ClusQuorum}
}
Function BuildVMsForLaptop1 {
CreateBaseVM -VMName "Hyper-V Management" -GuestOSName "HVManager" -IPAddress "10.100.7.7" -enableHyperV
CreateBaseVM -VMName "Hot Add & Remove" -GuestOSName "HotAddRemove" -IPAddress "10.100.7.15" -Desktop
CreateBaseVM -VMName "Different Checkpoints" -GuestOSName "Checkpoint" -IPAddress "10.100.7.14" -Desktop
#Build old VM
$VMName = "Old Virtual Machine"
$GuestOSName = "OldVM"
Write-Output "[$($VMName)]:: Removing old VM"
get-vm $VMName -ErrorAction SilentlyContinue | stop-vm -TurnOff -Force -Passthru | remove-vm -Force
if (test-path "$($VMPath)\$($GuestOSName).vhdx") {remove-item "$($VMPath)\$($GuestOSName).vhdx" -Force}
import-vm -Copy -Path "D:\Build\VMs\Old Virtual Machine\Virtual Machines\EBF49DE2-966B-4806-A9D0-5F33939AC6C0.xml" | set-vm -NewVMName $VMName
new-vhd -path "$($VMPath)\$($GuestOSName).vhdx" -ParentPath "D:\build\BaseVHDs\Old Virtual Machine.vhdx" | Out-Null
Add-VMHardDiskDrive -VMName $VMName -path "$($VMPath)\$($GuestOSName).vhdx"
start-vm $VMName
#Build Ubuntu VM
$VMName = "Ubuntu"
$GuestOSName = "Ubuntu"
Write-Output "[$($VMName)]:: Removing old VM"
get-vm $VMName -ErrorAction SilentlyContinue | stop-vm -TurnOff -Force -Passthru | remove-vm -Force
if (test-path "$($VMPath)\$($GuestOSName).vhdx") {remove-item "$($VMPath)\$($GuestOSName).vhdx" -Force}
new-vhd -path "$($VMPath)\$($GuestOSName).vhdx" -ParentPath "D:\Build\BaseVHDs\Ubuntu 14.vhdx" | Out-Null
new-vm -Name $VMName -MemoryStartupBytes 750mb -SwitchName $VirtualSwitchName `
-VHDPath "$($VMPath)\$($GuestOSName).vhdx" -Generation 2 | Set-VM -ProcessorCount 2 -StaticMemory -Passthru | `
Set-VMFirmware -SecureBootTemplate MicrosoftUEFICertificateAuthority
start-vm $VMName
}
get-vm | stop-vm -Force
BuildBaseImages
BuildVMsForLaptop1
| timbodv/Virtualization-Documentation | demos/2015-Ignite-Whats-New/scripts/WorkloadSetup.ps1 | PowerShell | mit | 13,897 |
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
Describe "Grani_TopShelf : TargetResource" {
$Key = "HKEY_LOCAL_MACHINE\SOFTWARE\hoge/piyo\fuga/nyao"
$key2 = "HKLM:\SOFTWARE\hoge/piyo\fuga/nyao"
$invalidKey = "H_CU\SOFTWARE\hoge/piyo\fuga/nyao"
$Ensure = "Present"
Context "Scratch environment without Registry exists." {
It "Get-TargetResource should not throw" {
{Get-TargetResource -Key $key -Ensure $Ensure} | Should not Throw
}
$get = Get-TargetResource -Key $key -Ensure $Ensure
It "Get-TargetResource should return Ensure : Absent" {
$get.Ensure | Should be "Absent"
}
It "Get-TargetResource should return Key : $Key" {
$get.Key | Should be $key
}
It "Test-TargetResource Present should return false" {
Test-TargetResource -Key $key -Ensure $Ensure | should be $false
}
It "Test-TargetResource Absent should return true" {
Test-TargetResource -Key $key -Ensure "Absent" | should be $true
}
It "Set-TargetResource Present should not Throw as Ensure : $Ensure" {
{Set-TargetResource -Key $key -Ensure $Ensure} | should not Throw
}
}
Context "Already Configured Environment should skip." {
It "Set-TargetResource $Ensure should not Throw" {
{Set-TargetResource -Key $key -Ensure $Ensure} | should not Throw
}
It "Test-TargetResource Present should return true" {
Test-TargetResource -Key $key -Ensure $Ensure | should be $true
}
It "Test-TargetResource Absent should return false" {
Test-TargetResource -Key $key -Ensure "Absent" | should be $false
}
}
Context "Remove Configured settings." {
It "Set-TargetResource Absent should not Throw" {
{Set-TargetResource -Key $key -Ensure "Absent"} | should not Throw
}
It "Test-TargetResource Present should return true" {
Test-TargetResource -Key $key -Ensure $Ensure | should be $false
}
It "Test-TargetResource Absent should return false" {
Test-TargetResource -Key $key -Ensure "Absent" | should be $true
}
}
Context "Scratch environment without Registry exists." {
It "Get-TargetResource should not throw" {
{Get-TargetResource -Key $key2 -Ensure $Ensure} | Should not Throw
}
$get = Get-TargetResource -Key $key2 -Ensure $Ensure
It "Get-TargetResource should return Ensure : Absent" {
$get.Ensure | Should be "Absent"
}
It "Get-TargetResource should return Key : $Key2" {
$get.Key | Should be $key2
}
It "Test-TargetResource Present should return false" {
Test-TargetResource -Key $key2 -Ensure $Ensure | should be $false
}
It "Test-TargetResource Absent should return true" {
Test-TargetResource -Key $key2 -Ensure "Absent" | should be $true
}
It "Set-TargetResource Present should not Throw as Ensure : $Ensure" {
{Set-TargetResource -Key $key2 -Ensure $Ensure} | should not Throw
}
}
Context "Already Configured Environment should skip." {
It "Set-TargetResource $Ensure should not Throw" {
{Set-TargetResource -Key $key2 -Ensure $Ensure} | should not Throw
}
It "Test-TargetResource Present should return true" {
Test-TargetResource -Key $key2 -Ensure $Ensure | should be $true
}
It "Test-TargetResource Absent should return false" {
Test-TargetResource -Key $key2 -Ensure "Absent" | should be $false
}
}
Context "Remove Configured settings." {
It "Set-TargetResource Absent should not Throw" {
{Set-TargetResource -Key $key2 -Ensure "Absent"} | should not Throw
}
It "Test-TargetResource Present should return true" {
Test-TargetResource -Key $key2 -Ensure $Ensure | should be $false
}
It "Test-TargetResource Absent should return false" {
Test-TargetResource -Key $key2 -Ensure "Absent" | should be $true
}
}
Context "invalid Key." {
It "Get-TargetResource should Throw" {
{Get-TargetResource -Key $invalidKey -Ensure $Ensure} | should Throw
}
It "Test-TargetResource Should Throw" {
{Test-TargetResource -Key $invalidKey -Ensure $Ensure} | should Throw
}
It "Set-TargetResource should throw" {
{Set-TargetResource -Key $invalidKey -Ensure $Ensure} | Should Throw
}
}
}
| guitarrapc/GraniResource | Tests/Grani_RegistryKey/TargetResource.Tests.ps1 | PowerShell | mit | 4,842 |
$packageName = 'speedfan'
$installerType = 'EXE'
$url = 'http://www.almico.com/speedfan450.exe'
$silentArgs = '/S'
$validExitCodes = @(0) #please insert other valid exit codes here, exit codes for ms http://msdn.microsoft.com/en-us/library/aa368542(VS.85).aspx
Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url" -validExitCodes $validExitCodes | dtgm/chocolatey-packages | automatic/_output/speedfan/4.50/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 376 |
# Be sure to run "Set-ExecutionPolicy RemoteSigned" before running powershell scripts
# Use TestExceptions to filter out tests with known problems, separated by a colon
# i.e. run_all_tests.ps1 -TestExceptions VkLayerTest.RequiredParameter:VkLayerTest.UnrecognizedValue
# To trigger Debug tests, specify the parameter with a hyphen
# i.e run_all_tests.ps1 -Debug
Param(
[switch]$Debug,
[string]$LoaderTestExceptions,
[string]$TestExceptions
)
if ($Debug) {
$dPath = "Debug"
} else {
$dPath = "Release"
}
$AboveDir = (Get-Item -Path ".." -Verbose).FullName
Write-Host "Using Vulkan run-time=$AboveDir\loader\$dPath"
Set-Item -path env:Path -value ("$AboveDir\loader\$dPath;" + $env:Path)
& $dPath\vk_loader_validation_tests --gtest_filter=-$LoaderTestExceptions
if ($lastexitcode -ne 0) {
exit 1
}
exit $lastexitcode
| endlessm/chromium-browser | third_party/angle/third_party/vulkan-loader/src/tests/_run_all_tests.ps1 | PowerShell | bsd-3-clause | 847 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# The Get-TargetResource cmdlet is used to fetch the desired state of the DSC managed node through a powershell script.
# This cmdlet executes the user supplied script (i.e., the script is responsible for validating the desired state of the
# DSC managed node). The result of the script execution is in the form of a hashtable containing all the information
# gathered from the GetScript execution.
function Get-TargetResource
{
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]
$text
)
$result = @{
Text = "Hello from Get!";
}
$result;
}
# The Set-TargetResource cmdlet is used to Set the desired state of the DSC managed node through a powershell script.
# The method executes the user supplied script (i.e., the script is responsible for validating the desired state of the
# DSC managed node). If the DSC managed node requires a restart either during or after the execution of the SetScript,
# the SetScript notifies the PS Infrastructure by setting the variable $DSCMachineStatus.IsRestartRequired to $true.
function Set-TargetResource
{
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]
$text
)
$path = "$env:SystemDrive\dscTestPath\hello3.txt"
New-Item -Path $path -Type File -force
Add-Content -Path $path -Value $text
}
# The Test-TargetResource cmdlet is used to validate the desired state of the DSC managed node through a powershell script.
# The method executes the user supplied script (i.e., the script is responsible for validating the desired state of the
# DSC managed node). The result of the script execution should be true if the DSC managed machine is in the desired state
# or else false should be returned.
function Test-TargetResource
{
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]
$text
)
$false
}
| Cowmonaut/PowerShell | test/powershell/Modules/Microsoft.PowerShell.Security/TestData/CatalogTestData/UserConfigProv/DSCResources/UserConfigProviderModVersion3/UserConfigProviderModVersion3.psm1 | PowerShell | mit | 2,165 |
Start-AutoRestCodeGeneration -ResourceProvider "locationbasedservices/resource-manager" -AutoRestVersion "latest"
| shahabhijeet/azure-sdk-for-net | src/SDKs/LocationBasedServices/Management.LocationBasedServices/generate.ps1 | PowerShell | mit | 114 |
<#
.SYNOPSIS
Creates a test package
.PARAMETER Id
The ID of the package to create
.PARAMETER Version
The version of the package to create (defaults to 1.0.0)
.PARAMETER Title
The title of the package to create (defaults to the ID)
.PARAMETER Description
The description of the package to create (defaults to "A test package")
.PARAMETER OutputDirectory
The directory in which to save the package (defaults to the current directory)
.PARAMETER AutoGenerateId
Set this switch to auto generate the ID
#>
param(
[Parameter(Mandatory=$true, ParameterSetName="AutoId")][switch]$AutoGenerateId,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="ManualId")][string]$Id,
[Parameter(Mandatory=$false, Position=1)][string]$Version = "1.0.0",
[Parameter(Mandatory=$false, Position=2)][string]$Title,
[Parameter(Mandatory=$false)][string]$Description = "A test package",
[Parameter(Mandatory=$false)][string]$OutputDirectory)
if(!(Get-Command nuget -ErrorAction SilentlyContinue)) {
throw "You must have nuget.exe in your path to use this command!"
}
if(($PsCmdlet.ParameterSetName -eq "AutoId") -and $AutoGenerateId) {
$ts = [DateTime]::Now.ToString("yyMMddHHmmss")
$Id = "$([Environment]::UserName)_test_$ts"
}
if(!$OutputDirectory) {
$OutputDirectory = Get-Location
}
$OutputDirectory = (Convert-Path $OutputDirectory)
if(!$Title) {
$Title = $Id
}
$tempdir = Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName())
mkdir $tempdir | Out-Null
$contentDir = Join-Path $tempdir "content"
mkdir $contentDir | Out-Null
$testFile = Join-Path $contentDir "Test.txt"
"Test" | Out-File -Encoding UTF8 -FilePath $testFile
$nuspec = Join-Path $tempdir "$Id.nuspec"
@"
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>$Id</id>
<version>$Version</version>
<title>$Title</title>
<authors>$([Environment]::UserName)</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>$Description</description>
</metadata>
</package>
"@ | Out-File -Encoding UTF8 -FilePath $nuspec
nuget pack "$nuspec" -BasePath "$tempdir" -OutputDirectory $OutputDirectory
rm -Recurse -Force $tempdir | mtian/SiteExtensionGallery | tools/New-TestPackage.ps1 | PowerShell | apache-2.0 | 2,320 |
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
<#
.SYNOPSIS
Tests creating an elastic pool
#>
function Test-CreateElasticPool
{
# Setup
$rg = Create-ResourceGroupForTest
$server = Create-ServerForTest $rg "Japan East"
try
{
# Create a pool with all values
$poolName = Get-ElasticPoolName
$ep1 = New-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName `
-ElasticPoolName $poolName -Edition Standard -Dtu 200 -DatabaseDtuMin 10 -DatabaseDtuMax 100 -StorageMB 204800
Assert-NotNull $ep1
Assert-AreEqual 200 $ep1.Dtu
Assert-AreEqual 204800 $ep1.StorageMB
Assert-AreEqual Standard $ep1.Edition
Assert-AreEqual 10 $ep1.DatabaseDtuMin
Assert-AreEqual 100 $ep1.DatabaseDtuMax
# Create a pool using piping and default values
$poolName = Get-ElasticPoolName
$ep2 = $server | New-AzureRmSqlElasticPool -ElasticPoolName $poolName
Assert-NotNull $ep2
Assert-AreEqual 200 $ep2.Dtu
Assert-AreEqual 204800 $ep2.StorageMB
Assert-AreEqual Standard $ep2.Edition
Assert-AreEqual 0 $ep2.DatabaseDtuMin
Assert-AreEqual 100 $ep2.DatabaseDtuMax
}
finally
{
Remove-ResourceGroupForTest $rg
}
}
<#
.SYNOPSIS
Tests updating an elastic pool
#>
function Test-UpdateElasticPool
{
# Setup
$rg = Create-ResourceGroupForTest
$server = Create-ServerForTest $rg "Japan East"
$poolName = Get-ElasticPoolName
$ep1 = New-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName `
-ElasticPoolName $poolName -Edition Standard -Dtu 200 -DatabaseDtuMin 10 -DatabaseDtuMax 100
Assert-NotNull $ep1
$poolName = Get-ElasticPoolName
$ep2 = $server | New-AzureRmSqlElasticPool -ElasticPoolName $poolName -Edition Standard -Dtu 400 -DatabaseDtuMin 10 `
-DatabaseDtuMax 100
Assert-NotNull $ep2
try
{
# Create a pool with all values
$sep1 = Set-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName `
-ElasticPoolName $ep1.ElasticPoolName -Dtu 400 -DatabaseDtuMin 0 -DatabaseDtuMax 50 -Edition Standard -StorageMB 409600
Assert-NotNull $sep1
Assert-AreEqual 400 $sep1.Dtu
Assert-AreEqual 409600 $sep1.StorageMB
Assert-AreEqual Standard $sep1.Edition
Assert-AreEqual 0 $sep1.DatabaseDtuMin
Assert-AreEqual 50 $sep1.DatabaseDtuMax
# Create a pool using piping
$sep2 = $server | Set-AzureRmSqlElasticPool -ElasticPoolName $ep2.ElasticPoolName -Dtu 200 `
-DatabaseDtuMin 10 -DatabaseDtuMax 50 -Edition Standard -StorageMB 204800
Assert-NotNull $sep2
Assert-AreEqual 200 $sep2.Dtu
Assert-AreEqual 204800 $sep2.StorageMB
Assert-AreEqual Standard $sep2.Edition
Assert-AreEqual 10 $sep2.DatabaseDtuMin
Assert-AreEqual 50 $sep2.DatabaseDtuMax
}
finally
{
Remove-ResourceGroupForTest $rg
}
}
<#
.SYNOPSIS
Tests getting an elastic pool
#>
function Test-GetElasticPool
{
# Setup
$rg = Create-ResourceGroupForTest
$server = Create-ServerForTest $rg "Japan East"
$poolName = Get-ElasticPoolName
$ep1 = New-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName `
-ElasticPoolName $poolName -Edition Standard -Dtu 200 -DatabaseDtuMin 10 -DatabaseDtuMax 100
Assert-NotNull $ep1
$poolName = Get-ElasticPoolName
$ep2 = $server | New-AzureRmSqlElasticPool -ElasticPoolName $poolName -Edition Standard -Dtu 400 -DatabaseDtuMin 0 `
-DatabaseDtuMax 100
Assert-NotNull $ep2
try
{
# Create a pool with all values
$gep1 = Get-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName `
-ElasticPoolName $ep1.ElasticPoolName
Assert-NotNull $ep1
Assert-AreEqual 200 $ep1.Dtu
Assert-AreEqual 204800 $ep1.StorageMB
Assert-AreEqual Standard $ep1.Edition
Assert-AreEqual 10 $ep1.DatabaseDtuMin
Assert-AreEqual 100 $ep1.DatabaseDtuMax
# Create a pool using piping
$gep2 = $ep2 | Get-AzureRmSqlElasticPool
Assert-NotNull $ep2
Assert-AreEqual 400 $ep2.Dtu
Assert-AreEqual 204800 $ep2.StorageMB
Assert-AreEqual Standard $ep2.Edition
Assert-AreEqual 0 $ep2.DatabaseDtuMin
Assert-AreEqual 100 $ep2.DatabaseDtuMax
$all = $server | Get-AzureRmSqlElasticPool
Assert-AreEqual $all.Count 2
}
finally
{
Remove-ResourceGroupForTest $rg
}
}
<#
.SYNOPSIS
Tests getting an elastic pool metric
#>
function Test-GetElasticPoolMetric
{
# This test requires that an elastic pool has been created and has metrics ready
# To prevent requiring putting something like a Sleep(10 minutes) in the code
# this test requires the server/elastic pool be pre-created with metrics data available.
# Setup and retrieve the existing pool
$rgName = "test-group"
$serverName = "groupserver1"
$elasticPoolName = "testpool2"
$ep1 = Get-AzureRmSqlElasticPool -ServerName $serverName -ResourceGroupName $rgName `
-ElasticPoolName $elasticPoolName
Assert-NotNull $ep1
# Get pool metrics with all values
$metrics = $ep1 | Get-AzureRmMetric -TimeGrain "0:5:0" -StartTime "2015-04-22T16:00:00Z" -EndTime "2015-04-22T17:00:00Z"
Assert-NotNull $metrics
Assert-True { $metrics.Count -gt 0 }
}
<#
.SYNOPSIS
Tests removing an elastic pool
#>
function Test-RemoveElasticPool
{
# Setup
$rg = Create-ResourceGroupForTest
$server = Create-ServerForTest $rg "12.0" "Japan East"
$poolName = Get-ElasticPoolName
$ep1 = New-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName `
-ElasticPoolName $poolName -Edition Standard -Dtu 200 -DatabaseDtuMin 10 -DatabaseDtuMax 100
Assert-NotNull $ep1
$poolName = Get-ElasticPoolName
$ep2 = $server | New-AzureRmSqlElasticPool -ElasticPoolName $poolName -Edition Standard -Dtu 400 -DatabaseDtuMin 0 `
-DatabaseDtuMax 100
Assert-NotNull $ep2
try
{
# Create a pool with all values
Remove-AzureRmSqlElasticPool -ServerName $server.ServerName -ResourceGroupName $rg.ResourceGroupName -ElasticPoolName $ep1.ElasticPoolName –Confirm:$false
# Create a pool using piping
$ep2 | Remove-AzureRmSqlElasticPool -Force
$all = $server | Get-AzureRmSqlElasticPool
Assert-AreEqual $all.Count 0
}
finally
{
Remove-ResourceGroupForTest $rg
}
} | zhencui/azure-powershell | src/ResourceManager/Sql/Commands.Sql.Test/ScenarioTests/ElasticPoolCrudTests.ps1 | PowerShell | apache-2.0 | 7,528 |
###NOTE: This test module requires use of credentials. The first run through of the tests will prompt for credentials from the logged on user.
###This module has the following additional requirements;
### * Requires that the ActiveDirectory module is installed
### * Requires that the DAG computer account has been precreated
### * Requires at least two Exchange servers
### * Requires two machines that can be used as File Share Witnesses
Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue
Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchDatabaseAvailabilityGroup\MSFT_xExchDatabaseAvailabilityGroup.psm1
Import-Module $PSScriptRoot\..\Misc\xExchangeCommon.psm1 -Verbose:0
Import-Module $PSScriptRoot\xExchange.Tests.Common.psm1 -Verbose:0
#Removes the test DAG if it exists, and any associated databases
function PrepTestDAG
{
[CmdletBinding()]
param
(
[string]
$TestServerName1,
[string]
$TestServerName2,
[string]
$TestDAGName,
[string]
$TestDBName
)
Write-Verbose "Cleaning up test DAG and related resources"
GetRemoteExchangeSession -Credential $Global:ShellCredentials -CommandsToLoad "*-MailboxDatabase","*-DatabaseAvailabilityGroup","Remove-DatabaseAvailabilityGroupServer","Get-MailboxDatabaseCopyStatus","Remove-MailboxDatabaseCopy"
$existingDB = Get-MailboxDatabase -Identity "$($TestDBName)" -Status -ErrorAction SilentlyContinue
#First remove the test database copies
if ($existingDB -ne $null)
{
$mountedOnServer = $TestServerName1
if (($existingDB.MountedOnServer.ToLower().StartsWith($TestServerName2.ToLower())) -eq $true)
{
$mountedOnServer = $TestServerName2
}
Get-MailboxDatabaseCopyStatus -Identity "$($TestDBName)" | where {$_.MailboxServer -ne "$($mountedOnServer)"} | Remove-MailboxDatabaseCopy -Confirm:$false
}
#Now remove the actual DB's
Get-MailboxDatabase | where {$_.Name -like "$($TestDBName)"} | Remove-MailboxDatabase -Confirm:$false
#Remove the files
Get-ChildItem -LiteralPath "\\$($TestServerName1)\c`$\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue
Get-ChildItem -LiteralPath "\\$($TestServerName2)\c`$\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($TestDBName)" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue
#Last remove the test DAG
$dag = Get-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -ErrorAction SilentlyContinue
if ($dag -ne $null)
{
Set-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -DatacenterActivationMode Off
foreach ($server in $dag.Servers)
{
Remove-DatabaseAvailabilityGroupServer -MailboxServer "$($server.Name)" -Identity "$($TestDAGName)" -Confirm:$false
}
Remove-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -Confirm:$false
}
if ((Get-DatabaseAvailabilityGroup -Identity "$($TestDAGName)" -ErrorAction SilentlyContinue) -ne $null)
{
throw "Failed to remove test DAG"
}
#Disable the DAG computer account
$compAccount = Get-ADComputer -Identity $TestDAGName -ErrorAction SilentlyContinue
if ($compAccount -ne $null -and $compAccount.Enabled -eq $true)
{
$compAccount | Disable-ADAccount
}
Write-Verbose "Finished cleaning up test DAG and related resources"
}
$adModule = Get-Module -ListAvailable ActiveDirectory -ErrorAction SilentlyContinue
if ($adModule -ne $null)
{
if ($Global:DAGName -eq $null)
{
$Global:DAGName = Read-Host -Prompt "Enter the name of the DAG to use for testing"
}
$compAccount = Get-ADComputer -Identity $Global:DAGName -ErrorAction SilentlyContinue
if ($compAccount -ne $null)
{
#Check if Exchange is installed on this machine. If not, we can't run tests
[bool]$exchangeInstalled = IsSetupComplete
[string]$Global:TestDBName = "TestDAGDB1"
if ($exchangeInstalled)
{
#Get required credentials to use for the test
if ($Global:ShellCredentials -eq $null)
{
[PSCredential]$Global:ShellCredentials = Get-Credential -Message "Enter credentials for connecting a Remote PowerShell session to Exchange"
}
#Get the Server FQDN for using in URL's
if ($Global:ServerFqdn -eq $null)
{
$Global:ServerFqdn = [System.Net.Dns]::GetHostByName($env:COMPUTERNAME).HostName
}
if ($Global:SecondDAGMember -eq $null)
{
$Global:SecondDAGMember = Read-Host -Prompt "Enter the host name of the second DAG member to use for testing"
}
if ($Global:Witness1 -eq $null)
{
$Global:Witness1 = Read-Host -Prompt "Enter the FQDN of the first File Share Witness for testing"
}
if ($Global:Witness2 -eq $null)
{
$Global:Witness2 = Read-Host -Prompt "Enter the FQDN of the second File Share Witness for testing"
}
#Remove the existing DAG
PrepTestDAG -TestServerName1 $env:COMPUTERNAME -TestServerName2 $Global:SecondDAGMember -TestDAGName $Global:DAGName -TestDBName $Global:TestDBName
Describe "Test Creating and Modifying a DAG, adding DAG members, creating a DAG database, and adding database copies" {
#Create a new DAG
$dagTestParams = @{
Name = $Global:DAGName
Credential = $Global:ShellCredentials
AlternateWitnessServer = $Global:Witness2
AlternateWitnessDirectory = "C:\FSW"
AutoDagAutoReseedEnabled = $true
AutoDagDatabaseCopiesPerDatabase = 2
AutoDagDatabaseCopiesPerVolume = 2
AutoDagDatabasesRootFolderPath = "C:\ExchangeDatabases"
AutoDagDiskReclaimerEnabled = $true
AutoDagTotalNumberOfServers = 2
AutoDagTotalNumberOfDatabases = 2
AutoDagVolumesRootFolderPath = "C:\ExchangeVolumes"
DatabaseAvailabilityGroupIpAddresses = "192.168.1.99","192.168.2.99"
DatacenterActivationMode = "DagOnly"
ManualDagNetworkConfiguration = $true
NetworkCompression = "Enabled"
NetworkEncryption = "InterSubnetOnly"
ReplayLagManagerEnabled = $true
SkipDagValidation = $true
WitnessDirectory = "C:\FSW"
WitnessServer = $Global:Witness1
}
#Skip checking DatacenterActivationMode until we have DAG members
$dagExpectedGetResults = @{
Name = $Global:DAGName
AlternateWitnessServer = $Global:Witness2
AlternateWitnessDirectory = "C:\FSW"
AutoDagAutoReseedEnabled = $true
AutoDagDatabaseCopiesPerDatabase = 2
AutoDagDatabaseCopiesPerVolume = 2
AutoDagDatabasesRootFolderPath = "C:\ExchangeDatabases"
AutoDagDiskReclaimerEnabled = $true
AutoDagTotalNumberOfServers = 2
AutoDagTotalNumberOfDatabases = 2
AutoDagVolumesRootFolderPath = "C:\ExchangeVolumes"
ManualDagNetworkConfiguration = $true
NetworkCompression = "Enabled"
NetworkEncryption = "InterSubnetOnly"
ReplayLagManagerEnabled = $true
WitnessDirectory = "C:\FSW"
WitnessServer = $Global:Witness1
}
Test-AllTargetResourceFunctions -Params $dagTestParams -ContextLabel "Create the test DAG" -ExpectedGetResults $dagExpectedGetResults
Test-ArrayContents -TestParams $dagTestParams -DesiredArrayContents $dagTestParams.DatabaseAvailabilityGroupIpAddresses -GetResultParameterName "DatabaseAvailabilityGroupIpAddresses" -ContextLabel "Verify DatabaseAvailabilityGroupIpAddresses" -ItLabel "DatabaseAvailabilityGroupIpAddresses should contain two values"
#Add this server as a DAG member
Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue
Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchDatabaseAvailabilityGroupMember\MSFT_xExchDatabaseAvailabilityGroupMember.psm1
$dagMemberTestParams = @{
MailboxServer = $env:COMPUTERNAME
Credential = $Global:ShellCredentials
DAGName = $Global:DAGName
SkipDagValidation = $true
}
$dagMemberExpectedGetResults = @{
MailboxServer = $env:COMPUTERNAME
DAGName = $Global:DAGName
}
Test-AllTargetResourceFunctions -Params $dagMemberTestParams -ContextLabel "Add first member to the test DAG" -ExpectedGetResults $dagMemberExpectedGetResults
#Add second DAG member
$dagMemberTestParams = @{
MailboxServer = $Global:SecondDAGMember
Credential = $Global:ShellCredentials
DAGName = $Global:DAGName
SkipDagValidation = $true
}
$dagMemberExpectedGetResults = @{
MailboxServer = $Global:SecondDAGMember
DAGName = $Global:DAGName
}
Test-AllTargetResourceFunctions -Params $dagMemberTestParams -ContextLabel "Add second member to the test DAG" -ExpectedGetResults $dagMemberExpectedGetResults
#Test the DAG again, with props that only take effect once there are members
Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue
Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchDatabaseAvailabilityGroup\MSFT_xExchDatabaseAvailabilityGroup.psm1
$dagExpectedGetResults.DatacenterActivationMode = "DagOnly"
Test-AllTargetResourceFunctions -Params $dagTestParams -ContextLabel "Set remaining props on the test DAG" -ExpectedGetResults $dagExpectedGetResults
Test-ArrayContents -TestParams $dagTestParams -DesiredArrayContents $dagTestParams.DatabaseAvailabilityGroupIpAddresses -GetResultParameterName "DatabaseAvailabilityGroupIpAddresses" -ContextLabel "Verify DatabaseAvailabilityGroupIpAddresses" -ItLabel "DatabaseAvailabilityGroupIpAddresses should contain two values"
#Create a new DAG database
Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue
Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxDatabase\MSFT_xExchMailboxDatabase.psm1
$dagDBTestParams = @{
Name = $Global:TestDBName
Credential = $Global:ShellCredentials
AllowServiceRestart = $true
DatabaseCopyCount = 2
EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)\$($Global:TestDBName).edb"
LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)"
Server = $env:COMPUTERNAME
}
$dagDBExpectedGetResults = @{
Name = $Global:TestDBName
EdbFilePath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)\$($Global:TestDBName).edb"
LogFolderPath = "C:\Program Files\Microsoft\Exchange Server\V15\Mailbox\$($Global:TestDBName)"
Server = $env:COMPUTERNAME
}
Test-AllTargetResourceFunctions -Params $dagDBTestParams -ContextLabel "Create test database" -ExpectedGetResults $dagDBExpectedGetResults
#Add DB Copy
Get-Module MSFT_xExch* | Remove-Module -ErrorAction SilentlyContinue
Import-Module $PSScriptRoot\..\DSCResources\MSFT_xExchMailboxDatabaseCopy\MSFT_xExchMailboxDatabaseCopy.psm1
$dagDBCopyTestParams = @{
Identity = $Global:TestDBName
MailboxServer = $Global:SecondDAGMember
Credential = $Global:ShellCredentials
ActivationPreference = 2
}
$dagDBCopyExpectedGetResults = @{
Identity = $Global:TestDBName
MailboxServer = $Global:SecondDAGMember
ActivationPreference = 2
}
Test-AllTargetResourceFunctions -Params $dagDBCopyTestParams -ContextLabel "Add a database copy" -ExpectedGetResults $dagDBCopyExpectedGetResults
}
}
else
{
Write-Verbose "Tests in this file require that Exchange is installed to be run."
}
}
else
{
Write-Verbose "Tests in this file require that the computer account for the DAG is precreated"
}
}
else
{
Write-Verbose "Tests in this file require that the ActiveDirectory module is installed. Run: Add-WindowsFeature RSAT-ADDS"
}
| KarolKaczmarek/xExchange | Test/MSFT_xExchDatabaseAvailabilityGroup.Integration.Tests.ps1 | PowerShell | mit | 13,695 |
function New-ComplexNumber {
<#
.SYNOPSIS
Creates a new System.Numerics.Complex object.
.DESCRIPTION
Creates a Numerics.Complex object using either Real and Imaginary inputs or Magnitude and Phase inputs.
Can also create a complex object from Real One, Imaginary One, or Zero constants.
When no arguments are passed, creates a Complex object with real and imaginary components of zero.
.PARAMETER Real
Real component of the new complex object.
.PARAMETER Imaginary
Imaginary component of the new complex object.
.PARAMETER Magnitude
Magnitude component of the new complex object.
.PARAMETER Phase
Phase component of the new complex object.
.PARAMETER ImaginaryOne
Creates a complex object with an imaginary component of 1 (0+i).
.PARAMETER One
Creates a complex object with an real component of 1 (1+0i).
.PARAMETER Zero
Creates a complex number no components (0+0i).
.INPUTS
Multiple
.OUTPUTS
Returns System.Numerics.Complex object
.EXAMPLE
PS> New-ComplexNumber -Real 2 -Imaginary -3
Real Imaginary Magnitude Phase
---- --------- --------- -----
2 -3 3.60555127546399 -0.982793723247329
.EXAMPLE
PS> $m = New-ComplexNumber 3 1
PS> $a
Real Imaginary Magnitude Phase
---- --------- --------- -----
3 1 3.16227766016838 0.321750554396642
.EXAMPLE
PS> New-ComplexNumber -ImaginaryOne
Real Imaginary Magnitude Phase
---- --------- --------- -----
0 1 1 1.5707963267949
.EXAMPLE
PS> New-ComplexNumber -Magnitude 3.5 -Phase 0.25
Real Imaginary Magnitude Phase
---- --------- --------- -----
3.39119347598726 0.86591385739083 3.5 0.25
.LINK
Show-ComplexNumber
.LINK
Invoke-ComplexMath
.NOTES
Requires PowerShell 2.0
Requires the System.Numerics.dll
#>
[CmdLetBinding(DefaultParameterSetName='Cartesian')]
[OutputType([System.Numerics.Complex])]
param (
[Parameter(Position=0, ParameterSetName='Cartesian')]
[Double] $Real,
[Parameter(Position=1, ParameterSetName='Cartesian')]
[Double] $Imaginary,
[Parameter(Position=0, ParameterSetName='Polar')]
[Double] $Magnitude,
[Parameter(Position=1, ParameterSetName ='Polar')]
[Double] $Phase,
[Parameter(ParameterSetName='ImaginaryOne')]
[Alias('i1')]
[Switch] $ImaginaryOne,
[Parameter(ParameterSetname='One')]
[Alias('1')]
[Switch] $One,
[Parameter(ParameterSetname='Zero')]
[Alias('0')]
[Switch] $Zero
)
begin {
function NewComplexNumber {
New-Object System.Numerics.Complex $Real, $Imaginary
}
function NewComplexNumberFromPolar {
[System.Numerics.Complex]::FromPolarCoordinates($Magnitude, $Phase)
}
function NewComplexNumberFromConstant ($constantMethod) {
[System.Numerics.Complex]::$constantMethod
}
}
process {
switch ($PsCmdlet.ParameterSetName) {
'Cartesian' { NewComplexNumber }
'Polar' { NewComplexNumberFromPolar }
'ImaginaryOne' { NewComplexNumberFromConstant $_ }
'One' { NewComplexNumberFromConstant $_ }
'Zero' { NewComplexNumberFromConstant $_ }
}
}
}# __func
# __END__
| endowdly/PSComplexNumbers | Public/New-ComplexNumber.ps1 | PowerShell | mit | 4,626 |
Function New-HtmlRepairFooter
{
[CmdletBinding()]
param(
)
$emailSection = ''
$emailSection += '</body>'
return $emailSection;
} | HiltonGiesenow/PoShMon | src/Functions/PoShMon.MessageFormatters.Html.Repairs/New-HtmlRepairFooter.ps1 | PowerShell | mit | 166 |
param(
[Parameter()]
[string]$OfficeDeploymentPath,
[Parameter(Mandatory=$true)]
[String]$OfficeDeploymentFileName = $NULL,
[Parameter()]
[string]$Quiet = "True"
)
Set-Location $OfficeDeploymentPath
$scriptPath = "."
. $scriptPath\SharedFunctions.ps1
$officeProducts = Get-OfficeVersion -ShowAllInstalledProducts | Select *
$Office2016C2RExists = $officeProducts | Where {$_.ClickToRun -eq $true -and $_.Version -like '16.*' }
if(!$Office2016C2RExists){
$ActionFile = "$OfficeDeploymentPath\$OfficeDeploymentFileName"
if($OfficeDeploymentFileName.EndsWith("msi")){
if($Quiet -eq "True"){
$argList = "/qn /norestart"
} else {
$argList = "/norestart"
}
$cmdLine = """$ActionFile"" $argList"
$cmd = "cmd /c msiexec /i $cmdLine"
} elseif($OfficeDeploymentFileName.EndsWith("exe")){
if($Quiet -eq "True"){
$argList = "/silent"
}
$cmd = "$ActionFile $argList"
}
Invoke-Expression $cmd
} | OfficeDev/Office-IT-Pro-Deployment-Scripts | Office-ProPlus-Deployment/Setup-GPOOfficeInstallation/DeploymentFiles/DeployOfficeInstallationFile.ps1 | PowerShell | mit | 1,035 |
#
# Run the new parser, return either errors or the ast
#
function Get-ParseResults
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$True,Mandatory=$True)]
[string]$src,
[switch]$Ast
)
$errors = $null
$result = [System.Management.Automation.Language.Parser]::ParseInput($src, [ref]$null, [ref]$errors)
if ($Ast) { $result } else { ,$errors }
}
#
# Run script and return errors
#
function Get-RuntimeError
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$True,Mandatory=$True)]
[string]$src
)
$errors = $null
try
{
[scriptblock]::Create($src).Invoke() > $null
}
catch
{
return $_.Exception.InnerException.ErrorRecord
}
}
function position_message
{
param($position)
if ($position.Line.Length -lt $position.ColumnNumber)
{
$position.Line + " <<<<"
}
else
{
$position.Line.Insert($position.ColumnNumber, " <<<<")
}
}
#
# Run the new parser, check the errors against the expected errors
#
function Test-Error
{
[CmdletBinding()]
param([string]$src, [string[]]$expectedErrors, [int[]]$expectedOffsets)
Assert ($expectedErrors.Count -eq $expectedOffsets.Count) "Test case error"
$errors = Get-ParseResults -Src $src
if ($null -ne $errors)
{
Assert ($errors.Count -eq $expectedErrors.Count) "Expected $($expectedErrors.Count) errors, got $($errors.Count)"
for ($i = 0; $i -lt $errors.Count; ++$i)
{
$err = $errors[$i]
Assert ($expectedErrors[$i] -eq $err.ErrorId) ("Unexpected error: {0,-30}{1}" -f ("$($err.ErrorId):",
(position_message $err.Extent.StartScriptPosition)))
Assert ($expectedOffsets[$i] -eq $err.Extent.StartScriptPosition.Offset) `
"Expected position: $($expectedOffsets[$i]), got $($err.Extent.StartScriptPosition.Offset)"
}
}
else
{
Assert $false "Expected errors but didn't receive any."
}
}
#
# Pester friendly version of Test-Error
#
function ShouldBeParseError
{
[CmdletBinding()]
param(
[string]$src,
[string[]]$expectedErrors,
[int[]]$expectedOffsets,
# This is a temporary solution after moving type creation from parse time to runtime
[switch]$SkipAndCheckRuntimeError
)
Context "Parse error expected: <<$src>>" {
# Test case error if this fails
$expectedErrors.Count | Should Be $expectedOffsets.Count
if ($SkipAndCheckRuntimeError)
{
It "error should happen at parse time, not at runtime" -Skip {}
$errors = Get-RuntimeError -Src $src
# for runtime errors we will only get the first one
$expectedErrors = ,$expectedErrors[0]
$expectedOffsets = ,$expectedOffsets[0]
}
else
{
$errors = Get-ParseResults -Src $src
}
It "Error count" { $errors.Count | Should Be $expectedErrors.Count }
for ($i = 0; $i -lt $errors.Count; ++$i)
{
$err = $errors[$i]
if ($SkipAndCheckRuntimeError)
{
$errorId = $err.FullyQualifiedErrorId
}
else
{
$errorId = $err.ErrorId
}
It "Error Id" { $errorId | Should Be $expectedErrors[$i] }
It "Error position" -Pending:$SkipAndCheckRuntimeError { $err.Extent.StartScriptPosition.Offset | Should Be $expectedOffsets[$i] }
}
}
}
function Flatten-Ast
{
[CmdletBinding()]
param([System.Management.Automation.Language.Ast] $ast)
$ast
$ast | gm -type property | ? { ($prop = $_.Name) -ne 'Parent' } | % {
$ast.$prop | ? { $_ -is [System.Management.Automation.Language.Ast] } | % { Flatten-Ast $_ }
}
}
function Test-ErrorStmt
{
param([string]$src, [string]$errorStmtExtent)
$ast = Get-ParseResults $src -Ast
$asts = @(Flatten-Ast $ast.EndBlock.Statements[0])
Assert ($asts[0] -is [System.Management.Automation.Language.ErrorStatementAst]) "Expected error statement"
Assert ($asts.Count -eq $args.Count + 1) "Incorrect number of nested asts"
Assert ($asts[0].Extent.Text -eq $errorStmtExtent) "Error statement expected <$errorStmtExtent>, got <$($asts[0].Extent.Text)>"
for ($i = 0; $i -lt $args.Count; ++$i)
{
Assert ($asts[$i + 1].Extent.Text -eq $args[$i]) "Nested ast incorrect: <$($asts[$i+1].Extent.Text)>, expected <$($args[$i])>"
}
}
function Test-Ast
{
param([string]$src)
$ast = Get-ParseResults $src -Ast
$asts = @(Flatten-Ast $ast)
Assert ($asts.Count -eq $args.Count) "Incorrect number of nested asts, got $($asts.Count), expected $($args.Count)"
for ($i = 0; $i -lt $args.Count; ++$i)
{
Assert ($asts[$i].Extent.Text -eq $args[$i]) "Nested ast incorrect: <$($asts[$i].Extent.Text)>, expected <$($args[$i])>"
}
}
Export-ModuleMember -Function Test-Error, Test-ErrorStmt, Test-Ast, ShouldBeParseError, Get-ParseResults, Get-RuntimeError
| PowerShell/PowerShell-Tests | Scripting/LanguageTestSupport.psm1 | PowerShell | mit | 5,135 |
##########################################################################
# Picassio is a provisioning/deployment script which uses a single linear
# JSON file to determine what commands to execute.
#
# Copyright (c) 2015, Matthew Kelly (Badgerati)
# Company: Cadaeic Studios
# License: MIT (see LICENSE for details)
#########################################################################
# Tools for which to utilise in Picassio modules and extensions
# Returns the current version of Picassio
function Get-Version()
{
return '$version$'
}
# Returns the current version of PowerShell
function Get-PowerShellVersion()
{
try
{
return [decimal]([string](Get-Host | Select-Object Version).Version)
}
catch
{
return [decimal]((Get-Host).Version.Major)
}
}
# Checks to see if the user has administrator priviledges
function Test-AdminUser()
{
try
{
$principal = New-Object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal -eq $null)
{
return $false
}
return $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
catch [exception]
{
Write-Host 'Error checking user administrator priviledges'
Write-Host $_.Exception.Message -ForegroundColor Red
return $false
}
}
# Writes the help manual to the console
function Write-Help()
{
Write-Host 'Help Manual' -ForegroundColor Green
Write-Host ([string]::Empty)
if (!(Test-PicassioInstalled))
{
Write-Host 'To install Picassio use: ".\Picassio.ps1 -install"' -ForegroundColor Yellow
Write-Host ([string]::Empty)
}
Write-Host 'The following is a list of possible commands:'
Write-Host " -help`t`t Displays the help page"
Write-Host " -voice`t`t Enables voice over for some textual output"
Write-Host " -validate`t Validates the palette"
Write-Host " -install`t Installs/Updates Picassio, extensions are kept intact"
Write-Host " -uninstall`t Uninstalls Picassio"
Write-Host " -reinstall`t Uninstalls and then re-installs Picassio"
Write-Host " -version`t Displays the current version of Picassio"
Write-Host " -palette`t Specifies the picassio palette file to use (Default: picassio.palette)"
Write-Host " -paint`t`t Runs the palette file's paint section"
Write-Host " -erase`t`t Runs the palette file's erase section, if one is present"
Write-Host " -username`t [Optional] Your username to use for initial credentials"
Write-Host " -password`t [Optional] Your password, this can be left blank"
Write-Host " -force`t`t Forces Picassio to run, regardless of the user having administrator priviledges"
Write-Host ([string]::Empty)
}
# Writes the current version of Picassio to the console
function Write-Version()
{
$version = Get-Version
$psVersion = Get-PowerShellVersion
Write-Host "Picassio v$version (PS $psVersion)" -ForegroundColor Green
}
# Wipes a given directory
function Remove-Directory($directory)
{
Write-Message "Removing directory: '$directory'."
Remove-Item -Recurse -Force $directory | Out-Null
if (!$?)
{
throw 'Failed to remove directory.'
}
Write-Message 'Directory removed successfully.'
}
# Backs up a directory, appending the current date/time
function Backup-Directory($directory)
{
Write-Message "Backing-up directory: '$directory'"
$newDir = $directory + '_' + ([DateTime]::Now.ToString('yyyy-MM-dd_HH-mm-ss'))
Rename-Item $directory $newDir -Force | Out-Null
if (!$?)
{
throw 'Failed to backup directory.'
}
Write-Message "Directory '$directory' renamed to '$newDir'"
}
# Returns whether Picassio has been installed or not
function Test-PicassioInstalled()
{
return !([String]::IsNullOrWhiteSpace($env:PicassioTools) -or [String]::IsNullOrWhiteSpace($env:PicassioModules) -or [String]::IsNullOrWhiteSpace($env:PicassioExtensions))
}
# Writes a general message to the console (cyan)
function Write-Message([string]$message, $speech = $null)
{
Write-Host $message -ForegroundColor Cyan
Speak-Text $message $speech
}
# Writes a new line to the console
function Write-NewLine()
{
Write-Host ([string]::Empty)
}
# Writes error text to the console (red)
function Write-Errors([string]$message, $speech = $null, [switch]$tag)
{
if ($tag)
{
$message = "[ERROR] $message"
}
Write-Host $message -ForegroundColor Red
Speak-Text $message $speech
}
# Writes the exception to the console (red)
function Write-Exception($exception)
{
Write-Host $exception.GetType().FullName -ForegroundColor Red
Write-Host $exception.Message -ForegroundColor Red
}
# Write informative text to the console (green)
function Write-Information([string]$message, $speech = $null)
{
Write-Host $message -ForegroundColor Green
Speak-Text $message $speech
}
# Write a stamp message to the console (magenta)
function Write-Stamp([string]$message, $speech = $null)
{
Write-Host $message -ForegroundColor Magenta
Speak-Text $message $speech
}
# Writes a warning to the console (yellow)
function Write-Warnings([string]$message, $speech = $null, [switch]$tag)
{
if ($tag)
{
$message = "[WARNING] $message"
}
Write-Host $message -ForegroundColor Yellow
Speak-Text $message $speech
}
# Writes a header to the console in uppercase (magenta)
function Write-Header([string]$message)
{
if ($message -eq $null)
{
$message = [string]::Empty
}
$count = 65
$message = $message.ToUpper()
if ($message.Length -gt $count)
{
Write-Host "$message>" -ForegroundColor Magenta
}
else
{
$length = $count - $message.Length
$padding = ('=' * $length)
Write-Host "=$message$padding>" -ForegroundColor Magenta
}
}
# Writes a sub-header to the console in uppercase (dark yellow)
function Write-SubHeader([string]$message)
{
if ($message -eq $null)
{
$message = [string]::Empty
}
$count = 65
$message = $message.ToUpper()
if ($message.Length -gt $count)
{
Write-Host "$message>" -ForegroundColor DarkYellow
}
else
{
$length = $count - $message.Length
$padding = ('-' * $length)
Write-Host "-$message$padding>" -ForegroundColor DarkYellow
}
}
# Speaks the passed text using the passed speech object
function Speak-Text([string]$text, $speech)
{
if ($speech -eq $null -or [string]::IsNullOrWhiteSpace($text))
{
return
}
try
{
$speech.SpeakAsync($text) | Out-Null
}
catch { }
}
# Read input for the user, to check if they are sure about something (asks y/n)
function Read-AreYouSure()
{
$valid = @('y', 'n')
$value = Read-Host -Prompt "Are you sure you wish to continue? y/n"
if ([string]::IsNullOrWhiteSpace($value) -or $valid -inotcontains $value)
{
return Read-AreYouSure
}
return $value -ieq 'y'
}
# Resets the PATH for the current session
function Reset-Path($showMessage = $true)
{
$env:Path = (Get-EnvironmentVariable 'Path') + ';' + (Get-EnvironmentVariable 'Path' 'User')
if ($showMessage)
{
Write-Message 'Path updated.'
}
}
# Check to see if a piece of software is installed
function Test-Software($command, $name = $null)
{
try
{
# attempt to see if it's install via chocolatey
if (![String]::IsNullOrWhiteSpace($name))
{
try
{
$result = (choco.exe list -lo | Where-Object { $_ -ilike "*$name*" } | Measure-Object).Count
}
catch [exception]
{
$result = 0
}
if ($result -ne 0)
{
return $true
}
}
# attempt to call the program, see if we get a response back
$output = powershell.exe /C "$command" | Out-Null
if ($LASTEXITCODE -ne 0)
{
return $false
}
return $true
}
catch [exception] { }
return $false
}
# Tests to see if a URL is valid
function Test-Url($url)
{
if ([string]::IsNullOrWhiteSpace($url))
{
return $false
}
try
{
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
return $response.StatusCode -eq 200
}
catch [exception]
{
return $false
}
finally
{
if ($response -ne $null)
{
$response.Close()
}
}
}
# Installs software via Chocolatey on an adhoc basis
function Install-AdhocSoftware($packageName, $name, $installer = 'choco')
{
Write-Message "Installing $name."
if ([string]::IsNullOrWhiteSpace($packageName))
{
throw 'Package name for installing adhoc software cannot be empty.'
}
switch ($installer)
{
'choco'
{
if (!(Test-Software 'choco -v'))
{
Write-Warnings 'Chocolatey is not installed'
Install-Chocolatey
}
Run-Command 'choco.exe' "install $packageName -y"
}
'npm'
{
if (!(Test-Software 'node.exe -v' 'nodejs'))
{
Write-Warnings 'node.js is not installed'
Install-AdhocSoftware 'nodejs.install' 'node.js'
}
Run-Command 'npm' "install -g $packageName" $false $true
}
default
{
throw "Invalid installer type found for adhoc software: '$installer'."
}
}
# Was the install successful
if (!$?)
{
throw "Failed to install $name."
}
Reset-Path $false
Write-Message "Installation of $name successful."
}
# Install Chocolatey - if already installed, will just update
function Install-Chocolatey()
{
if (Test-Software 'choco -v')
{
Write-Message 'Chocolatey is already installed.'
return
}
Write-Message 'Installing Chocolately.'
$policies = @('Unrestricted', 'ByPass')
if ($policies -inotcontains (Get-ExecutionPolicy))
{
Set-ExecutionPolicy Bypass -Force
}
Run-Command "Invoke-Expression ((New-Object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" $null $true $true
Write-Message 'Chocolately installed.'
Reset-Path
}
# Check to see if we have a paint colour of the passed type
function Test-ColourType($json, $type)
{
$list = [array]($json.palette.paint | Where-Object { $_.type.ToLower() -eq $type.ToLower() })
return ($list.Length -ne 0)
}
# Return an environment variable
function Get-EnvironmentVariable($name, $level = 'Machine')
{
$value = [Environment]::GetEnvironmentVariable($name, $level)
if (!$?)
{
throw "Failed to get environment variable '$name' from '$level' level."
}
return $value
}
# Sets an environment variable
function Set-EnvironmentVariable($name, $value, $level = 'Machine')
{
[Environment]::SetEnvironmentVariable($name, $value, $level)
if (!$?)
{
throw "Failed to set environment variable '$name' at '$level' level."
}
}
# Tests whether the current shell is open in a 32-bit host
function Test-Win32()
{
return [IntPtr]::Size -eq 4;
}
# Tests whether the current shell is open in a 64-bit host
function Test-Win64()
{
return [IntPtr]::Size -eq 8;
}
# Runs the passed command and arguments. If fails displays the last 200 lines of output
function Run-Command([string]$command, [string]$_args, [bool]$fullOutput = $false, [bool]$isPowershell = $false, [bool]$ignoreFailure = $false)
{
Write-Information "Running command: '$command $_args'"
if ($ignoreFailure)
{
Write-Warnings 'Failures are being suppressed' -tag
}
if ($isPowershell)
{
$output = powershell.exe /C "`"$command`" $_args"
if (!$? -and !$ignoreFailure)
{
if ($output -ne $null)
{
if (!$fullOutput)
{
$output = ($output | Select-Object -Last 200)
}
$output | ForEach-Object { Write-Errors $_ }
}
throw "Command '$command' failed to complete."
}
}
else
{
$output = cmd.exe /C "`"$command`" $_args"
$code = $LASTEXITCODE
if ($code -ne 0 -and !$ignoreFailure)
{
if ($output -ne $null)
{
if (!$fullOutput)
{
$output = ($output | Select-Object -Last 200)
}
$output | ForEach-Object { Write-Errors $_ }
}
throw "Command '$command' failed to complete. Exit code: $code"
}
}
}
# Returns the regex for variables
function Get-VariableRegex()
{
return '(?<var>[a-zA-Z0-9_]+)'
}
# Replaces a passed value with variable substitutes
function Replace-Variables($value, $variables)
{
if ($variables -eq $null -or $variables.Count -eq 0 -or [string]::IsNullOrWhiteSpace($value))
{
return $value
}
$varregex = Get-VariableRegex
$pattern = "#\($varregex\)"
$varnames = ($value | Select-String -Pattern $pattern -AllMatches | ForEach-Object { $_.Matches } | ForEach-Object { $_.Groups['var'].Value })
if ($varnames -eq $null -or $varnames.Count -eq 0)
{
return $value
}
ForEach ($varname in $varnames)
{
if (!$variables.ContainsKey($varname))
{
continue
}
$val = $variables[$varname]
$var = "#\($varname\)"
$value = ($value -replace $var, $val)
}
return $value
}
| Badgerati/Picassio | src/Tools/PicassioTools.psm1 | PowerShell | mit | 13,904 |
<#
.Synopsis
Convert an integer from the common object model (JSON)
{"Date": "2019-04-15T00:00:00+02:00"} => 2019-04-15T00:00:00
#>
[CmdletBinding()]
[OutputType([datetime])]
param(
[Parameter(Mandatory,ValueFromPipeline)][string]$InputObject
)
process {
# Support piped ($_) and parameter input ($InputObject)
if ($_) {$IN=$_}else{$IN=$InputObject}
$Val = $IN | ConvertFrom-Json
Get-Date $Val.Date
} | cawoodm/powowshell | core/adaptors/datetime.in.ps1 | PowerShell | mit | 423 |
# Copyright (c) 2002-2015 "Neo Technology,"
# Network Engine for Objects in Lund AB [http://neotechnology.com]
#
# This file is part of Neo4j.
#
# Neo4j is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
<#
.SYNOPSIS
Start a Neo4j shell process
.DESCRIPTION
Start a Neo4j shell process
.PARAMETER Neo4jServer
An object representing a Neo4j Server. Either an empty string (path determined by Get-Neo4jHome), a string (path to Neo4j installation) or a valid Neo4j Server object
.PARAMETER UseHost
The hostname of the Neo4j Shell server to connect to. If no host is specified, the host is determined from the Neo4j Configuration files (default)
.PARAMETER UsePort
The TCP port of the Neo4j Shell server to connect to. If no port is specified, the port is determined from the Neo4j Configuration files (default)
.PARAMETER Wait
Wait for the shell process to complete
.PARAMETER PassThru
Pass through the Neo4j Server object instead of the result of the shell process
.PARAMETER OtherArgs
All other parameters are passed through to the Neo4j Shell Utility
.EXAMPLE
'C:\Neo4j\neo4j-community' | Start-Neo4jShell -file "C:\Database.cypher" -Wait
Start and wait for a Neo4j Shell for the instance at C:\Neo4j\neo4j-community and execute the cypher statements in C:\Database.cypher
.OUTPUTS
System.Int32
Exitcode of shell process
System.Management.Automation.PSCustomObject
Neo4j Server object (-PassThru)
.LINK
Initialize-Neo4jServer
.LINK
http://neo4j.com/docs/stable/shell.html
#>
Function Start-Neo4jShell
{
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param (
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[object]$Neo4jServer = ''
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[Alias('Host')]
[string]$UseHost = ''
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[Alias('ShellPort','Port')]
[ValidateRange(0,65535)]
[int]$UsePort = -1
,[Parameter(Mandatory=$false)]
[switch]$Wait
,[Parameter(Mandatory=$false)]
[switch]$PassThru
,[Parameter(ValueFromRemainingArguments = $true)]
[Object[]]$OtherArgs
)
Begin
{
}
Process
{
# Get the Neo4j Server information
if ($Neo4jServer -eq $null) { $Neo4jServer = '' }
switch ($Neo4jServer.GetType().ToString())
{
'System.Management.Automation.PSCustomObject'
{
if (-not (Confirm-Neo4jServerObject -Neo4jServer $Neo4jServer))
{
Write-Error "The specified Neo4j Server object is not valid"
return
}
$thisServer = $Neo4jServer
}
default
{
$thisServer = Get-Neo4jServer -Neo4jHome $Neo4jServer
}
}
if ($thisServer -eq $null) { return }
$ShellRemoteEnabled = $false
$ShellHost = '127.0.0.1'
$Port = 1337
Get-Neo4jSetting -Neo4jServer $thisServer | ForEach-Object -Process `
{
if (($_.ConfigurationFile -eq 'neo4j.properties') -and ($_.Name -eq 'remote_shell_enabled')) { $ShellRemoteEnabled = ($_.Value.ToUpper() -eq 'TRUE') }
if (($_.ConfigurationFile -eq 'neo4j.properties') -and ($_.Name -eq 'remote_shell_host')) { $ShellHost = ($_.Value) }
if (($_.ConfigurationFile -eq 'neo4j.properties') -and ($_.Name -eq 'remote_shell_port')) { $Port = [int]($_.Value) }
}
if (!$ShellRemoteEnabled) { $ShellHost = 'localhost' }
if ($UseHost -ne '') { $ShellHost = $UseHost }
if ($UsePort -ne -1) { $Port = $UsePort }
$JavaCMD = Get-Java -Neo4jServer $thisServer -ForUtility -AppName 'neo4j-shell' -StartingClass 'org.neo4j.shell.StartClient'
if ($JavaCMD -eq $null)
{
Write-Error 'Unable to locate Java'
return
}
$ShellArgs = $JavaCMD.args
if ($ShellArgs -eq $null) { $ShellArgs = @() }
$ShellArgs += @('-host',"$ShellHost")
$ShellArgs += @('-port',"$Port")
# Add unbounded command line arguments
if ($OtherArgs -ne $null) { $ShellArgs += $OtherArgs }
if ($PSCmdlet.ShouldProcess("$($JavaCMD.java) $($ShellArgs)", 'Start Neo4j Shell'))
{
$result = (Start-Process -FilePath $JavaCMD.java -ArgumentList $ShellArgs -Wait:$Wait -NoNewWindow:$Wait -PassThru)
}
if ($PassThru) { Write-Output $thisServer } else { Write-Output $result.ExitCode }
}
End
{
}
}
| glennsarti/spike-Neo4J-Windows-Experiments | posh-neo-cm/packaging/standalone/src/main/distribution/shell-scripts/bin/Neo4j-Management/Start-Neo4jShell.ps1 | PowerShell | mit | 4,890 |
$betaProjectItemFragment = Get-Content -Raw "$PSScriptRoot/BetaProjectItemFragment.graphql"
function Add-GitHubBetaProjectItem {
<#
.SYNOPSIS
EXPERIMENTAL: Adds an item to a GitHub project (Beta).
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string] $ProjectNodeId,
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[Alias('node_id', 'id')]
[ValidateNotNullOrEmpty()]
[string] $ContentNodeId,
# Optional base URL of the GitHub API, for example "https://ghe.mycompany.com/api/v3/" (including the trailing slash).
# Defaults to "https://api.github.com"
[Uri] $BaseUri = [Uri]::new('https://api.github.com'),
[Security.SecureString] $Token
)
process {
$result = Invoke-GitHubGraphQlApi `
-Headers @{ 'GraphQL-Features' = 'projects_next_graphql' } `
-Query ('mutation($input: AddProjectNextItemInput!) {
addProjectNextItem(input: $input) {
projectNextItem {
...BetaProjectItemFragment
}
}
}
' + $betaProjectItemFragment) `
-Variables @{
input = @{
projectId = $ProjectNodeId
contentId = $ContentNodeId
}
} `
-BaseUri $BaseUri `
-Token $Token
$item = $result.addProjectNextItem.projectNextItem
Add-Member -InputObject $item -NotePropertyName 'ProjectNodeId' -NotePropertyValue $ProjectNodeId
# Expose fields as ergonomic name=>value hashtable
$fieldHashTable = [ordered]@{ }
foreach ($fieldValue in $item.fieldValues.nodes) {
$fieldValue.projectField.settings = $fieldValue.projectField.settings | ConvertFrom-Json
$fieldSettings = $fieldValue.projectField.settings
$value = if ($fieldSettings -and $fieldSettings.PSObject.Properties['options']) {
($fieldSettings.options | Where-Object { $_.id -eq $fieldValue.value }).Name
} else {
$fieldValue.value
}
$fieldHashTable[$fieldValue.projectField.name] = $value
}
Add-Member -InputObject $item -NotePropertyName 'Fields' -NotePropertyValue $fieldHashTable
if ($item.content) {
$item.content.labels = $item.content.labels.nodes
$item.content.assignees = $item.content.assignees.nodes
}
$item
}
}
| pcgeek86/PSGitHub | Functions/Public/Projects/Add-GitHubBetaProjectItem.ps1 | PowerShell | mit | 2,595 |
#requires -version 3.0
param
(
[string]$DeployEnvironment,
[switch]$ExecuteRemoteDeployment = $false,
[switch]$Interactive = $false
)
$ErrorActionPreference = "Stop"
function PSScriptRoot { $MyInvocation.ScriptName | Split-Path }
#Set-StrictMode -Version Latest
function Get-DeployEnvironment() {
$environmentPath = "$(PSScriptRoot)\..\Environments"
Write-Host "Environment to deploy was not specified. Valid environments are:" -ForegroundColor Yellow
Get-ChildItem $environmentPath -Directory | foreach {
Write-Host $_.Name
}
$environment = Read-Host "Specify the environment"
$candidatePath = "$($environmentPath)\$($environment)"
if(!(Test-Path $candidatePath)) {
Write-Host "Environment selected was not valid." -ForegroundColor Red
return Get-DeployEnvironment
}
else {
return $environment
}
}
if([string]::IsNullOrWhiteSpace($DeployEnvironment)) {
$DeployEnvironment = Get-DeployEnvironment
}
# Start up logging
. "$(PSScriptRoot)\ScriptLogger.ps1"
Start-Transcript -Path "$(PSScriptRoot)\..\build.log"
# Load global properties files in order
Get-ChildItem -Path "$(PSScriptRoot)\Properties" -Filter *.ps1 | foreach {
Write-Host "Loading global properties file $($_.FullName)" -ForegroundColor DarkGreen
. $_.FullName
}
. "$(PSScriptRoot)\Pipelines.ps1"
# Get all the cascade pipeline directories (e.g. all archetypes' pipelines and the environment's pipeline)
$CascadePipelineDirectories = @()
$ArchetypeDirectories | foreach {
$CascadePipelineDirectories += Join-Path $_ "Pipelines"
}
$CascadePipelineDirectories += Join-Path $EnvironmentDirectory "Pipelines"
# Make magic occur - invoke all global pipelines, followed by any cascading extensions and cascading custom pipelines
Invoke-PipelineCascade "$(PSScriptRoot)\..\Global" $CascadePipelineDirectories -Interactive:$Interactive
Write-Warning-Summary
Write-Error-Summary
Stop-Transcript
Write-Host "All done!" -ForegroundColor Magenta | kamsar/Beaver | Build/System/deploy.ps1 | PowerShell | mit | 2,025 |
$packageName = 'byteball'
$installerType = 'exe'
$silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
$url = 'https://github.com/byteball/byteball/releases/download/v1.11.0/Byteball-win32.exe'
$checksum = '07f97d16b84a9ac158b3cb07a7d244430a65d51ed2189b9e6011f950f70b8abe'
$checksumType = 'sha256'
$url64 = 'https://github.com/byteball/byteball/releases/download/v1.11.0/Byteball-win64.exe'
$checksum64 = '307ca94c76acb2c5e6134042a79148c43e9ef2bdfc10eb2cb8c4683d6a9ead42'
$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/byteball/1.11.0/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 1,064 |
$packageName = '{{PackageName}}'
$packageSearch = $packageName
$installerType = 'exe'
$silentArgs = '/S'
$validExitCodes = @(0)
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*" } `
| ForEach-Object { Uninstall-ChocolateyPackage -PackageName "$packageName" `
-FileType "$installerType" `
-SilentArgs "$($silentArgs)" `
-File "$($_.UninstallString.Replace('"',''))" `
-ValidExitCodes $validExitCodes } | dtgm/chocolatey-packages | automatic/winedt/tools/chocolateyUninstall.ps1 | PowerShell | apache-2.0 | 742 |
function Add-VSAmazonMQBrokerUser {
<#
.SYNOPSIS
Adds an AWS::AmazonMQ::Broker.User resource property to the template. The list of ActiveMQ users (persons or applications who can access queues and topics. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~. This value must be 2-100 characters long.
.DESCRIPTION
Adds an AWS::AmazonMQ::Broker.User resource property to the template.
The list of ActiveMQ users (persons or applications who can access queues and topics. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes (- . _ ~. This value must be 2-100 characters long.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html
.PARAMETER Username
The username of the ActiveMQ user. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes - . _ ~. This value must be 2-100 characters long.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-username
PrimitiveType: String
UpdateType: Mutable
.PARAMETER Groups
The list of groups 20 maximum to which the ActiveMQ user belongs. This value can contain only alphanumeric characters, dashes, periods, underscores, and tildes - . _ ~. This value must be 2-100 characters long.
PrimitiveItemType: String
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-groups
UpdateType: Mutable
.PARAMETER ConsoleAccess
Enables access to the the ActiveMQ Web Console for the ActiveMQ user.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-consoleaccess
PrimitiveType: Boolean
UpdateType: Mutable
.PARAMETER Password
The password of the ActiveMQ user. This value must be at least 12 characters long, must contain at least 4 unique characters, and must not contain commas.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-amazonmq-broker-user.html#cfn-amazonmq-broker-user-password
PrimitiveType: String
UpdateType: Mutable
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.AmazonMQ.Broker.User')]
[cmdletbinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","Password")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPasswordParams","Password")]
Param
(
[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 ", ")."))
}
})]
$Username,
[parameter(Mandatory = $false)]
$Groups,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Boolean","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$ConsoleAccess,
[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 ", ")."))
}
})]
$Password
)
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.AmazonMQ.Broker.User'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSAmazonMQBrokerUser.ps1 | PowerShell | apache-2.0 | 5,532 |
function Add-VSWAFv2WebACLSingleHeader {
<#
.SYNOPSIS
Adds an AWS::WAFv2::WebACL.SingleHeader resource property to the template.
.DESCRIPTION
Adds an AWS::WAFv2::WebACL.SingleHeader resource property to the template.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafv2-webacl-singleheader.html
.PARAMETER Name
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafv2-webacl-singleheader.html#cfn-wafv2-webacl-singleheader-name
UpdateType: Mutable
PrimitiveType: String
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.WAFv2.WebACL.SingleHeader')]
[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 ", ")."))
}
})]
$Name
)
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.WAFv2.WebACL.SingleHeader'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSWAFv2WebACLSingleHeader.ps1 | PowerShell | apache-2.0 | 2,186 |
<#
.Synopsis
My implementation of an command line for customized for the .net developer. Specifically tailored to my preferred tools.
(msbuild, mercurial, Visual Studio, and TeamCity)
.Description
My implementation of an improved command line for the .net developer. Specifically for those using my preferred tools.
Implement each of the following functions as you see fit for your project. For example, the 'develop_project' function
would likely open a .sln file, choosing the proper version of Visual Studio if necessary. That function might look like
this:
function develop_project {
devenv MySolution.sln
}
Note that when these functions are invoked, the current working directory is always set to the root of the project (which
is where this file is as well). Once the command exits the user will be returned to the directory they were in.
This file should be checked into your project's source control.
#>
function build_project {
msbuild .\AgentRalph.proj /v:minimal
}
function test_project {
&"c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe" Ralph.Test.Project\Ralph.Test.Project.sln /ReSharper.Plugin Bin\Debug\Ralph.Plugin.dll
}
function clean_project {
msbuild .\AgentRalph.proj /t:Clean /v:minimal
rm-orig
}
function rebuild_project {
#msbuild .\AgentRalph.proj /t:Rebuild /v:minimal
write-host "*****************************************************************************"
write-host "***Rebuild actually builds for release including making the nuget package.***"
write-host "*****************************************************************************"
msbuild .\AgentRalph.proj /t:Release /p:Configuration=Release /v:minimal /p:BUILD_NUMBER=3
}
function develop_project {
.\AgentRalph.sln
}
function pushenv_project {
"The 'pushenv' command has not been created. Edit your project-stuff.psm1 file and add your project specific command(s) to the pushenv_project function."
}
function popenv_project {
"The 'popenv' command has not been created. Edit your project-stuff.psm1 file and add your project specific command(s) to the popenv_project function."
}
export-modulemember -function build_project
export-modulemember -function test_project
export-modulemember -function clean_project
export-modulemember -function rebuild_project
export-modulemember -function develop_project
export-modulemember -function pushenv_project
export-modulemember -function popenv_project
| jbuedel/AgentRalphPlugin | .project-commands.psm1 | PowerShell | bsd-3-clause | 2,507 |
pandoc slides.md -f markdown -t beamer -o slides.pdf
| bjornbm/dimensional-dk-experimental | makeslides.ps1 | PowerShell | bsd-3-clause | 53 |
# PSJob Perf Test
$code = {
$begin = Get-Date
$result = Get-Process
$end = Get-Date
$begin
$end
$result
}
# Start job creation; also used for other reference
$start = Get-Date
$job = Start-Job -ScriptBlock $code
[void](Wait-Job $job)
#Job completed
$completed = Get-Date
$result = Receive-Job $job
#Time to get job results
$received = Get-Date
$spinup = $result[0]
$exit = $result[1]
$timeToLaunch = ($spinup - $start).TotalMilliseconds
$timeToExit = ($completed - $exit).TotalMilliseconds
$timeToRunCommand = ($exit - $spinup).TotalMilliseconds
$timeToReceive = ($received - $completed).TotalMilliseconds
$TotalTime = ($received - $start).TotalMilliseconds
[pscustomobject]@{
Type = 'PSJob'
SetUpJob = $timeToLaunch
RunCode = $timeToRunCommand
ExitJob = $timeToExit
RecieveResults = $timeToReceive
Total = $TotalTime
}
| proxb/Presentations | Tampa - A Look at PowerShell Runspaces/4_2_1_RunspacesDemo_PSJobPerf.ps1 | PowerShell | mit | 874 |
###############################################################################
##
## Description:
## Check NIC's RX and TX after reboot
##
###############################################################################
##
## Revision:
## V1.0 - boyang - 10/23/2017 - Build script
##
###############################################################################
<#
.Synopsis
Check NIC's RX and TX after reboot
.Description
Change NIC's RX and TX, reboot, check again
.Parameter vmName
Name of the test VM.
.Parameter hvServer
Name of the VIServer hosting the VM.
.Parameter testParams
Semicolon separated list of test parameters.
#>
param([String] $vmName, [String] $hvServer, [String] $testParams)
#
# Checking the input arguments
#
if (-not $vmName)
{
"FAIL: VM name cannot be null!"
exit
}
if (-not $hvServer)
{
"FAIL: hvServer cannot be null!"
exit
}
if (-not $testParams)
{
Throw "FAIL: No test parameters specified"
}
#
# Output test parameters so they are captured in log file
#
"TestParams : '${testParams}'"
#
# Parse test parameters
#
$rootDir = $null
$sshKey = $null
$ipv4 = $null
$logdir = $null
$params = $testParams.Split(";")
foreach ($p in $params)
{
$fields = $p.Split("=")
switch ($fields[0].Trim())
{
"rootDir" { $rootDir = $fields[1].Trim() }
"sshKey" { $sshKey = $fields[1].Trim() }
"ipv4" { $ipv4 = $fields[1].Trim() }
"TestLogDir" { $logdir = $fields[1].Trim()}
default {}
}
}
#
# Check all parameters are valid
#
if (-not $rootDir)
{
"Warn : no rootdir was specified"
}
else
{
if ( (Test-Path -Path "${rootDir}") )
{
cd $rootDir
}
else
{
"Warn : rootdir '${rootDir}' does not exist"
}
}
if ($null -eq $sshKey)
{
"FAIL: Test parameter sshKey was not specified"
return $False
}
if ($null -eq $ipv4)
{
"FAIL: Test parameter ipv4 was not specified"
return $False
}
if ($null -eq $logdir)
{
"FAIL: Test parameter logdir was not specified"
return $False
}
#
# Source tcutils.ps1
#
. .\setupscripts\tcutils.ps1
PowerCLIImport
ConnectToVIServer $env:ENVVISIPADDR `
$env:ENVVISUSERNAME `
$env:ENVVISPASSWORD `
$env:ENVVISPROTOCOL
###############################################################################
#
# Main Body
#
###############################################################################
$retVal = $Failed
#
# Confirm NIC interface types. RHELs has different NIC types, like "eth0" "ens192:" "enp0s25:"
# After snapshot, defalut, NIC works and MTU is 1500
#
$eth = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ls /sys/class/net/ | grep ^e[tn][hosp]"
#
# Check $eth Ring current RX, TX parameters
# For target RX, TX value = current RX TX value / 2
#
$rx_current = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ethtool -g $eth | grep ^RX: | awk 'NR==2{print `$2`}'"
Write-Host -F Gray "rx_current is $rx_current......."
Write-Output "rx_current is $rx_current"
$rx_other = $rx_current / 2
Write-Host -F Gray "rx_other is $rx_other......."
Write-Output "rx_other is $rx_other"
$tx_current = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ethtool -g $eth | grep ^TX: | awk 'NR==2{print `$2`}'"
Write-Host -F Gray "tx_current is $tx_current......."
Write-Output "tx_current is $tx_current"
$tx_other = $tx_current / 2
Write-Host -F Gray "tx_other is $tx_other......."
Write-Output "tx_other is $tx_other"
#
# Resize rx, tx to other value
#
$result = SendCommandToVM $ipv4 $sshKey "ethtool -G $eth rx $rx_other tx $tx_other"
if (-not $result)
{ Write-Host -F Red "WARNING: ethtool -G failed, abort......."
Write-Output "WARNING: ethtool -G failed, abort"
DisconnectWithVIServer
return $Aborted
}
#
# Confirm RX, TX other value is done
#
$rx_new = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ethtool -g $eth | grep ^RX: | awk 'NR==2{print `$2`}'"
Write-Host -F Gray "rx_new is $rx_new"
Write-Output "rx_new is $rx_new"
if ($rx_new -ne $rx_other)
{
Write-Host -F Gray "WARNING: Resize rx failed, abort......."
Write-Output "WARNING: Resize rx failed, abort"
DisconnectWithVIServer
return $Aborted
}
$tx_new = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ethtool -g $eth | grep ^TX: | awk 'NR==2{print `$2`}'"
Write-Host -F Gray "tx_new is $tx_new"
Write-Output "tx_new is $tx_new"
if ($tx_new -ne $tx_other)
{
Write-Host -F Gray "WARNING: Resize tx failed, abort......."
Write-Output "WARNING: Resize tx failed, abort"
DisconnectWithVIServer
return $Aborted
}
#
# Reboot the VM, rx / tx should be = $rx_current / $tx_current
#
Write-Host -F Gray "Start to reboot VM after change rx / tx value......."
Write-Output "Start to reboot VM after change rx / tx value"
bin\plink.exe -i ssh\${sshKey} root@${ipv4} "init 6"
$timeout = 360
while ($timeout -gt 0)
{
$vmObject = Get-VMHost -Name $hvServer | Get-VM -Name $vmName
$vmPowerState = $vmObject.PowerState
Write-Host -F Gray "The VM power state is $vmPowerState......."
Write-Output "The VM B power state is $vmPowerState"
if ($vmPowerState -eq "PoweredOn")
{
$ipv4 = GetIPv4 $vmName $hvServer
Write-Host -F Gray "The VM ipv4 is $ipv4......."
Write-Output "The VM ipv4 is $ipv4"
if ($ipv4 -ne $null)
{
# Maybe the first some times, will fail as rx / tx not ready
Start-Sleep -S 6
$rx_after_reboot = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ethtool -g $eth | grep ^RX: | awk 'NR==2{print `$2`}'"
$tx_after_reboot = bin\plink.exe -i ssh\${sshKey} root@${ipv4} "ethtool -g $eth | grep ^TX: | awk 'NR==2{print `$2`}'"
if ($rx_after_reboot -eq $rx_current -and $tx_after_reboot -eq $tx_current)
{
Write-Host -F Green "PASS: After reboot, rx / tx returns to original value......."
Write-Output "PASS: After reboot, rx / tx returns to original value"
$retVal = $Passed
break
}
else
{
Write-Host -F Red "FAIL: After reboot, rx / tx couldn't return to original value......."
Write-Output "FAIL: After reboot, rx / tx couldn't return to original value"
}
}
}
Start-Sleep -S 6
$timeout = $timeout - 6
if ($timeout -eq 0)
{
Write-Host -F Yellow "WARNING: Timeout to reboot the VM, abort......."
Write-Output "WARNING: Timeout to reboot the VM, abort"
return $Aborted
}
}
DisconnectWithVIServer
return $retVal | VirtQE-S1/ESX-LISA | testscripts/nw_check_rx_tx_after_reboot.ps1 | PowerShell | apache-2.0 | 6,560 |
<#######################################################################################
# MSDSCPack_IPAddress : DSC Resource that will set/test/get the current IP
# Address, by accepting values among those given in MSDSCPack_IPAddress.schema.mof
#######################################################################################>
######################################################################################
# The Get-TargetResource cmdlet.
# This function will get the present list of IP Address DSC Resource schema variables on the system
######################################################################################
function Get-TargetResource
{
[OutputType([System.Collections.Hashtable])]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$IPAddress,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$InterfaceAlias,
[uInt32]$SubnetMask = 16,
[ValidateNotNullOrEmpty()]
[String]$DefaultGateway,
[ValidateSet("IPv4", "IPv6")]
[String]$AddressFamily = "IPv4"
)
$returnValue = @{
IPAddress = [System.String]::Join(", ",(Get-NetIPAddress -InterfaceAlias $InterfaceAlias `
-AddressFamily $AddressFamily).IPAddress)
SubnetMask = $SubnetMask
DefaultGateway = $DefaultGateway
AddressFamily = $AddressFamily
InterfaceAlias=$InterfaceAlias
}
$returnValue
}
######################################################################################
# The Set-TargetResource cmdlet.
# This function will set a new IP Address in the current node
######################################################################################
function Set-TargetResource
{
param
(
#IP Address that has to be set
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$IPAddress,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$InterfaceAlias,
[uInt32]$SubnetMask,
[ValidateNotNullOrEmpty()]
[String]$DefaultGateway,
[ValidateSet("IPv4", "IPv6")]
[String]$AddressFamily = "IPv4"
)
ValidateProperties @PSBoundParameters -Apply
}
######################################################################################
# The Test-TargetResource cmdlet.
# This will test if the given IP Address is among the current node's IP Address collection
######################################################################################
function Test-TargetResource
{
[OutputType([System.Boolean])]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$IPAddress,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$InterfaceAlias,
[uInt32]$SubnetMask,
[ValidateNotNullOrEmpty()]
[String]$DefaultGateway,
[ValidateSet("IPv4", "IPv6")]
[String]$AddressFamily = "IPv4"
)
ValidateProperties @PSBoundParameters
}
#######################################################################################
# Helper function that validates the IP Address properties. If the switch parameter
# "Apply" is set, then it will set the properties after a test
#######################################################################################
function ValidateProperties
{
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$IPAddress,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$InterfaceAlias,
[ValidateNotNullOrEmpty()]
[String]$DefaultGateway,
[uInt32]$SubnetMask = 16,
[ValidateSet("IPv4", "IPv6")]
[String]$AddressFamily = "IPv4",
[Switch]$NoReset,
[Switch]$Apply
)
if(-not ([System.Net.Ipaddress]::TryParse($IPAddress, [ref]0)))
{
throw ( @(
"IP Address *$IPAddress* is not in the correct format. Please correct the IPAddress "
"parameter in the configuration and try again."
) -join ""
)
}
try
{
# Flag to signal whether settings are correct
$requiresChanges = $false
Write-Verbose -Message "Checking the IPAddress ..."
# Get the current IP Address based on the parameters given.
$currentIP = Get-NetIPAddress -InterfaceAlias $InterfaceAlias -AddressFamily `
$AddressFamily -ErrorAction Stop
# Test if the IP Address passed is present
if(-not $currentIP.IPAddress.Contains($IPAddress))
{
Write-Verbose -Message ( @(
"IPAddress does NOT match desired state. Expected $IPAddress, actual "
"$($currentIP.IPAddress)."
) -join ""
)
$requiresChanges = $true
}
else
{
Write-Verbose -Message "IPAddress is correct."
# Filter the IP addresses for the IP address to check
$filterIP = $currentIP | where { $_.IPAddress -eq $IPAddress }
# Only test the Subnet Mask if the IP address is present
if(-not $filterIP.PrefixLength.Equals([byte]$SubnetMask))
{
Write-Verbose -Message ( @(
"Subnet mask does NOT match desired state. Expected $SubnetMask, actual "
"$($filterIP.PrefixLength)."
) -join ""
)
$requiresChanges = $true
}
else
{
Write-Verbose -Message "Subnet mask is correct."
}
}
# Use $AddressFamily to select the IPv4 or IPv6 destination prefix
$DestinationPrefix = "0.0.0.0/0"
if($AddressFamily -eq "IPv6")
{
$DestinationPrefix = "::/0"
}
# Get all the default routes
$defaultRoutes = Get-NetRoute -InterfaceAlias $InterfaceAlias -AddressFamily `
$AddressFamily -ErrorAction Stop | `
where { $_.DestinationPrefix -eq $DestinationPrefix }
# Test if the Default Gateway passed is equal to the current default gateway
if($DefaultGateway)
{
if(-not ([System.Net.Ipaddress]::TryParse($DefaultGateway, [ref]0)))
{
throw ( @(
"Default Gateway *$DefaultGateway* is NOT in the correct format. Please "
"correct the DefaultGateway parameter in the configuration and try again."
) -join ""
)
}
# Filter for the specified $DefaultGateway
$filterGateway = $defaultRoutes | where { $_.NextHop -eq $DefaultGateway }
if(-not $filterGateway)
{
Write-Verbose -Message ( @(
"Default gateway does NOT match desired state. Expected $DefaultGateway, "
"actual $($defaultRoutes.NextHop)."
) -join ""
)
$requiresChanges = $true
}
else
{
Write-Verbose -Message "Default gateway is correct."
}
}
# Test if DHCP is already disabled
if(-not (Get-NetIPInterface -InterfaceAlias $InterfaceAlias -AddressFamily `
$AddressFamily).Dhcp.ToString().Equals('Disabled'))
{
Write-Verbose -Message "DHCP is NOT disabled."
$requiresChanges = $true
}
else
{
Write-Verbose -Message "DHCP is already disabled."
}
if($requiresChanges)
{
# Apply is true in the case of set - target resource - in which case, it will apply the
# required IP configuration
if($Apply)
{
Write-Verbose -Message ( @(
"At least one setting differs from the passed parameters. Applying "
"configuration..."
) -join ""
)
# Build parameter hash table
$Parameters = @{
IPAddress = $IPAddress
PrefixLength = $SubnetMask
InterfaceAlias = $InterfaceAlias
}
if($DefaultGateway)
{
$Parameters['DefaultGateway'] = $DefaultGateway
}
if(-not $NoReset)
{
# Remove any default routes on the specified interface -- it is important to do
# this *before* removing the IP address, particularly in the case where the IP
# address was auto-configured by DHCP
if($defaultRoutes)
{
$defaultRoutes | Remove-NetRoute -confirm:$false -ErrorAction Stop
}
# Remove any IP addresses on the specified interface
if($currentIP)
{
$currentIP | Remove-NetIPAddress -confirm:$false -ErrorAction Stop
}
}
else
{
# If the desired IP or default gateway is present, remove it even if NoReset
# was requested; this is required if one of the settings is correct but others
# are not -- otherwise, New-NetIPAddress will throw an error.
if($filterGateway)
{
$filterGateway | Remove-NetRoute -Confirm:$false
}
if($filterIP)
{
$filterIP | Remove-NetIPAddress -confirm:$false -ErrorAction Stop
}
}
# Apply the specified IP configuration
$null = New-NetIPAddress @Parameters -ErrorAction Stop
# Make the connection profile private
Get-NetConnectionProfile -InterfaceAlias $InterfaceAlias | `
Set-NetConnectionProfile -NetworkCategory Private -ErrorAction SilentlyContinue
Write-Verbose -Message "IP Interface was set to the desired state."
}
else
{
return $false
}
}
else
{
Write-Verbose -Message "IP interface is in the desired state."
return $true
}
}
catch
{
Write-Error -Message ( @(
"Can not set or find valid IPAddress using InterfaceAlias $InterfaceAlias and "
"AddressFamily $AddressFamily"
) -join ""
)
throw $_.Exception
}
}
# FUNCTIONS TO BE EXPORTED
Export-ModuleMember -function Get-TargetResource, Set-TargetResource, Test-TargetResource
| grayzu/BasicCI | Resources/xNetworking/DSCResources/MSFT_xIPAddress/MSFT_xIPAddress.psm1 | PowerShell | mit | 10,952 |
function Confirm-Host {
param(
[string] $Title = $null,
[string] $Message = "Are you sure you want to continue?",
[string[]] $Options = @("&Yes", "&No"),
[int] $DefaultOptionIndex = 0
)
$choices = new-object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
foreach ($opt in $Options) {
$choices.Add((new-object Management.Automation.Host.ChoiceDescription -ArgumentList $opt))
}
$Host.UI.PromptForChoice($Title, $Message, $choices, $DefaultOptionIndex)
} | Microsoft-Build-2016/CodeLabs-Data | Module4-Modern_Applications/Deployment/Deployment/deploy_utils.ps1 | PowerShell | mit | 562 |
<#Copyright 2017 Devia Software, LLC www.devia.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Testing:
Tested on Windows Server 2012 R2 against both Pageflex 8.X and Pageflex 9.X. There is no reason it should not work with other versions.
Description:
This Powershell Script installs All necessary Features required for PF SErver and Storefront to run. It basically automates the section
of the readme file:Internet Information Services (IIS), URL Rewrite Module, and Microsoft Message Queuing (MSMQ) AND Support Article 1545
#>
Install-WindowsFeature Web-Server,Web-Server,Web-Common-Http,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Static-Content,Web-Http-Redirect,Web-Health,Web-Http-Logging
Install-WindowsFeature NET-Framework-Features,NET-Framework-Core
Install-WindowsFeature MSMQ
Install-WindowsFeature Web-Performance, Web-Stat-Compression, Web-Dyn-Compression
Install-WindowsFeature Web-Security,Web-Filtering, Web-Windows-Auth
Install-WindowsFeature Web-App-Dev,Web-Net-Ext,Web-Net-Ext45,Web-Asp-Net,Web-Asp-Net45,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Includes
Install-WindowsFeature Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Web-Lgcy-Mgmt-Console,Web-Lgcy-Scripting,Web-WMI,Web-Scripting-Tools
| deviasoftware/azure-powershell | pageflex/PageflexWindowsFeatures.ps1 | PowerShell | mit | 2,226 |
./genCmake.ps1
cmake --build "build64" | Infinity95/crypto | build.ps1 | PowerShell | mit | 39 |
function Get-DbaPrivilege {
<#
.SYNOPSIS
Gets the users with local privileges on one or more computers.
.DESCRIPTION
Gets the users with local privileges 'Lock Pages in Memory', 'Instant File Initialization', 'Logon as Batch' on one or more computers.
Requires Local Admin rights on destination computer(s).
.PARAMETER ComputerName
The target SQL Server instance or instances.
.PARAMETER Credential
Credential object used to connect to the computer as a different user.
.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: Privilege
Author: Klaas Vandenberghe (@PowerDBAKlaas)
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Get-DbaPrivilege
.EXAMPLE
PS C:\> Get-DbaPrivilege -ComputerName sqlserver2014a
Gets the local privileges on computer sqlserver2014a.
.EXAMPLE
PS C:\> 'sql1','sql2','sql3' | Get-DbaPrivilege
Gets the local privileges on computers sql1, sql2 and sql3.
.EXAMPLE
PS C:\> Get-DbaPrivilege -ComputerName sql1,sql2 | Out-GridView
Gets the local privileges on computers sql1 and sql2, and shows them in a grid view.
#>
[CmdletBinding()]
param (
[parameter(ValueFromPipeline)]
[Alias("cn", "host", "Server")]
[DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME,
[PSCredential]$Credential,
[switch][Alias('Silent')]
$EnableException
)
begin {
$ResolveSID = @"
function Convert-SIDToUserName ([string] `$SID ) {
`$objSID = New-Object System.Security.Principal.SecurityIdentifier (`"`$SID`")
`$objUser = `$objSID.Translate( [System.Security.Principal.NTAccount])
`$objUser.Value
}
"@
$ComputerName = $ComputerName.ComputerName | Select-Object -Unique
}
process {
foreach ($computer in $ComputerName) {
try {
$null = Test-PSRemoting -ComputerName $Computer -EnableException
} catch {
Stop-Function -Message "Failure on $computer" -ErrorRecord $_ -Continue
}
try {
Write-Message -Level Verbose -Message "Getting Privileges on $Computer"
$Priv = $null
$Priv = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ScriptBlock {
$temp = ([System.IO.Path]::GetTempPath()).TrimEnd(""); secedit /export /cfg $temp\secpolByDbatools.cfg > $NULL;
Get-Content $temp\secpolByDbatools.cfg | Where-Object {
$_ -match "SeBatchLogonRight" -or $_ -match 'SeManageVolumePrivilege' -or $_ -match 'SeLockMemoryPrivilege'
}
}
if ($Priv.count -eq 0) {
Write-Message -Level Verbose -Message "No users with Batch Logon, Instant File Initialization, or Lock Pages in Memory Rights on $computer"
}
Write-Message -Level Verbose -Message "Getting Batch Logon Privileges on $Computer"
$BL = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ArgumentList $ResolveSID -ScriptBlock {
param ($ResolveSID)
. ([ScriptBlock]::Create($ResolveSID))
$temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
$blEntries = (Get-Content $temp\secpolByDbatools.cfg | Where-Object {
$_ -like "SeBatchLogonRight*"
})
if ($null -ne $blEntries) {
$blEntries.substring(20).split(",").replace("`*", "") | ForEach-Object {
Convert-SIDToUserName -SID $_
}
}
} -ErrorAction SilentlyContinue
if ($BL.count -eq 0) {
Write-Message -Level Verbose -Message "No users with Batch Logon Rights on $computer"
}
Write-Message -Level Verbose -Message "Getting Instant File Initialization Privileges on $Computer"
$ifi = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ArgumentList $ResolveSID -ScriptBlock {
param ($ResolveSID)
. ([ScriptBlock]::Create($ResolveSID))
$temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
$ifiEntries = (Get-Content $temp\secpolByDbatools.cfg | Where-Object {
$_ -like 'SeManageVolumePrivilege*'
})
if ($null -ne $ifiEntries) {
$ifiEntries.substring(26).split(",").replace("`*", "") | ForEach-Object {
Convert-SIDToUserName -SID $_
}
}
} -ErrorAction SilentlyContinue
if ($ifi.count -eq 0) {
Write-Message -Level Verbose -Message "No users with Instant File Initialization Rights on $computer"
}
Write-Message -Level Verbose -Message "Getting Lock Pages in Memory Privileges on $Computer"
$lpim = Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ArgumentList $ResolveSID -ScriptBlock {
param ($ResolveSID)
. ([ScriptBlock]::Create($ResolveSID))
$temp = ([System.IO.Path]::GetTempPath()).TrimEnd("");
$lpimEntries = (Get-Content $temp\secpolByDbatools.cfg | Where-Object {
$_ -like 'SeLockMemoryPrivilege*'
})
if ($null -ne $lpimEntries) {
$lpimEntries.substring(24).split(",").replace("`*", "") | ForEach-Object {
Convert-SIDToUserName -SID $_
}
}
} -ErrorAction SilentlyContinue
if ($lpim.count -eq 0) {
Write-Message -Level Verbose -Message "No users with Lock Pages in Memory Rights on $computer"
}
$users = @() + $BL + $ifi + $lpim | Select-Object -Unique
$users | ForEach-Object {
[PSCustomObject]@{
ComputerName = $computer
User = $_
LogonAsBatch = $BL -contains $_
InstantFileInitialization = $ifi -contains $_
LockPagesInMemory = $lpim -contains $_
}
}
Write-Message -Level Verbose -Message "Removing secpol file on $computer"
Invoke-Command2 -Raw -ComputerName $computer -Credential $Credential -ScriptBlock {
$temp = ([System.IO.Path]::GetTempPath()).TrimEnd(""); Remove-Item $temp\secpolByDbatools.cfg -Force > $NULL
}
} catch {
Stop-Function -Continue -Message "Failure" -ErrorRecord $_ -Target $computer
}
}
}
} | dsolodow/dbatools | functions/Get-DbaPrivilege.ps1 | PowerShell | mit | 7,718 |
function Expand-Result {
[CmdletBinding()]
param(
[Parameter( Mandatory, ValueFromPipeline )]
$InputObject
)
process {
foreach ($container in $script:PagingContainers) {
if (($InputObject) -and ($InputObject | Get-Member -Name $container)) {
Write-DebugMessage "Extracting data from [$container] containter"
$InputObject.$container
}
}
}
}
| AtlassianPS/JiraPS | JiraPS/Private/Expand-Result.ps1 | PowerShell | mit | 449 |
param($global:RestartRequired=0,
$global:MoreUpdates=0,
$global:MaxCycles=5)
function Check-ContinueRestartOrEnd() {
$RegistryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
$RegistryEntry = "InstallWindowsUpdates"
switch ($global:RestartRequired) {
0 {
$prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
if ($prop) {
Write-Host "Restart Registry Entry Exists - Removing It"
Remove-ItemProperty -Path $RegistryKey -Name $RegistryEntry -ErrorAction SilentlyContinue
}
Write-Host "No Restart Required"
Check-WindowsUpdates
if (($global:MoreUpdates -eq 1) -and ($script:Cycles -le $global:MaxCycles)) {
#Stop-Service $script:ServiceName -Force
#Set-Service -Name $script:ServiceName -StartupType Disabled -Status Stopped
Install-WindowsUpdates
} elseif ($script:Cycles -gt $global:MaxCycles) {
Write-Host "Exceeded Cycle Count - Stopping"
} else {
Write-Host "Done Installing Windows Updates"
#Set-Service -Name $script:ServiceName -StartupType Automatic -Status Running
}
}
1 {
$prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
if (-not $prop) {
Write-Host "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)"
} else {
Write-Host "Restart Registry Entry Exists Already"
}
Write-Host "Restart Required - Restarting..."
Stop-Process -ProcessName sshd -Force
Restart-Computer -Force
exit 0
}
default {
Write-Host "Unsure If A Restart Is Required"
break
}
}
}
function Install-WindowsUpdates() {
$script:Cycles++
Write-Host 'Evaluating Available Updates:'
$UpdatesToDownload = New-Object -ComObject 'Microsoft.Update.UpdateColl'
foreach ($Update in $SearchResult.Updates) {
if (($Update -ne $null) -and (!$Update.IsDownloaded)) {
[bool]$addThisUpdate = $false
if ($Update.InstallationBehavior.CanRequestUserInput) {
Write-Host "> Skipping: $($Update.Title) because it requires user input"
} else {
if (!($Update.EulaAccepted)) {
Write-Host "> Note: $($Update.Title) has a license agreement that must be accepted. Accepting the license."
$Update.AcceptEula()
[bool]$addThisUpdate = $true
} else {
[bool]$addThisUpdate = $true
}
}
if ([bool]$addThisUpdate) {
Write-Host "Adding: $($Update.Title)"
$UpdatesToDownload.Add($Update) |Out-Null
}
}
}
if ($UpdatesToDownload.Count -eq 0) {
Write-Host "No Updates To Download..."
} else {
Write-Host 'Downloading Updates...'
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Downloader.Download()
}
$UpdatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl'
[bool]$rebootMayBeRequired = $false
Write-Host 'The following updates are downloaded and ready to be installed:'
foreach ($Update in $SearchResult.Updates) {
if (($Update.IsDownloaded)) {
Write-Host "> $($Update.Title)"
$UpdatesToInstall.Add($Update) |Out-Null
if ($Update.InstallationBehavior.RebootBehavior -gt 0){
[bool]$rebootMayBeRequired = $true
}
}
}
if ($UpdatesToInstall.Count -eq 0) {
Write-Host 'No updates available to install...'
$global:MoreUpdates=0
$global:RestartRequired=0
#Set-Service -Name $script:ServiceName -StartupType Automatic -Status Running
break
}
if ($rebootMayBeRequired) {
Write-Host 'These updates may require a reboot'
$global:RestartRequired=1
}
Write-Host 'Installing updates...'
$Installer = $script:UpdateSession.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallationResult = $Installer.Install()
Write-Host "Installation Result: $($InstallationResult.ResultCode)"
Write-Host "Reboot Required: $($InstallationResult.RebootRequired)"
Write-Host '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() {
Write-Host "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
Write-Host $Message
$script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
$script:SearchResult = $script:UpdateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
if ($SearchResult.Updates.Count -ne 0) {
$script:SearchResult.Updates |Select-Object -Property Title, Description, SupportUrl, UninstallationNotes, RebootRequired, EulaAccepted |Format-List
$global:MoreUpdates=1
} else {
Write-Host '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:ServiceName = "OpenSSHd"
#Stop-Service $script:ServiceName -Force
#Set-Service -Name $script:ServiceName -StartupType Disabled -Status Stopped
if (!(Test-Path 'C:\packer-updates.txt')) {
Check-WindowsUpdates
if ($global:MoreUpdates -eq 1) {
Install-WindowsUpdates
} else {
Check-ContinueRestartOrEnd
}
} else {
Write-Host "Updates already completed"
} | ScoreBig/packer-templates | scripts/win-updates.ps1 | PowerShell | mit | 7,094 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
function Add-TrustedHost
{
<#
.SYNOPSIS
Adds an item to the computer's list of trusted hosts.
.DESCRIPTION
Adds an entry to this computer's list of trusted hosts. If the item already exists, nothing happens.
PowerShell Remoting needs to be turned on for this function to work.
.LINK
Enable-PSRemoting
.EXAMPLE
Add-TrustedHost -Entry example.com
Adds `example.com` to the list of this computer's trusted hosts. If `example.com` is already on the list of trusted hosts, nothing happens.
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[string[]]
[Alias("Entries")]
# The computer name(s) to add to the trusted hosts
$Entry
)
Set-StrictMode -Version 'Latest'
Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState
$trustedHosts = @( Get-TrustedHost )
$newEntries = @()
$Entry | ForEach-Object {
if( $trustedHosts -notcontains $_ )
{
$trustedHosts += $_
$newEntries += $_
}
}
if( $pscmdlet.ShouldProcess( "trusted hosts", "adding $( ($newEntries -join ',') )" ) )
{
Set-TrustedHost -Entry $trustedHosts
}
}
Set-Alias -Name 'Add-TrustedHosts' -Value 'Add-TrustedHost'
| lweniger/PowerShell | Modules/downloaded/powershellgallery/Carbon/2.2.0/Functions/Add-TrustedHost.ps1 | PowerShell | mit | 1,858 |
Function Set-PVUserPhoto {
<#
.SYNOPSIS
Saves a User’s photo in the Vault.
.DESCRIPTION
Exposes the PACLI Function: "PUTUSERPHOTO"
.PARAMETER destUser
The name of the User in the photograph.
.PARAMETER localFolder
The location of the folder in which the photograph is stored
.PARAMETER localFile
The name of the file in which the photograph is stored
.EXAMPLE
Set-PVUserPhoto -destUser user1 -localFolder D:\ -localFile photo.jpg
Sets D:\photo.jpg as user photo for vault user user1
.NOTES
AUTHOR: Pete Maan
#>
[CmdLetBinding(SupportsShouldProcess)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess", "", Justification = "ShouldProcess handling is in Invoke-PACLICommand")]
param(
[Parameter(
Mandatory = $True,
ValueFromPipelineByPropertyName = $True)]
[Alias("Username")]
[string]$destUser,
[Parameter(
Mandatory = $True,
ValueFromPipelineByPropertyName = $True)]
[string]$localFolder,
[Parameter(
Mandatory = $True,
ValueFromPipelineByPropertyName = $True)]
[string]$localFile
)
PROCESS {
$Null = Invoke-PACLICommand $Script:PV.ClientPath PUTUSERPHOTO $($PSBoundParameters | ConvertTo-ParameterString)
}
} | pspete/PoShPACLI | PoShPACLI/Functions/UserMangement/Set-PVUserPhoto.ps1 | PowerShell | mit | 1,217 |
function Get-Gamma {
<#
.SYNOPSIS
.DESCRIPTION
.EXAMPLE
Get-Gamma 4
.LINK
http://www.johndcook.com/Gamma.cs
http://www.johndcook.com/stand_alone_code.html
http://en.wikipedia.org/wiki/Gamma_function
https://communary.wordpress.com/
https://github.com/gravejester/Communary.ToolBox
.NOTES
Author: Øyvind Kallstad (translated from code by John D. Cook)
Date: 23.05.2015
Version: 1.0
Dependencies: Get-LogGamma
#>
param (
[ValidateRange(0,[double]::MaxValue)]
[double] $x
)
# First interval: (0, 0.001)
# Euler's gamma constant
[double]$gamma = 0.577215664901532860606512090
if ($x -lt 0.001) {
return (1.0 / ($x * (1.0 + $gamma * $x)))
}
# Second interval: (0.001, 12)
if ($x -lt 12.0) {
# The algorithm directly approximates gamma over (1,2) and uses
# reduction identities to reduce other arguments to this interval.
[double] $y = $x
[int]$n = 0
[bool]$argumentWasLessThanOne = ($y -lt 1.0)
# Add or subtract integers as necessary to bring y into (1,2)
# Will correct for this below
if ($argumentWasLessThanOne) {
$y += 1.0
}
else {
$n = [int]([math]::Floor($y) - 1)
$y -= $n
}
# numerator coefficients for approximation over the interval (1,2)
[double[]] $p = (
-1.71618513886549492533811E+0,
2.47656508055759199108314E+1,
-3.79804256470945635097577E+2,
6.29331155312818442661052E+2,
8.66966202790413211295064E+2,
-3.14512729688483675254357E+4,
-3.61444134186911729807069E+4,
6.64561438202405440627855E+4
)
# denominator coefficients for approximation over the interval (1,2)
[double[]] $q = (
-3.08402300119738975254353E+1,
3.15350626979604161529144E+2,
-1.01515636749021914166146E+3,
-3.10777167157231109440444E+3,
2.25381184209801510330112E+4,
4.75584627752788110767815E+3,
-1.34659959864969306392456E+5,
-1.15132259675553483497211E+5
)
[double] $num = 0.0
[double] $den = 1.0
[double] $z = $y - 1
for ($i = 0; $i -lt 8; $i++) {
$num = ($num + $p[$i]) * $z
$den = $den * $z + $q[$i]
}
[double] $results = $num / $den + 1.0
# Apply correction if argument was not initially in (1,2)
if ($argumentWasLessThanOne) {
# Use identity gamma(z) = gamma(z+1)/z
# The variable "result" now holds gamma of the original y + 1
# Thus we use y-1 to get back the orginal y.
$results /= ($y - 1.0)
}
else {
# Use the identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z)
for ($i = 0; $i -lt $n; $i++) {
$results *= $y++
}
}
return $results
}
# Third interval: (12, infinity)
if ($x -gt 171.624) {
# Correct answer too large to display.
return ([double]::PositiveInfinity)
}
return ([math]::Exp((Get-LogGamma $x)))
} | gravejester/Communary.ToolBox | Functions/Math/Get-Gamma.ps1 | PowerShell | mit | 3,358 |
# ---------------------------------------------------------------------------
# Author: Jachymko
# Desc: Jachym's prompt, colors and host window title updates.
# Date: Nov 07, 2009
# Site: http://pscx.codeplex.com
# Usage: In your options hashtable place the following setting:
#
# PromptTheme = 'Jachym'
# ---------------------------------------------------------------------------
#requires -Version 2.0
param([hashtable]$Theme)
Set-StrictMode -Version 2.0
# ---------------------------------------------------------------------------
# Colors
# ---------------------------------------------------------------------------
$Theme.HostBackgroundColor = if ($Pscx:IsAdmin) { 'DarkRed' } else { 'Black' }
$Theme.HostForegroundColor = if ($Pscx:IsAdmin) { 'White' } else { 'Gray' }
$Theme.PromptForegroundColor = if ($Pscx:IsAdmin) { 'Yellow' } else { 'White' }
$Theme.PrivateData.ErrorForegroundColor = if ($Pscx:IsAdmin) { 'DarkCyan' }
# ---------------------------------------------------------------------------
# Prompt ScriptBlock
# ---------------------------------------------------------------------------
$Theme.PromptScriptBlock = {
param($Id)
if($NestedPromptLevel)
{
new-object string ([char]0xB7), $NestedPromptLevel
}
"[$Id] $([char]0xBB)"
}
# ---------------------------------------------------------------------------
# Window Title Update ScriptBlock
# ---------------------------------------------------------------------------
$Theme.UpdateWindowTitleScriptBlock = {
(Get-Location)
'-'
'Windows PowerShell'
if($Pscx:IsAdmin)
{
'(Administrator)'
}
if ($Pscx:IsWow64Process)
{
'(x86)'
}
}
# SIG # Begin signature block
# MIIfVQYJKoZIhvcNAQcCoIIfRjCCH0ICAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU9zyRz7XLN7ov3ZOCRQwiscAS
# UEigghqHMIIGbzC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re96O5Z5IPin
# lqn8eebyYZkBzqI2qZKu9v6Wlx+E7jXgZzLqSrQo+F/Uqtjyg656C4zflCB8GGzF
# Pm+7clv0y+puQ0OqO7fvx+VGBScS5YIk052Hweag3+ckC95uBY7wKbQ1z2vLFdO3
# /DhY2v+rZD77
# SIG # End signature block
| nylyst/Powershell | Modules/pscx/Modules/Prompt/Themes/Jachym.ps1 | PowerShell | mit | 12,932 |
function Test-DateDifference([array]$date, [datetime]$compare, [int]$range) {
<#
.SYNOPSIS
Compares a series of dates against a desired date to find the closest matching date/time
.DESCRIPTION
The Rubrik API returns snapshot dates down to the millisecond, but the user may not provide this much detail in their Date argument.
This function can be used to compare a specified date to the list of snapshot dates in order to find the one that is closest.
A snapshot date may be in the future by milliseconds, but this is considered valid since that is most likely the intent of the user
.PARAMETER date
An array of ISO 8601 style dates (e.g. YYYY-MM-DDTHH:MM:SSZ)
.PARAMETER compare
A single ISO 8601 style date to compare against the $date array
.PARAMETER range
defines how many days away from $compare to search for the closest match. Ex: $range = 3 will look within a 3 day period to find a match
#>
# A simple hashtable is created to compare each date value against one another
# The value that is closest to 0 (e.g. least distance away from the $compare date) is stored
# Otherwise, the date of $null is returned meaning no match
Write-Verbose -Message "Finding closest matching date"
$datematrix = @{
date = $null
value = $range
}
foreach ($_ in $date) {
# The $c is just a check variable used to hold the total number of days between the current $date item and the $compare value
$c = (New-TimeSpan -Start $_ -End $compare).TotalDays
# Should we find a value that is less than the existing winning value, store it
# Note: 0 would be a perfect match (e.g. 0 days different between what we found and what the user wants in $compare)
# Note: Negative values indicate a future (e.g. supply yesterday for $compare but finding a $date from today)
# Absolute values are used so negatives are ignored and we find the closest actual match.
if ([Math]::Abs($c) -lt $datematrix.value) {
$datematrix.date = $_
$datematrix.value = [Math]::Abs($c)
}
# If $c = 0, a perfect match has been found
if ($datematrix.value -eq 0) { break }
}
If ($null -ne $datematrix.date) {
Write-Verbose -Message "Using date $($datematrix.date)"
}
else {
Write-Verbose -Message "Could not find matching date within one day of $($compare.ToString())"
}
return $datematrix.date
}
| rubrikinc/PowerShell-Module | Rubrik/Private/Test-DateDifference.ps1 | PowerShell | mit | 2,419 |
# Copyright 2012 Aaron Jensen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
& (Join-Path -Path $PSScriptRoot -ChildPath '..\Initialize-CarbonDscResource.ps1' -Resolve)
function Get-TargetResource
{
[CmdletBinding()]
[OutputType([Hashtable])]
param (
[Parameter(Mandatory=$true)]
[string]
$Name,
[bool]
$Enabled = $true,
[ValidateSet('In','Out')]
[string]
$Direction,
[ValidateSet('Any','Domain','Private','Public')]
[string[]]
$Profile = @( 'Any' ),
[string]
$LocalIPAddress = 'Any',
[string]
$LocalPort,
[string]
$RemoteIPAddress = 'Any',
[string]
$RemotePort,
[string]
$Protocol = 'Any',
[ValidateSet('Yes', 'No', 'DeferUser','DeferApp')]
[string]
$EdgeTraversalPolicy = 'No',
[ValidateSet('Allow','Block','Bypass')]
[string]
$Action,
[ValidateSet('Any','Wireless','LAN','RAS')]
[string]
$InterfaceType = 'Any',
[ValidateSet('NotRequired','Authenticate','AuthEnc','AuthDynEnc','AuthNoEncap')]
[string]
$Security = 'NotRequired',
[string]
$Description,
[string]
$Program,
[string]
$Service,
[ValidateSet('Present','Absent')]
[string]
$Ensure = 'Present'
)
Set-StrictMode -Version 'Latest'
$rule = Get-FirewallRule -LiteralName $Name
$resource = @{
'Action' = $Action;
'Description' = $Description;
'Direction' = $Direction;
'EdgeTraversalPolicy' = $EdgeTraversalPolicy
'Enabled' = $Enabled;
'Ensure' = 'Absent';
'InterfaceType' = $InterfaceType
'LocalIPAddress' = $LocalIPAddress;
'LocalPort' = $LocalPort;
'Name' = $Name;
'Profile' = $Profile;
'Program' = $Program;
'Protocol' = $Protocol;
'RemoteIPAddress' = $RemoteIPAddress;
'RemotePort' = $RemotePort;
'Security' = $Security;
'Service' = $Service;
}
if( $rule )
{
$propNames = $resource.Keys | ForEach-Object { $_ }
$propNames |
Where-Object { $_ -ne 'Ensure' } |
ForEach-Object {
$propName = $_
switch( $propName )
{
'Profile' { $value = $rule.Profile.ToString() -split ',' }
'Enabled' { $value = $rule.Enabled }
default
{
$value = ($rule.$propName).ToString()
}
}
$resource[$propName] = $value
}
$resource.Ensure = 'Present'
}
return $resource
}
function Set-TargetResource
{
<#
.SYNOPSIS
DSC resource for managing firewall rules.
.DESCRIPTION
The `Carbon_FirewallRule` resource manages firewall rules. It uses the `netsh advfirewall firewall` command. Please see [Netsh AdvFirewall Firewall Commands](http://technet.microsoft.com/en-us/library/dd734783.aspx) or run `netsh advfirewall firewall set rule` for documentation on how to configure the firewall.
When modifying existing rules, only properties you pass are updated/changed. All other properties are left as-is.
`Carbon_FirewallRule` is new in Carbon 2.0.
.LINK
Get-FirewallRule
.LINK
http://technet.microsoft.com/en-us/library/dd734783.aspx
.EXAMPLE
>
Demonstrates how to enable a firewall rule.
Carbon_FirewallRule EnableHttpIn
{
Name = 'World Wide Web Services (HTTP Traffic-In)'
Enabled = $true;
Ensure = 'Present'
}
.EXAMPLE
>
Demonstrates how to delete a firewall rule.
Carbon_FirewallRule DeleteMyRule
{
Name = 'MyCustomRule';
Ensure = 'Absent';
}
There may be multiple rules with the same name, so we recommend disabling rules instead.
.EXAMPLE
>
Demonstrates how to create/modify an incoming firewall rule.
Carbon_FirewallRule MyAppPorts
{
Name = 'My App Ports';
Action = 'Allow';
Direction = 'In';
Protocol = 'tcp';
LocalPort = '8080,8180';
Ensure = 'Present';
}
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[string]
# The name of the rule.
$Name,
[bool]
# If `$true`, the rule is enabled. If `$false`, the rule is disabled.
$Enabled = $true,
[ValidateSet('In','Out')]
[string]
# If set to `In`, the rule applies to inbound network traffic. If set to `Out`, the rule applies to outbound traffic.
$Direction,
[ValidateSet('Any','Domain','Private','Public')]
[string[]]
# Specifies the profile(s) to which the firewall rule is assigned. The rule is active on the local computer only when the specified profile is currently active. Valid values are `Any`, `Domain`, `Public`, and `Private`.
$Profile,
[string]
# The local IP addresses the rule applies to. Valid values are `any`, an exact IPv4 or IPv6 address, a subnet mask (e.g. 192.168.0.0/24), or a range. Separate each value with a comma; no spaces.
$LocalIPAddress,
[string]
# The local port the rule applies to. Valid values are a specific port number, a range of port numbers (e.g. `5000-5010`), a comma-separate list of numbers and ranges, `any`, `rpc`, `rpc-epmap`, `Teredo`, and `iphttps`.
$LocalPort,
[string]
# The remote IP addresses the rules applies to. Valid values are `any`, an exact IPv4 or IPv6 address, a subnet mask (e.g. 192.168.0.0/24), or a range. Separate each value with a comma; no spaces.
$RemoteIPAddress,
[string]
# The remote port the rule applies to. Valid values are a specific port number, a range of port numbers (e.g. `5000-5010`), a comma-separate list of numbers and ranges, `any`, `rpc`, `rpc-epmap`, `Teredo`, and `iphttps`.
$RemotePort,
[string]
# The protocol the rule applies to. Valid values are `any`, the protocol number, `icmpv4`, `icmpv6', `icmpv4:type,code`, `icmpv6:type,code`, `tcp`, or `udp`. Separate multiple values with a comma; no spaces.
$Protocol,
[ValidateSet('Yes', 'No', 'DeferUser','DeferApp')]
[string]
# For inbound rules, specifies that traffic that traverses an edge device, such as a Network Address Translation (NAT) enabled router, between the local and remote computer matches this rule. Valid values are `any`, `deferapp`, `deferuse`, or `no`.
$EdgeTraversalPolicy,
[ValidateSet('Allow','Block','Bypass')]
[string]
# Specifies what to do when packets match the rule. Valid values are `Allow`, `Block`, or `Bypass`.
$Action,
[ValidateSet('Any','Wireless','LAN','RAS')]
[string]
# Specifies that only network packets passing through the indicated interface types match this rule. Valid values are `Any`, `Wireless`, `LAN`, or `RAS`.
$InterfaceType,
[ValidateSet('NotRequired','Authenticate','AuthEnc','AuthDynEnc','AuthNoEncap')]
[string]
# Specifies that only network packets protected with the specified type of IPsec options match this rule. Valid values are `NotRequired`, `Authenticate`, `AuthEnc`, `AuthDynEnc`, or `AuthNoEncap`.
$Security,
[string]
# A description of the rule.
$Description,
[string]
# Specifies that network traffic generated by the identified executable program matches this rule.
$Program,
[string]
# Specifies that traffic generated by the identified service matches this rule. The ServiceShortName for a service can be found in Services MMC snap-in, by right-clicking the service, selecting Properties, and examining Service Name.
$Service,
[ValidateSet('Present','Absent')]
[string]
# Set to `Present` to create the fireall rule. Set to `Absent` to delete it.
$Ensure = 'Present'
)
Set-StrictMode -Version 'Latest'
$resource = Get-TargetResource -Name $Name
if( $Ensure -eq 'Absent' -and $resource.Ensure -eq 'Present' )
{
Write-Verbose ('Deleting firewall rule ''{0}''' -f $Name)
$output = netsh advfirewall firewall delete rule name=$Name
if( $LASTEXITCODE )
{
Write-Error ($output -join ([Environment]::NewLine))
return
}
$output | Write-Verbose
return
}
$cmd = 'add'
$cmdDisplayName = 'Adding'
$newArg = ''
if( $Ensure -eq 'Present' -and $resource.Ensure -eq 'Present' )
{
$cmd = 'set'
$cmdDisplayName = 'Setting'
$newArg = 'new'
}
else
{
if( -not $Direction -and -not $Action )
{
Write-Error ('Parameters ''Direction'' and ''Action'' are required when adding a new firewall rule.')
return
}
elseif( -not $Direction )
{
Write-Error ('Parameter ''Direction'' is required when adding a new firewall rule.')
return
}
elseif( -not $Action )
{
Write-Error ('Parameter ''Action'' is required when adding a new firewall rule.')
return
}
}
$argMap = @{
'Direction' = 'dir';
'Enabled' = 'enable';
'LocalIPAddress' = 'localip';
'RemoteIPAddress' = 'remoteip';
'EdgeTraversalPolicy' = 'edge';
}
$netshArgs = New-Object 'Collections.Generic.List[string]'
$resource.Keys |
Where-Object { $_ -ne 'Ensure' -and $_ -ne 'Name' } |
Where-Object { $PSBoundParameters.ContainsKey($_) } |
ForEach-Object {
$argName = $_.ToLowerInvariant()
$argValue = $PSBoundParameters[$argName]
if( $argValue -is [bool] )
{
$argValue = if( $argValue ) { 'yes' } else { 'no' }
}
if( $argMap.ContainsKey($argName) )
{
$argName = $argMap[$argName]
}
[void]$netshArgs.Add( ('{0}=' -f $argName) )
[void]$netshArgs.Add( $argValue )
}
Write-Verbose ('{0} firewall rule ''{1}''' -f $cmdDisplayName,$Name)
$output = netsh advfirewall firewall $cmd rule name= $Name $newArg $netshArgs
if( $LASTEXITCODE )
{
Write-Error ($output -join ([Environment]::NewLine))
return
}
$output | Write-Verbose
}
function Test-TargetResource
{
[CmdletBinding()]
[OutputType([bool])]
param (
[Parameter(Mandatory=$true)]
[string]
$Name,
[bool]
$Enabled,
[ValidateSet('In','Out')]
[string]
$Direction,
[ValidateSet('Any','Domain','Private','Public')]
[string[]]
$Profile,
[string]
$LocalIPAddress,
[string]
$LocalPort,
[string]
$RemoteIPAddress,
[string]
$RemotePort,
[string]
$Protocol,
[ValidateSet('Yes', 'No', 'DeferUser','DeferApp')]
[string]
$EdgeTraversalPolicy,
[ValidateSet('Allow','Block','Bypass')]
[string]
$Action,
[ValidateSet('Any','Wireless','LAN','RAS')]
[string]
$InterfaceType,
[ValidateSet('NotRequired','Authenticate','AuthEnc','AuthDynEnc','AuthNoEncap')]
[string]
$Security,
[string]
$Description,
[string]
$Program,
[string]
$Service,
[ValidateSet('Present','Absent')]
[string]
$Ensure = 'Present'
)
Set-StrictMode -Version 'Latest'
$resource = Get-TargetResource @PSBoundParameters
if( $Ensure -eq 'Absent' )
{
$result = ($resource.Ensure -eq 'Absent')
if( $result )
{
Write-Verbose ('Firewall rule ''{0}'' not found.' -f $Name)
}
else
{
Write-Verbose ('Firewall rule ''{0}'' found.' -f $Name)
}
return $result
}
if( $Ensure -eq 'Present' -and $resource.Ensure -eq 'Absent' )
{
Write-Verbose ('Firewall rule ''{0}'' not found.' -f $Name)
return $false
}
return Test-DscTargetResource -TargetResource $resource -DesiredResource $PSBoundParameters -Target ('Firewall rule ''{0}''' -f $Name)
}
| MattHubble/carbon | Carbon/DscResources/Carbon_FirewallRule/Carbon_FirewallRule.psm1 | PowerShell | apache-2.0 | 13,902 |
# ************************************************************************
# *
# * Copyright 2016 OSIsoft, LLC
# * 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.
# *
# ************************************************************************
<#
Global Variables
PISysAuditShowUI
ScriptsPath
PasswordPath
PISysAuditInitialized
PISysAuditCachedSecurePWD
PISysAuditIsElevated
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification="Where used, we do not need to recapture, redirect, or suppress output.")]
param()
# ........................................................................
# Internal Functions
# ........................................................................
function GetFunctionName
{ return (Get-Variable MyInvocation -Scope 1).Value.MyCommand.Name }
function SetFolders {
# Retrieve the folder from which this script is called ..\Scripts and split the path
# to remove the Scripts part.
$modulePath = $PSScriptRoot
# ..\
# ..\Scripts
# ..\Scripts\PISYSAUDIT
# ..\Scripts\Temp
# ..\Export
# ..\pwd
$scriptsPath = Split-Path $modulePath
$rootPath = Split-Path $scriptsPath
$exportPath = PathConcat -ParentPath $rootPath -ChildPath "Export"
if (!(Test-Path $exportPath)) {
$result = New-Item $exportPath -type directory
Write-Host $("Export directory added: " + $result)
}
$scriptsPathTemp = PathConcat -ParentPath $scriptsPath -ChildPath "Temp"
if (!(Test-Path $scriptsPathTemp)) {
$result = New-Item $scriptsPathTemp -type directory
Write-Host $("Script temp directory added: " + $result)
}
$pwdPath = PathConcat -ParentPath $rootPath -ChildPath "pwd"
$logFile = PathConcat -ParentPath $exportPath -ChildPath "PISystemAudit.log"
# Store them at within the global scope range.
$globalVariables = @{
ScriptsPath = $scriptsPath;
ScriptsPathTemp = $scriptsPathTemp;
PasswordPath = $pwdPath;
ExportPath = $exportPath;
PISystemAuditLogFile = $logFile;
}
foreach ($globalVariable in $globalVariables.GetEnumerator()) {
if ($null -eq (Get-Variable ($globalVariable.Key) -Scope "Global" -ErrorAction "SilentlyContinue").Value) {
New-Variable -Name ($globalVariable.Key) -Option "Constant" -Scope "Global" -Visibility "Public" -Value ($globalVariable.Value)
}
}
}
function NewObfuscateValue {
[OutputType([System.String])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("v")]
[string]
$Value)
$fn = GetFunctionName
try {
# Create a Rijndael symmetric key encryption object.
$r = New-Object System.Security.Cryptography.RijndaelManaged
# Set the key and initialisation vector to 128-bytes each of (1..16).
$c = $r.CreateEncryptor((1..16), (1..16))
# Create so objectes needed for manipulation.
$ms = New-Object IO.MemoryStream
# Target data stream, transformation, and mode.
$cs = New-Object Security.Cryptography.CryptoStream $ms, $c, "Write"
$sw = New-Object IO.StreamWriter $cs
# Write the string through the crypto stream into the memory stream
$sw.Write($Value)
# Clean up
$sw.Close()
$cs.Close()
$ms.Close()
$r.Clear()
# Convert to byte array from the encrypted memory stream.
[byte[]]$result = $ms.ToArray()
# Convert to base64 for transport.
$encryptedValue = [Convert]::ToBase64String($result)
# return the encryptedvalue
return $encryptedValue
}
catch {
# Return the error message.
$msg = "The obfuscation of the value has failed"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
function NewAuditFunction {
<#
.SYNOPSIS
(Core functionality) Creates an audit function object.
.DESCRIPTION
Creates an audit function object which associates the name, unique ID and
whether the function is included in a Basic or Verbose audit.
#>
Param($name, $level, $id)
$obj = New-Object pscustomobject
$obj | Add-Member -MemberType NoteProperty -Name 'Name' -Value $name
$obj | Add-Member -MemberType NoteProperty -Name 'Level' -Value $level
$obj | Add-Member -MemberType NoteProperty -Name 'ID' -Value $id
return $obj
}
function WriteHostPartialResult {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[object]
$AuditItem)
if ($AuditItem.AuditItemValue -eq $false) {
$a = $AuditItem # for brevity
$msg = "{0,-9} {1,-8} {2,-20} {3,40}"
Write-Host ($msg -f $a.Severity, $a.ID, $a.ServerName, $a.AuditItemName)
}
}
function CheckIfRunningElevated {
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
$fn = GetFunctionName
try {
if ($ExecutionContext.SessionState.LanguageMode -eq "ConstrainedLanguage") {
<#
sfc utility requires admin to run on all supported OSes
when run elevated, it will return the list of arguments
if not run elevated, it will return a message stating
the user must be admin.
#>
return ($(sfc /? | Out-String) -like '*/*')
}
else {
$windowsPrinciple = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
return $windowsPrinciple.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
}
catch {
$msg = "Error encountered when checking if running elevated."
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $false
}
}
function ResolveComputerName {
[OutputType([System.String])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("rcn")]
[string]
$RemoteComputerName)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Return the right server name to use.
if ($LocalComputer) {
# Obtain the machine name from the environment variable.
return (get-content env:computername)
}
else {
if ($RemoteComputerName -eq "") {
$msg = "The remote computer name is empty."
Write-PISysAudit_LogMessage $msg "Error" $fn
return $null
}
else
{ return $RemoteComputerName }
}
}
catch
{ return $null }
}
function ReturnSQLServerName {
[OutputType([System.String])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[string]
$ServerName,
[parameter(Mandatory = $true, Position = 2, ParameterSetName = "Default")]
[AllowEmptyString()]
[string]
$InstanceName)
try {
# Build the connection string.
if (($InstanceName.ToLower() -eq "default") `
-or ($InstanceName.ToLower() -eq "mssqlserver") `
-or ($SQLServerInstanceName -eq "")) {
# Use the Server name only as the identity of the server.
return $ServerName
}
else {
# Use the Server\Named Instance as the identity of the server.
return ($ServerName + "\" + $InstanceName)
}
}
catch
{ return $null }
}
function SetSQLAccountPasswordInCache {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[string]
$ServerName,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[string]
$InstanceName,
[parameter(Mandatory = $true, Position = 2, ParameterSetName = "Default")]
[string]
$UserName)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Define the password message template
$msgPasswordTemplate = "Please enter the password for the user {0} for the SQL Server: {1}"
# Get the SQL Server name.
$sqlServerName = ReturnSQLServerName $ServerName $InstanceName
# Get the password via a protected prompt.
$msgPassword = [string]::Format($msgPasswordTemplate, $UserName, $sqlServerName)
$securePWD = Read-Host -assecurestring $msgPassword
# Verbose only if Debug Level is 2+
$msg = "The user was prompted to enter the password for SQL connection"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
# Cache the secure password for next usage.
if ($null -eq (Get-Variable "PISysAuditCachedSecurePWD" -Scope "Global" -ErrorAction "SilentlyContinue").Value) {
New-Variable -Name "PISysAuditCachedSecurePWD" -Scope "Global" -Visibility "Public" -Value $securePWD
}
else {
Set-Variable -Name "PISysAuditCachedSecurePWD" -Scope "Global" -Visibility "Public" -Value $securePWD
}
}
catch {
# Return the error message.
$msg = "Set the SQL Account passwor into cache failed"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
function ExecuteCommandLineUtility
# Run a command line utility on the local or remote computer,
# directing the output to a file. Read from the file, delete the
{ # file, then delete the file and return the output.
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("exec")]
[string]
$UtilityExec,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("output")]
[string]
$OutputFilePath,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("args")]
[string]
$ArgList,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$UtilityExecutable, [string]$ArgumentList, [string]$FilePath)
if (Test-Path $FilePath) { Remove-Item $FilePath }
Start-Process -FilePath $UtilityExecutable -ArgumentList $ArgumentList -RedirectStandardOutput $FilePath -Wait -NoNewWindow
$FileContent = Get-Content -Path $FilePath
if (Test-Path $FilePath) { Remove-Item $FilePath }
return $FileContent
}
# Verbose only if Debug Level is 2+
$msgTemplate = "Command: {0}; Target: {1}"
$msg = [string]::Format($msgTemplate, $scriptBlock.ToString(), $RemoteComputerName)
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
if ($LocalComputer) {
$outputFileContent = & $scriptBlock -UtilityExecutable $UtilityExec -ArgumentList $ArgList -FilePath $OutputFilePath
}
else {
$outputFileContent = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $UtilityExec, $ArgList, $OutputFilePath
}
return $outputFileContent
}
catch {
# Return the error message.
$msgTemplate1 = "A problem occurred with {0} on local computer"
$msgTemplate2 = "A problem occurred with {0} on {1} computer"
if ($LocalComputer)
{ $msg = [string]::Format($msgTemplate1, $UtilityExec) }
else
{ $msg = [string]::Format($msgTemplate2, $UtilityExec, $RemoteComputerName) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
function GetPasswordOnDisk {
[OutputType([System.String])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[string]
$File)
$fn = GetFunctionName
try {
# Read from the global constant bag.
$pwdPath = (Get-Variable "PasswordPath" -Scope "Global").Value
# Set the path.
$pwdFile = PathConcat -ParentPath $pwdPath -ChildPath $File
# Decrypt.
# Key is undefined to use Windows Data Protection API (DPAPI) to encrypt the standard string.
# Visit this URL: http://msdn.microsoft.com/en-us/library/ms995355.aspx to know more.
$securePWD = Get-Content -Path $pwdFile | ConvertTo-SecureString
return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePWD))
}
catch {
# Return the error message.
$msg = "Decrypting the password has failed"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
function ValidateIfHasPIDataArchiveRole {
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
try {
# Get the PISERVER variable.
if ($LocalComputer)
{ $PIServer_path = Get-PISysAudit_EnvVariable "PISERVER" }
else
{ $PIServer_path = Get-PISysAudit_EnvVariable "PISERVER" -lc $false -rcn $RemoteComputerName }
# Validate...
if ($null -eq $PIServer_path) { return $false }
return $true
}
catch
{ return $false }
}
function ValidateIfHasPIAFServerRole {
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
try {
$className = "Win32_Service"
$namespace = "root\CIMV2"
$filterExpression = [string]::Format("name='{0}'", "AFService")
$WMIObject = ExecuteWMIQuery $className -n $namespace -lc $LocalComputer -rcn $RemoteComputerName -FilterExpression $filterExpression -DBGLevel $DBGLevel
if ($null -eq $WMIObject) { return $false}
return $true
}
catch
{ return $false }
}
function ValidateIfHasSQLServerRole {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Justification="Specifying a filename, not a password.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "PasswordFile", Justification="This variable is a filename.")]
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$InstanceName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[boolean]
$IntegratedSecurity = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$UserName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$PasswordFile = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
try {
$result = $false
# Simplest query to return a response to ensure we can query the SQL server
$result = (Invoke-PISysAudit_Sqlcmd_ScalarValue -Query 'SELECT 1 as TEST' -LocalComputer $ComputerParams.IsLocal -RemoteComputerName $ComputerParams.ComputerName `
-InstanceName $ComputerParams.InstanceName -IntegratedSecurity $ComputerParams.IntegratedSecurity `
-UserName $ComputerParams.SQLServerUserID -PasswordFile $ComputerParams.PasswordFile `
-ScalarValue 'TEST' -DBGLevel $DBGLevel) -eq 1
return $result
}
catch
{ return $false }
}
function ValidateIfHasPIVisionRole {
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
try {
$result = $false
$RegKeyPath = "HKLM:\Software\PISystem\PIVision"
$result = Get-PISysAudit_TestRegistryKey -lc $LocalComputer -rcn $RemoteComputerName -rkp $RegKeyPath -DBGLevel $DBGLevel
# If PI Vision is not present, check for previous name.
if ($result -eq $false) {
$RegKeyPath = "HKLM:\Software\PISystem\Coresight"
$result = Get-PISysAudit_TestRegistryKey -lc $LocalComputer -rcn $RemoteComputerName -rkp $RegKeyPath -DBGLevel $DBGLevel
}
return $result
}
catch
{ return $false }
}
function ValidateIfHasPIWebApiRole {
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
try {
$result = $false
$RegKeyPath = "HKLM:\Software\PISystem\WebAPI"
$result = Get-PISysAudit_TestRegistryKey -lc $LocalComputer -rcn $RemoteComputerName -rkp $RegKeyPath -DBGLevel $DBGLevel
return $result
}
catch
{ return $false }
}
function ExecuteWMIQuery {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWMICmdlet", "", Justification="CIM favored over WMI for consistency cross platform, but this tool only supports Windows.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("wcn")]
[string]
$WMIClassName,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("n")]
[string]
$Namespace = "root\CIMV2",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("f")]
[string]
$FilterExpression = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$Namespace, [string]$WMIClassName, [parameter(Mandatory = $false)][string]$FilterExpression = "")
if ($FilterExpression -eq "")
{ Get-WMIObject -Namespace $Namespace -Class $WMIClassName -ErrorAction SilentlyContinue }
else
{ Get-WMIObject -Namespace $Namespace -Class $WMIClassName -Filter $FilterExpression -ErrorAction SilentlyContinue }
}
# Verbose only if Debug Level is 2+
$msgTemplate = "Local command to send is: {0}"
$msg = [string]::Format($msgTemplate, $scriptBlock.ToString())
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
if ($LocalComputer) {
$WMIObject = & $scriptBlock -Namespace $Namespace -WMIClassName $WMIClassName -FilterExpression $FilterExpression
}
else {
$WMIObject = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $Namespace, $WMIClassName, $FilterExpression
}
return $WMIObject
}
catch {
# Return the error message.
$msgTemplate1 = "Query the WMI classes from local computer has failed"
$msgTemplate2 = "Query the WMI classes from {0} has failed"
if ($LocalComputer)
{ $msg = $msgTemplate1 }
else
{ $msg = [string]::Format($msgTemplate2, $RemoteComputerName) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
function ValidateWSMan {
[OutputType([System.Boolean])]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
$fn = GetFunctionName
try {
# Only need the 'Computer' role
$ComputerParams = $ComputerParams.Value | Where-Object AuditRoleType -EQ "Computer"
# Test non-local computer to validate if WSMan is working.
if ($ComputerParams.IsLocal) {
$result = $true
$msg = "The server: {0} does not need WinRM communication because it will use a local connection" -f $ComputerParams.ComputerName
Write-PISysAudit_LogMessage $msg "Debug" $fn -dbgl $DBGLevel -rdbgl 1
}
else {
$result = Test-WSMan -authentication default -ComputerName $ComputerParams.ComputerName -ErrorAction SilentlyContinue
}
return $result
}
catch {
# Return the error message.
$msg = "A problem has occurred during the validation with WSMan"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an 'Computer' -fn $fn -msg $msg
# Validation has failed.
return $false
}
}
function Test-PISysAudit_PrincipalOrGroupType {
<#
.SYNOPSIS
(Core functionality) Checks a specified characteristic of a Principal or Group.
.DESCRIPTION
Checks a specified Principal or Group Type based on the SID.
Return values include LowPrivileged, Administrator, Machine or Custom
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[string]
$SID,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
$type = 'Custom'
# Enumerate test arrays https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems
$WellKnownSIDs = @{
'S-1-1-0' = 'LowPrivileged'; # Everyone
'S-1-5-7' = 'LowPrivileged'; # Anonymous
'S-1-5-11' = 'LowPrivileged'; # Authenticated Users
'S-1-5-18' = 'Machine'; # Local System
'S-1-5-19' = 'Machine'; # Local Service
'S-1-5-20' = 'Machine'; # Network Service
'S-1-5-32-544' = 'Administrator'; # Administrators
'S-1-5-32-545' = 'LowPrivileged'; # Users
'S-1-5-32-546' = 'LowPrivileged'; # Guests
'S-1-5-32-555' = 'LowPrivileged'; # Remote Desktop Users
'S-1-5-21*-500' = 'Administrator'; # Administrator
'S-1-5-21*-501' = 'LowPrivileged'; # Guest
'S-1-5-21*-512' = 'Administrator'; # Domain Admins
'S-1-5-21*-513' = 'LowPrivileged'; # Domain Users
'S-1-5-21*-514' = 'LowPrivileged'; # Domain Guests
'S-1-5-21*-515' = 'Machine'; # Domain Computers
'S-1-5-21*-519' = 'Administrator'; # Enterprise Admins
}
try {
$type = $WellKnownSIDs.GetEnumerator() | Where-Object {$SID -like $_.Name} | Select-Object -ExpandProperty Value
return $type
}
catch {
# Return the error message.
$msgTemplate = "A problem occurred checking the condition {0} on account {1}. Error:{2}"
$msg = [string]::Format($msgTemplate, $Condition, $AccountSID, $_.Exception.Message)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Test-WebAdministrationModuleAvailable {
<#
.SYNOPSIS
(Core functionality) Checks for the WebAdministration module.
.DESCRIPTION
Validate that IIS module can be loaded and configuration data can be accessed.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
$value = $false
try {
# Sometimes the module is imported and the IIS drive is inaccessible
$scriptBlock = {
Import-Module -Name "WebAdministration"
$value = Test-Path IIS:\
return $value
}
if ($LocalComputer)
{ $value = & $scriptBlock }
else
{ $value = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock }
return $value
}
catch {
# Return the error message.
$msgTemplate1 = "A problem occurred checking for IIS scripting tools: {0} from local machine."
$msgTemplate2 = "A problem occurred checking for IIS scripting tools: {0} from {1} machine."
if ($LocalComputer)
{ $msg = [string]::Format($msgTemplate1, $_.Exception.Message) }
else
{ $msg = [string]::Format($msgTemplate2, $_.Exception.Message, $RemoteComputerName) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Test-PowerShellToolsForPISystemAvailable {
<#
.SYNOPSIS
(Core functionality) Checks if PowerShell Tools for the PI System are available.
.DESCRIPTION
Checks if PowerShell Tools for the PI System are available.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "ArePowerShellToolsAvailable", Justification="Global variable used by validation checks.")]
param()
# Check for availability of PowerShell Tools for the PI System
if (-not(Test-Path variable:global:ArePowerShellToolsAvailable)) {
if (Get-Module -ListAvailable -Name OSIsoft.PowerShell) {
Import-Module -Name OSIsoft.PowerShell
$global:ArePowerShellToolsAvailable = $true
$version = $(Get-Module OSIsoft.PowerShell).Version
if ($version.Major -lt 2) {
$msg = "Legacy version of PowerShell Tools for the PI System (OSIsoft.PowerShell module version $version) detected."
$msg += "Install the latest version of PI System Management Tools to update the module for best performance."
Write-PISysAudit_LogMessage $msg "Warning" $fn
}
}
else {
$global:ArePowerShellToolsAvailable = $false
}
}
}
function Test-AFServerConnectionAvailable {
<#
.SYNOPSIS
(Core functionality) Checks if AF Server is connected.
.DESCRIPTION
Validate AF Server is connected.
#>
if ($null -ne $global:AFServerConnection.IsConnected) {
$global:AFServerConnection.IsConnected
}
else {
$global:AFServerConnection.ConnectionInfo.IsConnected
}
}
function PathConcat {
<#
.SYNOPSIS
(Core functionality) Concatenate a file path.
.DESCRIPTION
Concatenate a file path. This function is used in place of Join-Path
because paths are sometimes constructed locally and then used in remote
commands and Join-Path will fail if the path does not exist locally.
#>
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("pp")]
[string]
$ParentPath,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("cp")]
[string]
$ChildPath,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
$FullPath = ($ParentPath.TrimEnd('\', '/') + '\' + $ChildPath.TrimStart('\', '/'))
return $FullPath
}
catch {
# Return the error message.
$msgTemplate = "An error occurred building file path {0} with PowerShell."
$msg = [string]::Format($msgTemplate, $FullPath)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function SafeReplace {
<#
.SYNOPSIS
(Core functionality) Perform a properly escaped string replace
.DESCRIPTION
Perform a properly escaped string replace
#>
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("s")]
[string]
$String,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("o")]
[string]
$Original,
[parameter(Mandatory = $false, Position = 2, ParameterSetName = "Default")]
[alias("n")]
[string]
$New,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
$Original = [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($Original)
$New = [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($New)
$ReplacedString = $String -replace $Original, $New
return $ReplacedString
}
catch {
$msg = "An error occurred performing the replacement operation."
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function ExecuteComplianceChecks {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("lof")]
$ListOfFunctions,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("act")]
[string]
$Activity = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
# Set message templates.
$statusMsgProgressTemplate1 = "Perform check {0}/{1}: {2}"
$complianceCheckFunctionTemplate = "Compliance Check function: {0}, arguments: {1}, {2}, {3}, {4}"
# Proceed with all the compliance checks.
$i = 0
foreach ($function in $ListOfFunctions.GetEnumerator()) {
# Set the progress.
if ($ShowUI) {
# Increment the counter.
$i++
$auditItem = (Get-Help $function.Name).Synopsis
$statusMsg = [string]::Format($statusMsgProgressTemplate1, $i, $ListOfFunctions.Count.ToString(), $auditItem)
$pctComplete = ($i - 1) / $listOfFunctions.Count * 100
Write-Progress -activity $activityMsg1 -Status $statusMsg -ParentId 1 -PercentComplete $pctComplete
}
$msg = [string]::Format($complianceCheckFunctionTemplate, $function.Name, $AuditTable, `
$LocalComputer, $RemoteComputerName, $DBGLevel)
Write-PISysAudit_LogMessage $msg "Debug" $fn -dbgl $DBGLevel -rdbgl 2
if ($global:SuppressCheckIDList -notcontains $function.ID) {
# Call the function to execute the check.
& $function.Name $AuditTable -lc $LocalComputer -rcn $RemoteComputerName -dbgl $DBGLevel
}
else {
$msg = "Suppressing audit check " + $function.ID + " against " + $computerParams.ComputerName
Write-PISysAudit_LogMessage $msg "Debug" $fn -dbgl $DBGLevel -rdbgl 2
}
}
}
function StartComputerAudit {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[int]
$AuditLevelInt = 1,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
try {
Get-PISysAudit_GlobalMachineConfiguration -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -DBGLevel $DBGLevel
}
catch {
$msgTemplate = "An error occurred while accessing the global configuration of {0}"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "Machine Audit" -fn $fn -msg $msg
return
}
# Get the list of functions to execute.
$listOfFunctions = Get-PISysAudit_FunctionsFromLibrary1 -lvl $AuditLevelInt
# There is nothing to execute.
if ($listOfFunctions.Count -eq 0) {
# Return the error message.
$msg = "No machine checks have been found."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Set message templates.
$activityMsgTemplate1 = "Check computer '{0}'..."
$statusMsgCompleted = "Completed"
$activityMsg1 = [string]::Format($activityMsgTemplate1, $ComputerParams.ComputerName)
# Proceed with all the compliance checks.
ExecuteComplianceChecks -AuditTable $AuditTable -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -lof $listOfFunctions -dbgl $DBGLevel -act $activityMsg1
# Set the progress.
if ($ShowUI) {
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -PercentComplete 100
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -Completed
}
}
catch {
# Return the error message.
$msg = "A problem occurred during the processing of computer checks"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function StartPIDataArchiveAudit {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[int]
$AuditLevelInt = 1,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Validate the presence of a PI Data Archive
if ((ValidateIfHasPIDataArchiveRole -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -dbgl $DBGLevel) -eq $false) {
# Return the error message.
$msgTemplate = "The computer {0} does not have a PI Data Archive role or the validation failed"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Data Archive Audit" -fn $fn -msg $msg
return
}
# Check for availability of PowerShell Tools for the PI System
Test-PowerShellToolsForPISystemAvailable
if ($global:ArePowerShellToolsAvailable) {
try {
$success = Get-PISysAudit_GlobalPIDataArchiveConfiguration -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -lvl $AuditLevelInt -dbgl $DBGLevel
if (-not($success)) {
$msg = "Failed to access PI Data Archive information from {0}" -f $ComputerParams.ComputerName
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Data Archive Audit" -fn $fn -msg $msg
return
}
}
catch {
# Return the error message.
$msgTemplate = "An error occurred connecting to the PI Data Archive {0} with PowerShell. Terminating PI Data Archive audit"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Data Archive Audit" -fn $fn -msg $msg
return
}
}
else {
$msg = "Unable to locate module OSIsoft.Powershell on the computer running this script. Terminating PI Data Archive audit"
Write-PISysAudit_LogMessage $msg "Error" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Data Archive Audit" -fn $fn -msg $msg
return
}
# Get the list of functions to execute.
$listOfFunctions = Get-PISysAudit_FunctionsFromLibrary2 -lvl $AuditLevelInt
# There is nothing to execute.
if ($listOfFunctions.Count -eq 0) {
# Return the error message.
$msg = "No PI Data Archive checks have been found."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Set message templates.
$activityMsgTemplate1 = "Check PI Data Archive component on '{0}' computer"
$activityMsg1 = [string]::Format($activityMsgTemplate1, $ComputerParams.ComputerName)
$statusMsgCompleted = "Completed"
# Proceed with all the compliance checks.
ExecuteComplianceChecks -AuditTable $AuditTable -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -lof $listOfFunctions -dbgl $DBGLevel -act $activityMsg1
# Disconnect if PowerShell Tools are used.
if ($global:PIDataArchiveConfiguration.Connection) {
if ($global:PIDataArchiveConfiguration.Connection.Connected) {$global:PIDataArchiveConfiguration.Connection.Disconnect()}
}
# Set the progress.
if ($ShowUI) {
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -PercentComplete 100
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -Completed
}
}
catch {
# Return the error message.
$msg = "A problem occurred during the processing of PI Data Archive checks"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function StartPIAFServerAudit {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "AFServerConnection", Justification="Global variable set that is used by the validation checks.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "AFDiagOutput", Justification="Global variable set that is used by the validation checks.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[int]
$AuditLevelInt = 1,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Validate the presence of a PI AF Server
if ((ValidateIfHasPIAFServerRole -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -dbgl $DBGLevel) -eq $false) {
# Return the error message.
$msgTemplate = "The computer {0} does not have a PI AF Server role or the validation failed"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI AF Server Audit" -fn $fn -msg $msg
return
}
# Get the list of functions to execute.
$listOfFunctions = Get-PISysAudit_FunctionsFromLibrary3 -lvl $AuditLevelInt
# There is nothing to execute.
if ($listOfFunctions.Count -eq 0) {
# Return the error message.
$msg = "No PI AF Server checks have been found."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Check for availability of PowerShell Tools for the PI System
Test-PowerShellToolsForPISystemAvailable
if ($global:ArePowerShellToolsAvailable) {
try {
$global:AFServerConnection = Connect-AFServer -AFServer $(Get-AFServer -Name $ComputerParams.ComputerName)
if (Test-AFServerConnectionAvailable) {
$msgTemplate = "Successfully connected to the PI AF Server {0} with PowerShell."
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Debug" $fn -dbgl $DBGLevel -rdbgl 2
}
else {
$msgTemplate = "Unable to access the PI AF Server {0} with PowerShell. Check if there is a valid mapping for your user."
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI AF Server Audit" -fn $fn -msg $msg
return
}
}
catch {
# Return the error message.
$msgTemplate = "An error occurred connecting to the PI AF Server {0} with PowerShell."
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI AF Server Audit" -fn $fn -msg $msg
return
}
}
# Set message templates.
$activityMsgTemplate1 = "Check PI AF Server component on '{0}' computer"
$activityMsg1 = [string]::Format($activityMsgTemplate1, $ComputerParams.ComputerName)
$statusMsgCompleted = "Completed"
# Prepare data required for multiple compliance checks
Write-Progress -Activity $activityMsg1 -Status "Gathering PI AF Server Configuration"
$global:AFDiagOutput = Invoke-PISysAudit_AFDiagCommand -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -dbgl $DBGLevel
ExecuteComplianceChecks -AuditTable $AuditTable -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -lof $listOfFunctions -dbgl $DBGLevel -act $activityMsg1
# Set the progress.
if ($ShowUI) {
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -PercentComplete 100
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -Completed
}
}
catch {
# Return the error message.
$msg = "A problem occurred during the processing of PI AF Server checks"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function StartSQLServerAudit {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[int]
$AuditLevelInt = 1,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# If no password has been given and SQL Server security is in use,
# prompt for a password and store in the cache.
# This will avoid to ask many times to the user when a
# SQL query is performed.
if (($ComputerParams.IntegratedSecurity -eq $false) -and ($ComputerParams.PasswordFile -eq ""))
{ SetSQLAccountPasswordInCache $ComputerParams.ComputerName $ComputerParams.InstanceName $ComputerParams.SQLServerUserID}
# Validate the presence of a SQL Server
try {
if (-not (Get-Module -ListAvailable -Name SQLPS)) {
# Return if SQLPS not available on machine
$msg = "Unable to locate module SQLPS on the computer running this script. Terminating SQL Server audit"
Write-PISysAudit_LogMessage $msg "Error" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "SQL Server Audit" -fn $fn -msg $msg
return
}
# Push and Pop are to prevent a context switch to the SQL shell from persisting after invocation of SQL commands.
Push-Location
Import-Module SQLPS -DisableNameChecking
Pop-Location
if ((ValidateIfHasSQLServerRole -LocalComputer $ComputerParams.IsLocal -RemoteComputerName $ComputerParams.ComputerName `
-InstanceName $ComputerParams.InstanceName -IntegratedSecurity $ComputerParams.IntegratedSecurity `
-UserName $ComputerParams.SQLServerUserID -PasswordFile $ComputerParams.PasswordFile `
-dbgl $DBGLevel) -eq $false) {
# Return the error message.
$msgTemplate = "The computer {0} does not have a SQL Server role or the validation failed"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "SQL Server Audit" -fn $fn -msg $msg
return
}
}
catch {
# Return the error message.
$msgTemplate = "Could not execute test query against SQL Server on computer {0}"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "SQL Server Audit" -fn $fn -msg $msg
return
}
# Get the list of functions to execute.
$listOfFunctions = Get-PISysAudit_FunctionsFromLibrary4 -lvl $AuditLevelInt
# There is nothing to execute.
if ($listOfFunctions.Count -eq 0) {
# Return the error message.
$msg = "No SQL Server checks have been found."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Set message templates.
$activityMsgTemplate1 = "Check SQL Server component on '{0}' computer"
$activityMsg1 = [string]::Format($activityMsgTemplate1, $ComputerParams.ComputerName)
$statusMsgProgressTemplate1 = "Perform check {0}/{1}: {2}"
$statusMsgCompleted = "Completed"
$complianceCheckFunctionTemplate = "Compliance Check function: {0} and arguments are:" `
+ " Audit Table = {1}, Server Name = {2}, SQL Server Instance Name = {3}," `
+ " Use Integrated Security = {4}, User name = {5}, Password file = {6}, Debug Level = {7}"
# Proceed with all the compliance checks.
$i = 0
foreach ($function in $listOfFunctions.GetEnumerator()) {
# Set the progress.
if ($ShowUI) {
# Increment the counter.
$i++
$auditItem = (Get-Help $function.Name).Synopsis
$statusMsg = [string]::Format($statusMsgProgressTemplate1, $i, $listOfFunctions.Count.ToString(), $auditItem)
$pctComplete = ($i - 1) / $listOfFunctions.Count * 100
Write-Progress -activity $activityMsg1 -Status $statusMsg -ParentId 1 -PercentComplete $pctComplete
}
# ............................................................................................................
# Verbose at Debug Level 2+
# Show some extra messages.
# ............................................................................................................
$msg = [string]::Format($complianceCheckFunctionTemplate, $function.Name, $AuditTable, $ComputerParams.ComputerName, `
$ComputerParams.InstanceName, $ComputerParams.IntegratedSecurity, `
$ComputerParams.SQLServerUserID, $ComputerParams.PasswordFile, $DBGLevel)
Write-PISysAudit_LogMessage $msg "Debug" $fn -dbgl $DBGLevel -rdbgl 2
# Call the function.
& $function.Name $AuditTable -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-InstanceName $ComputerParams.InstanceName `
-IntegratedSecurity $ComputerParams.IntegratedSecurity `
-user $ComputerParams.SQLServerUserID `
-pf $ComputerParams.PasswordFile `
-dbgl $DBGLevel
}
# Set the progress.
if ($ShowUI) {
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -PercentComplete 100
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -Completed
}
}
catch {
# Return the error message.
$msg = "A problem occurred during the processing of SQL Server checks"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function StartPIVisionServerAudit {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[int]
$AuditLevelInt = 1,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
$IsElevated = (Get-Variable "PISysAuditIsElevated" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Validate the presence of IIS
if ((ValidateIfHasPIVisionRole -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -dbgl $DBGLevel) -eq $false) {
# Return the error message.
$msgTemplate = "The computer {0} does not have the PI Vision role or the validation failed"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Vision Server Audit" -fn $fn -msg $msg
return
}
if ($ComputerParams.IsLocal -and -not($IsElevated)) {
$msg = "Elevation required to run Audit checks using IIS Cmdlet. Run PowerShell as Administrator to complete these checks."
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Vision Server Audit" -fn $fn -msg $msg
return
}
if ((Get-PISysAudit_InstalledWin32Feature -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -wfn "IIS-ManagementScriptingTools" -DBGLevel $DBGLevel) -ne 1) {
# Return the error message.
$msgTemplate = "The computer {0} does not have the IIS Management Scripting Tools Feature (IIS cmdlets) or the validation failed; some audit checks may not be available."
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Vision Server Audit" -fn $fn -msg $msg
return
}
# Set message templates.
$activityMsgTemplate1 = "Check PI Vision component on '{0}' computer"
$activityMsg1 = [string]::Format($activityMsgTemplate1, $ComputerParams.ComputerName)
# $statusMsgProgressTemplate1 = "Perform check {0}/{1}: {2}"
$statusMsgCompleted = "Completed"
<# $complianceCheckFunctionTemplate = "Compliance Check function: {0} and arguments are:" `
+ " Audit Table = {1}, Server Name = {2}," `
+ " Debug Level = {3}" #>
try {
Write-Progress -Activity $activityMsg1 -Status "Gathering PI Vision Configuration" -ParentId 1
Get-PISysAudit_GlobalPIVisionConfiguration -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -al $ComputerParams.Alias -DBGLevel $DBGLevel
}
catch {
# Return the error message.
$msgTemplate = "An error occurred while accessing the global configuration of PI Vision on {0}"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Vision Server Audit" -fn $fn -msg $msg
return
}
# Get the list of functions to execute.
$listOfFunctions = Get-PISysAudit_FunctionsFromLibrary5 -lvl $AuditLevelInt
# There is nothing to execute.
if ($listOfFunctions.Count -eq 0) {
# Return the error message.
$msg = "No PI Vision checks have been found."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Proceed with all the compliance checks.
ExecuteComplianceChecks -AuditTable $AuditTable -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -lof $listOfFunctions -dbgl $DBGLevel -act $activityMsg1
# Set the progress.
if ($ShowUI) {
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -PercentComplete 100
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -Completed
}
}
catch {
# Return the error message.
$msg = "A problem occurred during the processing of PI Vision checks"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
function StartPIWebApiServerAudit {
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[int]
$AuditLevelInt = 1,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
# Get and store the function Name.
$fn = GetFunctionName
try {
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Validate that PI Web API is installed
if ((ValidateIfHasPIWebApiRole -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -dbgl $DBGLevel) -eq $false) {
# Return the error message.
$msgTemplate = "The computer {0} does not have the PI Web API role or the validation failed"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Web API Server Audit" -fn $fn -msg $msg
return
}
# Check for availability of PowerShell Tools for the PI System
Test-PowerShellToolsForPISystemAvailable
if (-not $global:ArePowerShellToolsAvailable) {
$msg = "Unable to locate module OSIsoft.Powershell on the computer running this script. Terminating PI Web API audit"
Write-PISysAudit_LogMessage $msg "Error" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Web API Audit" -fn $fn -msg $msg
return
}
# Set message templates.
$activityMsgTemplate1 = "Check PI Web API component on '{0}' computer"
$activityMsg1 = [string]::Format($activityMsgTemplate1, $ComputerParams.ComputerName)
# $statusMsgProgressTemplate1 = "Perform check {0}/{1}: {2}"
$statusMsgCompleted = "Completed"
<# $complianceCheckFunctionTemplate = "Compliance Check function: {0} and arguments are:" `
+ " Audit Table = {1}, Server Name = {2}," `
+ " Debug Level = {3}" #>
try {
Write-Progress -Activity $activityMsg1 -Status "Gathering PI Web API Configuration" -ParentId 1
Get-PISysAudit_GlobalPIWebApiConfiguration -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -DBGLevel $DBGLevel
}
catch {
# Return the error message.
$msgTemplate = "An error occurred while accessing the global configuration of PI Web API on {0}"
$msg = [string]::Format($msgTemplate, $ComputerParams.ComputerName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
$AuditTable = New-PISysAuditError -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName `
-at $AuditTable -an "PI Web API Server Audit" -fn $fn -msg $msg
return
}
# Get the list of functions to execute.
$listOfFunctions = Get-PISysAudit_FunctionsFromLibrary6 -lvl $AuditLevelInt
# There is nothing to execute.
if ($listOfFunctions.Count -eq 0) {
# Return the error message.
$msg = "No PI Web API checks have been found."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Proceed with all the compliance checks.
ExecuteComplianceChecks -AuditTable $AuditTable -lc $ComputerParams.IsLocal -rcn $ComputerParams.ComputerName -lof $listOfFunctions -dbgl $DBGLevel -act $activityMsg1
# Set the progress.
if ($ShowUI) {
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -PercentComplete 100
Write-Progress -activity $activityMsg1 -Status $statusMsgCompleted -ParentId 1 -Completed
}
}
catch {
# Return the error message.
$msg = "A problem occurred during the processing of PI Web API checks"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return
}
}
# ........................................................................
# Public Functions
# ........................................................................
function Initialize-PISysAudit {
<#
.SYNOPSIS
(Core functionality) Initialize the module.
.DESCRIPTION
Initialize the module.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[boolean]
$ShowUI = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
# Read from the global constant bag.
$isPISysAuditInitialized = (Get-Variable "PISysAuditInitialized" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Set folder names required by the script.
SetFolders
# Set the initialization flag..
if (($null -eq $isPISysAuditInitialized) -or ($isPISysAuditInitialized -eq $false)) {
# Set global variable checking for elevated status.
$IsElevated = CheckIfRunningElevated
New-Variable -Name "PISysAuditIsElevated" -Scope "Global" -Visibility "Public" -Value $IsElevated
# Validate if used with PowerShell version 3.x and more
$majorVersionPS = $PSVersionTable.PSVersion.Major
if ($majorVersionPS -lt 3) {
$msg = "This script won't execute under less than version 3.0 of PowerShell"
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Set the ShowUI flag
if ($null -eq (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value)
{ New-Variable -Name "PISysAuditShowUI" -Scope "Global" -Visibility "Public" -Value $true }
# Set an PISysAuditInitialized flag
New-Variable -Name "PISysAuditInitialized" -Scope "Global" -Visibility "Public" -Value $true
}
}
END {}
#***************************
#End of exported function
#***************************
}
function New-PISysAudit_PasswordOnDisk {
<#
.SYNOPSIS
(Core functionality) Encrypt password on disk.
.DESCRIPTION
Encrypt password on disk.
#>
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Initialize the module if needed
Initialize-PISysAudit
# Read from the global constant bag.
$isPISysAuditInitialized = (Get-Variable "PISysAuditInitialized" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# If initialization failed, leave the function.
if (($null -eq $isPISysAuditInitialized) -or ($isPISysAuditInitialized -eq $false)) {
$msg = "This script won't execute because initialization has not completed"
Write-PISysAudit_LogMessage $msg "Warning" $fn
return
}
# Read from the global constant bag.
$pwdPath = (Get-Variable "PasswordPath" -Scope "Global").Value
# Get the password.
$pwd = Read-Host -assecurestring "Please enter the password to save on disk for further usage"
# Define the file to save it.
$file = Read-Host "Please enter the file name to store it"
# Validate.
if ([string]::IsNullOrEmpty($file)) {
Write-PISysAudit_LogMessage "No file name has been entered. Please retry!" "Error" $fn -sc $true
return
}
# Set the path.
$pwdFile = PathConcat -ParentPath $pwdPath -ChildPath $file
# Encrypt.
# Key is left undefined to leverage the Windows Data Protection API (DPAPI) to encrypt the standard string.
# Visit http://msdn.microsoft.com/en-us/library/ms995355.aspx to know more.
$securepwd = ConvertFrom-SecureString $pwd
# Save.
Out-File -FilePath $pwdFile -InputObject $securePWD
}
catch {
# Return the error message.
$msgTemplate = "The creation of {0} file containing your password has failed."
$msg = [string]::Format($msgTemplate, $pwdFile)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Write-PISysAudit_LogMessage {
<#
.SYNOPSIS
(Core functionality) Write to console and/or log file (PISystemAudit.log) in the same folder where the script is found.
.DESCRIPTION
Write to console and/or log file (PISystemAudit.log) in the same folder where the script is found.
.NOTES
The non-use of Write-Error, Write-Verbose, Write-Warning have been deliberately taken for design purposes.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("msg,M")]
[string]
$Message,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("mt")]
[ValidateSet("Error", "Warning", "Info", "Debug")]
[string]
$MessageType,
[parameter(Mandatory = $true, Position = 2, ParameterSetName = "Default")]
[alias("fn")]
[string]
$FunctionName,
[parameter(ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$CurrentDBGLevel = 0,
[parameter(ParameterSetName = "Default")]
[alias("rdbgl")]
[int]
$RequiredDBGLevel = 0,
[parameter(ParameterSetName = "Default")]
[alias("sc")]
[boolean]
$ShowToConsole = $false,
[parameter(ParameterSetName = "Default")]
[alias("eo")]
[object]
$ErrorObject = $null)
BEGIN {}
PROCESS {
# Skip if this the proper level is not reached.
if ($CurrentDBGLevel -lt $RequiredDBGLevel) { return }
# Get the defined PISystemAudit log file.
$logPath = (Get-Variable "PISystemAuditLogFile" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Read from the global constant bag.
$ShowUI = (Get-Variable "PISysAuditShowUI" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# Get current date for log message prefix
$ts = (Get-Date -Format "yyyy-MM-dd HH:mm:ss") + ", "
# Templates
$msgTemplate1 = "Function: {0}, Error: {1}."
#$msgTemplate2 = "Function: {0}, Error: {1}, Details: {2}."
$msgTemplate3 = "Function: {0}, Line: {1}, Error: {2}, Details: {3}."
$msgTemplate4 = "Warning, {0}."
$msgTemplate5 = "Information, {0}."
$msgTemplate6 = "Function: {0}, Debug: {1}."
if ($Message.EndsWith("."))
{ $Message = $Message.Trim(".") }
# Message.
$msg = ""
if ($MessageType.ToLower() -eq "error") {
# This type of message is always shown whatever the debug level.
# Form the message.
if ($null -eq $ErrorObject)
{ $msg = $msgTemplate1 -f $FunctionName, $Message }
else {
# Remove the trailing period of the error message, template already contains
# a period to end the message.
if ($ErrorObject.Exception.Message.EndsWith("."))
{ $modifiedErrorMessage = $ErrorObject.Exception.Message.SubString(0, $ErrorObject.Exception.Message.Length - 1) }
else
{ $modifiedErrorMessage = $ErrorObject.Exception.Message }
$msg = $msgTemplate3 -f $FunctionName, $ErrorObject.InvocationInfo.ScriptLineNumber, `
$Message, $modifiedErrorMessage
}
# Write the content.
Add-Content -Path $logPath -Value ($ts + $msg) -Encoding ASCII
# Force to show on console.
$ShowToConsole = $true
# Set color.
$ForegroundColor = "Red"
$BackgroundColor = "Black"
if ($ShowToConsole -and $ShowUI) { Write-Host $msg -ForeGroundColor $ForegroundColor -BackgroundColor $BackgroundColor }
}
elseif ($MessageType.ToLower() -eq "warning") {
# Form the message.
$msg = $msgTemplate4 -f $Message
# Write the content.
Add-Content -Path $logPath -Value ($ts + $msg) -Encoding ASCII
# Force to show on console.
$ShowToConsole = $true
# Set color.
$ForegroundColor = "Yellow"
$BackgroundColor = "Black"
if ($ShowToConsole -and $ShowUI) { Write-Host $msg -ForeGroundColor $ForegroundColor -BackgroundColor $BackgroundColor }
}
elseif ($MessageType.ToLower() -eq "info") {
if ($Message -ne "") {
# Form the message.
$msg = $msgTemplate5 -f $Message
$msgConsole = $Message
# Write the content.
Add-Content -Path $logPath -Value ($ts + $msg) -Encoding ASCII
if ($ShowToConsole -and $ShowUI) { Write-Host $msgConsole }
}
}
elseif ($MessageType.ToLower() -eq "debug") {
# Do nothing if the debug level is not >= required debug level
if ($CurrentDBGLevel -ge $RequiredDBGLevel) {
# Form the message.
$msg = $msgTemplate6 -f $FunctionName, $Message
# Write the content.
Add-Content -Path $logPath -Value ($ts + $msg) -Encoding ASCII
if ($ShowToConsole -and $ShowUI) { Write-Host $msg }
}
}
else {
$msg = $msgTemplate1 -f $FunctionName, "An invalid level of message has been picked."
# Write the content.
Add-Content -Path $logPath -Value ($ts + $msg) -Encoding ASCII
# Set color.
$ForegroundColor = "Red"
$BackgroundColor = "Black"
if ($ShowToConsole -and $ShowUI) { Write-Host $msg -ForeGroundColor $ForegroundColor -BackgroundColor $BackgroundColor }
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_EnvVariable {
<#
.SYNOPSIS
(Core functionality) Get a machine related environment variable.
.DESCRIPTION
Get a machine related environment variable.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("vn")]
[string]
$VariableName,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("t")]
[ValidateSet("Machine", "User", "Process")]
[string]
$Target = "Machine",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$Variable)
if (Test-Path -Path $('Env:' + $Variable)) {
Get-ChildItem -Path $('Env:' + $Variable) | Select-Object -ExpandProperty Value
}
}
# Execute the GetEnvironmentVariable method locally or remotely via the Invoke-Command cmdlet.
if ($LocalComputer) {
$value = & $scriptBlock -Variable $VariableName
}
else {
$value = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $VariableName
}
# Verbose if debug level is 2+
$msg = "Value returned is: $value"
Write-PISysAudit_LogMessage $msg "Debug" $fn -rdbgl 2 -dbgl $DBGLevel
# Return the value found.
return $value
}
catch {
# Return the error message.
$msgTemplate1 = "A problem occurred during the reading of the environment variable: {0} from local machine."
$msgTemplate2 = "A problem occurred during the reading of the environment variable: {0} from {1} machine."
if ($LocalComputer)
{ $msg = [string]::Format($msgTemplate1, $_.Exception.Message) }
else
{ $msg = [string]::Format($msgTemplate2, $_.Exception.Message, $RemoteComputerName) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_RegistryKeyValue {
<#
.SYNOPSIS
(Core functionality) Read a value from the Windows Registry Hive.
.DESCRIPTION
Read a value from the Windows Registry Hive.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("rkp")]
[string]
$RegKeyPath,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("a")]
[string]
$Attribute,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$Path, [string]$Name)
if (Test-Path -Path $Path) {
$Value = Get-ItemProperty -Path $Path -Name $Name | Select-Object -ExpandProperty $Name
}
else {
$Value = $null
}
return $Value
}
if ($LocalComputer)
{ $value = & $scriptBlock -Path $RegKeyPath -Name $Attribute }
else
{ $value = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $RegKeyPath, $Attribute }
# Return the value found.
return $value
}
catch {
# Return the error message.
$msgTemplate1 = "A problem occurred during the reading of the registry key: {0} from local machine."
$msgTemplate2 = "A problem occurred during the reading of the registry key: {0} from {1} machine."
if ($LocalComputer)
{ $msg = [string]::Format($msgTemplate1, $_.Exception.Message) }
else
{ $msg = [string]::Format($msgTemplate2, $_.Exception.Message, $RemoteComputerName) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_TestRegistryKey {
<#
.SYNOPSIS
(Core functionality) Test for the existence of a key in the Windows Registry Hive.
.DESCRIPTION
Test for the existence of a key in the Windows Registry Hive.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("rkp")]
[string]
$RegKeyPath,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$Path)
return $(Test-Path -Path $Path)
}
# Execute the Test-Path cmdlet method locally or remotely via the Invoke-Command cmdlet.
if ($LocalComputer)
{ $value = & $scriptBlock -Path $RegKeyPath }
else
{ $value = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $RegKeyPath }
# Return the value found.
return $value
}
catch {
# Return the error message.
$msgTemplate1 = "A problem occurred during the reading of the registry key: {0} from local machine."
$msgTemplate2 = "A problem occurred during the reading of the registry key: {0} from {1} machine."
if ($LocalComputer)
{ $msg = [string]::Format($msgTemplate1, $_.Exception.Message) }
else
{ $msg = [string]::Format($msgTemplate2, $_.Exception.Message) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_ParseDomainAndUserFromString {
<#
.SYNOPSIS
(Core functionality) Parse the domain portion out of an account string.
.DESCRIPTION
Parse the domain portion out of an account string. Supports UPN or Down-Level format
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("us")]
[string]
$UserString,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
If ($UserString.ToLower() -in
@("localsystem", "networkservice", "localservice",
"local system", "network service", "local service",
"nt authority\localsystem", "nt authority\networkservice", "nt authority\localservice",
"nt authority\local system", "nt authority\network service", "nt authority\local service",
"applicationpoolidentity", "nt service\afservice", "nt service\pinetmgr", "nt service\piwebapi", "nt service\picrawler", "nt service\pisqldas" )) {
$ServiceAccountDomain = 'MACHINEACCOUNT'
$parsingPosDL = $UserString.IndexOf('\')
If ($parsingPosDL -ne -1 ) {
$ServiceAccount = $UserString.Substring($parsingPosDL + 1)
}
Else {
$ServiceAccount = $UserString
}
}
Else {
# Parse as UPN or Down-Level Logon format
$parsingPosDL = $UserString.IndexOf('\') # DL
$parsingPosUPN = $UserString.IndexOf('@') # UPN
If ($parsingPosDL -ne -1 ) {
$ServiceAccountDomain = $UserString.Substring(0, $parsingPosDL)
$ServiceAccount = $UserString.Substring($parsingPosDL + 1)
}
ElseIf ($parsingPosUPN -ne -1) {
$ServiceAccountDomain = $UserString.Substring($parsingPosUPN + 1)
$ServiceAccount = $UserString.Substring(0, $parsingPosUPN)
}
Else {
$ServiceAccountDomain = $null
$ServiceAccount = $UserString
}
}
$AccountObject = New-Object PSCustomObject
Add-Member -InputObject $AccountObject -MemberType NoteProperty -Name "UserName" -Value $ServiceAccount
Add-Member -InputObject $AccountObject -MemberType NoteProperty -Name "Domain" -Value $ServiceAccountDomain
return $AccountObject
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Unable to determine account domain." "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_ServiceProperty {
<#
.SYNOPSIS
(Core functionality) Get a property (state, startup type, or logon account) of a service on a given computer.
.DESCRIPTION
Get a property (state, startup type, or logon account) of a service on a given computer.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("sn")]
[string]
$ServiceName,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("sp")]
[ValidateSet("State", "StartupType", "LogOnAccount")]
[string]
$ServiceProperty,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
# Map cmdlet parameter to actual property name of WMI object
# State -> State
# StartupType -> StartMode
# LogOnAccount -> StartName
if ($ServiceProperty -eq 'State') { $Property = 'State'}
elseif ($ServiceProperty -eq 'StartupType') { $Property = 'StartMode' }
elseif ($ServiceProperty -eq 'LogOnAccount') { $Property = 'StartName'}
try {
$className = "Win32_Service"
$namespace = "root\CIMV2"
$filterExpression = [string]::Format("name='{0}'", $ServiceName)
$WMIObject = ExecuteWMIQuery $className -n $namespace -lc $LocalComputer -rcn $RemoteComputerName -FilterExpression $filterExpression -DBGLevel $DBGLevel
return ($WMIObject | Select-Object -ExpandProperty $Property)
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Execution of WMI Query has failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_CertificateProperty {
<#
.SYNOPSIS
(Core functionality) Get a property of a certificate on a given computer.
.DESCRIPTION
Get a property of a certificate on a given computer.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("ct")]
[string]
$CertificateThumbprint,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
[ValidateSet("Issuer")]
[string]
$CertificateProperty,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$Thumbprint, [string]$Property)
Get-ChildItem -Path $('Cert:\LocalMachine\My\' + $Thumbprint) | Format-List -Property $Property | Out-String
}
if ($LocalComputer)
{ $value = & $scriptBlock -Thumbprint $CertificateThumbprint -Property $CertificateProperty }
else
{ $value = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $CertificateThumbprint, $CertificateProperty }
# Only return the value, otherwise every check will have to massage it
$value = $value.Split('=')[1].Trim()
return $value
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Accessing certificate properties failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_BoundCertificate {
<#
.SYNOPSIS
(Core functionality) Determine what certificate is bould to a particular IP and Port.
.DESCRIPTION
Determine what certificate is bould to a particular IP and Port.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("pt")]
[string]
$Port,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("ip")]
[string]
$IPAddress = "0.0.0.0",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
param([string]$IPPort)
netsh http show sslcert ipport=$($IPPort)
}
$IPPort = $IPAddress + ':' + $Port
if ($LocalComputer)
{ $value = & $scriptBlock -IPPort $IPPort }
else
{ $value = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $IPPort }
return $value
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Accessing certificate properties failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_ResolveDnsName {
<#
.SYNOPSIS
(Core functionality) Retrieves attributes of a DNS record
.DESCRIPTION
Wraps nslookup or Resolve-DnsName depending on PS version used. Currently
only supports returning the Type of record.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("ln")]
[string]
$LookupName,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("at")]
[ValidateSet('Type', 'HostName', 'FQDN')]
[string]
$Attribute = 'Type',
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
if (Get-Command Resolve-DnsName -ErrorAction SilentlyContinue) {
$record = Resolve-DnsName -Name $LookupName
$recordObjectType = $record.GetType().Name
if ($recordObjectType -eq 'Object[]') { # Either CNAME and corresponding A records or collection of A and AAAA records
if ($record[0].GetType().Name -eq 'DnsRecord_PTR') {
$type = $record[0].Type
$name = $record[0].NameHost
}
else {
$type = 'A'
$name = $record[0].Name
}
}
else {
if ($recordObjectType -in @('DnsRecord_A', 'DnsRecord_AAAA'))
{ $type = 'A' }
else
{ $type = $record.Type }
$name = $record.Name
}
}
else {
# non-authoritative answer returns an error with nslookup, but not with the more modern Resolve-DnsName
# for consistent implementation, sending error output to null for nslookup and noting error if not results
# are returned.
$record = nslookup $LookupName 2> $null
if ($null -eq $record) {
$msgTemplate = "No results returned by nslookup for {0}"
$msg = [string]::Format($msgTemplate, $LookupName)
Write-PISysAudit_LogMessage $msg "Warning" $fn
return $null
}
else {
if ($null -eq $($record -match 'Aliases:')) # Host entry
{ $type = 'A' }
else # Alias
{ $type = 'CNAME' }
foreach ($line in $record) {
if ($line -match 'Name:') {
$name = $line.ToString().Split(':')[1].Trim()
break
}
}
}
}
switch ($Attribute) {
'Type' {$returnvalue = $type}
'HostName' {
if ($name.IndexOf('.') -ne -1)
{ $returnvalue = $name.Split('.')[0] }
else
{ $returnvalue = $name }
}
'FQDN' {$returnvalue = $name}
}
return $returnvalue
}
catch {
Write-PISysAudit_LogMessage "Accessing DNS record failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_InstalledComponent {
<#
.SYNOPSIS
(Core functionality) Get installed software on a given computer.
.DESCRIPTION
Get installed software on a given computer.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Retrieve installed 64-bit programs (or all programs on 32-bit machines)
$mainNodeKey = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall'
# If it exists, also get 32-bit programs from the corresponding Wow6432Node keys
$wow6432NodeKey = 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$scriptBlock = {
param([string]$RegKey)
if ($RegKey -like 'Wow6432') { $Action = 'SilentlyContinue' }
else { $Action = 'Continue' }
Get-ChildItem $RegKey -ErrorAction $Action | ForEach-Object { Get-ItemProperty $_.PsPath } | Where-Object { $_.Displayname -and ($_.Displayname -match ".*") }
}
if ($LocalComputer) {
$unsortedAndUnfilteredResult = & $scriptBlock -RegKey $mainNodeKey
$wow6432NodeResult = & $scriptBlock -RegKey $wow6432NodeKey
}
else {
$unsortedAndUnfilteredResult = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $mainNodeKey
$wow6432NodeResult = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $wow6432NodeKey
}
$result = $unsortedAndUnfilteredResult + $wow6432NodeResult | Sort-Object Displayname | Select-Object DisplayName, Publisher, DisplayVersion, InstallDate
return $result
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Reading the registry for installed components failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_InstalledKB {
<#
.SYNOPSIS
(Core functionality) Get installed Microsoft KBs (patches) on a given computer.
.DESCRIPTION
Get installed Microsoft KBs (patches) on a given computer.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("tp")]
[ValidateSet('HotFix', 'Reliability', 'All')]
[string]
$Type = 'All',
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$namespace = "root\CIMV2"
$WMIObject = @()
if ($Type -eq 'HotFix' -or $Type -eq 'All') {
$className = "Win32_quickfixengineering"
$filterExpression = ""
$WMIObject += ExecuteWMIQuery $className -n $namespace -lc $LocalComputer -rcn $RemoteComputerName -FilterExpression $filterExpression -DBGLevel $DBGLevel `
| Select-Object @{LABEL = "Name"; EXPRESSION = {$_.HotFixID}}, @{LABEL = "InstalledOn"; EXPRESSION = {Get-Date $_.InstalledOn}}
}
if ($Type -eq 'Reliability' -or $Type -eq 'All') {
$className = 'win32_reliabilityRecords'
$filterExpression = "sourcename='Microsoft-Windows-WindowsUpdateClient'"
$reliabilityRecords = ExecuteWMIQuery $className -n $namespace -lc $LocalComputer -rcn $RemoteComputerName -FilterExpression $filterExpression -DBGLevel $DBGLevel
# Custom Select-Object expression required to convert date string of format yyyyMMddHHmmss.fff000-000
# e.g. 20170522150218.793000-000 --> 5/22/2017 3:02:18 PM
$WMIObject += $reliabilityRecords | Select-Object @{LABEL = "Name"; EXPRESSION = {$_.ProductName}}, @{LABEL = "InstalledOn"; EXPRESSION = {
[datetime]::ParseExact($_.TimeGenerated.Substring(0, 14), 'yyyyMMddHHmmss', $null) }
}
}
return $WMIObject | Sort-Object Name
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Execution of WMI Query has failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_InstalledWin32Feature {
<#
.SYNOPSIS
(Core functionality) Get install status of Windows Feature on a given computer.
.DESCRIPTION
Get install status of Windows Feature on a given computer.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("wfn")]
[string]
$WindowsFeatureName,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$className = "Win32_OptionalFeature"
$namespace = "root\CIMV2"
$filterExpressionTemplate = "Name='{0}'"
$filterExpression = [string]::Format($filterExpressionTemplate, $WindowsFeatureName)
$WMIObject = ExecuteWMIQuery $className -n $namespace -lc $LocalComputer -rcn $RemoteComputerName -FilterExpression $filterExpression -DBGLevel $DBGLevel
return $WMIObject.InstallState
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "Reading the registry for installed components failed!" "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_FirewallState {
<#
.SYNOPSIS
(Core functionality) Validate the state of a firewall.
.DESCRIPTION
Validate the state of a firewall.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
if (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue) {
Get-NetFirewallProfile
}
else {
# Disabling the Use of Windows Firewall Across Your Network
# https://technet.microsoft.com/en-us/library/bb490624.aspx
$policyKey = 'HKLM:\SOFTWARE\Policies\Microsoft\WindowsFirewall'
if ((Test-Path $policyKey) -eq $false) {
$policyKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy'
}
# These keys return 0 if disabled, 1 if enabled
$domain = Get-ItemProperty -Path ($policyKey + "\DomainProfile") | Select-Object -ExpandProperty EnableFirewall
$private = Get-ItemProperty -Path ($policyKey + "\StandardProfile") | Select-Object -ExpandProperty EnableFirewall
$public = Get-ItemProperty -Path ($policyKey + "\PublicProfile") | Select-Object -ExpandProperty EnableFirewall
# Assemble and return a list of objects that will mimic the profile objects returned by Get-NetFirewallProfile
$firewallState = @()
$firewallState += New-Object PSCustomObject -Property @{'Name' = 'Domain'; 'Enabled' = $domain}
$firewallState += New-Object PSCustomObject -Property @{'Name' = 'Private'; 'Enabled' = $private}
$firewallState += New-Object PSCustomObject -Property @{'Name' = 'Public'; 'Enabled' = $public}
$firewallState
}
}
if ($LocalComputer) {
$firewallState = & $scriptBlock
}
else {
$firewallState = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock
}
# Return the content.
return $firewallState
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "A problem occurred when calling the Get-NetFirewallProfile cmdlet." "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_AppLockerState {
<#
.SYNOPSIS
(Core functionality) Get the state of AppLocker.
.DESCRIPTION
Get the state of AppLocker.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWMICmdlet", "", Justification="CIM favored over WMI for consistency cross platform, but this tool only supports Windows.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$scriptBlock = {
[xml]$Policy = Get-AppLockerPolicy -Effective -XML
$ServiceEnabled = $(Get-WmiObject -Class Win32_Service -Filter "Name='AppIdSvc'" -Property StartMode | Select-Object -ExpandProperty StartMode | Out-String).ToLower() -ne "disabled"
$AppLockerConfiguration = New-Object PSCustomObject
$AppLockerConfiguration | Add-Member -MemberType NoteProperty -Name Policy -Value $Policy
$AppLockerConfiguration | Add-Member -MemberType NoteProperty -Name ServiceEnabled -Value $ServiceEnabled
return $AppLockerConfiguration
}
if ($LocalComputer) {
$appLockerPolicy = & $scriptBlock
}
else {
$appLockerPolicy = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock
}
# Return the content.
return $appLockerPolicy
}
catch {
# Return the error message.
Write-PISysAudit_LogMessage "A problem occurred while retrieving the AppLocker configuration." "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
Function Get-PISysAudit_KnownServers {
<#
.SYNOPSIS
(Core functionality) Get the servers in the PI Data Archive or PI AF Server KST.
.DESCRIPTION
Get the servers in the PI Data Archive or PI AF Server KST.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="Plural noun is appropriate since KST returned as a collection.")]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("st")]
[ValidateSet('PIServer', 'AFServer')]
[string]
$ServerType,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0
)
$fn = GetFunctionName
If ($ServerType -eq 'PIServer') {
# Get PI Servers
$regpathKST = 'HKLM:\SOFTWARE\PISystem\PI-SDK\1.0\ServerHandles'
$scriptBlock = {param([string]$RegPath) Get-ChildItem $RegPath | ForEach-Object {Get-ItemProperty $_.pspath} | where-object {$_.path} | Foreach-Object {$_.path}}
if ($LocalComputer)
{ $KnownServers = & $scriptBlock -RegPath $regpathKST }
Else
{ $KnownServers = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $regpathKST }
}
Else {
# Get AF Servers
$programDataWebServer = Get-PISysAudit_EnvVariable "ProgramData" -lc $LocalComputer -rcn $RemoteComputerName -Target Process
$afsdkConfigPathWebServer = "$programDataWebServer\OSIsoft\AF\AFSDK.config"
$scriptBlock = { param([string]$ConfigPath) Get-Content -Path $ConfigPath | Out-String }
# Verbose only if Debug Level is 2+
$msgTemplate = "Remote command to send to {0} is: {1}"
$msg = [string]::Format($msgTemplate, $RemoteComputerName, $scriptBlock.ToString())
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
if ($LocalComputer)
{ $AFSDK = & $scriptBlock -ConfigPath $afsdkConfigPathWebServer }
Else
{ $AFSDK = Invoke-Command -ComputerName $RemoteComputerName -ScriptBlock $scriptBlock -ArgumentList $afsdkConfigPathWebServer }
$KnownServers = [regex]::Matches($AFSDK, 'host=\"([^\"]*)')
}
$msgTemplate = "Known servers found: {0}"
$msg = [string]::Format($msgTemplate, $KnownServers)
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
return $KnownServers
}
function Get-PISysAudit_ServicePrivilege {
<#
.SYNOPSIS
(Core functionality) Return the access token (security) of a process or service.
.DESCRIPTION
Return the access token (security) of a process or service.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("sn")]
[string]
$ServiceName,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$FilterExpression = "name='$ServiceName'"
$ServiceInfo = ExecuteWMIQuery -WMIClassName Win32_Service -FilterExpression $FilterExpression -LocalComputer $LocalComputer -RemoteComputerName $RemoteComputerName -DBGLevel $DBGLevel
if ($null -ne ($ServiceInfo | Get-Member -Name ProcessId)) {
$ProcessId = $ServiceInfo.ProcessId
}
else {
# Return the error message.
$msg = "Process ID could not be identified for: $ServiceName"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
# Set the path to the inner script.
$scriptsPath = (Get-Variable "scriptsPath" -Scope "Global").Value
$checkProcessPrivilegePSScript = PathConcat -ParentPath $scriptsPath -ChildPath "\Utilities\CheckProcessPrivilege.ps1"
$msg = "Command to execute is: CheckProcessPrivilege.ps1 $ProcessId"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
if ($LocalComputer) {
$result = & $checkProcessPrivilegePSScript $ProcessId
}
else {
$result = Invoke-Command -ComputerName $RemoteComputerName -FilePath $checkProcessPrivilegePSScript -ArgumentList @( $ProcessId )
}
$msg = "Privileges detected: $result"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
}
catch {
$msg = "Reading privileges from the process failed"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
return $result
}
END {}
#***************************
#End of exported function
#***************************
}
function Get-PISysAudit_ProcessedPIConnectionStatistics {
<#
.SYNOPSIS
(Core functionality) Transpose and filter PI Connection Statistics.
.DESCRIPTION
Transpose and filter PI Connection Statistics. Options to filter returned results by
protocol and whether the connection is local or remote.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="A plural noun makes sense since the connection stats are only accepted in a batch.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("pic")]
[object]
$PIDataArchiveConnection,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("pics")]
[object]
$PIConnectionStats,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[ValidateSet('Windows', 'Trust', 'ExplicitLogin', 'Subsystem', 'Any')]
[alias("ap")]
[string]
$ProtocolFilter = "Any",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("ro")]
[boolean]
$RemoteOnly = $false,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("so")]
[boolean]
$SuccessOnly = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("cts")]
[boolean]
$CheckTransportSecurity = $false,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Get timezone offset between PI Data Archive and here if necessary
# This offset can be added to the remote times to get local time
$offsetMinutes = 0
if (-not $LocalComputer) {
$localGmtOffset = ExecuteWMIQuery -lc $true -WMIClassName 'win32_timezone' | Select-Object -ExpandProperty Bias
$remoteGmtOffset = ExecuteWMIQuery -lc $false -rcn $RemoteComputerName -WMIClassName 'win32_timezone' | Select-Object -ExpandProperty Bias
$offsetMinutes = $localGmtOffset - $remoteGmtOffset
}
$transposedStats = @()
Foreach ($stat in $PIConnectionStats) {
# Determine properties included in the connection statistic
$hasProperty = @()
foreach ($property in $stat.StatisticType) {
if ($stat.StatisticType -contains $property -and "" -ne $stat.Item($property).Value.ToString()) {
# Grouped connections will have a List object for a property, even if all entries are null. This logic verifies
# the property has a non-null entry
if ($stat.Item($property).Value.GetType().Name -eq "List``1")
{ foreach ($entry in $stat.Item($property).Value) { if ("" -ne $entry) { $hasProperty += $property; break } } }
else
{ $hasProperty += $property }
}
}
# Identify the Authentication Protocol
$statAuthProtocol = "Unknown"
if (($hasProperty -contains 'ConnectionType') -and ($hasProperty -contains 'ConnectionStatus')) {
# Only include active connections
if ($stat.Item('ConnectionStatus').Value -eq '[0] Success' -or ($SuccessOnly -eq $false)) {
if ($hasProperty -contains 'Trust')
{ $statAuthProtocol = 'Trust' }
elseif ($hasProperty -contains 'OSUser')
{ $statAuthProtocol = 'Windows' }
elseif ($hasProperty -contains 'User')
{ $statAuthProtocol = 'ExplicitLogin' }
elseif ($Stat.Item('ConnectionType').Value -eq 'Local Connection')
{ $statAuthProtocol = 'Subsystem' }
}
}
elseif ($hasProperty -contains 'ServerID') # PINetMgr is a special case
{ $statAuthProtocol = 'Subsystem' }
# Determine whether or not the connection is remote.
[boolean]$IsRemote = $false
if ($hasProperty -contains 'ConnectionType') {
if ($stat.Item('ConnectionType').Value -eq 'Remote resolver' -or `
($stat.Item('ConnectionType').Value -eq 'PI-API Connection' -and $stat.Item('PeerAddress').Value -notin ('127.0.0.1', '')))
{ $IsRemote = $true }
}
# Apply protocol and RemoteOnly filters if applicable
if (($statAuthProtocol -eq $ProtocolFilter -or $ProtocolFilter -eq 'Any') -and ($IsRemote -or $RemoteOnly -eq $false)) {
$transposedStat = New-Object PSObject
# Add an authentication protocol attribute for easy filtering
$transposedStat | Add-Member -MemberType NoteProperty -Name 'AuthenticationProtocol' -Value $statAuthProtocol
$transposedStat | Add-Member -MemberType NoteProperty -Name 'Remote' -Value $IsRemote.ToString()
# Transpose the object into PSObject with NoteProperties
$allStatisticTypes = @('ID', 'PIPath', 'Name', 'ProcessID', 'RegisteredAppName', 'RegisteredAppType', 'RegisteredAppID', 'ProtocolVersion', 'PeerAddress', 'PeerPort',
'ConnectionType', 'NetworkType', 'ConnectionStatus', 'ConnectedTime', 'LastCallTime', 'ElapsedTime', 'BytesSent', 'BytesReceived', 'MessageSent',
'MessageReceived', 'ReceiveErrors', 'SendErrors', 'APIConnectionCount', 'SDKConnectionCount', 'ServerID', 'PINetManagerVersion', 'OperatingSystemName',
'OperatingSystemVersion', 'OperatingSystemBuild', 'User', 'OSUser', 'Trust')
foreach ($property in $allStatisticTypes) {
if ($stat.StatisticType -contains $property) {
if ($stat.Item($property).Value.GetType().Name -eq "List``1") {
# If the property is a list, flatten it to a string we can print to file.
$value = ""
$parsingChar = " | "
foreach ($entry in $stat.Item($property).Value)
{ if ("" -ne $entry) { $value += $entry + $parsingChar } }
if ($value.IndexOf($parsingChar) -ne -1)
{ $value = $value.Substring(0, $value.Length - $parsingChar.Length) }
}
else
{ $value = $stat.Item($property).Value }
# Apply timezone offset to ConnectedTime and LastCallTime properties
if ($property -eq 'ConnectedTime' -or $property -eq 'LastCallTime')
{ $value = (Get-Date $value).AddMinutes($offsetMinutes) }
}
else
{ $value = "" }
$transposedStat | Add-Member -MemberType NoteProperty -Name $property -Value $value
}
$transposedStats += $transposedStat
}
}
if ($CheckTransportSecurity)
{ $transposedStats = Test-PISysAudit_SecurePIConnection -PIDataArchiveConnection $PIDataArchiveConnection -PIConnections $transposedStats -DBGLevel $DBGLevel }
return $transposedStats
}
catch {
$msg = "A problem occurred while processing PI Connection Statistics."
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Invoke-PISysAudit_AFDiagCommand {
<#
.SYNOPSIS
(Core functionality) Perform a diagnostic check with the AFDiag.exe command.
.DESCRIPTION
Perform a diagnostic check with the AFDiag.exe command.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Get the AF Server installation path to locate the service executable and afdiag.
$PIHome_AF_path = Get-PISysAudit_RegistryKeyValue "HKLM:\SOFTWARE\PISystem\AF Server" "CurrentInstallationPath" -lc $LocalComputer -rcn $RemoteComputerName -DBGLevel $DBGLevel
# Set the path to reach out the afdiag.exe CLU.
$AFDiagExec = PathConcat -ParentPath $PIHome_AF_path -ChildPath "afdiag.exe"
# Set the path to reach out the AFService executable.
$pathToService = PathConcat -ParentPath $PIHome_AF_path -ChildPath "AFService.exe"
if ($LocalComputer) {
$IsElevated = (Get-Variable "PISysAuditIsElevated" -Scope "Global" -ErrorAction "SilentlyContinue").Value
if (-not($IsElevated)) {
$msg = "Elevation required to run Audit checks using AFDiag. Run PowerShell as Administrator to complete these checks."
Write-PISysAudit_LogMessage $msg "Warning" $fn
return $null
}
# Set the output folder.
$scriptTempFilesPath = (Get-Variable "scriptsPathTemp" -Scope "Global").Value
}
else {
$PIHome_path = Get-PISysAudit_EnvVariable "PIHOME" -lc $false -rcn $RemoteComputerName
# Set the PIPC\dat folder (64 bit).
$scriptTempFilesPath = PathConcat -ParentPath $PIHome_path -ChildPath "dat"
}
# Define the arguments required by the afdiag.exe command
$argListTemplate = "/ExeFile:`"{0}`""
$argList = [string]::Format($ArgListTemplate, $pathToService)
# Set the output for the CLU.
$outputFilePath = PathConcat -ParentPath $scriptTempFilesPath -ChildPath "afdiag_output.txt"
$outputFileContent = ExecuteCommandLineUtility -lc $LocalComputer -rcn $RemoteComputerName -UtilityExec $AFDiagExec `
-ArgList $argList -OutputFilePath $outputFilePath -DBGLevel $DBGLevel
return $outputFileContent
}
catch {
# Return the error message.
$msgTemplate1 = "A problem occurred with afdiag.exe on local computer"
$msgTemplate2 = "A problem occurred with afdiag.exe on {0} computer"
if ($LocalComputer)
{ $msg = $msgTemplate1 }
else
{ $msg = [string]::Format($msgTemplate2, $RemoteComputerName) }
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Invoke-PISysAudit_SPN {
<#
.SYNOPSIS
(Core functionality) Perform an SPN check with the setspn.exe command.
.DESCRIPTION
Perform an SPN check with the setspn.exe command.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("rcn")]
[string]
$RemoteComputerName = "",
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("svcname")]
[string]
$ServiceName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("svctype")]
[string]
$ServiceType,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$AppPool,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$CustomHeader,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Get Domain info.
$MachineDomain = Get-PISysAudit_RegistryKeyValue "HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters" "Domain" -lc $LocalComputer -rcn $RemoteComputerName -dbgl $DBGLevel
# Get Hostname.
$hostname = Get-PISysAudit_RegistryKeyValue "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName" "ComputerName" -lc $LocalComputer -rcn $RemoteComputerName -dbgl $DBGLevel
# Machine is not joined to a Windows Domain.
If (!$MachineDomain) {
$msg = "Machine $hostname is not joined to Windows Domain. SPN checks don't apply."
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
# Build FQDN using hostname and domain strings.
$fqdn = $hostname + "." + $MachineDomain
$hostnameSPN = $($serviceType.ToLower() + "/" + $hostname.ToLower())
$fqdnSPN = $($serviceType.ToLower() + "/" + $fqdn.ToLower())
# SPN check is done for PI Vision using a custom host header.
If ( $ServiceName -eq "pivision_custom" ) {
# Pass the AppPool identity as the service account.
$svcacc = $AppPool
$svcaccParsed = Get-PISysAudit_ParseDomainAndUserFromString -UserString $svcacc -DBGLevel $DBGLevel
<#
Check if the custom header is a Alias (CNAME) or Host (A) entry.
In case of Alias (CNAME), SPNs should exist for both the Alias (CNAME)
and the machine the Alias (CNAME) is pointing to. Overall, there should be 3 SPNs.
With Host (A) alias, the SPN is needed for the alias. We don't want to fail the check
for a missing SPN if they only intend for clients to access by the alias.
#>
$AliasTypeCheck = Get-PISysAudit_ResolveDnsName -LookupName $CustomHeader -Attribute Type -DBGLevel $DBGLevel
If ($AliasTypeCheck -eq 'CNAME') {
$CustomHeaderSPN = $($serviceType.ToLower() + "/" + $CustomHeader.ToLower())
$result = Test-PISysAudit_ServicePrincipalName -HostName $hostname -MachineDomain $MachineDomain `
-SPNShort $hostnameSPN -SPNLong $fqdnSPN `
-SPNAlias $CustomHeaderSPN -SPNAliasType $AliasTypeCheck `
-TargetAccountName $svcaccParsed.UserName -TargetDomain $svcaccParsed.Domain -DBGLevel $DBGLevel
return $result
}
ElseIf ($AliasTypeCheck -eq 'A') {
$CustomHeaderSPN = $($serviceType.ToLower() + "/" + $CustomHeader.ToLower())
$result = Test-PISysAudit_ServicePrincipalName -HostName $hostname -MachineDomain $MachineDomain `
-SPNShort $hostnameSPN -SPNLong $fqdnSPN `
-SPNAlias $CustomHeaderSPN -SPNAliasType $AliasTypeCheck `
-TargetAccountName $svcaccParsed.UserName -TargetDomain $svcaccParsed.Domain -DBGLevel $DBGLevel
return $result
}
Else {
$msg = "Unexpected DNS record type: $AliasTypeCheck"
Write-PISysAudit_LogMessage $msg "Error" $fn
return $null
}
}
# SPN Check is done for PI Vision or other service
Else {
# SPN check is done for PI Vision without custom headers.
If ( $ServiceName -eq "pivision" ) {
# AppPool account is used in the SPN check.
$svcacc = $AppPool
}
# SPN check is not done for PI Vision.
Else {
# Get the Service account
$svcacc = Get-PISysAudit_ServiceProperty -sn $ServiceName -sp LogOnAccount -lc $LocalComputer -rcn $RemoteComputerName -dbgl $DBGLevel
}
$svcaccParsed = Get-PISysAudit_ParseDomainAndUserFromString -UserString $svcacc -DBGLevel $DBGLevel
# Distinguish between Domain/Virtual account and Machine Accounts.
$result = Test-PISysAudit_ServicePrincipalName -HostName $hostname -MachineDomain $MachineDomain `
-SPNShort $hostnameSPN -SPNLong $fqdnSPN `
-TargetAccountName $svcaccParsed.UserName -TargetDomain $svcaccParsed.Domain -DBGLevel $DBGLevel
return $result
}
}
catch {
$msg = "A problem occurred using setspn.exe"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Test-PISysAudit_SecurePIConnection {
<#
.SYNOPSIS
(Core functionality) Check if connections are protected by transport security
.DESCRIPTION
Check if connections are protected by transport security. Adds SecureStatus and
SecureStatusDetail note properties to the connection objects checked
.PARAMETER PIDataArchiveConnection
Pass the PI Data Archive connection object for the connections you want to verify.
.PARAMETER PIConnections
You can use the output of the command Get-PISysAudit_ProcessedPIConnectionStatistics
directly. Otherwise, requires the connecttime, ID and AuthenticationProtocol for each
connection.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("pic")]
[object]
$PIDataArchiveConnection,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("con")]
[Object[]]
$PIConnections,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
$logCutoffExceeded = 0
$timeBuffer = 3 # Second buffer checking connection messages
$wisMessageID = 7082
# Check Message Log Cutoff tuning parameter
$messageLog_DayLimitParameter = Get-PITuningParameter -Connection $PIDataArchiveConnection -Name 'MessageLog_DayLimit'
$Now = Get-Date
if ($null -eq $messageLog_DayLimitParameter.Value)
{ $MessageLog_CutoffDate = $Now.AddDays(-1 * $messageLog_DayLimitParameter.Default) }
else
{ $MessageLog_CutoffDate = $Now.AddDays(-1 * $messageLog_DayLimitParameter.Value) }
Foreach ($PIConnection in $PIConnections) {
$SecureStatus = "Unknown"
$SecureStatusDetail = "Connection not found."
if ($PIConnection.AuthenticationProtocol -eq 'Subsystem') {
$SecureStatus = "Secure"
$SecureStatusDetail = "Subsystem"
}
elseif ($PIConnection.AuthenticationProtocol -ne 'Windows') { # Only Windows Connections can use transport security
$SecureStatus = "Not Secure"
$SecureStatusDetail = "Insecure protocol ({0})" -f $PIConnection.AuthenticationProtocol
}
elseif ($PIConnection.AuthenticationProtocol -eq 'Windows' -and $PIConnection.Remote -eq $true `
-and ($PIConnection.RegisteredAppName -eq 'pibasess' -or $PIConnection.RegisteredAppName -eq 'pilicmgr')) { # Collective communication requires special handling
# PINet version appears of form 'PI X.X.XXX.XXXX'
$PinetVersionTokens = $PIConnection.PINetManagerVersion.Substring(3).Split('.')
$temp = $PinetVersionTokens[0] + $PinetVersionTokens[1] + $PinetVersionTokens[2] + $PinetVersionTokens[3]
$PinetVersion = [Convert]::ToInt64($temp)
if ($PinetVersion -ge 344101256)
{ $SecureStatus = "Secure"; $SecureStatusDetail = "HACertifiedSubsys" }
else
{ $SecureStatus = "Not Secure"; $SecureStatusDetail = "HACertifiedSubsys (pre-2017)" }
}
elseif ($MessageLog_CutoffDate -gt $PIConnection.ConnectedTime) { # Remove connections too old to exist in the logs
$logCutoffExceeded++
$SecureStatus = "Unknown"
$SecureStatusDetail = "Connection before log cutoff date."
}
else { # Verify remaining connections with successful connection message
$connectedTime = $(Get-Date $PIConnection.ConnectedTime)
# Message ID 7082 corresponds to a successful connection with Windows
$connectionMessages = Get-PIMessage -Connection $PIDataArchiveConnection -StartTime $connectedTime.AddSeconds(-1 * $timeBuffer) -EndTime $connectedTime.AddSeconds($timeBuffer) -Id $wisMessageID -Program pinetmgr
foreach ($message in $connectionMessages) {
if ($message.ID -eq $wisMessageID) {
# Extract the connection ID
$targetText = 'ID:'
$startID = $message.Message.IndexOf($targetText)
$endID = $message.Message.IndexOf('. Address:')
if ($startID -eq -1 -or $endID -eq -1) {
$msg = "Unable to parse the connection message: {0}" -f $message.Message
Write-PISysAudit_LogMessage $msg "Warning" $fn
}
else {
$startID += $targetText.Length
[int]$connectionId = $message.Message.Substring($startID, $endID - $startID).Trim()
# Check ID against the set of connections
if ($connectionId -eq $PIConnection.ID) {
# Parse the Method attribute out of the message text
$targetText = '. Method:'
$startMethodPOS = $message.Message.IndexOf($targetText)
if ($startMethodPOS -eq -1) {
$msg = "Unable to parse the Method from connection mesage: {0}" -f $message.Message
Write-PISysAudit_LogMessage $msg "Warning" $fn
}
else {
$startMethod = $startMethodPOS + $targetText.Length
$connectionMethod = $message.Message.Substring($startMethod).Trim()
# Parse the cipher info
$startCipher = $connectionMethod.IndexOf('(')
$endCipher = $connectionMethod.IndexOf(')')
if ($startCipher -eq -1 -or $endCipher -eq -1) {
$msg = "Unable to parse the Cipher from connection mesage: {0}" -f $message.Message
Write-PISysAudit_LogMessage $msg "Warning" $fn
}
else {
$startCipher += 1
$cipherInfo = $connectionMethod.Substring($startCipher, $endCipher - $startCipher)
if ($connectionMethod -match 'HMAC')
{ $SecureStatus = "Secure" }
else
{ $SecureStatus = "Not Secure" }
$SecureStatusDetail = $cipherInfo
}
}
}
}
}
}
}
# Set the Security attributes on the connection
Add-Member -InputObject $PIConnection -MemberType NoteProperty -Name SecureStatus -Value $SecureStatus
Add-Member -InputObject $PIConnection -MemberType NoteProperty -Name SecureStatusDetail -Value $SecureStatusDetail
}
if ($logCutoffExceeded -gt 0) {
$msg = "The message log cutoff date {0} is later than some connect times. {1} connections were be skipped." -f $MessageLog_CutoffDate, $logCutoffExceeded
Write-PISysAudit_LogMessage $msg "Warning" $fn
}
return $PIConnections
}
catch {
$msg = "A problem occurred while verifying transport security on connections: {0}" -f $_.Exception.Message
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Test-PISysAudit_ServicePrincipalName {
<#
.SYNOPSIS
(Core functionality) Check for an SPN
.DESCRIPTION
Check for the existence of an SPN
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("host")]
[string]
$HostName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[string]
$MachineDomain,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("SPNS")]
[string]
$SPNShort,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("SPNL")]
[string]
$SPNLong,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("SPNA")]
[string]
$SPNAlias = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("SPNAT")]
[ValidateSet('CNAME', 'A', 'None')]
[string]
$SPNAliasType = "None",
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("TargetAccountName")]
[string]
$strSPNtargetAccount,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("TargetDomain")]
[string]
$strSPNtargetDomain = ".",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0 )
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Set the list of SPNs to check.
switch ($SPNAliasType) {
'CNAME' { $spnList = @($SPNShort, $SPNLong, $SPNAlias); break }
'A' { $spnList = @($SPNAlias); break }
'None' { $spnList = @($SPNShort, $SPNLong); break }
}
$msg = "Searching for SPNs: " + $($spnList -join ",")
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
# Define user syntax for SPN command
If ($strSPNtargetDomain -eq 'MACHINEACCOUNT') { # Use the hostname when a machine account is identified
$accountNane = $MachineDomain + '\' + $HostName + '$'
}
ElseIf ($strSPNtargetDomain -eq '.') # Local account detected means SPN call will fail
{ return $false }
Else { # Use parsed name
$accountNane = $strSPNtargetDomain + '\' + $strSPNtargetAccount
}
# Run setspn. Redirect stderr to null to prevent errors from bubbling up
$spnCheck = $(setspn -l $accountNane 2>$null)
$msg = "SPN query returned: $spnCheck"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
# Null if something went wrong
if ($null -eq $spnCheck) {
$msg = "setspn failed to retrieve SPNs for $accountNane"
Write-PISysAudit_LogMessage $msg "Error" $fn
return $false
}
# Loop through SPNs, trimming and ensure all lower for comparison
$spnCounter = 0
foreach ($line in $spnCheck) {
if ($line.ToLower().Trim() -in $spnList) {
$spnCounter++
}
}
# Return details to improve messaging in case of failure.
If ($spnCounter -eq $spnList.Count) {
$result = $true
}
Else {
$result = $false
}
return $result
}
catch {
# Return the error message.
$msg = "A problem occurred using setspn.exe"
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $false
}
}
END {}
#***************************
#End of exported function
#***************************
}
function Invoke-PISysAudit_Sqlcmd_ScalarValue {
<#
.SYNOPSIS
(Core functionality) Perform a SQL query against a local/remote computer using the Invoke-Sqlcmd Cmdlet.
.DESCRIPTION
Perform a SQL query against a local/remote computer using the Invoke-Sqlcmd Cmdlet.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Justification="Specifying a filename, not a password.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "PasswordFile", Justification="This variable is a filename.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("rcn")]
[string]
$RemoteComputerName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("q")]
[string]
$Query,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[string]
$ScalarValue,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$InstanceName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[boolean]
$IntegratedSecurity = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("user")]
[string]
$UserName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("pf")]
[string]
$PasswordFile = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Define the requested server name.
$computerName = ResolveComputerName $LocalComputer $RemoteComputerName
# Define the complete SQL Server name (Server + instance name)
$SQLServerName = ReturnSQLServerName $computerName $InstanceName
$msg = "Invoking query: $Query"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
# Integrated Security or SQL Security?
if ($IntegratedSecurity -eq $false) {
if ($PasswordFile -eq "") {
# Read from the global constant bag.
# Read the secure password from the cache
$securePWDFromCache = (Get-Variable "PISysAuditCachedSecurePWD" -Scope "Global" -ErrorAction "SilentlyContinue").Value
if (($null -eq $securePWDFromCache) -or ($securePWDFromCache -eq "")) {
# Return the error message.
$msg = "The password is not stored in cache"
Write-PISysAudit_LogMessage $msg "Error" $fn
return $null
}
else {
# Verbose only if Debug Level is 2+
$msg = "The password stored in cached will be used for SQL connection"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
# The CLU does not understand secure string and needs to get the raw password
# Use the pointer method to reach the value in memory.
$pwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePWDFromCache))
}
}
else {
$pwd = GetPasswordOnDisk $PasswordFile
}
$value = Invoke-Sqlcmd -Query $Query -ServerInstance $SQLServerName -Username $UserName -Password $pwd | Select-Object -ExpandProperty $ScalarValue
}
else {
$value = Invoke-Sqlcmd -Query $Query -ServerInstance $SQLServerName | Select-Object -ExpandProperty $ScalarValue
}
$msg = "Query returned: $value"
Write-PISysAudit_LogMessage $msg "debug" $fn -dbgl $DBGLevel -rdbgl 2
}
catch {
# Return the error message.
$msgTemplate = "A problem occurred during the SQL Query: {0}"
$msg = [string]::Format($msgTemplate, $_.Exception.Message)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
$value = $null
}
return $value
}
END {}
#***************************
#End of exported function
#***************************
}
function Import-PISysAuditComputerParamsFromCsv {
<#
.SYNOPSIS
(Core functionality) Parse CSV file with components to audit.
.DESCRIPTION
Parse a CSV file with computer parameters and put them in the appropriate format
to run an audit. The CSV file must have the following headings: ComputerName,
PISystemComponentType, InstanceName, IntegratedSecurity, SQLServerUserID,
PasswordFile.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("cpf")]
[string]
$ComputerParametersFile
)
BEGIN {}
PROCESS {
$fn = GetFunctionName
$ComputerParamsTable = $null
If (Test-Path -Path $ComputerParametersFile) {
$ComputerParameters = Import-Csv -Path $ComputerParametersFile
}
Else {
$msg = "Computer parameters file not found at '$ComputerParametersFile'."
Write-PISysAudit_LogMessage $msg "Error" $fn -sc $true
return $null
}
if ($null -eq $ComputerParameters) {
$msg = "No computer parameters found in file '$ComputerParametersFile'."
Write-PISysAudit_LogMessage $msg "Error" $fn -sc $true
return $null
}
$requiredHeaders = @("ComputerName", "PISystemComponentType")
$headers = ($ComputerParameters | Get-Member -MemberType NoteProperty).Name
# Compare-Object is case-insensitive and does not require sequential order by default
if ( @(Compare-Object $headers $requiredHeaders -IncludeEqual -ExcludeDifferent).Length -ne 2 ) {
$msg = "Valid header line must be included in top line of parameter file. Columns must include 'ComputerName' and 'PISystemComponentType' at minimum."
Write-PISysAudit_LogMessage $msg "Error" $fn -sc $true
return $null
}
$sqlServerLabels = @('sql', 'sqlserver')
Foreach ($ComputerParameter in $ComputerParameters) {
If ($null -ne $ComputerParameter.PISystemComponentType `
-and $ComputerParameter.PISystemComponentType.ToLower() -in $sqlServerLabels) {
If ($null -ne $ComputerParameter.IntegratedSecurity -and $ComputerParameter.IntegratedSecurity.ToLower() -eq 'false') {
$ComputerParameter.IntegratedSecurity = $false
}
Else {
$ComputerParameter.IntegratedSecurity = $true
}
$ComputerParamsTable = New-PISysAuditComputerParams -ComputerParamsTable $ComputerParamsTable `
-ComputerName $ComputerParameter.ComputerName `
-PISystemComponent $ComputerParameter.PISystemComponentType `
-InstanceName $ComputerParameter.InstanceName `
-IntegratedSecurity $ComputerParameter.IntegratedSecurity `
-SQLServerUserID $ComputerParameter.SQLServerUserID `
-PasswordFile $ComputerParameter.PasswordFile
}
ElseIf ($null -ne ($ComputerParameter | Get-Member -Name Alias)) {
$ComputerParamsTable = New-PISysAuditComputerParams -ComputerParamsTable $ComputerParamsTable `
-ComputerName $ComputerParameter.ComputerName `
-PISystemComponent $ComputerParameter.PISystemComponentType `
-Alias $ComputerParameter.Alias
}
Else {
$ComputerParamsTable = New-PISysAuditComputerParams -ComputerParamsTable $ComputerParamsTable `
-ComputerName $ComputerParameter.ComputerName `
-PISystemComponent $ComputerParameter.PISystemComponentType
}
}
return $ComputerParamsTable
}
END {}
}
function New-PISysAuditObject {
<#
.SYNOPSIS
(Core functionality) Create an audit object and place it inside a hash table object.
.DESCRIPTION
Create an audit object and place it inside a hash table object.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("rcn")]
[string]
$RemoteComputerName,
[parameter(Mandatory = $true, Position = 2, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditHashTable,
[parameter(Mandatory = $true, Position = 3, ParameterSetName = "Default")]
[alias("id")]
[String]
$AuditItemID,
[parameter(Mandatory = $true, Position = 4, ParameterSetName = "Default")]
[alias("ain")]
[String]
$AuditItemName,
[parameter(Mandatory = $true, Position = 5, ParameterSetName = "Default")]
[alias("aiv")]
[object]
$AuditItemValue,
[parameter(Mandatory = $true, Position = 5, ParameterSetName = "Default")]
[alias("aif")]
[String]
$AuditItemFunction,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("msg")]
[String]
$MessageList = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("g1")]
[String]
$Group1 = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("g2")]
[String]
$Group2 = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("g3")]
[String]
$Group3 = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("g4")]
[String]
$Group4 = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("s")]
[ValidateSet("Unknown", "N/A", "Low", "Medium", "High", "Critical")]
[String]
$Severity = "Low")
BEGIN {}
PROCESS {
# Define the server name to use for reporting.
$computerName = ResolveComputerName $LocalComputer $RemoteComputerName
# Create a custom object.
$tempObj = New-Object PSCustomObject
# Create an unique ID with the item ID and computer name.
$myKey = $AuditItemID + "-" + $computerName
# If the validation succeeds, there is no issue; if the validation fails, we can't accurately assess severity.
if ($AuditItemValue) {$Severity = "N/A"}
elseif ($AuditItemValue -eq "N/A") {$Severity = "Unknown"}
switch ($Severity) {
'Critical' { $SeverityLevel = 0; break }
'High' { $SeverityLevel = 1; break }
'Medium' { $SeverityLevel = 2; break }
'Low' { $SeverityLevel = 3; break }
default { $SeverityLevel = 'N/A'; break }
}
# Set the properties.
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "ID" -Value $AuditItemID
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "ServerName" -Value $computerName
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "AuditItemName" -Value $AuditItemName
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "AuditItemValue" -Value $AuditItemValue
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "AuditItemFunction" -Value $AuditItemFunction
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "MessageList" -Value $MessageList
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Group1" -Value $Group1
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Group2" -Value $Group2
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Group3" -Value $Group3
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Group4" -Value $Group4
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Severity" -Value $Severity
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "SeverityLevel" -Value $SeverityLevel
# Add this custom object to the hash table.
$AuditHashTable.Add($myKey, $tempObj)
# Show partial results on screen.
WriteHostPartialResult $tempObj
# return the table
return $AuditHashTable
}
END {}
#***************************
#End of exported function
#***************************
}
function New-PISysAuditError {
<#
.SYNOPSIS
(Core functionality) Create an audit error object and place it inside a hash table object.
.DESCRIPTION
Create an audit error object and place it inside a hash table object.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("lc")]
[boolean]
$LocalComputer,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("rcn")]
[string]
$RemoteComputerName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditHashTable,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("an")]
[String]
$AuditName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("fn")]
[String]
$FunctionName,
[parameter(Mandatory = $true, ParameterSetName = "Default")]
[alias("msg")]
[String]
$MessageList)
BEGIN {}
PROCESS {
# Define the server name to use for reporting.
$computerName = ResolveComputerName $LocalComputer $RemoteComputerName
# Create a custom object.
$tempObj = New-Object PSCustomObject
# Create an unique ID with format "ERROR_<function>-<computerName>
$myKey = "ERROR_" + $FunctionName + "-" + $computerName
# If the validation succeeds, there is no issue; if the validation fails, we can't accurately assess severity.
# Set the properties.
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Severity" -Value "Error"
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "ServerName" -Value $computerName
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "AuditName" -Value $AuditName
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "FunctionName" -Value $FunctionName
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "MessageList" -Value $MessageList
# Add this custom object to the hash table.
$AuditHashTable.Add($myKey, $tempObj)
# return the table
return $AuditHashTable
}
END {}
#***************************
#End of exported function
#***************************
}
function New-PISysAuditComputerParams {
<#
.SYNOPSIS
Generate parameters that define the servers to audit with the New-PISysAuditReport cmdlet.
.DESCRIPTION
Generate parameters that define the servers to audit with the New-PISysAuditReport cmdlet.
The syntax is...
New-PISysAuditComputerParams [[-ComputerParamsTable | -cpt] <hashtable>]
[[-ComputerName | -cn] <string>]
[[-PISystemComponentType | -type] <string>]
[-InstanceName <string>]
[-IntegratedSecurity <boolean>]
[[-SQLServerUserID | -user] <string>]
[[-PasswordFile | -pf] <string>]
[-ShowUI <boolean>]
.INPUTS
.OUTPUTS
<hashtable> containing the PISysAuditComputerParams objects.
.PARAMETER ComputerParamsTable
Parameter table defining which computers/servers
to audit and for which PI System components. If a $null
value is passed or the parameter is skipped, the cmdlet
will assume to audit the local machine.
.PARAMETER ComputerName
Name of the target computer with the PI System component.
.PARAMETER PISystemComponentType
PI System Component to audit. All supported commponents
with their supported aliases are listed below.
Component - Supported Values
PI Data Archive - "PIServer", "PIDataArchive", "PIDA"
PI AF Server - "PIAFServer", "AFServer", "PIAF", "AF"
MS SQL Server - "SQLServer", "SQL", "PICoresightServer"
PI Vision - "PIVision", "PV", "Vision", "PIVisionServer",
"CoresightServer", "PICoresight", "Coresight",
"PICS", "CS","VisionServer"
PI Web API - "PIWebAPIServer", "PIWebAPI", "WebAPI",
"WebAPIServer"
Machine Only - "MachineOnly", "Machine", "ComputerOnly",
"Computer"
.PARAMETER InstanceName
Parameter to specify the instance name of your SQL Server. If a blank string
or "default" or "mssqlserver" is passed, this will refer to the default
instance.
.PARAMETER IntegratedSecurity
Use or not the Windows integrated security. Default is true.
.PARAMETER SQLServerUserID
Specify a SQL user account to use if you are not using the
Windows integrated security.
.PARAMETER PasswordFile
Specifiy a file that will contained a ciphered password obtained with the
New-PISysAudit_PasswordOnDisk cmdlet. If not specify and the -user parameter
is configured, the end-user will be prompted to enter the password once. This
password will be kept securely in memory until the end of the execution.
.PARAMETER ShowUI
Output messages on the command prompt or not.
.PARAMETER Alias
Name other than the machine name used by clients to access the server.
Presently only used by PI Vision checks.
.EXAMPLE
$cpt = New-PISysAuditComputerParams -cpt $cpt -cn "MyPIServer" -type "pi"
The -cpt will use the hashtable of parameters to know how to audit
The -dbgl switch sets the debug level to 2 (full debugging)
.LINK
https://pisquare.osisoft.com
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseSingularNouns", "", Justification="Users are used to this name.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPassWordParams", "", Justification="Specifying a filename, not a password.")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "", Justification="Specifying a filename, not a password.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[AllowNull()]
[alias("cpt")]
[System.Collections.HashTable]
$ComputerParamsTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[AllowEmptyString()]
[alias("cn")]
[string]
$ComputerName,
[parameter(Mandatory = $true, Position = 2, ParameterSetName = "Default")]
[ValidateSet(
"PIServer", "PIDataArchive", "PIDA",
"PIAFServer", "AFServer", "PIAF", "AF",
"SQLServer", "SQL", "PICoresightServer",
"CoresightServer", "PICoresight",
"Coresight", "PICS", "CS", "PIVision",
"PIVisionServer", "Vision", "VisionServer", "PV",
"PIWebAPIServer", "PIWebAPI", "WebAPI", "WebAPIServer",
"MachineOnly", "Machine", "ComputerOnly", "Computer")]
[alias("type")]
[string]
$PISystemComponentType,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[string]
$InstanceName = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[boolean]
$IntegratedSecurity = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("user")]
[string]
$SQLServerUserID = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("pf")]
[string]
$PasswordFile = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("al")]
[string]
$Alias = "",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[boolean]
$ShowUI = $true)
BEGIN {}
PROCESS {
$fn = GetFunctionName
# Initialize objects.
$localComputer = $false
$resolvedComputerName = ""
if ($null -eq $ComputerParamsTable) { $ComputerParamsTable = @{}
}
$skipParam = $false
# ............................................................................................................
# Initialize the module if needed
# ............................................................................................................
Initialize-PISysAudit -ShowUI $ShowUI
# Read from the global constant bag.
$isPISysAuditInitialized = (Get-Variable "PISysAuditInitialized" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# If initialization failed, leave!
if (($null -eq $isPISysAuditInitialized) -or ($isPISysAuditInitialized -eq $false)) {
$msg = "PI System Audit Module initialization failed"
Write-PISysAudit_LogMessage $msg "Error" $fn
return
}
# ............................................................................................................
# Validate if computer name refers to a local or remote entity and perform substitution if required.
# ............................................................................................................
# Obtain the machine name from the environment variable.
$localComputerName = get-content env:computername
# Validate if the server name refers to the local one
if (($ComputerName -eq "") -or ($ComputerName.ToLower() -eq "localhost")) {
$resolvedComputerName = $localComputerName.ToLower()
$localComputer = $true
}
elseif ($localComputerName.ToLower() -eq $ComputerName.ToLower()) {
$resolvedComputerName = $localComputerName.ToLower()
$localComputer = $true
}
else {
$localComputer = $false
$resolvedComputerName = $ComputerName.ToLower()
}
# ............................................................................................................
# Create an object to manipulate that contains the directives on what to audit.
# ............................................................................................................
# Create a custom object (PISysAuditComputerParams).
$tempObj = New-Object PSCustomObject
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "ComputerName" -Value $resolvedComputerName
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "IsLocal" -Value $localComputer
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "AuditRoleType" -Value $null
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "Alias" -Value $null
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "InstanceName" -Value $null
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "IntegratedSecurity" -Value $null
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "SQLServerUserID" -Value $null
Add-Member -InputObject $tempObj -MemberType NoteProperty -Name "PasswordFile" -Value $null
if ($PISystemComponentType.ToLower() -in @("piserver", "pidataarchive", "pida", "dataarchive")) {
$tempObj.AuditRoleType = "PIDataArchive"
}
elseif ($PISystemComponentType.ToLower() -in @("piafserver", "afserver", "piaf", "af")) {
$tempObj.AuditRoleType = "PIAFServer"
}
elseif ($PISystemComponentType.ToLower() -in @("sqlserver", "sql")) {
$tempObj.AuditRoleType = "SQLServer"
$tempObj.InstanceName = $InstanceName
$tempObj.IntegratedSecurity = $IntegratedSecurity
$tempObj.InstanceName = $InstanceName
$tempObj.SQLServerUserID = $SQLServerUserID
$tempObj.PasswordFile = $PasswordFile
# Test if a user name has been passed if Window integrated security is not used
if ($IntegratedSecurity -eq $false) {
if ($SQLServerUserID -eq "") {
$msg = "No user name has been given. This parameter will be skipped"
Write-PISysAudit_LogMessage $msg "Error" $fn -sc $true
$skipParam = $true
}
else {
if ($PasswordFile -eq "") {
# Warning message to the end-user that a password will be asked
# before the first query is executed.
$msg = "You will be prompted for the SQL user account password before the first query!"
Write-PISysAudit_LogMessage $msg "Warning" $fn -sc $true
$skipParam = $false
}
else {
# Read from the global constant bag.
$pwdPath = (Get-Variable "PasswordPath" -Scope "Global").Value
# Set the path.
$pwdFile = PathConcat -ParentPath $pwdPath -ChildPath $PasswordFile
# Test the password file
if ((Test-Path $pwdFile) -eq $false) {
$msg = "The password file specified cannot be found. If you haven't defined one" `
+ " yet, use the New-PISysAudit_PasswordOnDisk cmdlet to create one. This parameter will be skipped"
Write-PISysAudit_LogMessage $msg "Error" $fn -sc $true
$skipParam = $true
}
}
}
}
}
elseif ($PISystemComponentType.ToLower() -in @("picoresightserver", "picoresight", "coresightserver", "coresight", "cs", "pics", "pivision", "visionserver", "vision", "pivisionserver", "pv")) {
$tempObj.AuditRoleType = "PIVisionServer"
$tempObj.Alias = $Alias
}
elseif ($PISystemComponentType.ToLower() -in @("piwebapiserver", "piwebapi", "webapiserver", "webapi")) {
$tempObj.AuditRoleType = "PIWebApiServer"
}
elseif ($PISystemComponentType.ToLower() -in @("machineonly", "machine", "computeronly", "computer")) {
# Don't add another parameter if only Machine checks are required, just use the computer audit parameter.
$tempObj.AuditRoleType = "MachineOnly"
$skipParam = $true
}
# Add hashtable item and computer audit if not already in params table
if (-not $ComputerParamsTable.Contains($resolvedComputerName)) {
# Build object for Computer audit
$computerObj = New-Object PSCustomObject
Add-Member -InputObject $computerObj -MemberType NoteProperty -Name "ComputerName" -Value $resolvedComputerName
Add-Member -InputObject $computerObj -MemberType NoteProperty -Name "IsLocal" -Value $localComputer
Add-Member -InputObject $computerObj -MemberType NoteProperty -Name "AuditRoleType" -Value "Computer"
# Add computer audit as part of an array
$ComputerParamsTable[$resolvedComputerName] = @($computerObj)
}
# Skip the addition of the new parameter or not.
if ($skipParam -eq $false) {
# Check for an existing check of this role on this machine
$existingCheck = $ComputerParamsTable[$resolvedComputerName] | Where-Object AuditRoleType -EQ $tempObj.AuditRoleType
if ($null -eq $existingCheck) {
$ComputerParamsTable[$resolvedComputerName] += $tempObj
}
}
# Return the computer parameters table.
return $ComputerParamsTable
}
END {}
#***************************
#End of exported function
#***************************
}
function Write-PISysAuditReport {
<#
.SYNOPSIS
(Core functionality) Writes a report of all checks performed.
.DESCRIPTION
Writes a concise CSV report of all checks performed and optionally a detailed HTML report.
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditHashTable,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("obf")]
[boolean]
$ObfuscateSensitiveData = $false,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dtl")]
[boolean]
$DetailReport = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
$fn = GetFunctionName
try {
# Get the current timestamp for naming the file uniquely.
$now = Get-Date
$reportTimestamp = $now.ToString("dd-MMM-yyyy HH:mm:ss")
$reportFileTimestamp = $now.ToString("yyyy-MM-dd_HH-mm-ss")
# Get the Scripts path.
$exportPath = (Get-Variable "ExportPath" -Scope "Global").Value
# Create the log file in the same folder as the script.
$fileName = "PISecurityAudit_$reportFileTimestamp.csv"
$fileToExport = PathConcat -ParentPath $exportPath -ChildPath $fileName
# Build a collection for errors
$errs = @()
foreach ($item in $AuditHashTable.GetEnumerator() | Where-Object Name -Like "ERROR*") {
$errs += $item.Value
}
# Build a collection for output.
$results = @()
foreach ($item in $AuditHashTable.GetEnumerator() | Where-Object Name -NotLike "ERROR*") {
# Protect sensitive data if necessary.
if ($ObfuscateSensitiveData) {
# Obfuscate the server name.
$newServerName = NewObfuscateValue $item.Value.ServerName
$item.Value.ServerName = $newServerName
}
# Transform the true/false answer into Pass/Fail one.
if ($item.Value.AuditItemValue -eq $true)
{ $item.Value.AuditItemValue = "Pass" }
elseif ($item.Value.AuditItemValue -eq $false)
{ $item.Value.AuditItemValue = "Fail" }
# Add to collection.
$results += $item.Value
}
# Export to .csv but sort the results table first to have Failed items on the top sorted by Severity
$results = $results | Sort-Object @{Expression = "AuditItemValue"; Descending = $false}, `
@{Expression = "SeverityLevel"; Descending = $false}, `
@{Expression = "ServerName"; Descending = $false}, `
@{Expression = "ID"; Descending = $false}
$results | Export-Csv -Path $fileToExport -Encoding ASCII -NoType
if ($DetailReport) {
$fileName = "PISecurityAudit_DetailReport_$reportFileTimestamp.html"
$fileToExport = PathConcat -ParentPath $exportPath -ChildPath $fileName
# Note about suppressed Check IDs
$suppressedCheckIDs = ""
if ($global:SuppressCheckIDList.Length -ne 0) {
$suppressedCheckIDs = "The following validation checks were explicitly suppressed: "
foreach ($suppressedCheckID in $global:SuppressCheckIDList) {
$suppressedCheckIDs += $suppressedCheckID + "; "
}
$suppressedCheckIDs = $suppressedCheckIDs.Trim('; ')
}
# Construct HTML table for errors
$errorRows = ""
if ($errs) {
foreach ($err in $errs) {
$style = "`"error`""
$errorRow = @"
<tr class=$style>
<td>$($err.Severity)</td>
<td>$($err.ServerName)</td>
<td>$($err.AuditName)</td>
<td>$($err.MessageList)</td>
</tr>
"@
$errorRows += $errorRow
}
$errorTable = @"
<table class="errortable table">
<thead>
<tr>
<th colspan="4">Errors</th>
</tr>
</thead>
<thead>
<tr>
<th>Severity</th>
<th>Server</th>
<th>Audit Name</th>
<th>Message</th>
</tr>
</thead>
$errorRows
</table>
<br/>
"@
}
# Construct HTML table and color code the rows by result and severity.
$tableRows = ""
foreach ($result in $results) {
$highlight = "`"`""
switch ($result.Severity.ToLower()) {
"critical" {$highlight = "`"critical`""; break}
"high" {$highlight = "`"high`""; break}
"medium" {$highlight = "`"medium`""; break}
"low" {$highlight = "`"low`""; break}
}
if ($result.AuditItemValue -eq "N/A") {$highlight = "`"error`""}
$anchorTag = ""
if ($result.AuditItemValue -ieq "fail") {
$anchorTag = @"
<a href="#$($result.ID)">
"@
}
$tableRow = @"
<tr class=$highlight>
<td>$anchorTag$($result.ID)</a></td>
<td>$($result.ServerName)</td>
<td>$($result.AuditItemName)</td>
<td>$($result.AuditItemValue)</td>
<td>$($result.Severity)</td>
<td>$($result.MessageList)</td>
<td>$($result.Group1)</td>
<td>$($result.Group2)</td>
</tr>
"@
$tableRows += $tableRow
}
# Get failed results and construct the recommendation section
$fails = @()
$fails = $results | Where-Object {$_.AuditItemValue -ieq "fail"}
$recommendations = ""
if ($null -ne $fails) {
$recommendations = "<div>
<h2>Recommendations for failed validations:</h2>"
$fails | ForEach-Object {
$AuditFunctionName = $_.AuditItemFunction
$recommendationInfo = Get-Help $AuditFunctionName
if ($PSVersionTable.PSVersion.Major -eq 2) {$recommendationInfoDescription = $recommendationInfo.Description[0].Text}
else {$recommendationInfoDescription = $recommendationInfo.Description.Text}
$recommendations += @"
<b id="$($_.ID)">$($_.ID + " - " + $_.AuditItemName)</b>
<br/>
<p>$recommendationInfoDescription</p>
<br/>
"@
}
$recommendations += "</div>"
}
# HTML report.
$reportHTML = @"
<html>
<head><meta name="viewport" content="width=device-width" />
<style type="text/css">
body {
font-size: 100%;
font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;
}
h2{
font-size: 1.875em;
}
p{
font-size: 0.875em;
}
a{
color: black;
}
.summarytable {
width: 100%;
border-collapse: collapse;
}
.summarytable td, .summarytable th {
border: 1px solid #ddd;
font-size: 0.875em;
}
.summarytable th{
background-color: #f2f2f2;
}
.errortable {
width: 100%;
border-collapse: collapse;
}
.errortable td, .errortable th {
border: 1px solid #ddd;
font-size: 0.875em;
}
.errortable th{
background-color: #f2f2f2;
}
.low{
background-color: #FFF59D;
}
.medium{
background-color: #FFCC80;
}
.high{
background-color: #FFAB91;
}
.critical{
background-color: #F26B41;
}
.error{
color: #FF0000;
}
</style>
</head>
<body>
<div style="padding-bottom:1em">
<h2>AUDIT SUMMARY </h2>
<h4>$reportTimestamp</h4>
<h6>$suppressedCheckIDs</h6>
</div>
$errorTable
<table class="summarytable table">
<thead>
<tr>
<th colspan="8">Audit Results</th>
</tr>
</thead>
<thead>
<tr>
<th>ID</th>
<th>Server</th>
<th>Validation</th>
<th>Result</th>
<th>Severity</th>
<th>Message</th>
<th>Category</th>
<th>Area</th>
</tr>
</thead>
$tableRows
</table>
<br/>
$recommendations
</body>
</html>
"@
# Print report to file.
$reportHTML | Out-File $fileToExport
}
# Return the report name.
return $fileName
}
catch {
# Return the error message.
$msgTemplate = "A problem occurred during generation of the report"
$msg = [string]::Format($msgTemplate, $_.Exception.Message)
Write-PISysAudit_LogMessage $msg "Error" $fn -eo $_
return $null
}
}
END {}
#***************************
#End of exported function
#***************************
}
function New-PISysAuditReport {
<#
.SYNOPSIS
Generate a PI System audit report.
.DESCRIPTION
Generate a PI System audit report. The syntax is...
New-PISysAuditReport [[-ComputerParamsTable | -cpt] <hashtable>]
[[-ObfuscateSensitiveData | -obf] <boolean>]
[-ShowUI <boolean>]
[[-DBGLevel | -dbgl] <int>]
.INPUTS
.OUTPUTS
.PARAMETER ComputerParamsTable
Alias: -cpt
Parameter table defining which computers/servers
to audit and for which PI System components. If a $null
value is passed or the parameter is skipped, the cmdlet
will assume to audit the local machine, unless cpf
specifies a CSV file.
.PARAMETER ComputerParametersFile
Alias: -cpf
CSV file defining which computers/servers to audit and
for which PI System components. Headings must be included
in the CSV file. See "Running a batch of audits" in the
readme.txt in the module folder.
.PARAMETER ObfuscateSensitiveData
Alias: -obf
Obfuscate or not the name of computers/servers
exposed in the audit report.
.PARAMETER ShowUI
Enable or disable message output and progress bar on the command prompt.
.PARAMETER DetailReport
Alias: -dtl
Enable or disable creation of detailed HTML report at end of audit.
.PARAMETER AuditLevel
Alias: -lvl
Choose level of audit to be performed. Higher levels may result
in slow runtimes.
.PARAMETER SuppressCheckID
Alias: -scid
Provide an array of IDs for validation checks to skip. The intention
for this setting is to allow administrators to whitelist specific checks
that are not applicable to their implementation.
.PARAMETER DBGLevel
Alias: -dbgl
DebugLevel: 0 for no verbose, 1 for intermediary message
to help debugging, 2 for full level of details
.EXAMPLE
New-PISysAuditReport -cpt $cpt -obf $false
The -cpt switch will use the hashtable of parameters to know how to audit
The -cpf switch can be used to load parameters from a CSV file
The -obf switch deactivate the obfuscation of the server name.
The -dbgl switch sets the debug level to 2 (full debugging)
.EXAMPLE
New-PISysAuditReport -cpt $cpt -dbgl 2 -lvl Verbose
-- See Example 1 for explanations of switch -cpt
-- The -dbgl switch sets the debug level to 2 (full debugging)
-- The -lvl switch sets the audit level to 'Verbose'
.LINK
https://pisquare.osisoft.com
#>
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("cpt")]
[System.Collections.HashTable]
$ComputerParamsTable = $null,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("cpf")]
[string]
$ComputerParametersFile,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("obf")]
[boolean]
$ObfuscateSensitiveData = $false,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[boolean]
$ShowUI = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dtl")]
[boolean]
$DetailReport = $true,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("lvl")]
[ValidateSet("Basic", "Verbose")]
[string]
$AuditLevel = "Basic",
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("scid")]
[string[]]
$SuppressCheckID = @(),
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
# Get and store the function Name.
$fn = GetFunctionName
# ............................................................................................................
# Initialize the module if needed
# ............................................................................................................
Initialize-PISysAudit -ShowUI $ShowUI -dbgl $DBGLevel
if ($null -eq (Get-Variable "SuppressCheckIDList" -Scope "Global" -ErrorAction "SilentlyContinue").Value) {
New-Variable -Name "SuppressCheckIDList" -Scope "Global" -Visibility "Public" -Value $SuppressCheckID
}
else {
Set-Variable -Name "SuppressCheckIDList" -Scope "Global" -Visibility "Public" -Value $SuppressCheckID
}
# Read from the global constant bag.
$isPISysAuditInitialized = (Get-Variable "PISysAuditInitialized" -Scope "Global" -ErrorAction "SilentlyContinue").Value
# If initialization failed, leave!
if (($null -eq $isPISysAuditInitialized) -or ($isPISysAuditInitialized -eq $false)) {
$msg = "PI System Audit Module initialization failed"
Write-PISysAudit_LogMessage $msg "Error" $fn
return
}
# Initialize some objects.
$ActivityMsg = "Launch analysis on PI System"
$statusMsgCompleted = "Completed"
# Map AuditLevel to the internal AuditLevelInt integer
switch ($AuditLevel) {
"Basic" { $AuditLevelInt = 1 }
"Verbose" { $AuditLevelInt = 8 }
default { $AuditLevelInt = 1 }
}
# ............................................................................................................
# Initialize the table of results
# ............................................................................................................
$auditHashTable = @{}
# ............................................................................................................
# Validate if a ComputerParams table has been passed, if not create one that use localhost as the default
# ............................................................................................................
if ($null -eq $ComputerParamsTable) {
# Initialize.
$ComputerParamsTable = @{}
if ($null -eq $ComputerParametersFile -or $ComputerParametersFile -eq "") {
# This means an audit on the local computer is required only PI Data Archive and PI AF Server are checked by default.
# SQL Server checks ommitted by default as SQL Server will often require an instancename
$ComputerParamsTable = New-PISysAuditComputerParams $ComputerParamsTable "localhost" "PIServer"
$ComputerParamsTable = New-PISysAuditComputerParams $ComputerParamsTable "localhost" "PIAFServer"
}
Else {
$ComputerParamsTable = Import-PISysAuditComputerParamsFromCsv -cpf $ComputerParametersFile
if ($null -eq $ComputerParamsTable) {
# Failed to load params from file
return
}
}
}
# Write the first message in the log file.
$msg = "----- Start the audit -----"
Write-PISysAudit_LogMessage $msg "Info" $fn
# Add 1 line of padding before showing audit failure list
if ($ShowUI)
{ Write-Host "`r`n" }
# Write headers for issues that are found
$msg = "{0,-9} {1,-8} {2,-20} {3,40}"
Write-Host ($msg -f 'Severity', 'ID', 'Server', 'Audit Item Name')
Write-Host ('-' * 80)
# ............................................................................................................
# Get total count of audit role checks to be performed, prep messages for progress bar
# ............................................................................................................
$totalCheckCount = 0
foreach ($cpt in $ComputerParamsTable.GetEnumerator()) {
$totalCheckCount += $cpt.Value.Count
}
$currCheck = 1
$ActivityMsg = "Performing $AuditLevel PI System Security Audit"
$statusMsgTemplate = "Checking Role {0}/{1}..."
$statusMsgCompleted = "Completed"
# ....................................................................................
# For each computer, perform checks for all roles
# ....................................................................................
foreach ($item in $ComputerParamsTable.GetEnumerator()) {
# Run no checks if WSMan is not available
$wsManValidated = ValidateWSMan -cp $item -at $auditHashTable -dbgl $DBGLevel
# If WSman fails we can check if IsLocal is set properly.
# This check is too expensive to check frivolously, so we only check on failure.
if (-not($wsManValidated)) {
$computerRole = $item.Value[0]
$resolvedName = Get-PISysAudit_ResolveDnsName -LookupName $computerRole.ComputerName -Attribute HostName -DBGLevel $DBGLevel
$localComputerName = Get-Content Env:\COMPUTERNAME
if ($resolvedName.ToLower() -eq $localComputerName.ToLower()) {
foreach ($role in $item.Value)
{ $role.IsLocal = $true }
$wsManValidated = $true
$msg = "The server: {0} does not need WinRM communication because it will use a local connection (alias used)" -f $role.ComputerName
Write-PISysAudit_LogMessage $msg "Debug" $fn -dbgl $DBGLevel -rdbgl 1
}
else {
$msg = "Unable to connect to server: " + $computerRole.ComputerName + ". Please try running the audit scripts locally on the target machine. "
$msg += "This issue usually occurs if PSRemoting is disabled, or authentication failed during the PSRemoting connection attempt. "
$msg += "For more information see 'Running the scripts remotely' in the wiki (https://github.com/osisoft/PI-Security-Audit-Tools/wiki/Running-the-scripts-remotely)"
Write-PISysAudit_LogMessage $msg "Error" $fn
New-PISysAuditError -lc $computerRole.IsLocal -rcn $computerRole.ComputerName `
-at $auditHashTable -an 'Computer' -fn $fn -msg $msg
}
}
if ($wsManValidated) {
foreach ($role in $item.Value) {
# Write status to progress bar
$statusMsg = [string]::Format($statusMsgTemplate, $currCheck, $totalCheckCount)
$pctComplete = ($currCheck - 1) / $totalCheckCount * 100
Write-Progress -Activity $ActivityMsg -Status $statusMsg -Id 1 -PercentComplete $pctComplete
# Proceed based on component type.
if ($role.AuditRoleType -eq "Computer")
{ StartComputerAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel }
elseif ($role.AuditRoleType -eq "PIDataArchive")
{ StartPIDataArchiveAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel }
elseif ($role.AuditRoleType -eq "PIAFServer")
{ StartPIAFServerAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel }
elseif ($role.AuditRoleType -eq "SQLServer")
{ StartSQLServerAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel }
elseif ($role.AuditRoleType -eq "PIVisionServer") {
StartPIVisionServerAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel
# Call PI Web API implicitly for PI Vision audit.
StartPIWebApiServerAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel
}
elseif ($role.AuditRoleType -eq "PIWebApiServer" -and !('PIVisionServer' -in $item.Value.AuditRoleType)) {
# Skip the explicit call to PI Web API audit if this machine includes a PI Vision role.
StartPIWebApiServerAudit $auditHashTable $role -lvl $AuditLevelInt -dbgl $DBGLevel
}
$currCheck++
}
}
else {
# Skip progress bar ahead for these ckecks since WSman failed
$currCheck += $item.Value.Count
}
}
Write-Progress -Activity $ActivityMsg -Status $statusMsgCompleted -Id 1 -PercentComplete 100
Write-Progress -Activity $ActivityMsg -Status $statusMsgCompleted -Id 1 -Completed
# Pad console ouput with one line
Write-Host "`r`n"
# ....................................................................................
# Show results.
# ....................................................................................
$ActivityMsg = "Generate report"
if ($ShowUI) { Write-Progress -activity $ActivityMsg -Status "in progress..." -Id 1 }
$reportName = Write-PISysAuditReport $auditHashTable -obf $ObfuscateSensitiveData -dtl $DetailReport -dbgl $DBGLevel
if ($ShowUI) {
Write-Progress -activity $ActivityMsg -Status $statusMsgCompleted -Id 1 -PercentComplete 100
Write-Progress -activity $ActivityMsg -Status $statusMsgCompleted -Id 1 -Completed
}
# ............................................................................................................
# Display that the analysis is completed and where the report can be found.
# ............................................................................................................
# Read from the global constant bag.
$exportPath = (Get-Variable "ExportPath" -Scope "Global" -ErrorAction "SilentlyContinue").Value
$msg = "Report file: $reportName"
Write-PISysAudit_LogMessage $msg "Info" $fn -sc $true
$msg = "Report location: $exportPath"
Write-PISysAudit_LogMessage $msg "Info" $fn -sc $true
$msg = "----- Audit Completed -----"
Write-PISysAudit_LogMessage $msg "Info" $fn
$InstallationType = Get-ItemProperty -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion" -Name "InstallationType" | Select-Object -ExpandProperty "InstallationType" | Out-String
if ($ExecutionContext.SessionState.LanguageMode -ne 'ConstrainedLanguage' -and $InstallationType -ne 'Server Core') {
$title = "PI Security Audit Report"
$message = "Would you like to view the PI Security Audit Report now?"
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Open the report in your default browser."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "View the report later."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
if ($result -eq 0)
{ Start-Process -FilePath $(PathConcat $exportPath -ChildPath $reportName) }
}
}
END {}
#***************************
#End of exported function
#***************************
}
# ........................................................................
# Add your core function by replacing the Verb-PISysAudit_TemplateCore one.
# Implement the functionality you want. Don't forget to modify the parameters
# if necessary.
# ........................................................................
function Verb-PISysAudit_TemplateCore {
<#
.SYNOPSIS
Add a synopsis.
.DESCRIPTION
Add a description.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "", Justification="Template function; implementer expected to rename.")]
[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $false)]
param(
[parameter(Mandatory = $true, Position = 0, ParameterSetName = "Default")]
[alias("at")]
[System.Collections.HashTable]
$AuditTable,
[parameter(Mandatory = $true, Position = 1, ParameterSetName = "Default")]
[alias("cp")]
$ComputerParams,
[parameter(Mandatory = $false, ParameterSetName = "Default")]
[alias("dbgl")]
[int]
$DBGLevel = 0)
BEGIN {}
PROCESS {
# ........................................................................
# Add your code here...
# ........................................................................
}
END {}
#***************************
#End of exported function
#***************************
}
# ........................................................................
# Create an alias on the cmdlet
# ........................................................................
# <Do not remove>
Set-Alias piaudit New-PISysAuditReport
Set-Alias piauditparams New-PISysAuditComputerParams
Set-Alias pisysauditparams New-PISysAuditComputerParams
Set-Alias pwdondisk New-PISysAudit_PasswordOnDisk
# </Do not remove>
# ........................................................................
# Export Module Member
# ........................................................................
# <Do not remove>
Export-ModuleMember NewAuditFunction
Export-ModuleMember PathConcat
Export-ModuleMember SafeReplace
Export-ModuleMember Initialize-PISysAudit
Export-ModuleMember Get-PISysAudit_EnvVariable
Export-ModuleMember Get-PISysAudit_RegistryKeyValue
Export-ModuleMember Get-PISysAudit_TestRegistryKey
Export-ModuleMember Get-PISysAudit_ParseDomainAndUserFromString
Export-ModuleMember Get-PISysAudit_ServiceProperty
Export-ModuleMember Get-PISysAudit_CertificateProperty
Export-ModuleMember Get-PISysAudit_BoundCertificate
Export-ModuleMember Get-PISysAudit_ResolveDnsName
Export-ModuleMember Get-PISysAudit_ServicePrivilege
Export-ModuleMember Get-PISysAudit_InstalledComponent
Export-ModuleMember Get-PISysAudit_InstalledKB
Export-ModuleMember Get-PISysAudit_InstalledWin32Feature
Export-ModuleMember Get-PISysAudit_FirewallState
Export-ModuleMember Get-PISysAudit_AppLockerState
Export-ModuleMember Get-PISysAudit_KnownServers
Export-ModuleMember Get-PISysAudit_ProcessedPIConnectionStatistics
Export-ModuleMember Test-PISysAudit_SecurePIConnection
Export-ModuleMember Test-PISysAudit_ServicePrincipalName
Export-ModuleMember Test-PISysAudit_PrincipalOrGroupType
Export-ModuleMember Invoke-PISysAudit_AFDiagCommand
Export-ModuleMember Invoke-PISysAudit_Sqlcmd_ScalarValue
Export-ModuleMember Invoke-PISysAudit_SPN
Export-ModuleMember New-PISysAuditObject
Export-ModuleMember New-PISysAuditError
Export-ModuleMember New-PISysAudit_PasswordOnDisk
Export-ModuleMember New-PISysAuditComputerParams
Export-ModuleMember New-PISysAuditReport
Export-ModuleMember Write-PISysAuditReport
Export-ModuleMember Write-PISysAudit_LogMessage
Export-ModuleMember -Alias piauditparams
Export-ModuleMember -Alias pisysauditparams
Export-ModuleMember -Alias piaudit
Export-ModuleMember -Alias pwdondisk
Export-ModuleMember Test-AFServerConnectionAvailable
Export-ModuleMember Test-PowerShellToolsForPISystemAvailable
Export-ModuleMember Test-WebAdministrationModuleAvailable
# </Do not remove>
# ........................................................................
# Add your new Export-ModuleMember instruction after this section.
# Replace the Verb-PISysAudit_TemplateCore with the name of your
# function.
# ........................................................................
# Export-ModuleMember Verb-PISysAudit_TemplateCore
| hpaul-osi/PI-Security-Audit-Tools | PISecurityAudit/Scripts/PISYSAUDIT/PISYSAUDITCORE.psm1 | PowerShell | apache-2.0 | 204,541 |
#
# Module manifest for module 'Azure'
#
# Generated by: Microsoft Corporation
#
# Generated on: 5/23/2012
#
@{
# Version number of this module.
ModuleVersion = '0.9.9'
# ID used to uniquely identify this module
GUID = 'D48CF693-4125-4D2D-8790-1514F44CE325'
# 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 - Service Management'
# 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 the .NET Framework required by this module
DotNetFrameworkVersion = '4.0'
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion='4.0'
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'None'
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = @(
'.\Services\Microsoft.WindowsAzure.Commands.Websites.Types.ps1xml',
'.\Sql\Microsoft.WindowsAzure.Commands.SqlDatabase.Types.ps1xml',
'.\Azure.Storage\Microsoft.WindowsAzure.Commands.Storage.Types.ps1xml',
'.\StorSimple\Microsoft.WindowsAzure.Commands.StorSimple.Types.ps1xml'
)
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @(
'.\Services\Microsoft.WindowsAzure.Commands.Websites.format.ps1xml',
'.\Services\Microsoft.WindowsAzure.Commands.CloudService.format.ps1xml',
'.\Services\Microsoft.WindowsAzure.Commands.ServiceBus.format.ps1xml',
'.\Azure.Storage\Microsoft.WindowsAzure.Commands.Storage.format.ps1xml',
'.\Services\Microsoft.WindowsAzure.Commands.Store.format.ps1xml',
'.\Services\Microsoft.WindowsAzure.Commands.Scheduler.format.ps1xml',
'.\Compute\Microsoft.WindowsAzure.Commands.ServiceManagement.format.ps1xml',
'.\Services\Microsoft.WindowsAzure.Commands.Profile.format.ps1xml',
'.\Networking\Microsoft.WindowsAzure.Commands.ServiceManagement.Network.format.ps1xml',
'.\StorSimple\Microsoft.WindowsAzure.Commands.StorSimple.format.ps1xml'
)
# Modules to import as nested modules of the module specified in ModuleToProcess
NestedModules = '.\Services\Microsoft.WindowsAzure.Commands.dll',
'.\Automation\Microsoft.Azure.Commands.Automation.dll',
'.\TrafficManager\Microsoft.WindowsAzure.Commands.TrafficManager.dll',
'.\Services\Microsoft.WindowsAzure.Commands.Profile.dll',
'.\Compute\Microsoft.WindowsAzure.Commands.ServiceManagement.dll',
'.\Sql\Microsoft.WindowsAzure.Commands.SqlDatabase.dll',
'.\Azure.Storage\Microsoft.WindowsAzure.Commands.Storage.dll',
'.\ManagedCache\Microsoft.Azure.Commands.ManagedCache.dll',
'.\HDInsight\Microsoft.WindowsAzure.Commands.HDInsight.dll',
'.\Networking\Microsoft.WindowsAzure.Commands.ServiceManagement.Network.dll',
'.\StorSimple\Microsoft.WindowsAzure.Commands.StorSimple.dll',
'.\RemoteApp\Microsoft.WindowsAzure.Commands.RemoteApp.dll',
'.\RecoveryServices\Microsoft.Azure.Commands.RecoveryServices.dll'
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = @(
'Add-WAPackEnvironment',
'Disable-WAPackWebsiteApplicationDiagnostic'
'Enable-WAPackWebsiteApplicationDiagnositc'
'Get-WAPackEnvironment',
'Get-WAPackPublishSettingsFile',
'Get-WAPackSBLocation',
'Get-WAPackSBNamespace',
'Get-WAPackSubscription',
'Get-WAPackWebsite',
'Get-WAPackWebsiteDeployment',
'Get-WAPackWebsiteLocation',
'Get-WAPackWebsiteLog',
'Import-WAPackPublishSettingsFile',
'New-WAPackSBNamespace',
'New-WAPackWebsite',
'Remove-WAPackEnvironment',
'Remove-WAPackSBNamespace',
'Remove-WAPackSubscription',
'Remove-WAPackWebsite',
'Restart-WAPackWebsite',
'Restore-WAPackWebsiteDeployment',
'Save-WAPackWebsiteLog',
'Select-WAPackSubscription',
'Set-WAPackEnvironment',
'Set-WAPackSubscription',
'Set-WAPackWebsite',
'Show-WAPackPortal',
'Show-WAPackWebsite',
'Start-WAPackWebsite',
'Stop-WAPackWebsite',
'Test-WAPackName',
'Add-AzureHDInsightConfigValues',
'Add-AzureHDInsightMetastore',
'Add-AzureHDInsightStorage',
'Get-AzureHDInsightCluster',
'Get-AzureHDInsightJob',
'Get-AzureHDInsightJobOutput',
'Get-AzureHDInsightProperties',
'Invoke-Hive',
'New-AzureHDInsightCluster',
'New-AzureHDInsightClusterConfig',
'New-AzureHDInsightHiveJobDefinition',
'New-AzureHDInsightMapReduceJobDefinition',
'New-AzureHDInsightPigJobDefinition',
'New-AzureHDInsightSqoopJobDefinition',
'New-AzureHDInsightStreamingMapReduceJobDefinition',
'Remove-AzureHDInsightCluster',
'Revoke-AzureHDInsightHttpServicesAccess',
'Set-AzureHDInsightDefaultStorage',
'Start-AzureHDInsightJob',
'Stop-AzureHDInsightJob',
'Use-AzureHDInsightCluster',
'Wait-AzureHDInsightJob',
'Get-AzureStorageContainerAcl',
'Start-CopyAzureStorageBlob',
'Stop-CopyAzureStorageBlob',
'Get-SSAccessControlRecord',
'Get-SSDevice',
'Get-SSDeviceBackup',
'Get-SSDeviceBackupPolicy',
'Get-SSDeviceConnectedInitiator',
'Get-SSDeviceVolume',
'Get-SSDeviceVolumeContainer',
'Get-SSFailoverVolumeContainers',
'Get-SSJob',
'Get-SSResource',
'Get-SSResourceContext',
'Get-SSStorageAccountCredential',
'Get-SSTask',
'New-SSAccessControlRecord',
'New-SSDeviceBackupPolicy',
'New-SSDeviceBackupScheduleAddConfig',
'New-SSDeviceBackupScheduleUpdateConfig',
'New-SSDeviceVolume',
'New-SSDeviceVolumeContainer',
'New-SSInlineStorageAccountCredential',
'New-SSNetworkConfig',
'New-SSStorageAccountCredential',
'New-SSVirtualDevice',
'Remove-SSAccessControlRecord',
'Remove-SSDeviceBackup',
'Remove-SSDeviceBackupPolicy',
'Remove-SSDeviceVolume',
'Remove-SSDeviceVolumeContainer',
'Remove-SSStorageAccountCredential',
'Select-SSResource',
'Set-SSAccessControlRecord',
'Set-SSDevice',
'Set-SSDeviceBackupPolicy',
'Set-SSDeviceVolume',
'Set-SSStorageAccountCredential',
'Set-SSVirtualDevice',
'Start-SSBackupCloneJob',
'Start-SSDeviceBackupJob',
'Start-SSDeviceBackupRestoreJob',
'Start-SSDeviceFailoverJob',
'Stop-SSJob',
'Confirm-SSLegacyVolumeContainerStatus',
'Get-SSLegacyVolumeContainerConfirmStatus',
'Get-SSLegacyVolumeContainerMigrationPlan',
'Get-SSLegacyVolumeContainerStatus',
'Import-SSLegacyApplianceConfig',
'Import-SSLegacyVolumeContainer',
'Start-SSLegacyVolumeContainerMigrationPlan'
)
# 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 ModuleToProcess
PrivateData = ''
}
| mayurid/azure-powershell | src/ServiceManagement/Services/Commands.Utilities/Azure.psd1 | PowerShell | apache-2.0 | 7,378 |
function Add-VSLakeFormationPermissionsDataLakePrincipal {
<#
.SYNOPSIS
Adds an AWS::LakeFormation::Permissions.DataLakePrincipal resource property to the template. The AWS Lake Formation principal.
.DESCRIPTION
Adds an AWS::LakeFormation::Permissions.DataLakePrincipal resource property to the template.
The AWS Lake Formation principal.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lakeformation-permissions-datalakeprincipal.html
.PARAMETER DataLakePrincipalIdentifier
An identifier for the AWS Lake Formation principal.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lakeformation-permissions-datalakeprincipal.html#cfn-lakeformation-permissions-datalakeprincipal-datalakeprincipalidentifier
PrimitiveType: String
UpdateType: Mutable
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.LakeFormation.Permissions.DataLakePrincipal')]
[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 ", ")."))
}
})]
$DataLakePrincipalIdentifier
)
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.LakeFormation.Permissions.DataLakePrincipal'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSLakeFormationPermissionsDataLakePrincipal.ps1 | PowerShell | apache-2.0 | 2,526 |
function New-VSNetworkManagerGlobalNetwork {
<#
.SYNOPSIS
Adds an AWS::NetworkManager::GlobalNetwork resource to the template. Creates a new, empty global network.
.DESCRIPTION
Adds an AWS::NetworkManager::GlobalNetwork resource to the template. Creates a new, empty global network.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-globalnetwork.html
.PARAMETER LogicalId
The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template. Use the logical name to reference the resource in other parts of the template. For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance.
.PARAMETER Description
A description of the global network.
Length Constraints: Maximum length of 256 characters.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-globalnetwork.html#cfn-networkmanager-globalnetwork-description
UpdateType: Mutable
PrimitiveType: String
.PARAMETER Tags
The tags for the global network.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-globalnetwork.html#cfn-networkmanager-globalnetwork-tags
UpdateType: Mutable
Type: List
ItemType: Tag
.PARAMETER DeletionPolicy
With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted. You specify a DeletionPolicy attribute for each resource that you want to control. If a resource has no DeletionPolicy attribute, AWS CloudFormation deletes the resource by default.
To keep a resource when its stack is deleted, specify Retain for that resource. You can use retain for any resource. For example, you can retain a nested stack, S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks.
You must use one of the following options: "Delete","Retain","Snapshot"
.PARAMETER UpdateReplacePolicy
Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation.
When you initiate a stack update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template and parameters. If you update a resource property that requires that the resource be replaced, AWS CloudFormation recreates the resource during the update. Recreating the resource generates a new physical ID. AWS CloudFormation creates the replacement resource first, and then changes references from other dependent resources to point to the replacement resource. By default, AWS CloudFormation then deletes the old resource. Using the UpdateReplacePolicy, you can specify that AWS CloudFormation retain or (in some cases) create a snapshot of the old resource.
For resources that support snapshots, such as AWS::EC2::Volume, specify Snapshot to have AWS CloudFormation create a snapshot before deleting the old resource instance.
You can apply the UpdateReplacePolicy attribute to any resource. UpdateReplacePolicy is only executed if you update a resource property whose update behavior is specified as Replacement, thereby causing AWS CloudFormation to replace the old resource with a new one with a new physical ID. For example, if you update the Engine property of an AWS::RDS::DBInstance resource type, AWS CloudFormation creates a new resource and replaces the current DB instance resource with the new one. The UpdateReplacePolicy attribute would then dictate whether AWS CloudFormation deleted, retained, or created a snapshot of the old DB instance. The update behavior for each property of a resource is specified in the reference topic for that resource in the AWS Resource and Property Types Reference. For more information on resource update behavior, see Update Behaviors of Stack Resources.
The UpdateReplacePolicy attribute applies to stack updates you perform directly, as well as stack updates performed using change sets.
Note
Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources. Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots. UpdateReplacePolicy retains the old physical resource or snapshot, but removes it from AWS CloudFormation's scope.
UpdateReplacePolicy differs from the DeletionPolicy attribute in that it only applies to resources replaced during stack updates. Use DeletionPolicy for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update.
You must use one of the following options: "Delete","Retain","Snapshot"
.PARAMETER DependsOn
With the DependsOn attribute you can specify that the creation of a specific resource follows another. When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute.
This parameter takes a string or list of strings representing Logical IDs of resources that must be created prior to this resource being created.
.PARAMETER Metadata
The Metadata attribute enables you to associate structured data with a resource. By adding a Metadata attribute to a resource, you can add data in JSON or YAML to the resource declaration. In addition, you can use intrinsic functions (such as GetAtt and Ref), parameters, and pseudo parameters within the Metadata attribute to add those interpreted values.
You must use a PSCustomObject containing key/value pairs here. This will be returned when describing the resource using AWS CLI.
.PARAMETER UpdatePolicy
Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource. AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group.
You must use the "Add-UpdatePolicy" function here.
.PARAMETER Condition
Logical ID of the condition that this resource needs to be true in order for this resource to be provisioned.
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.NetworkManager.GlobalNetwork')]
[cmdletbinding()]
Param
(
[parameter(Mandatory = $true,Position = 0)]
[ValidateScript( {
if ($_ -match "^[a-zA-Z0-9]*$") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String 'The LogicalID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.'))
}
})]
[System.String]
$LogicalId,
[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 ", ")."))
}
})]
$Description,
[VaporShell.Core.TransformTag()]
[parameter(Mandatory = $false)]
$Tags,
[ValidateSet("Delete","Retain","Snapshot")]
[System.String]
$DeletionPolicy,
[ValidateSet("Delete","Retain","Snapshot")]
[System.String]
$UpdateReplacePolicy,
[parameter(Mandatory = $false)]
[System.String[]]
$DependsOn,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Management.Automation.PSCustomObject"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "The UpdatePolicy parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$Metadata,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "Vaporshell.Resource.UpdatePolicy"
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 ", ")."))
}
})]
$UpdatePolicy,
[parameter(Mandatory = $false)]
$Condition
)
Begin {
$ResourceParams = @{
LogicalId = $LogicalId
Type = "AWS::NetworkManager::GlobalNetwork"
}
$commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
}
Process {
foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
switch ($key) {
LogicalId {}
DeletionPolicy {
$ResourceParams.Add("DeletionPolicy",$DeletionPolicy)
}
UpdateReplacePolicy {
$ResourceParams.Add("UpdateReplacePolicy",$UpdateReplacePolicy)
}
DependsOn {
$ResourceParams.Add("DependsOn",$DependsOn)
}
Metadata {
$ResourceParams.Add("Metadata",$Metadata)
}
UpdatePolicy {
$ResourceParams.Add("UpdatePolicy",$UpdatePolicy)
}
Condition {
$ResourceParams.Add("Condition",$Condition)
}
Tags {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name Tags -Value @($Tags)
}
Default {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters[$key]
}
}
}
}
End {
$obj = New-VaporResource @ResourceParams
$obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.NetworkManager.GlobalNetwork'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Types/New-VSNetworkManagerGlobalNetwork.ps1 | PowerShell | apache-2.0 | 11,719 |
#requires -Version 3.0
#region Info
<#
Support: https://github.com/jhochwald/NETX/issues
#>
#endregion Info
#region License
<#
Copyright (c) 2016, Quality Software Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
By using the Software, you agree to the License, Terms and Conditions above!
#>
<#
This is a third-party Software!
The developer of this Software is NOT sponsored by or affiliated with
Microsoft Corp (MSFT) or any of its subsidiaries in any way
The Software is not supported by Microsoft Corp (MSFT)!
More about Quality Software Ltd. http://www.q-soft.co.uk
#>
#endregion License
function Global:Initialize-ModuleUpdate {
<#
.SYNOPSIS
Refresh the PowerShell Module Information
.DESCRIPTION
Refresh the PowerShell Module Information
Wrapper for the following command: Get-Module -ListAvailable -Refresh
.PARAMETER Verbosity
Verbose output, default is not
.EXAMPLE
PS C:\> Initialize-ModuleUpdate -Verbose
Description
-----------
Refresh the PowerShell Module Information
.EXAMPLE
PS C:\> Initialize-ModuleUpdate -Verbose
Description
-----------
Refresh the PowerShell Module Information
.NOTES
PowerShell will auto-load modules. However, with some modules, this
technique may fail.
Their cmdlets will still only be available after you manually import
the module using Import-Module.
The reason most likely is the way these modules were built.
PowerShell has no way of detecting which cmdlets are exported by
these modules.
#>
param
(
[Parameter(Position = 0)]
[switch]$Verbosity
)
BEGIN {
Write-Output -InputObject 'Update...'
}
PROCESS {
if ($Verbosity) {
Get-Module -ListAvailable -Refresh
} else {
(Get-Module -ListAvailable -Refresh) > $null 2>&1 3>&1
}
}
}
# SIG # Begin signature block
# MIIfOgYJKoZIhvcNAQcCoIIfKzCCHycCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUXidlqGdI8yRMG113RHWPFEZe
# 6v6gghnLMIIEFDCCAvygAwIBAgILBAAAAAABL07hUtcwDQYJKoZIhvcNAQEFBQAw
# VzELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNV
# BAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0
# MTMxMDAwMDBaFw0yODAxMjgxMjAwMDBaMFIxCzAJBgNVBAYTAkJFMRkwFwYDVQQK
# ExBHbG9iYWxTaWduIG52LXNhMSgwJgYDVQQDEx9HbG9iYWxTaWduIFRpbWVzdGFt
# cGluZyBDQSAtIEcyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlO9l
# +LVXn6BTDTQG6wkft0cYasvwW+T/J6U00feJGr+esc0SQW5m1IGghYtkWkYvmaCN
# d7HivFzdItdqZ9C76Mp03otPDbBS5ZBb60cO8eefnAuQZT4XljBFcm05o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9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE2MTAxMjEzMTM0MVowIwYJKoZIhvcN
# AQkEMRYEFLV4NiJTYbmQlaxduH+kz/8ACSCkMIGdBgsqhkiG9w0BCRACDDGBjTCB
# ijCBhzCBhAQUY7gvq2H1g5CWlQULACScUCkz7HkwbDBWpFQwUjELMAkGA1UEBhMC
# QkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExKDAmBgNVBAMTH0dsb2JhbFNp
# Z24gVGltZXN0YW1waW5nIENBIC0gRzICEhEh1pmnZJc+8fhCfukZzFNBFDANBgkq
# hkiG9w0BAQEFAASCAQCU4U/7PgaSdBeqHGi28X7m7y4aM6yjbBgQsktogaIgnfBs
# p07K352J+3r1fD3ioM3Ait41bcFvcVrc31ztbA7jBYBVm7KBbosKXw05yftIUAFX
# mK/TjVu68TswhRIkgw1aH49ltFJzKzV0i8PuwPh4RYcCH4jwprp5Q2KYMViy05xG
# S5QdpzEhOF0kI9GtWV4yfWFjpgUuVDSQXtpawJ6glcM9hOEhTub5MlftGTMHCjkF
# xoGLSfT4qmE4LphigFbILXoEyStgMLeo0QfyIrS1wRTw7YM2qGbt8l5dfDqBEOnS
# fj/Gkje4hwD+YD3p0ZscL8SF75YXwaqLgLbv+CtD
# SIG # End signature block
| jhochwald/NETX | Profile/functions/Initialize-ModuleUpdate.ps1 | PowerShell | bsd-3-clause | 14,491 |
# Returns Branch Cache Client Status details BranchCacheServiceStartType
# Example - Manual, Automatic
# Get-BCStatus | Select-Object -ExpandProperty BranchCacheServiceStartType
# Return Type: String
# Execution Context: System
$branchcache = Get-BCStatus
write-output $branchcache.BranchCacheServiceStartType
| vmwaresamples/AirWatch-samples | Windows-Samples/Sensors/bc_status_branchcacheservicestarttype.ps1 | PowerShell | bsd-3-clause | 315 |
if ($deployHelpLoaded -eq $null)
{
$DeployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)
. $DeployToolsDir\deployHelp.ps1
}
if ($compressionHelperLoaded -eq $null)
{
. $DeployToolsDir\compressionHelper.ps1
}
Write-Host "Ensconce - WebHelper Loading"
Function UploadFileAndGetStringResponse([string]$url, [string]$file)
{
Write-Host "Uploading file '$file' to $url"
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$responseBytes = $webClient.UploadFile($url, $file)
$response = [System.Text.Encoding]::ASCII.GetString($responseBytes)
Write-Host "Response: $response"
$response
}
Function UploadFolderAsZipAndGetStringResponse([string]$url, [string]$sourcePath)
{
$basePath = Get-Location
$file = "$basePath\Temp.zip"
CreateZip $sourcePath $file
UploadFileAndGetStringResponse $url $file
}
Function UploadValuesAndGetStringResponse([string]$url, [System.Collections.Specialized.NameValueCollection]$values)
{
Write-Host "Uploading values to $url"
Write-Host "Values:"
foreach ($key in $values) {
$value = $values[$key]
Write-Host "$key : $value"
}
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$responseBytes = $webClient.UploadValues($url, $values)
$response = [System.Text.Encoding]::ASCII.GetString($responseBytes)
Write-Host "Response: $response"
$response
}
Function DownloadFile([string]$url, [string]$destinationPath)
{
Write-Host "Downloading $url to $destinationPath"
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$webClient.DownloadFile($url, $destinationPath)
}
Function DownloadString([string]$url)
{
Write-Host "Downloading $url"
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
$response = $webClient.DownloadString($url)
Write-Host "Response: $response"
$response
}
Function DownloadStringUntilOK([string]$url, [int] $maxChecks, [int] $sleepSeconds, [String[]] $okText, [String[]] $failText)
{
$responseText = ""
$checkedTimes = 0
$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true
while($checkedTimes -lt $maxChecks)
{
$checkedTimes++
Write-Host "Downloading $url on attempt $checkedTimes"
$responseText = $webClient.DownloadString($url)
if ($failText.Contains($responseText))
{
throw "Got '$responseText' from API on attempt $checkedTimes, this indicates a failure"
}
elseif ($okText.Contains($responseText))
{
Write-Host "Got '$responseText' from API on attempt $checkedTimes, this indicates a success"
break
}
else
{
Write-Host "Got '$responseText' from API on attempt $checkedTimes, this is unknown - sleeping for $sleepSeconds seconds"
Start-Sleep -s $sleepSeconds
}
}
if ($checkedTimes -ge $maxChecks)
{
throw "API text checking timed out after the maxiumum $maxChecks checks"
}
}
Write-Host "Ensconce - WebHelper Loaded"
$webHelperLoaded = $true
| 15below/Ensconce | src/Scripts/webHelper.ps1 | PowerShell | mit | 3,260 |
$env = "test"
$regex = "(esw)"
$rg = ""
$vaultName = "colin-test"
$sqlPass = "#testing1234"
$kvKeyName = "sqlkvtest"
Remove-Module -Name DevOpsFlex.Automation.PowerShell -ErrorAction SilentlyContinue -Verbose
Import-Module $PSScriptRoot\..\DevOpsFlex.Automation.PowerShell.psd1 -Force -Verbose
#Register-AzureServiceBusInKeyVault -KeyVaultName $vaultName -Environment $env -Regex $regex
Register-AzureSqlDatabaseInKeyVault -KeyVaultName $vaultName -Environment $env -Regex $regex -SqlSaPassword $sqlPass
#Register-AzureCosmosDBInKeyVault -KeyVaultName $vaultName -ResourceGroup $rg -Environment $env -Regex $regex
#Register-AzureRedisCacheInKeyVault -KeyVaultName $vaultName -ResourceGroup $rg -Environment $env -Regex $regex | eShopWorld/devopsflex-automation | src/DevOpsFlex.Automation.PowerShell/Debug/RegisterAzureServicesInKeyVault.ps1 | PowerShell | mit | 734 |
function Invoke-DbMirrorValidation {
<#
.SYNOPSIS
Validates if a mirror is ready
.DESCRIPTION
Validates if a mirror is ready
Thanks to https://github.com/mmessano/PowerShell/blob/master/SQL-ConfigureDatabaseMirroring.ps1
.PARAMETER Primary
SQL Server name or SMO object representing the primary SQL Server.
.PARAMETER PrimarySqlCredential
Login to the primary instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
.PARAMETER Mirror
SQL Server name or SMO object representing the mirror SQL Server.
.PARAMETER MirrorSqlCredential
Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
.PARAMETER Witness
SQL Server name or SMO object representing the witness SQL Server.
.PARAMETER WitnessSqlCredential
Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
.PARAMETER Database
The database or databases to mirror
.PARAMETER SharedPath
The network share where the backups will be
.PARAMETER InputObject
Enables piping from Get-DbaDatabase
.PARAMETER EnableException
By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
.NOTES
Tags: Mirror, HA
Author: Chrissy LeMaire (@cl), netnerds.net
dbatools PowerShell module (https://dbatools.io)
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.EXAMPLE
PS C:\> $params = @{
Primary = 'sql2017a'
Mirror = 'sql2017b'
MirrorSqlCredential = 'sqladmin'
Witness = 'sql2019'
Database = 'onthewall'
SharedPath = '\\nas\sql\share'
}
PS C:\> Invoke-DbMirrorValidation @params
Do things
#>
[CmdletBinding()]
param (
[DbaInstanceParameter]$Primary,
[PSCredential]$PrimarySqlCredential,
[parameter(Mandatory)]
[DbaInstanceParameter[]]$Mirror,
[PSCredential]$MirrorSqlCredential,
[DbaInstanceParameter]$Witness,
[PSCredential]$WitnessSqlCredential,
[string[]]$Database,
[string]$SharedPath,
[parameter(ValueFromPipeline)]
[Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
[switch]$EnableException
)
process {
if ((Test-Bound -ParameterName Primary) -and (Test-Bound -Not -ParameterName Database)) {
Stop-Function -Message "Database is required when SqlInstance is specified"
return
}
if ($Primary) {
$InputObject += Get-DbaDatabase -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -Database $Database
}
foreach ($db in $InputObject) {
$server = $db.Parent
$dbName = $db.Name
$canmirror = $true
$dest = Connect-DbaInstance -SqlInstance $Mirror -SqlCredential $MirrorSqlCredential
$endpoints = @()
$endpoints += Get-DbaEndpoint -SqlInstance $server | Where-Object EndpointType -eq DatabaseMirroring
$endpoints += Get-DbaEndpoint -SqlInstance $dest | Where-Object EndpointType -eq DatabaseMirroring
if (Test-Bound -ParameterName Witness) {
try {
$witserver = Connect-DbaInstance -SqlInstance $Witness -SqlCredential $WitnessSqlCredential
$endpoints += Get-DbaEndpoint -SqlInstance $witserver | Where-Object EndpointType -eq DatabaseMirroring
$witdb = Get-DbaDatabase -SqlInstance $witserver -Database $db.Name
$wexists = $true
if ($witdb.Status -ne 'Restoring') {
$canmirror = $false
}
if ($witdb) {
$witexists = $true
} else {
Write-Message -Level Verbose -Message "Database ($dbName) exists on witness server"
$canmirror = $false
$witexists = $false
}
} catch {
$wexists = $false
$canmirror = $false
}
}
if ($db.MirroringStatus -ne [Microsoft.SqlServer.Management.Smo.MirroringStatus]::None) {
Write-Message -Level Verbose -Message "Cannot setup mirroring on database ($dbName) due to its current mirroring state: $($db.MirroringStatus)"
$canmirror = $false
}
if ($db.Status -ne [Microsoft.SqlServer.Management.Smo.DatabaseStatus]::Normal) {
Write-Message -Level Verbose -Message "Cannot setup mirroring on database ($dbName) due to its current Status: $($db.Status)"
$canmirror = $false
}
if ($db.RecoveryModel -ne 'Full') {
Write-Message -Level Verbose -Message "Cannot setup mirroring on database ($dbName) due to its current recovery model: $($db.RecoveryModel)"
$canmirror = $false
}
$destdb = Get-DbaDatabase -SqlInstance $dest -Database $db.Name
if ($destdb.RecoveryModel -ne 'Full') {
$canmirror = $false
}
if ($destdb.Status -ne 'Restoring') {
$canmirror = $false
}
if ($destdb) {
$destdbexists = $true
} else {
Write-Message -Level Verbose -Message "Database ($dbName) does not exist on mirror server"
$canmirror = $false
$destdbexists = $false
}
if ((Test-Bound -ParameterName SharedPath) -and -not (Test-DbaPath -SqlInstance $dest -Path $SharedPath)) {
Write-Message -Level Verbose -Message "Cannot access $SharedPath from $($destdb.Parent.Name)"
$canmirror = $false
$nexists = $false
} else {
$nexists = $true
}
if ($server.EngineEdition -ne $dest.EngineEdition) {
Write-Message -Level Verbose -Message "This mirroring configuration is not supported. Because the principal server instance, $server, is $($server.EngineEdition) Edition, the mirror server instance must also be $($server.EngineEdition) Edition."
$canmirror = $false
$edition = $false
} else {
$edition = $true
}
# There's a better way to do this but I'm sleepy
if ((Test-Bound -ParameterName Witness)) {
if ($endpoints.Count -eq 3) {
$endpointpass = $true
} else {
$endpointpass = $false
}
} else {
if ($endpoints.Count -eq 2) {
$endpointpass = $true
} else {
$endpointpass = $false
}
}
$results = [pscustomobject]@{
Primary = $Primary
Mirror = $Mirror
Witness = $Witness
Database = $db.Name
RecoveryModel = $db.RecoveryModel
MirroringStatus = $db.MirroringStatus
State = $db.Status
EndPoints = $endpointpass
DatabaseExistsOnMirror = $destdbexists
DatabaseExistsOnWitness = $witexists
OnlineWitness = $wexists
EditionMatch = $edition
AccessibleShare = $nexists
DestinationDbStatus = $destdb.Status
WitnessDbStatus = $witdb.Status
ValidationPassed = $canmirror
}
if ((Test-Bound -ParameterName Witness)) {
$results | Select-DefaultView -Property Primary, Mirror, Witness, Database, RecoveryModel, MirroringStatus, State, EndPoints, DatabaseExistsOnMirror, OnlineWitness, DatabaseExistsOnWitness, EditionMatch, AccessibleShare, DestinationDbStatus, WitnessDbStatus, ValidationPassed
} else {
$results | Select-DefaultView -Property Primary, Mirror, Database, RecoveryModel, MirroringStatus, State, EndPoints, DatabaseExistsOnMirror, EditionMatch, AccessibleShare, DestinationDbStatus, ValidationPassed
}
}
}
} | wsmelton/dbatools | internal/functions/Invoke-DbMirrorValidation.ps1 | PowerShell | mit | 9,313 |
$packageName = 'cmake.portable'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url = 'http://www.cmake.org/files/v3.2/cmake-3.2.1-win32-x86.zip'
$checksum = '4011f4f18c002a9ff97c76ea1d397eca9b675f98'
$checksumType = 'sha1'
Install-ChocolateyZipPackage -PackageName "$packageName" `
-Url "$url" `
-UnzipLocation "$toolsDir" `
-Url64bit "" `
-Checksum "$checksum" `
-ChecksumType "$checksumType" | dtgm/chocolatey-packages | automatic/_output/cmake.portable/3.2.1/tools/chocolateyInstall.ps1 | PowerShell | apache-2.0 | 564 |
function Get-TargetResource
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
[parameter(Mandatory = $true)]
[System.String]
$Identity,
[parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$Credential,
[System.String]
$AutoDiscoverServiceInternalUri,
[System.String[]]
$AutoDiscoverSiteScope,
[System.String]
$DomainController
)
#Load helper module
Import-Module "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.Parent.FullName)\Misc\xExchangeCommon.psm1" -Verbose:0
LogFunctionEntry -Parameters @{"Identity" = $Identity} -VerbosePreference $VerbosePreference
#Establish remote Powershell session
GetRemoteExchangeSession -Credential $Credential -CommandsToLoad "Get-ClientAccessServer" -VerbosePreference $VerbosePreference
$cas = GetClientAccessServer @PSBoundParameters
if ($cas -ne $null)
{
if ($cas.AutoDiscoverSiteScope -ne $null)
{
$sites = $cas.AutoDiscoverSiteScope.ToArray()
}
$returnValue = @{
Identity = $Identity
AutoDiscoverServiceInternalUri = $cas.AutoDiscoverServiceInternalUri
AutoDiscoverSiteScope = $sites
}
}
$returnValue
}
function Set-TargetResource
{
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[System.String]
$Identity,
[parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$Credential,
[System.String]
$AutoDiscoverServiceInternalUri,
[System.String[]]
$AutoDiscoverSiteScope,
[System.String]
$DomainController
)
#Load helper module
Import-Module "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.Parent.FullName)\Misc\xExchangeCommon.psm1" -Verbose:0
LogFunctionEntry -Parameters @{"Identity" = $Identity} -VerbosePreference $VerbosePreference
#Establish remote Powershell session
GetRemoteExchangeSession -Credential $Credential -CommandsToLoad "Set-ClientAccessServer" -VerbosePreference $VerbosePreference
RemoveParameters -PSBoundParametersIn $PSBoundParameters -ParamsToRemove "Credential"
SetEmptyStringParamsToNull -PSBoundParametersIn $PSBoundParameters
Set-ClientAccessServer @PSBoundParameters
}
function Test-TargetResource
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
[parameter(Mandatory = $true)]
[System.String]
$Identity,
[parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$Credential,
[System.String]
$AutoDiscoverServiceInternalUri,
[System.String[]]
$AutoDiscoverSiteScope,
[System.String]
$DomainController
)
#Load helper module
Import-Module "$((Get-Item -LiteralPath "$($PSScriptRoot)").Parent.Parent.FullName)\Misc\xExchangeCommon.psm1" -Verbose:0
LogFunctionEntry -Parameters @{"Identity" = $Identity} -VerbosePreference $VerbosePreference
#Establish remote Powershell session
GetRemoteExchangeSession -Credential $Credential -CommandsToLoad "Get-ClientAccessServer" -VerbosePreference $VerbosePreference
$cas = GetClientAccessServer @PSBoundParameters
if ($cas -eq $null)
{
return $false
}
else
{
if (!(VerifySetting -Name "AutoDiscoverServiceInternalUri" -Type "String" -ExpectedValue $AutoDiscoverServiceInternalUri -ActualValue $cas.AutoDiscoverServiceInternalUri.AbsoluteUri -PSBoundParametersIn $PSBoundParameters -VerbosePreference $VerbosePreference))
{
return $false
}
if (!(VerifySetting -Name "AutoDiscoverSiteScope" -Type "Array" -ExpectedValue $AutoDiscoverSiteScope -ActualValue $cas.AutoDiscoverSiteScope -PSBoundParametersIn $PSBoundParameters -VerbosePreference $VerbosePreference))
{
return $false
}
}
return $true
}
#Runs Get-ClientAcccessServer, only specifying Identity, and optionally DomainController
function GetClientAccessServer
{
[CmdletBinding()]
param
(
[parameter(Mandatory = $true)]
[System.String]
$Identity,
[parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$Credential,
[System.String]
$AutoDiscoverServiceInternalUri,
[System.String[]]
$AutoDiscoverSiteScope,
[System.String]
$DomainController
)
#Remove params we don't want to pass into the next command
RemoveParameters -PSBoundParametersIn $PSBoundParameters -ParamsToKeep "Identity","DomainController"
return (Get-ClientAccessServer @PSBoundParameters)
}
Export-ModuleMember -Function *-TargetResource
| phongdly/puppetlabs-dsc | lib/puppet_x/dsc_resources/xExchange/DSCResources/MSFT_xExchClientAccessServer/MSFT_xExchClientAccessServer.psm1 | PowerShell | apache-2.0 | 4,903 |
[T4Scaffolding.Scaffolder(Description = "Creates a repository")][CmdletBinding()]
param(
[parameter(Position = 0, Mandatory = $true, ValueFromPipelineByPropertyName = $true)][string]$ModelType,
[string]$DbContextType,
[string]$Area,
[string]$Project,
[string]$CodeLanguage,
[switch]$NoChildItems = $false,
[string[]]$TemplateFolders,
[switch]$Force = $false
)
# Ensure you've referenced System.Data.Entity
(Get-Project $Project).Object.References.Add("System.Data.Entity") | Out-Null
$foundModelType = Get-ProjectType $ModelType -Project $Project -BlockUi
if (!$foundModelType) { return }
$primaryKey = Get-PrimaryKey $foundModelType.FullName -Project $Project -ErrorIfNotFound
if (!$primaryKey) { return }
if(!$DbContextType) { $DbContextType = [System.Text.RegularExpressions.Regex]::Replace((Get-Project $Project).Name, "[^a-zA-Z0-9]", "") + "Context" }
$outputPath = Join-Path Models ($foundModelType.Name + "Repository")
if ($Area) {
$areaFolder = Join-Path Areas $Area
if (-not (Get-ProjectItem $areaFolder -Project $Project)) {
Write-Error "Cannot find area '$Area'. Make sure it exists already."
return
}
$outputPath = Join-Path $areaFolder $outputPath
}
if (!$NoChildItems) {
$dbContextScaffolderResult = Scaffold DbContext -ModelType $ModelType -DbContextType $DbContextType -Area $Area -Project $Project -CodeLanguage $CodeLanguage -BlockUi
$foundDbContextType = $dbContextScaffolderResult.DbContextType
if (!$foundDbContextType) { return }
}
if (!$foundDbContextType) { $foundDbContextType = Get-ProjectType $DbContextType -Project $Project }
if (!$foundDbContextType) { return }
$modelTypePluralized = Get-PluralizedWord $foundModelType.Name
$defaultNamespace = (Get-Project $Project).Properties.Item("DefaultNamespace").Value
$repositoryNamespace = [T4Scaffolding.Namespaces]::Normalize($defaultNamespace + "." + [System.IO.Path]::GetDirectoryName($outputPath).Replace([System.IO.Path]::DirectorySeparatorChar, "."))
$modelTypeNamespace = [T4Scaffolding.Namespaces]::GetNamespace($foundModelType.FullName)
Add-ProjectItemViaTemplate $outputPath -Template Repository -Model @{
ModelType = [MarshalByRefObject]$foundModelType;
PrimaryKey = [string]$primaryKey;
DefaultNamespace = $defaultNamespace;
RepositoryNamespace = $repositoryNamespace;
ModelTypeNamespace = $modelTypeNamespace;
ModelTypePluralized = [string]$modelTypePluralized;
DbContextNamespace = $foundDbContextType.Namespace.FullName;
DbContextType = [MarshalByRefObject]$foundDbContextType;
} -SuccessMessage "Added repository '{0}'" -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force
| kissarat/dandy | packages/T4Scaffolding.1.0.5/tools/EFRepository/T4Scaffolding.EFRepository.ps1 | PowerShell | bsd-3-clause | 2,728 |
#Requires -Version 3.0
Param(
[string] $ResourceGroupLocation = 'West US',
[string] $ResourceGroupName = 'VMwithPublicIP',
[switch] $UploadArtifacts,
[string] $StorageAccountName,
[string] $StorageContainerName = $ResourceGroupName.ToLowerInvariant() + '-stageartifacts',
[string] $TemplateFile = '..\Templates\DeploymentTemplate.json',
[string] $TemplateParametersFile = '..\Templates\DeploymentTemplate.param.dev.json',
[string] $ArtifactStagingDirectory = '..\bin\Debug\Artifacts',
[string] $AzCopyPath = '..\Tools\AzCopy.exe'
)
Set-StrictMode -Version 3
Import-Module Azure -ErrorAction SilentlyContinue
try {
$AzureToolsUserAgentString = New-Object -TypeName System.Net.Http.Headers.ProductInfoHeaderValue -ArgumentList 'VSAzureTools', '1.4'
[Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.UserAgents.Add($AzureToolsUserAgentString)
} catch { }
$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)
Set-Variable ArtifactsLocationName '_artifactsLocation' -Option ReadOnly
Set-Variable ArtifactsLocationSasTokenName '_artifactsLocationSasToken' -Option ReadOnly
$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
}
}
Switch-AzureMode AzureServiceManagement
$StorageAccountKey = (Get-AzureStorageKey -StorageAccountName $StorageAccountName).Primary
$StorageAccountContext = New-AzureStorageContext $StorageAccountName (Get-AzureStorageKey $StorageAccountName).Primary
# 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"""
# 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 (defaults to 1 hour).
$ArtifactsLocationSasToken = New-AzureStorageContainerSASToken -Container $StorageContainerName -Context $StorageAccountContext -Permission r
$ArtifactsLocationSasToken = ConvertTo-SecureString $ArtifactsLocationSasToken -AsPlainText -Force
$OptionalParameters[$ArtifactsLocationSasTokenName] = $ArtifactsLocationSasToken
}
}
# Create or update the resource group using the specified template file and template parameters file
Switch-AzureMode AzureResourceManager
New-AzureResourceGroup -Name $ResourceGroupName `
-Location $ResourceGroupLocation `
-TemplateFile $TemplateFile `
-TemplateParameterFile $TemplateParametersFile `
@OptionalParameters `
-Force -Verbose
| praveenrajpl/FortiGateOne | VMwithPublicIP.Solution/VMwithPublicIP/Scripts/Deploy-AzureResourceGroup.ps1 | PowerShell | mit | 4,576 |
if ([System.IntPtr]::Size -eq 8) {
$arch = "x64\*.*"
} elseif (([System.IntPtr]::Size -eq 4) -and (Test-Path Env:\PROCESSOR_ARCHITEW6432)) {
$arch = "x64\*.*"
} elseif ([System.IntPtr]::Size -eq 4) {
$arch = "x86\*.*"
}
$nativePath = $(Join-Path $installPath "lib\native")
$nativePath = $(Join-Path $nativePath $arch)
$LibLuaPostBuildCmd = "
xcopy /s /y `"$nativePath`" `"`$(TargetDir)`"" | RoyAwesome/Watertight-Engine | packages/NLua.1.3.0.2/tools/net45/GetLibLuaPostBuildCmd.ps1 | PowerShell | mit | 408 |
[CmdletBinding()]
param()
. $PSScriptRoot\..\..\..\Tests\lib\Initialize-Test.ps1
$serviceConnectionName = "random connection name"
$composeFilePath = "docker-compose.yml"
$applicationName = "fabric:/Application1"
$serverCertThumbprint = "random thumbprint"
$userName = "random user"
$password = "random password"
$connectionEndpointFullUrl = "https://mycluster.com:19000"
$connectionEndpoint = ([System.Uri]$connectionEndpointFullUrl).Authority
# Setup input arguments
Register-Mock Get-VstsInput { $serviceConnectionName } -Name serviceConnectionName -Require
Register-Mock Get-VstsInput { $composeFilePath } -Name composeFilePath -Require
Register-Mock Get-VstsInput { $applicationName } -Name applicationName -Require
Register-Mock Get-VstsInput { $null } -Name deployTimeoutSec
Register-Mock Get-VstsInput { $null } -Name removeTimeoutSec
Register-Mock Get-VstsInput { $null } -Name getStatusTimeoutSec
Register-Mock Get-VstsInput { "None" } -Name registryCredentials -Require
Register-Mock Get-VstsInput { "false" } -Name upgrade
# Setup file resolution
Register-Mock Find-VstsFiles { $composeFilePath } -- -LegacyPattern $composeFilePath
Register-Mock Assert-VstsPath
Register-Mock Test-Path { $true } -- "HKLM:\SOFTWARE\Microsoft\Service Fabric SDK"
# Setup mock Azure Pipelines service endpoint
$vstsEndpoint = @{
"url" = $connectionEndpointFullUrl
"Auth" = @{
"Scheme" = "UserNamePassword"
"Parameters" = @{
"ServerCertThumbprint" = $serverCertThumbprint
"Username" = $userName
"Password" = $password
}
}
}
Register-Mock Get-VstsEndpoint { $vstsEndpoint } -- -Name $serviceConnectionName -Require
# Setup mock Registry for Service Fabric
$SfRegistry = @{
"FabricSDKVersion" = "2.8.1.2"
}
Register-Mock Get-ItemProperty { $SfRegistry } -- -Path 'HKLM:\SOFTWARE\Microsoft\Service Fabric SDK\' -ErrorAction SilentlyContinue
# Setup mock results of cluster connection
Register-Mock Connect-ServiceFabricClusterFromServiceEndpoint { } -- -ClusterConnectionParameters @{} -ConnectedServiceEndpoint $vstsEndpoint
$serviceFabricComposeDeploymentStatus = @{
"DeploymentName" = $applicationName
"ComposeDeploymentStatus" = "Created"
"StatusDetails" = ""
}
# Need to store the bool in an object so the lambdas will share the reference
$removed = New-Object 'System.Collections.Generic.Dictionary[string, bool]'
$removed.Value = $true
Register-Mock Get-ServiceFabricComposeDeploymentStatus {
if (($removed.Value -eq $true))
{
return $null;
}
else
{
return $serviceFabricComposeDeploymentStatus
}
} -DeploymentName: $applicationName
Register-Mock Remove-ServiceFabricComposeDeployment {
$removed.Value = $true
} -Force: True -DeploymentName: $applicationName
Register-Mock Test-ServiceFabricApplicationPackage { } -- -ComposeFilePath: $composeFilePath -ErrorAction: Stop
Register-Mock New-ServiceFabricComposeDeployment {
$removed.Value = $false
} -- -DeploymentName: $applicationName -Compose: $composeFilePath
# Act
. $PSScriptRoot\..\..\..\Tasks\ServiceFabricComposeDeployV0\ps_modules\ServiceFabricHelpers\Connect-ServiceFabricClusterFromServiceEndpoint.ps1
@( & $PSScriptRoot/../../../Tasks/ServiceFabricComposeDeployV0/ServiceFabricComposeDeploy.ps1 )
# Assert
Assert-WasCalled Get-ServiceFabricComposeDeploymentStatus -Times 2
Assert-WasCalled Remove-ServiceFabricComposeDeployment -Times 0
Assert-WasCalled New-ServiceFabricComposeDeployment -Times 1 | grawcho/vso-agent-tasks | Tasks/ServiceFabricComposeDeployV0/Tests/Deploy.2.8.ps1 | PowerShell | mit | 3,554 |
# This file is a temporary workaround for internal builds to be able to restore from private AzDO feeds.
# This file should be removed as part of this issue: https://github.com/dotnet/arcade/issues/4080
#
# What the script does is iterate over all package sources in the pointed NuGet.config and add a credential entry
# under <packageSourceCredentials> for each Maestro managed private feed. Two additional credential
# entries are also added for the two private static internal feeds: dotnet3-internal and dotnet3-internal-transport.
#
# This script needs to be called in every job that will restore packages and which the base repo has
# private AzDO feeds in the NuGet.config.
#
# See example YAML call for this script below. Note the use of the variable `$(dn-bot-dnceng-artifact-feeds-rw)`
# from the AzureDevOps-Artifact-Feeds-Pats variable group.
#
# - task: PowerShell@2
# displayName: Setup Private Feeds Credentials
# condition: eq(variables['Agent.OS'], 'Windows_NT')
# inputs:
# filePath: $(Build.SourcesDirectory)/eng/common/SetupNugetSources.ps1
# arguments: -ConfigFile $(Build.SourcesDirectory)/NuGet.config -Password $Env:Token
# env:
# Token: $(dn-bot-dnceng-artifact-feeds-rw)
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)][string]$ConfigFile,
[Parameter(Mandatory = $true)][string]$Password
)
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 2.0
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
. $PSScriptRoot\tools.ps1
# Add source entry to PackageSources
function AddPackageSource($sources, $SourceName, $SourceEndPoint, $creds, $Username, $Password) {
$packageSource = $sources.SelectSingleNode("add[@key='$SourceName']")
if ($packageSource -eq $null)
{
$packageSource = $doc.CreateElement("add")
$packageSource.SetAttribute("key", $SourceName)
$packageSource.SetAttribute("value", $SourceEndPoint)
$sources.AppendChild($packageSource) | Out-Null
}
else {
Write-Host "Package source $SourceName already present."
}
AddCredential -Creds $creds -Source $SourceName -Username $Username -Password $Password
}
# Add a credential node for the specified source
function AddCredential($creds, $source, $username, $password) {
# Looks for credential configuration for the given SourceName. Create it if none is found.
$sourceElement = $creds.SelectSingleNode($Source)
if ($sourceElement -eq $null)
{
$sourceElement = $doc.CreateElement($Source)
$creds.AppendChild($sourceElement) | Out-Null
}
# Add the <Username> node to the credential if none is found.
$usernameElement = $sourceElement.SelectSingleNode("add[@key='Username']")
if ($usernameElement -eq $null)
{
$usernameElement = $doc.CreateElement("add")
$usernameElement.SetAttribute("key", "Username")
$sourceElement.AppendChild($usernameElement) | Out-Null
}
$usernameElement.SetAttribute("value", $Username)
# Add the <ClearTextPassword> to the credential if none is found.
# Add it as a clear text because there is no support for encrypted ones in non-windows .Net SDKs.
# -> https://github.com/NuGet/Home/issues/5526
$passwordElement = $sourceElement.SelectSingleNode("add[@key='ClearTextPassword']")
if ($passwordElement -eq $null)
{
$passwordElement = $doc.CreateElement("add")
$passwordElement.SetAttribute("key", "ClearTextPassword")
$sourceElement.AppendChild($passwordElement) | Out-Null
}
$passwordElement.SetAttribute("value", $Password)
}
function InsertMaestroPrivateFeedCredentials($Sources, $Creds, $Username, $Password) {
$maestroPrivateSources = $Sources.SelectNodes("add[contains(@key,'darc-int')]")
Write-Host "Inserting credentials for $($maestroPrivateSources.Count) Maestro's private feeds."
ForEach ($PackageSource in $maestroPrivateSources) {
Write-Host "`tInserting credential for Maestro's feed:" $PackageSource.Key
AddCredential -Creds $creds -Source $PackageSource.Key -Username $Username -Password $Password
}
}
if (!(Test-Path $ConfigFile -PathType Leaf)) {
Write-PipelineTelemetryError -Category 'Build' -Message "Eng/common/SetupNugetSources.ps1 returned a non-zero exit code. Couldn't find the NuGet config file: $ConfigFile"
ExitWithExitCode 1
}
if (!$Password) {
Write-PipelineTelemetryError -Category 'Build' -Message 'Eng/common/SetupNugetSources.ps1 returned a non-zero exit code. Please supply a valid PAT'
ExitWithExitCode 1
}
# Load NuGet.config
$doc = New-Object System.Xml.XmlDocument
$filename = (Get-Item $ConfigFile).FullName
$doc.Load($filename)
# Get reference to <PackageSources> or create one if none exist already
$sources = $doc.DocumentElement.SelectSingleNode("packageSources")
if ($sources -eq $null) {
$sources = $doc.CreateElement("packageSources")
$doc.DocumentElement.AppendChild($sources) | Out-Null
}
# Looks for a <PackageSourceCredentials> node. Create it if none is found.
$creds = $doc.DocumentElement.SelectSingleNode("packageSourceCredentials")
if ($creds -eq $null) {
$creds = $doc.CreateElement("packageSourceCredentials")
$doc.DocumentElement.AppendChild($creds) | Out-Null
}
$userName = "dn-bot"
# Insert credential nodes for Maestro's private feeds
InsertMaestroPrivateFeedCredentials -Sources $sources -Creds $creds -Username $userName -Password $Password
$dotnet3Source = $sources.SelectSingleNode("add[@key='dotnet3']")
if ($dotnet3Source -ne $null) {
AddPackageSource -Sources $sources -SourceName "dotnet3-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3-internal/nuget/v2" -Creds $creds -Username $userName -Password $Password
AddPackageSource -Sources $sources -SourceName "dotnet3-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3-internal-transport/nuget/v2" -Creds $creds -Username $userName -Password $Password
}
$dotnet31Source = $sources.SelectSingleNode("add[@key='dotnet3.1']")
if ($dotnet31Source -ne $null) {
AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal/nuget/v2" -Creds $creds -Username $userName -Password $Password
AddPackageSource -Sources $sources -SourceName "dotnet3.1-internal-transport" -SourceEndPoint "https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v2" -Creds $creds -Username $userName -Password $Password
}
$doc.Save($filename) | jmarolf/roslyn | eng/common/SetupNugetSources.ps1 | PowerShell | mit | 6,615 |
$ErrorActionPreference = "Stop"
$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Path
import-module $currentPath\..\..\xSqlServerAlwaysOnUtil.psm1 -ErrorAction Stop
function Get-TargetResource
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
[parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[parameter(Mandatory = $true)]
[System.String]
$NodeName,
[parameter(Mandatory = $true)]
[ValidateLength(1,15)]
[System.String]
$Name,
[parameter(Mandatory = $true)]
[System.String]
$AvailabilityGroup
)
try {
$listner = Get-SQLAlwaysOnAvailabilityGroupListner -Name $Name -AvailabilityGroup $AvailabilityGroup -NodeName $NodeName -InstanceName $InstanceName
if( $null -ne $listner ) {
Write-Verbose "Listner $Name already exist"
$ensure = "Present"
$port = [uint16]( $listner | Select-Object -ExpandProperty PortNumber )
$presentIpAddress = $listner.AvailabilityGroupListenerIPAddresses
$dhcp = [bool]( $presentIpAddress | Select-Object -first 1 IsDHCP )
$ipAddress = @()
foreach( $currentIpAddress in $presentIpAddress ) {
$ipAddress += "$($currentIpAddress.IPAddress)/$($currentIpAddress.SubnetMask)"
}
} else {
Write-Verbose "Listner $Name does not exist"
$ensure = "Absent"
$port = 0
$dhcp = $false
$ipAddress = $null
}
} catch {
throw "Unexpected result when trying to verify existance of listner $Name. Error: $($_.Exception.Message)"
}
$returnValue = @{
InstanceName = [System.String]$InstanceName
NodeName = [System.String]$NodeName
Name = [System.String]$Name
Ensure = [System.String]$ensure
AvailabilityGroup = [System.String]$AvailabilityGroup
IpAddress = [System.String[]]$ipAddress
Port = [System.UInt16]$port
DHCP = [System.Boolean]$dhcp
}
return $returnValue
}
function Set-TargetResource
{
[CmdletBinding(SupportsShouldProcess)]
param
(
[parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[parameter(Mandatory = $true)]
[System.String]
$NodeName,
[parameter(Mandatory = $true)]
[ValidateLength(1,15)]
[System.String]
$Name,
[ValidateSet("Present","Absent")]
[System.String]
$Ensure,
[parameter(Mandatory = $true)]
[System.String]
$AvailabilityGroup,
[System.String[]]
$IpAddress,
[System.UInt16]
$Port,
[System.Boolean]
$DHCP
)
$parameters = @{
InstanceName = [System.String]$InstanceName
NodeName = [System.String]$NodeName
Name = [System.String]$Name
AvailabilityGroup = [System.String]$AvailabilityGroup
}
$listnerState = Get-TargetResource @parameters
if( $null -ne $listnerState ) {
if( $Ensure -ne "" -and $listnerState.Ensure -ne $Ensure ) {
$InstanceName = Get-SQLInstanceName -InstanceName $InstanceName
if( $Ensure -eq "Present") {
if( ( $PSCmdlet.ShouldProcess( $Name, "Create listner on $AvailabilityGroup" ) ) ) {
$newListnerParams = @{
Name = $Name
Path = "SQLSERVER:\SQL\$NodeName\$InstanceName\AvailabilityGroups\$AvailabilityGroup"
}
if( $Port ) {
Write-Verbose "Listner port set to $Port"
$newListnerParams += @{
Port = $Port
}
}
if( $DHCP -and $IpAddress.Count -gt 0 ) {
Write-Verbose "Listner set to DHCP with subnet $IpAddress"
$newListnerParams += @{
DhcpSubnet = [string]$IpAddress
}
} elseif ( -not $DHCP -and $IpAddress.Count -gt 0 ) {
Write-Verbose "Listner set to static IP-address(es); $($IpAddress -join ', ')"
$newListnerParams += @{
StaticIp = $IpAddress
}
} else {
Write-Verbose "Listner using DHCP with server default subnet"
}
New-SqlAvailabilityGroupListener @newListnerParams -Verbose:$False | Out-Null # Suppressing Verbose because it prints the entire T-SQL statement otherwise
}
} else {
if( ( $PSCmdlet.ShouldProcess( $Name, "Remove listner from $AvailabilityGroup" ) ) ) {
Remove-Item "SQLSERVER:\SQL\$NodeName\$InstanceName\AvailabilityGroups\$AvailabilityGroup\AvailabilityGroupListeners\$Name"
}
}
} else {
if( $Ensure -ne "" ) { Write-Verbose "State is already $Ensure" }
if( $listnerState.Ensure -eq "Present") {
if( -not $DHCP -and $listnerState.IpAddress.Count -lt $IpAddress.Count ) { # Only able to add a new IP-address, not change existing ones.
Write-Verbose "Found at least one new IP-address."
$ipAddressEqual = $False
} else {
# No new IP-address
if( $null -eq $IpAddress -or -not ( Compare-Object -ReferenceObject $IpAddress -DifferenceObject $listnerState.IpAddress ) ) {
$ipAddressEqual = $True
} else {
throw "IP-address configuration mismatch. Expecting $($IpAddress -join ', ') found $($listnerState.IpAddress -join ', '). Resource does not support changing IP-address. Listner needs to be removed and then created again."
}
}
if( $listnerState.Port -ne $Port -or -not $ipAddressEqual ) {
Write-Verbose "Listner differ in configuration."
if( $listnerState.Port -ne $Port ) {
if( ( $PSCmdlet.ShouldProcess( $Name, "Changing port configuration" ) ) ) {
$InstanceName = Get-SQLInstanceName -InstanceName $InstanceName
$setListnerParams = @{
Path = "SQLSERVER:\SQL\$NodeName\$InstanceName\AvailabilityGroups\$AvailabilityGroup\AvailabilityGroupListeners\$Name"
Port = $Port
}
Set-SqlAvailabilityGroupListener @setListnerParams -Verbose:$False | Out-Null # Suppressing Verbose because it prints the entire T-SQL statement otherwise
}
}
if( -not $ipAddressEqual ) {
if( ( $PSCmdlet.ShouldProcess( $Name, "Adding IP-address(es)" ) ) ) {
$InstanceName = Get-SQLInstanceName -InstanceName $InstanceName
$newIpAddress = @()
foreach( $currentIpAddress in $IpAddress ) {
if( -not $listnerState.IpAddress -contains $currentIpAddress ) {
$newIpAddress += $currentIpAddress
}
}
$setListnerParams = @{
Path = "SQLSERVER:\SQL\$NodeName\$InstanceName\AvailabilityGroups\$AvailabilityGroup\AvailabilityGroupListeners\$Name"
StaticIp = $newIpAddress
}
Add-SqlAvailabilityGroupListenerStaticIp @setListnerParams -Verbose:$False | Out-Null # Suppressing Verbose because it prints the entire T-SQL statement otherwise
}
}
} else {
Write-Verbose "Listner configuration is already correct."
}
} else {
throw "Trying to make a change to an listner that does not exist."
}
}
} else {
throw "Got unexpected result from Get-TargetResource. No change is made."
}
#Include this line if the resource requires a system reboot.
#$global:DSCMachineStatus = 1
}
function Test-TargetResource
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
[parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[parameter(Mandatory = $true)]
[System.String]
$NodeName,
[parameter(Mandatory = $true)]
[ValidateLength(1,15)]
[System.String]
$Name,
[ValidateSet("Present","Absent")]
[System.String]
$Ensure,
[parameter(Mandatory = $true)]
[System.String]
$AvailabilityGroup,
[System.String[]]
$IpAddress,
[System.UInt16]
$Port,
[System.Boolean]
$DHCP
)
$parameters = @{
InstanceName = [System.String]$InstanceName
NodeName = [System.String]$NodeName
Name = [System.String]$Name
AvailabilityGroup = [System.String]$AvailabilityGroup
}
Write-Verbose "Testing state of listner $Name"
$listnerState = Get-TargetResource @parameters
if( $null -ne $listnerState ) {
if( $null -eq $IpAddress -or ($null -ne $listnerState.IpAddress -and -not ( Compare-Object -ReferenceObject $IpAddress -DifferenceObject $listnerState.IpAddress ) ) ) {
$ipAddressEqual = $True
} else {
$ipAddressEqual = $False
}
if( ( $Ensure -eq "" -or ( $Ensure -ne "" -and $listnerState.Ensure -eq $Ensure) ) -and ($Port -eq "" -or $listnerState.Port -eq $Port) -and $ipAddressEqual ) {
[System.Boolean]$result = $True
} else {
[System.Boolean]$result = $False
}
} else {
throw "Got unexpected result from Get-TargetResource. No change is made."
}
return $result
}
function Get-SQLAlwaysOnAvailabilityGroupListner
{
[CmdletBinding()]
[OutputType()]
param
(
[parameter(Mandatory = $true)]
[System.String]
$Name,
[parameter(Mandatory = $true)]
[System.String]
$AvailabilityGroup,
[parameter(Mandatory = $true)]
[System.String]
$InstanceName,
[parameter(Mandatory = $true)]
[System.String]
$NodeName
)
$instance = Get-SQLPSInstance -InstanceName $InstanceName -NodeName $NodeName
$Path = "$($instance.PSPath)\AvailabilityGroups\$AvailabilityGroup\AvailabilityGroupListeners"
Write-Debug "Connecting to $Path as $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
[string[]]$presentListner = Get-ChildItem $Path
if( $presentListner.Count -ne 0 -and $presentListner.Contains("[$Name]") ) {
Write-Debug "Connecting to availability group $Name as $([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)"
$listner = Get-Item "$Path\$Name"
} else {
$listner = $null
}
return $listner
}
Export-ModuleMember -Function *-TargetResource
| johlju/xSqlServerAlwaysOn | DSCResources/xSQLServerAlwaysOnAvailabilityGroupListner/xSQLServerAlwaysOnAvailabilityGroupListner.psm1 | PowerShell | mit | 11,729 |
# You'll need node.js and docco to build the documentation. If you don't have
# docco yet, you can install it via
#
# npm install -g docco
# Make the project root directory the working directory (regardless of where the
# script has been called from).
$scriptPath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptPath
Push-Location $dir
# Build doc
docco -o docs .\demo\index.php .\demo\suggest.php .\demo\tracking.php `
.\demo\userdata\initialization.php
# Move back to original directory
Pop-Location
| FACT-Finder/FACT-Finder-PHP-Library-Demo | build-doc.ps1 | PowerShell | mit | 530 |
Function Get-UnityVMwareNFS {
<#
.SYNOPSIS
Queries the EMC Unity array to retrieve informations about VMware NFS LUN.
.DESCRIPTION
git Queries the EMC Unity array to retrieve informations about VMware NFS LUN.
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 Name
Specifies the object name.
.PARAMETER ID
Specifies the object ID.
.EXAMPLE
Get-UnityVMwareNFS
Retrieve information about all VMware NFS LUN
.EXAMPLE
Get-UnityVMwareNFS -Name 'DATASTORE01'
Retrieves information about VMware NFS LUN named DATASTORE01
#>
[CmdletBinding(DefaultParameterSetName="ID")]
Param (
[Parameter(Mandatory = $false,HelpMessage = 'EMC Unity Session')]
$session = ($global:DefaultUnitySession | where-object {$_.IsConnected -eq $true}),
[Parameter(Mandatory = $false,ParameterSetName="Name",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'VMware NFS LUN Name')]
[String[]]$Name='*',
[Parameter(Mandatory = $false,ParameterSetName="ID",ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True,HelpMessage = 'VMware NFS LUN ID')]
[String[]]$ID='*'
)
Begin {
Write-Debug -Message "[$($MyInvocation.MyCommand.Name)] Executing function"
Write-Debug -Message "[$($MyInvocation.MyCommand.Name)] ParameterSetName: $($PsCmdlet.ParameterSetName)"
Write-Debug -Message "[$($MyInvocation.MyCommand.Name)] PSBoundParameters: $($PSBoundParameters | Out-String)"
#Initialazing variables
$ResultCollection = @()
$Typename = 'UnityVMwareNFS'
$StorageResourceURI = '/api/types/storageResource/instances?fields=id,filesystem&filter=type eq 3'
#Loop through each sessions
Foreach ($Sess in $session) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Processing Session: $($Sess.Server) with SessionId: $($Sess.SessionId)"
#Test if session is alive
If ($Sess.TestConnection()) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Retrieve vmwarefs storage resources"
$StorageResource = (($Sess.SendGetRequest($StorageResourceURI)).content | ConvertFrom-Json ).entries.content
If ($StorageResource) {
#Retrieve filesytems associated to storage resources
Write-Debug -Message "[$($MyInvocation.MyCommand)] Retrieve filesytems associated to storage resources"
$ResultCollection += Get-UnityFilesystem -Session $Sess -ID $StorageResource.filesystem.id -Typename $Typename -ErrorAction SilentlyContinue
}
}
}
}
Process {
#Filter results
If ($ResultCollection) {
Switch ($PsCmdlet.ParameterSetName) {
'Name' {
Foreach ($N in $Name) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Return result(s) with the filter: $($N)"
$Result = $ResultCollection | Where-Object {$_.Name -like $N}
Write-Debug -Message "[$($MyInvocation.MyCommand)] Found $($ResultCollection.Count) item(s)"
}
}
'ID' {
Foreach ($I in $ID) {
Write-Debug -Message "[$($MyInvocation.MyCommand)] Return result(s) with the filter: $($I)"
$Result = $ResultCollection | Where-Object {$_.Id -like $I}
Write-Debug -Message "[$($MyInvocation.MyCommand)] Found $($ResultCollection.Count) item(s)"
}
}
} #End Switch
If ($Result) {
$Result
} else {
Write-Error -Message "Object not found with the specified filter(s)" -Category "ObjectNotFound"
} # End If ($Result)
} else {
Write-Error -Message "Object(s) not found" -Category "ObjectNotFound"
} # End If ($ResultCollection)
} # End Process
} # End Function
| equelin/Unity-Powershell | Unity-Powershell/Public/Get-UnityVMwareNFS.ps1 | PowerShell | mit | 4,031 |
Param ($ParentDiskPath,$vmPath,$OSVHDX,$Unattendpath,$Assetspath)
$VMName = "CONTOSODC"
$ProgressPreference = "SilentlyContinue"
#Local Credential
$localCred = new-object -typename System.Management.Automation.PSCredential -argumentlist "Administrator", (ConvertTo-SecureString "Password01" -AsPlainText -Force)
#Create Virtual Machine
$date = Get-date
$msgtxt = "$date : Creating ContosoDC VM Differencing Disks."
Write-Host $msgtxt -ForegroundColor Cyan
$msgtxt | Out-File ($LogFilePath + "VMDeployment.log") -Append -Force
New-VHD -Differencing -ParentPath ($ParentDiskPath + $OSVHDX) -Path ($vmpath + $VMName + '\' + $VMName + '.vhdx') | Out-Null
New-VM -Name $VMName -VHDPath ($vmpath + $VMName + '\' + $VMName + '.vhdx') -Path ($vmpath + $VMName) -Generation 2 | Out-Null
Set-VMMemory -VMName $VMName -DynamicMemoryEnabled $true -StartupBytes 2GB -MaximumBytes 2GB -MinimumBytes 500MB | Out-Null
Remove-VMNetworkAdapter -VMName $VMName -Name "Network Adapter" | Out-Null
Add-VMNetworkAdapter -VMName $VMName -Name "Contoso" -SwitchName "vSwitch-Fabric" -DeviceNaming On | Out-Null
Set-VMProcessor -VMName $VMName -Count 2 | Out-Null
set-vm -Name $VMName -AutomaticStopAction TurnOff | Out-Null
#Inject Answer File
#MountVHDXFile
$date = Get-date
$msgtxt = "$date : Mounting and Injecting Answer File into the $VMName VM."
Write-Host $msgtxt -ForegroundColor Cyan
$msgtxt | Out-File ($LogFilePath + "VMDeployment.log") -Append -Force
New-Item -Path "C:\TempMount" -ItemType Directory | Out-Null
Mount-WindowsImage -Path "C:\TempMount" -Index 1 -ImagePath ($vmpath + $VMName + '\' + $VMName + '.vhdx') | Out-Null
Write-Host "Applying Unattend file to Disk Image..." -ForegroundColor Cyan
#Remove-Item -Path "C:\TempVMMMount\Windows\Panther\Unattend.xml"
New-Item -Path C:\TempMount\windows -ItemType Directory -Name Panther -Force | Out-Null
Copy-Item -Path $Unattendpath -Destination "C:\TempMount\Windows\Panther\Unattend.xml" | Out-Null
#Copy Backinfo
Copy-Item -Path $Assetspath\BACKINFO -Destination C:\TempMount -Recurse
$date = Get-date
$msgtxt = "$date : Saving OS Customizations."
Write-Host $msgtxt -ForegroundColor Cyan
$msgtxt | Out-File ($LogFilePath + "VMDeployment.log") -Append -Force
Dismount-WindowsImage -Path "C:\TempMount" -Save | Out-Null
Remove-Item "C:\TempMount" | Out-Null
#Start Virtual Machine
$date = Get-date
$msgtxt = "$date : Starting VM $VMName."
Write-Host $msgtxt -ForegroundColor Cyan
$msgtxt | Out-File ($LogFilePath + "VMDeployment.log") -Append -Force
Start-VM -Name $VMName | Out-Null
while ((icm -VMName $VMName -Credential $localcred {"Test"} -ea SilentlyContinue) -ne "Test") {Sleep -Seconds 1}
#Wait until the VM is restarted
$date = Get-date
$msgtxt = "$date : Configuring CONTOSODC VM and Installing Active Directory."
Write-Host $msgtxt -ForegroundColor Cyan
$msgtxt | Out-File ($LogFilePath + "VMDeployment.log") -Append -Force
Invoke-Command -VMName $VMName -Credential $localCred -ScriptBlock {
$NIC = Get-NetAdapterAdvancedProperty -RegistryKeyWord "HyperVNetworkAdapterName" | where {$_.RegistryValue -eq "Contoso"}
Rename-NetAdapter -name $NIC.name -newname "Contoso" | Out-Null
New-NetIPAddress -InterfaceAlias "Contoso" –IPAddress 192.168.1.254 -PrefixLength 24 -DefaultGateway 192.168.1.1 | Out-Null
Set-DnsClientServerAddress -InterfaceAlias “Contoso” -ServerAddresses 192.168.1.254 | Out-Null
Install-WindowsFeature -name AD-Domain-Services –IncludeManagementTools | Out-Null
$SecureString = ConvertTo-SecureString "Password01" -AsPlainText -Force
Write-Host "`n`n`n`n`n`n`nInstalling Active Directory..." -ForegroundColor Yellow
Install-ADDSForest -DomainName "contoso.com" -DomainMode WinThreshold -DatabasePath "c:\Domain" -InstallDns `
-DomainNetbiosName "contoso" -SafeModeAdministratorPassword $secureString `
-Confirm -Force -NoRebootOnCompletion | Out-Null
#Install BackInfo
New-Item -Path 'C:\Program Files (x86)\Backinfo' -ItemType Directory -Force | Out-Null
Copy-Item -Path 'C:\BackInfo\Shortcut to BackInfo.exe.lnk' -Destination 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp' -Force
Copy-Item -Path 'C:\BackInfo\BackInfo.exe' -Destination 'C:\Program Files (x86)\Backinfo' -Force
Copy-Item -Path 'C:\BackInfo\BackInfo.ini' -Destination 'C:\Program Files (x86)\Backinfo' -Force
}
Get-VM $VMName | Stop-VM
Get-VM $VMName | Start-VM
#Wait until DC is created and rebooted
$password = "Password01" | ConvertTo-SecureString -asPlainText -Force
$username = "contoso\administrator"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
while ((icm -VMName $VMName -Credential $credential {(Get-ADDomainController contosodc).enabled} -ea SilentlyContinue) -ne $true) {Sleep -Seconds 1}
$date = Get-date
$msgtxt = "$date : Configuring Accounts in Active Directory."
Write-Host $msgtxt -ForegroundColor Cyan
$msgtxt | Out-File ($LogFilePath + "VMDeployment.log") -Append -Force
Invoke-Command -VMName $VMName -Credential $credential -ScriptBlock {
Set-ADDefaultDomainPasswordPolicy -ComplexityEnabled $false -Identity contoso.com -MinPasswordLength 0
New-ADUser -Name "NC Admin" -GivenName NC -Surname Admin -SamAccountName NCAdmin -UserPrincipalName NCAdmin@contoso.com -AccountPassword $SecureString -Enabled $True -ChangePasswordAtLogo $False
New-ADUser -Name "NC Client" -GivenName NC -Surname Client -SamAccountName NCClient -UserPrincipalName NCClient@contoso.com -AccountPassword $SecureString -Enabled $True -ChangePasswordAtLogo $False
NEW-ADGroup –name “NCAdmins” –groupscope Global
NEW-ADGroup –name “NCClients” –groupscope Global
add-ADGroupMember "Domain Admins" "NCAdmin"
add-ADGroupMember "NCAdmins" "NCAdmin"
add-ADGroupMember "NCClients" "NCClient"
add-ADGroupMember "NCClients" "Administrator"
add-ADGroupMember "NCAdmins" "Administrator"
}
| billcurtis/Public | SDNNESTED/VMConfigs/ProvisionContosoDC.ps1 | PowerShell | mit | 5,871 |
<#
.SYNOPSIS
Manages a Visual Studio Tools for Office (VSTO) add-in
.DESCRIPTION
Launches the installation or uninstallation of a VSTO add-in.
.PARAMETER Operation
The operation to perform on the VSTO add-in.
Valid operations are:
- Install
- Uninstall
.PARAMETER ManifestPath
Path to the manifest file for the VSTO add-in.
The path can be any of:
- A path on the local computer
- A path to a UNC file share
- A path to a HTTP(S) site
.PARAMETER Silent
Runs the VSTO operation silently.
.EXAMPLE
Manage-VSTOAddin -Operation Install -ManifestPath "https://example.s3.amazonaws.com/live/MyAddin.vsto" -Silent
Silently installs the VSTO add-in described by the provided manifest.
.NOTES
The Visual Studio 2010 Tools for Office Runtime, which includes VSTOInstaller.exe, must be present on the system.
Silent mode requires the certificate with which the manifest is signed to be present in the Trusted Publishers certificate store.
The VSTOInstaller.exe which matches the bitness of the PowerShell runtime will be used (e.g. 64-bit VSTOInstaller.exe with 64-bit PowerShell).
Parameters for VSTOInstaller.exe
https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/bb772078(v=vs.100)#parameters-for-vstoinstallerexe
VSTOInstaller Error Codes
https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/bb757423(v=vs.100)
.LINK
https://github.com/ralish/PSWinGlue
#>
#Requires -Version 3.0
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateSet('Install', 'Uninstall')]
[String]$Operation,
[Parameter(Mandatory)]
[String]$ManifestPath,
[Switch]$Silent
)
$VstoInstaller = '{0}\Microsoft Shared\VSTO\10.0\VSTOInstaller.exe' -f $env:CommonProgramFiles
$VstoArguments = @(('/{0}' -f $Operation), ('"{0}"' -f $ManifestPath))
if ($Silent) {
$VstoArguments += '/Silent'
}
if (!(Test-Path -Path $VstoInstaller)) {
throw 'VSTO Installer not present at: {0}' -f $VstoInstaller
}
Write-Verbose -Message ('{0}ing VSTO add-in with arguments: {1}' -f $Operation, [String]::Join(' ', $VstoArguments))
$VstoProcess = Start-Process -FilePath $VstoInstaller -ArgumentList $VstoArguments -Wait -PassThru
if ($VstoProcess.ExitCode -ne 0) {
throw 'VSTO Installer failed with code: {0}' -f $VstoProcess.ExitCode
}
| ralish/PSWinGlue | Scripts/Manage-VSTOAddin.ps1 | PowerShell | mit | 2,420 |
<#
.SYNOPSIS
Creates a dummy empty file of a specified size
.DESCRIPTION
This will create one or a number of empty files of a specified size
Useful for creating demos or dummy files to delete as an emergency when
drives are full
.PARAMETER FilePath
The Directory for the files
.PARAMETER Name
The Name of the file, will have underscore integer added if more than one file requested - If you include an extension it will retained otherwise it will have a .dmp extension
.PARAMETER Size
The Size of the File(s) to be created in Mb unless the Gb switch is used
.PARAMETER Number
The number of files to create defaults to 1
.PARAMETER Gb
Switch to change Size to Gb instead of Mb
.PARAMETER Force
OverWrite Existing Files
.EXAMPLE
New-DummyFile -FilePath C:\temp -Name Jeremy -Size 10
Will create 1 file of size 10Mb called jeremy.dmp at C:\temp
.EXAMPLE
New-DummyFile -FilePath C:\temp -Name Jeremy.txt -Size 10 -Number 10
Will create 10 files of size 10Mb called jeremy_N.txt where N is 1-10 at C:\temp
.EXAMPLE
New-DummyFile -FilePath C:\temp -Name Jeremy -Size 10 -Gb
Will create 1 file of size 10Gb called jeremy.dmp at C:\temp
.EXAMPLE
New-DummyFile -FilePath C:\temp -Name Jeremy.txt -Size 10 -Number 10 -Gb
Will create 10 files of size 10Gb called jeremy_N.txt where N is 1-10 at C:\temp
.EXAMPLE
New-DummyFile -FilePath C:\temp -Name Jeremy -Size 10 -Force
Will create 1 file of size 10Mb called jeremy.dmp at C:\temp and overwrite the exisitng file if it exists
.NOTES
SQLDBAWithABeard @SqlDbaWithABeard
#>
function New-DummyFile {
[CmdletBinding(SupportsShouldProcess)]
Param (
[Parameter(Mandatory = $true)]
[string]$FilePath,
[string]$Name = 'DummyFile',
[Parameter(Mandatory = $true)]
[int]$Size,
[int]$Number = 1,
[Switch]$Gb ,
[switch]$Force
)
Begin {
if ($Gb) {
$SizeMsg = "$Size Gb"
}
else {
$SizeMsg = "$Size Mb"
}
Write-Verbose "Creating $Number files of $SizeMsg named $Name at $FilePath "
$fileSize = $Size * 1024 * 1024
if ($Gb) {
$fileSize = $fileSize * 1024
}
}
Process {
for ($i = 1; $i -le $Number; $i++) {
$BaseName, $extension = $Name.Split('.')
if ($null -eq $extension) { $extension = 'dmp' }
if($i -ne 1){
$FileName = "$FilePath\$($BaseName)_$i.$Extension"
} else{
$FileName = "$FilePath\$($BaseName).$Extension"
}
if (-not $Force) {
if (Test-Path $FileName) {
Write-Warning "Nope I am not creating the file as -Force was not specified and $FileName already exists"
Continue
}
}
if ($PSCmdlet.ShouldProcess("$FilePath", "Creating $FileName ($i/$Number) $FilePath\$FileName")) {
$file = [System.IO.File]::Create($FileName)
$file.SetLength($fileSize)
$file.Close()
}
}
}
End {
Write-Verbose "Done!"
}
}
| SQLDBAWithABeard/Functions | New-DummyFile.ps1 | PowerShell | mit | 3,134 |
function setVersionInfo() {
$assemblyVersion = git describe --abbrev=0 --tags
$assemblyInformationalVersion = git describe --tags --long
(Get-Content .\Chainly\project.json) -replace "1.0.0-*", "$assemblyVersion-" | Out-File .\Chainly\project.json
}
function makeBuildFolder() {
if(Test-Path -Path ".\Chainly\" ){
Remove-Item -Recurse -Force .\Chainly\
}
New-Item -ItemType directory .\Chainly\
robocopy /E ..\Source\chainly\ .\Chainly\ /MIR
copy ..\Source\global.json .\Chainly\
}
function verifyNuget() {
if() {
Throw "Could not find dotnet command"
}
}
function createPackage() {
cd Chainly\
& dotnet pack -c Release
cd..
}
function movePackage() {
move Chainly\bin\Release\*.nupkg .\
}
function cleanup() {
Remove-Item -Recurse -Force .\Chainly\
}
verifyNuget
Write-Host Copying files for build...
makeBuildFolder
Write-Host Setting version info...
setVersionInfo
Write-Host Version info set
Write-Host Creating package...
createPackage
movePackage
Write-Host Package created
Write-Host Cleaning up...
cleanup
Write-Host Done!
| smatsson/Chainly | Tools/build_nuget.ps1 | PowerShell | mit | 1,117 |
<#
.SYNOPSIS
Copy-PhotoRecFilesbyExtension copies all files from the PhotoRec folders to new folders named by file extension.
.DESCRIPTION
Copy-PhotoRecFilesbyExtension uses the file extensions to create folders and then copy in the folder all the files founds with the same extension.
If a file with the same name is found in another folder it's renamed adding (1)...(2) and so on and then copied, to keep all the versions as default.
To keep only one version set the parameter OverWriteDuplicated to $True.
IMPORTANT: *** THIS SCRIPT IS PROVIDED WITHOUT WARRANTY, USE AT YOUR OWN RISK ***
.PARAMETER RootPhotoRec
The Root folder used by PhotoRec to store recovered files
.PARAMETER RootDestFolder
The Root folder where new folders and files will be created and copied.
.PARAMETER OverWriteDuplicated
To Overwrite any recurring file with the same name in the same destination folder. Only the last copied is keep.
By default OverWriteDuplicated is set to False.
.PARAMETER CustomFileFilter
Is possible to set a filter to reorganize only a type of file. The filter must start with a * such as *jpg
.EXAMPLE
Copy-PhotoRecFilesbyExtension -RootPhotoRecFolder G:\PhotoRec\* -RootDestinationFolder H:\PhotoOrderedbyExtension
.EXAMPLE
Copy-PhotoRecFilesbyExtension -RootPhotoRecFolder G:\PhotoRec\* -RootDestinationFolder H:\PhotoOrderedbyExtension -OverWriteDuplicated $True
Any file found in the destination folder with the same name is overwritten
.EXAMPLE
Copy-PhotoRecFilesbyExtension -RootPhotoRecFolder G:\PhotoRec\* -RootDestinationFolder H:\PhotoOrderedbyExtension -CustomFileFilter *mp3
In this example only MP3 files will be copied from the source folder to the destination. By default any file type is copied and reorganized.
.EXAMPLE
Copy-PhotoRecFilesbyExtension -RootPhotoRecFolder G:\PhotoRec\* -RootDestinationFolder H:\PhotoOrderedbyExtension -CustomFileFilter "*mp4","*avi"
In this example only MP4 and AVI files will be copied from the source folder to the destination. Enclose with double quote and separate with a comma any extension required; don't forget the *.
.LINK
http://www.powershellacademy.it/scripts
.NOTES
Written by: Luca Conte
Find me on:
* Website: http://lucaconte.it
* Twitter: http://twitter.com/desmox796
* Memrise: http://www.memrise.com/user/desmox/courses/teaching/
* MyBlog: http://desmox796.wordpress.com
IMPORTANT: *** THIS SCRIPT IS PROVIDED WITHOUT WARRANTY, USE AT YOUR OWN RISK ***
License:
The MIT License (MIT)
Copyright (c) 2016 Luca Conte
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$True,HelpMessage="Enter the Source PhotoRec Source Folder")]
[String]$RootPhotoRec,
[Parameter(Mandatory=$True,HelpMessage="Enter the Destination Folder where your data will be reorganized")]
[String]$RootDestFolder,
[bool]$OverWriteDuplicated=$False,
[String[]]$CustomFileFilter="*"
)
Clear-Host
#How many PhotoRec folders have to be analyzed?
$NrFolderToAnalyze=(Get-ChildItem -Path $RootPhotoRec -Directory).Count
# Write-Host "Found $NrFolderToAnalyze folder to Analyze!"
$FolderCounter=0
Get-ChildItem -Path $RootPhotoRec -Directory | foreach {
$FolderSource = $_.FullName
$FolderCounter++
$PercProgress=[int]($FolderCounter/$NrFolderToAnalyze*100)
Write-Progress -id 1 -Activity "Working on PhotoRec folders..." -CurrentOperation "($PercProgress%) [$FolderCounter of $NrFolderToAnalyze] Copying from $FolderSource ..." -Status "Please wait." -PercentComplete ($PercProgress) #Show folder Progress
# Write-Host "Found $NrFileToAnalyze files to analyze"
$PathToAnalyze=$_.FullName
if (!($PathToAnalyze.EndsWith("\*"))){
$PathToAnalyze+="\*"
}
$FileCounter=0
$FilesToAnalyze = Get-ChildItem -Path $PathToAnalyze -File -Include $CustomFileFilter
$NrFileToAnalyze= $FilesToAnalyze.Count
# Get-ChildItem -Path $PathToAnalyze -File -Include $CustomFileFilter
$FilesToAnalyze | foreach {
$fileSource = $_.FullName # G:\_photorec\recup_dir.10\f109643736.jpg
$fileName = (Get-Item $fileSource).BaseName #f109643736
$fileExt = (Get-Item $fileSource).Extension #.jpg
$FolderDest = Join-Path -Path $RootdestFolder -ChildPath $fileExt # G:\_PhotoRecOrg\.jpg
$fileDest = Join-Path -Path $FolderDest -ChildPath $fileName$fileExt # G:\_PhotoRecOrg\.jpg\f109643736.jpg
if(!(Test-Path -Path $FolderDest )) # Setup a new folder if missing
{
new-item -ItemType Directory -Path $FolderDest
Write-Host #Echo
}
$trigger = $false
$counter = 1
if (!($OverWriteDuplicated)) {
Do {
If (!(Test-Path -Path $fileDest)) { # G:\_PhotoRecOrg\.jpg\f109643736.jpg check if a file with the same name NOT exist in the destination folder
$trigger = $true
} Else { # Otherwise rename the source file as (1) ... (2) and so on to keep all the versions
$fileNameNew = "$fileName{0}" -f "("+$counter+")" # f109643736(1)
$fileDest = Join-Path -Path $FolderDest -ChildPath "$fileNameNew$fileExt" # G:\_PhotoRecOrg\.jpg\f109643736(1).jpg
$counter++
}
} Until ($trigger)
}
$FileCounter++
$PercFileProgress=[int]($FileCounter/$NrFileToAnalyze*100)
Write-Progress -id 2 -ParentId 1 -Activity "Working on $CustomFileFilter Files (Overwrite =$OverWriteDuplicated)..." -CurrentOperation "($PercFileProgress%) [$FileCounter of $NrFileToAnalyze] - Copying file $Filename to $FolderDest" -Status "Please wait." -PercentComplete ($PercFileProgress) # progress of the file copy
Copy-Item -Path $fileSource -Destination $fileDest # Copy
}
}
| lconte/Copy-PhotoRecFilesbyExtension.ps1 | Copy-PhotoRecFilesbyExtension.ps1 | PowerShell | mit | 6,850 |
function push-nuget() {
$SOLUTION_DIR = Resolve-Path "."
$ARTIFACTS = Join-Path $SOLUTION_DIR "artifacts/nuget"
$NUGET_API_KEY = $env:NUGET_API_KEY
if (!$NUGET_API_KEY) {
Write-Host "`$NUGET_API_KEY is not set" -f yellow
return
}
Get-ChildItem -Path $ARTIFACTS -Filter *.nupkg -File | % {
$package = $_.FullName
Write-Host "Pushing package $package"
& dotnet nuget push --api-key $NUGET_API_KEY --force-english-output -s https://www.nuget.org/api/v2/package $package
if ($LASTEXITCODE -ne 0) {
Write-Host "'dotnet nuget push' exited with $LASTEXITCODE"
exit 1
}
}
}
function push-choco() {
$SOLUTION_DIR = Resolve-Path "."
$ARTIFACTS = Join-Path $SOLUTION_DIR "artifacts/choco"
$VERSION = $env:MARKDOCS_BUILD_VERSION
if (!$VERSION) {
$VERSION = "0.0.0-dev"
}
$package = "markdocs.$VERSION.nupkg"
$path = Join-Path $ARTIFACTS $package
if (-not (Test-Path $path)) {
Write-Host "Package file `"$path`" doesn't exist"
exit 1
}
function push-once($url, $apiKey, $isEnabled, $type) {
if (-not ([string]::IsNullOrEmpty($url)) -and -not ([string]::IsNullOrEmpty($apiKey)) -and ([int]$isEnabled -ne 0)) {
Write-host "Pushing package $package to $type..."
choco push $path --apikey=$apiKey -v --source="$url"
if ($LASTEXITCODE -ne 0) {
Write-Host "'choco push' exited with $LASTEXITCODE"
exit 1
}
Write-Host "Success"
}
else {
Write-host "Won't push package to $type"
}
}
# push-once "https://push.chocolatey.org/" $env:CHOCO_API_KEY $env:CHOCO_PUSH_PUBLIC "chocolatey.org"
push-once $env:CHOCO_PRIVATE_URL $env:CHOCO_PRIVATE_API_KEY $env:CHOCO_PUSH_PRIVATE "private chocolatey feed"
}
function push-usage() {
write-host "USAGE:"
write-host " ./push.ps1 [<command>]"
write-host "COMMANDS:"
write-host " nuget - publish NuGet packages"
write-host " choco - publish CLI tools"
write-host " all - publish everything"
write-host " -?|-h|--help|help"
}
if ($args.Length -gt 0) {
switch ($args[0]) {
"nuget" { push-nuget }
"choco" { push-choco }
"all" {
push-nuget
push-choco
}
"-?" { push-usage }
"-h" { push-usage }
"--help" { push-usage }
"help" { push-usage }
Default {
write-host "Invalid arguments: `"$args`"" -f red
write-host "Type `"./push.ps1 --help`" to get help"
exit 1
}
}
}
else {
write-host "Type `"./push.ps1 --help`" to get help"
exit 1
} | ITGlobal/MarkDocs | push.ps1 | PowerShell | mit | 2,818 |
#Requires -Version 3.0
<#
Get-SPClientContentType.ps1
Copyright (c) 2017 karamem0
This software is released under the MIT License.
https://github.com/karamem0/SPClient/blob/master/LICENSE
#>
function Get-SPClientContentType {
<#
.SYNOPSIS
Gets one or more content types.
.DESCRIPTION
The Get-SPClientContentType function lists all content types or retrieves the specified content type.
If not specified filterable parameter, returns all content types of the site or list.
Otherwise, returns a content type which matches the parameter.
.PARAMETER ClientContext
Indicates the client context. If not specified, uses a default context.
.PARAMETER ParentObject
Indicates the site or list which the content types are contained.
.PARAMETER NoEnumerate
If specified, suppresses enumeration in output.
.PARAMETER Identity
Indicates the content type ID.
.PARAMETER Name
Indicates the content type name.
.PARAMETER Retrieval
Indicates the data retrieval expression.
.EXAMPLE
Get-SPClientContentType $web
.EXAMPLE
Get-SPClientContentType $web -Identity "0X01009BD26CA6BE114008A9D56E68022DD1A7"
.EXAMPLE
Get-SPClientContentType $web -Name "Custom Content Type"
.EXAMPLE
Get-SPClientContentType $web -Retrieval "Title"
.INPUTS
None or SPClient.SPClientContentTypeParentPipeBind
.OUTPUTS
Microsoft.SharePoint.Client.ContentType[]
.LINK
https://github.com/karamem0/SPClient/blob/master/doc/Get-SPClientContentType.md
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param (
[Parameter(Mandatory = $false)]
[Microsoft.SharePoint.Client.ClientContext]
$ClientContext = $SPClient.ClientContext,
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[SPClient.SPClientContentTypeParentPipeBind]
$ParentObject,
[Parameter(Mandatory = $false, ParameterSetName = 'All')]
[switch]
$NoEnumerate,
[Parameter(Mandatory = $true, ParameterSetName = 'Identity')]
[Alias('Id')]
[string]
$Identity,
[Parameter(Mandatory = $true, ParameterSetName = 'Name')]
[string]
$Name,
[Parameter(Mandatory = $false)]
[string]
$Retrieval
)
process {
if ($ClientContext -eq $null) {
throw "Cannot bind argument to parameter 'ClientContext' because it is null."
}
$ClientObjectCollection = $ParentObject.ClientObject.ContentTypes
if ($PSCmdlet.ParameterSetName -eq 'All') {
Invoke-ClientContextLoad `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrieval $Retrieval
Write-Output $ClientObjectCollection -NoEnumerate:$NoEnumerate
}
if ($PSCmdlet.ParameterSetName -eq 'Identity') {
$PathMethod = New-Object Microsoft.SharePoint.Client.ObjectPathMethod( `
$ClientContext, `
$ClientObjectCollection.Path, `
'GetById', `
[object[]]$Identity)
$ClientObject = New-Object Microsoft.SharePoint.Client.ContentType($ClientContext, $PathMethod)
Invoke-ClientContextLoad `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrieval $Retrieval
if ($ClientObject.Id -eq $null) {
throw 'The specified content type could not be found.'
}
Write-Output $ClientObject
}
if ($PSCmdlet.ParameterSetName -eq 'Name') {
Invoke-ClientContextLoad `
-ClientContext $ClientContext `
-ClientObject $ClientObjectCollection `
-Retrieval 'Include(Name)'
$ClientObject = $ClientObjectCollection | Where-Object { $_.Name -eq $Name }
if ($ClientObject -eq $null) {
throw 'The specified content type could not be found.'
}
Invoke-ClientContextLoad `
-ClientContext $ClientContext `
-ClientObject $ClientObject `
-Retrieval $Retrieval
Write-Output $ClientObject
}
}
}
| karamem0/SPClient | source/SPClient/functions/SPClientContentType/Get-SPClientContentType.ps1 | PowerShell | mit | 4,212 |
param([bool]$nuget=$false)
$root = Split-Path -Parent $PSCommandPath
Push-Location $root
Get-ChildItem *.nupkg | Remove-Item
.\nuget.exe pack .\Framework.Shared\OmniBus.Framework.Shared.csproj -Build -Symbols -IncludeReferencedProjects -ForceEnglishOutput -Properties Configuration=Release
.\nuget.exe pack .\Framework\OmniBus.Framework.csproj -Build -Symbols -IncludeReferencedProjects -ForceEnglishOutput -Properties Configuration=Release
.\nuget.exe pack .\Framework.GUI\OmniBus.Framework.GUI.csproj -Build -Symbols -IncludeReferencedProjects -ForceEnglishOutput -Properties Configuration=Release
if ($nuget -eq $true) {
Get-ChildItem *.nupkg | Where-Object { $_.Name -notmatch ".*\.symbols\.nupkg" } | foreach-object { & .\nuget.exe push $_.FullName -Source https://www.nuget.org/api/v2/package }
}
if ((Get-ChildItem . -Filter "TempPackages") -ne $null) {
Get-ChildItem *.nupkg | Move-Item -Destination ./TempPackages -Force
}
Pop-Location | jdunkerley/AlteryxAddIns | PublishFrameworkToNuGet.ps1 | PowerShell | mit | 954 |
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" -Name PagingFiles -Value "" | dschelchkov/windows-imaging | scripts/Delete-Pagefile.ps1 | PowerShell | apache-2.0 | 125 |
function Add-VSOpsWorksInstanceEbsBlockDevice {
<#
.SYNOPSIS
Adds an AWS::OpsWorks::Instance.EbsBlockDevice resource property to the template. Describes an Amazon EBS volume. This data type maps directly to the Amazon EC2 EbsBlockDevice: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html data type.
.DESCRIPTION
Adds an AWS::OpsWorks::Instance.EbsBlockDevice resource property to the template.
Describes an Amazon EBS volume. This data type maps directly to the Amazon EC2 EbsBlockDevice: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html data type.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html
.PARAMETER DeleteOnTermination
Whether the volume is deleted on instance termination.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-deleteontermination
PrimitiveType: Boolean
UpdateType: Mutable
.PARAMETER Iops
The number of I/O operations per second IOPS that the volume supports. For more information, see EbsBlockDevice: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-iops
PrimitiveType: Integer
UpdateType: Mutable
.PARAMETER SnapshotId
The snapshot ID.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-snapshotid
PrimitiveType: String
UpdateType: Mutable
.PARAMETER VolumeSize
The volume size, in GiB. For more information, see EbsBlockDevice: https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_EbsBlockDevice.html.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-volumesize
PrimitiveType: Integer
UpdateType: Mutable
.PARAMETER VolumeType
The volume type. gp2 for General Purpose SSD volumes, io1 for Provisioned IOPS SSD volumes, st1 for Throughput Optimized hard disk drives HDD, sc1 for Cold HDD,and standard for Magnetic volumes.
If you specify the io1 volume type, you must also specify a value for the Iops attribute. The maximum ratio of provisioned IOPS to requested volume size in GiB is 50:1. AWS uses the default volume size in GiB specified in the AMI attributes to set IOPS to 50 x volume size.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-volumetype
PrimitiveType: String
UpdateType: Mutable
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.OpsWorks.Instance.EbsBlockDevice')]
[cmdletbinding()]
Param
(
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Boolean","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$DeleteOnTermination,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Int32","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$Iops,
[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 ", ")."))
}
})]
$SnapshotId,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Int32","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$VolumeSize,
[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 ", ")."))
}
})]
$VolumeType
)
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.OpsWorks.Instance.EbsBlockDevice'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$($obj | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Property Types/Add-VSOpsWorksInstanceEbsBlockDevice.ps1 | PowerShell | apache-2.0 | 7,092 |
function New-VSDocDBDBCluster {
<#
.SYNOPSIS
Adds an AWS::DocDB::DBCluster resource to the template. The AWS::DocDB::DBCluster Amazon DocumentDB (with MongoDB compatibility resource describes a DBCluster. Amazon DocumentDB is a fully managed, MongoDB-compatible document database engine. For more information, see DBCluster: https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DBCluster.html in the *Amazon DocumentDB Developer Guide*.
.DESCRIPTION
Adds an AWS::DocDB::DBCluster resource to the template. The AWS::DocDB::DBCluster Amazon DocumentDB (with MongoDB compatibility resource describes a DBCluster. Amazon DocumentDB is a fully managed, MongoDB-compatible document database engine. For more information, see DBCluster: https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DBCluster.html in the *Amazon DocumentDB Developer Guide*.
.LINK
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html
.PARAMETER LogicalId
The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template. Use the logical name to reference the resource in other parts of the template. For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance.
.PARAMETER StorageEncrypted
Specifies whether the cluster is encrypted.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-storageencrypted
PrimitiveType: Boolean
UpdateType: Immutable
.PARAMETER EngineVersion
The version number of the database engine to use.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-engineversion
PrimitiveType: String
UpdateType: Immutable
.PARAMETER KmsKeyId
The AWS KMS key identifier for an encrypted cluster.
The AWS KMS key identifier is the Amazon Resource Name ARN for the AWS KMS encryption key. If you are creating a cluster using the same AWS account that owns the AWS KMS encryption key that is used to encrypt the new cluster, you can use the AWS KMS key alias instead of the ARN for the AWS KMS encryption key.
If an encryption key is not specified in KmsKeyId:
+ If ReplicationSourceIdentifier identifies an encrypted source, then Amazon DocumentDB uses the encryption key that is used to encrypt the source. Otherwise, Amazon DocumentDB uses your default encryption key.
+ If the StorageEncrypted parameter is true and ReplicationSourceIdentifier is not specified, Amazon DocumentDB uses your default encryption key.
AWS KMS creates the default encryption key for your AWS account. Your AWS account has a different default encryption key for each AWS Region.
If you create a replica of an encrypted cluster in another AWS Region, you must set KmsKeyId to a KMS key ID that is valid in the destination AWS Region. This key is used to encrypt the replica in that AWS Region.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-kmskeyid
PrimitiveType: String
UpdateType: Immutable
.PARAMETER AvailabilityZones
A list of Amazon EC2 Availability Zones that instances in the cluster can be created in.
PrimitiveItemType: String
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-availabilityzones
UpdateType: Immutable
.PARAMETER SnapshotIdentifier
The identifier for the snapshot or cluster snapshot to restore from.
You can use either the name or the Amazon Resource Name ARN to specify a cluster snapshot. However, you can use only the ARN to specify a snapshot.
Constraints:
+ Must match the identifier of an existing snapshot.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-snapshotidentifier
PrimitiveType: String
UpdateType: Immutable
.PARAMETER Port
Specifies the port that the database engine is listening on.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-port
PrimitiveType: Integer
UpdateType: Mutable
.PARAMETER DBClusterIdentifier
The cluster identifier. This parameter is stored as a lowercase string.
Constraints:
+ Must contain from 1 to 63 letters, numbers, or hyphens.
+ The first character must be a letter.
+ Cannot end with a hyphen or contain two consecutive hyphens.
Example: my-cluster
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-dbclusteridentifier
PrimitiveType: String
UpdateType: Immutable
.PARAMETER PreferredMaintenanceWindow
The weekly time range during which system maintenance can occur, in Universal Coordinated Time UTC.
Format: ddd:hh24:mi-ddd:hh24:mi
The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region, occurring on a random day of the week.
Valid days: Mon, Tue, Wed, Thu, Fri, Sat, Sun
Constraints: Minimum 30-minute window.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-preferredmaintenancewindow
PrimitiveType: String
UpdateType: Mutable
.PARAMETER DBSubnetGroupName
A subnet group to associate with this cluster.
Constraints: Must match the name of an existing DBSubnetGroup. Must not be default.
Example: mySubnetgroup
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-dbsubnetgroupname
PrimitiveType: String
UpdateType: Immutable
.PARAMETER DeletionProtection
Protects clusters from being accidentally deleted. If enabled, the cluster cannot be deleted unless it is modified and DeletionProtection is disabled.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-deletionprotection
PrimitiveType: Boolean
UpdateType: Mutable
.PARAMETER PreferredBackupWindow
The daily time range during which automated backups are created if automated backups are enabled using the BackupRetentionPeriod parameter.
The default is a 30-minute window selected at random from an 8-hour block of time for each AWS Region.
Constraints:
+ Must be in the format hh24:mi-hh24:mi.
+ Must be in Universal Coordinated Time UTC.
+ Must not conflict with the preferred maintenance window.
+ Must be at least 30 minutes.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-preferredbackupwindow
PrimitiveType: String
UpdateType: Mutable
.PARAMETER MasterUserPassword
The password for the master database user. This password can contain any printable ASCII character except forward slash /, double quote ", or the "at" symbol @.
Constraints: Must contain from 8 to 100 characters.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-masteruserpassword
PrimitiveType: String
UpdateType: Mutable
.PARAMETER VpcSecurityGroupIds
A list of EC2 VPC security groups to associate with this cluster.
PrimitiveItemType: String
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-vpcsecuritygroupids
UpdateType: Mutable
.PARAMETER MasterUsername
The name of the master user for the cluster.
Constraints:
+ Must be from 1 to 63 letters or numbers.
+ The first character must be a letter.
+ Cannot be a reserved word for the chosen database engine.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-masterusername
PrimitiveType: String
UpdateType: Immutable
.PARAMETER DBClusterParameterGroupName
The name of the cluster parameter group to associate with this cluster.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-dbclusterparametergroupname
PrimitiveType: String
UpdateType: Mutable
.PARAMETER BackupRetentionPeriod
The number of days for which automated backups are retained. You must specify a minimum value of 1.
Default: 1
Constraints:
+ Must be a value from 1 to 35.
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-backupretentionperiod
PrimitiveType: Integer
UpdateType: Mutable
.PARAMETER Tags
The tags to be assigned to the cluster.
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-tags
ItemType: Tag
UpdateType: Mutable
.PARAMETER EnableCloudwatchLogsExports
A list of log types that need to be enabled for exporting to Amazon CloudWatch Logs.
PrimitiveItemType: String
Type: List
Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-docdb-dbcluster.html#cfn-docdb-dbcluster-enablecloudwatchlogsexports
UpdateType: Mutable
.PARAMETER DeletionPolicy
With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted. You specify a DeletionPolicy attribute for each resource that you want to control. If a resource has no DeletionPolicy attribute, AWS CloudFormation deletes the resource by default.
To keep a resource when its stack is deleted, specify Retain for that resource. You can use retain for any resource. For example, you can retain a nested stack, S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks.
You must use one of the following options: "Delete","Retain","Snapshot"
.PARAMETER UpdateReplacePolicy
Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation.
When you initiate a stack update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template and parameters. If you update a resource property that requires that the resource be replaced, AWS CloudFormation recreates the resource during the update. Recreating the resource generates a new physical ID. AWS CloudFormation creates the replacement resource first, and then changes references from other dependent resources to point to the replacement resource. By default, AWS CloudFormation then deletes the old resource. Using the UpdateReplacePolicy, you can specify that AWS CloudFormation retain or (in some cases) create a snapshot of the old resource.
For resources that support snapshots, such as AWS::EC2::Volume, specify Snapshot to have AWS CloudFormation create a snapshot before deleting the old resource instance.
You can apply the UpdateReplacePolicy attribute to any resource. UpdateReplacePolicy is only executed if you update a resource property whose update behavior is specified as Replacement, thereby causing AWS CloudFormation to replace the old resource with a new one with a new physical ID. For example, if you update the Engine property of an AWS::RDS::DBInstance resource type, AWS CloudFormation creates a new resource and replaces the current DB instance resource with the new one. The UpdateReplacePolicy attribute would then dictate whether AWS CloudFormation deleted, retained, or created a snapshot of the old DB instance. The update behavior for each property of a resource is specified in the reference topic for that resource in the AWS Resource and Property Types Reference. For more information on resource update behavior, see Update Behaviors of Stack Resources.
The UpdateReplacePolicy attribute applies to stack updates you perform directly, as well as stack updates performed using change sets.
Note
Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources. Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots. UpdateReplacePolicy retains the old physical resource or snapshot, but removes it from AWS CloudFormation's scope.
UpdateReplacePolicy differs from the DeletionPolicy attribute in that it only applies to resources replaced during stack updates. Use DeletionPolicy for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update.
You must use one of the following options: "Delete","Retain","Snapshot"
.PARAMETER DependsOn
With the DependsOn attribute you can specify that the creation of a specific resource follows another. When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute.
This parameter takes a string or list of strings representing Logical IDs of resources that must be created prior to this resource being created.
.PARAMETER Metadata
The Metadata attribute enables you to associate structured data with a resource. By adding a Metadata attribute to a resource, you can add data in JSON or YAML to the resource declaration. In addition, you can use intrinsic functions (such as GetAtt and Ref), parameters, and pseudo parameters within the Metadata attribute to add those interpreted values.
You must use a PSCustomObject containing key/value pairs here. This will be returned when describing the resource using AWS CLI.
.PARAMETER UpdatePolicy
Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource. AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group.
You must use the "Add-UpdatePolicy" function here.
.PARAMETER Condition
Logical ID of the condition that this resource needs to be true in order for this resource to be provisioned.
.FUNCTIONALITY
Vaporshell
#>
[OutputType('Vaporshell.Resource.DocDB.DBCluster')]
[cmdletbinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword","MasterUserPassword")]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingUserNameAndPasswordParams","MasterUserPassword")]
Param
(
[parameter(Mandatory = $true,Position = 0)]
[ValidateScript( {
if ($_ -match "^[a-zA-Z0-9]*$") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String 'The LogicalID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.'))
}
})]
[System.String]
$LogicalId,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Boolean","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$StorageEncrypted,
[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 ", ")."))
}
})]
$EngineVersion,
[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 ", ")."))
}
})]
$KmsKeyId,
[parameter(Mandatory = $false)]
$AvailabilityZones,
[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 ", ")."))
}
})]
$SnapshotIdentifier,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Int32","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$Port,
[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 ", ")."))
}
})]
$DBClusterIdentifier,
[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 ", ")."))
}
})]
$PreferredMaintenanceWindow,
[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 ", ")."))
}
})]
$DBSubnetGroupName,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Boolean","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$DeletionProtection,
[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 ", ")."))
}
})]
$PreferredBackupWindow,
[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 ", ")."))
}
})]
$MasterUserPassword,
[parameter(Mandatory = $false)]
$VpcSecurityGroupIds,
[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 ", ")."))
}
})]
$MasterUsername,
[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 ", ")."))
}
})]
$DBClusterParameterGroupName,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Int32","Vaporshell.Function"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$BackupRetentionPeriod,
[VaporShell.Core.TransformTag()]
[parameter(Mandatory = $false)]
$Tags,
[parameter(Mandatory = $false)]
$EnableCloudwatchLogsExports,
[ValidateSet("Delete","Retain","Snapshot")]
[System.String]
$DeletionPolicy,
[ValidateSet("Delete","Retain","Snapshot")]
[System.String]
$UpdateReplacePolicy,
[parameter(Mandatory = $false)]
[System.String[]]
$DependsOn,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "System.Management.Automation.PSCustomObject"
if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") {
$true
}
else {
$PSCmdlet.ThrowTerminatingError((New-VSError -String "The UpdatePolicy parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ")."))
}
})]
$Metadata,
[parameter(Mandatory = $false)]
[ValidateScript( {
$allowedTypes = "Vaporshell.Resource.UpdatePolicy"
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 ", ")."))
}
})]
$UpdatePolicy,
[parameter(Mandatory = $false)]
$Condition
)
Begin {
$ResourceParams = @{
LogicalId = $LogicalId
Type = "AWS::DocDB::DBCluster"
}
$commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable')
}
Process {
foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) {
switch ($key) {
LogicalId {}
DeletionPolicy {
$ResourceParams.Add("DeletionPolicy",$DeletionPolicy)
}
UpdateReplacePolicy {
$ResourceParams.Add("UpdateReplacePolicy",$UpdateReplacePolicy)
}
DependsOn {
$ResourceParams.Add("DependsOn",$DependsOn)
}
Metadata {
$ResourceParams.Add("Metadata",$Metadata)
}
UpdatePolicy {
$ResourceParams.Add("UpdatePolicy",$UpdatePolicy)
}
Condition {
$ResourceParams.Add("Condition",$Condition)
}
AvailabilityZones {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name AvailabilityZones -Value @($AvailabilityZones)
}
VpcSecurityGroupIds {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name VpcSecurityGroupIds -Value @($VpcSecurityGroupIds)
}
Tags {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name Tags -Value @($Tags)
}
EnableCloudwatchLogsExports {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name EnableCloudwatchLogsExports -Value @($EnableCloudwatchLogsExports)
}
Default {
if (!($ResourceParams["Properties"])) {
$ResourceParams.Add("Properties",([PSCustomObject]@{}))
}
$ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters[$key]
}
}
}
}
End {
$obj = New-VaporResource @ResourceParams
$obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.DocDB.DBCluster'
Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5)`n"
}
}
| scrthq/Vaporshell | VaporShell/Public/Resource Types/New-VSDocDBDBCluster.ps1 | PowerShell | apache-2.0 | 29,904 |
configuration XD7LabStorefrontHttps {
param (
## Citrix XenDesktop installation source root
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.String] $XenDesktopMediaPath,
## Pfx certificate thumbprint
[Parameter(Mandatory)]
[System.String] $PfxCertificateThumbprint,
## XenDesktop controller address for Director connectivity
[Parameter(Mandatory)]
[System.String[]] $ControllerAddress,
## Pfx certificate password
[Parameter()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.CredentialAttribute()]
$PfxCertificateCredential,
## Personal information exchange (Pfx) ertificate file path
[Parameter()]
[System.String] $PfxCertificatePath
)
Import-DscResource -ModuleName PSDesiredStateConfiguration, XenDesktop7, xWebAdministration, xCertificate;
$features = @(
'NET-Framework-45-ASPNET',
'Web-Server',
'Web-Common-Http',
'Web-Default-Doc',
'Web-Http-Errors',
'Web-Static-Content',
'Web-Http-Redirect',
'Web-Http-Logging',
'Web-Filtering',
'Web-Basic-Auth',
'Web-Client-Auth',
'Web-Windows-Auth',
'Web-Net-Ext45',
'Web-AppInit',
'Web-Asp-Net45',
'Web-ISAPI-Ext',
'Web-ISAPI-Filter',
'Web-Mgmt-Console',
'Web-Scripting-Tools'
)
foreach ($feature in $features) {
WindowsFeature $feature {
Name = $feature;
Ensure = 'Present';
}
}
XD7Feature 'XD7StoreFront' {
Role = 'Storefront';
SourcePath = $XenDesktopMediaPath;
DependsOn = '[WindowsFeature]Web-Server';
}
XD7Feature 'XD7Director' {
Role = 'Director';
SourcePath = $XenDesktopMediaPath;
DependsOn = '[WindowsFeature]Web-Server';
}
foreach ($controller in $ControllerAddress) {
xWebConfigKeyValue "ServiceAutoDiscovery_$controller" {
ConfigSection = 'AppSettings';
Key = 'Service.AutoDiscoveryAddresses';
Value = $controller;
IsAttribute = $false;
WebsitePath = 'IIS:\Sites\Default Web Site\Director';
DependsOn = '[WindowsFeature]Web-Server','[XD7Feature]XD7Director';
}
}
$xWebSiteDependsOn = @('[WindowsFeature]Web-Server');
if (($PSBoundParameters.ContainsKey('PfxCertificatePath')) -or
($PSBoundParameters.ContainsKey('PfxCertificateCredential'))) {
xPfxImport 'PfxCertificate' {
Thumbprint = $PfxCertificateThumbprint;
Location = 'LocalMachine';
Store = 'My';
Path = $PfxCertificatePath;
Credential = $PfxCertificateCredential;
}
$xWebSiteDependsOn += '[xPfxImport]PfxCertificate';
}
xWebSite 'DefaultWebSite' {
Name = 'Default Web Site';
PhysicalPath = 'C:\inetpub\wwwroot';
BindingInfo = @(
MSFT_xWebBindingInformation { Protocol = 'HTTPS'; Port = 443; CertificateThumbprint = $PfxCertificateThumbprint; CertificateStoreName = 'My'; }
MSFT_xWebBindingInformation { Protocol = 'HTTP'; Port = 80; }
)
DependsOn = $xWebSiteDependsOn;
}
} #end configuration XD7LabStorefrontHttps
| VirtualEngine/CitrixXenDesktop7Lab | DSCResources/XD7LabStorefrontHttps/XD7LabStorefrontHttps.schema.psm1 | PowerShell | mit | 3,495 |
<#
# Copyright (c) 2014 All Rights Reserved by the SDL Group.
#
# 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.
#>
#
# Module manifest for module 'SDLDevTools'
#
# Generated by: SDL plc
#
# Generated on: 2/2/2017
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'SDLDevTools.psm1'
# Version number of this module.
ModuleVersion = '0.3'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '02ce33ce-a397-46fe-8610-131a2a991616'
# Author of this module
Author = 'SDL plc'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = 'SDL plc'
# Description of the functionality provided by this module
Description = 'SDL Development automation module'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# 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 = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Get-SDLOpenSourceHeader', 'Get-SDLOpenSourceHeaderFormat',
'Set-SDLOpenSourceHeader', 'Test-SDLOpenSourceHeader'
# 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-SDLOpenSourceHeader', 'Get-SDLOpenSourceHeaderFormat',
'Set-SDLOpenSourceHeader', 'Test-SDLOpenSourceHeader'
# 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 = @()
# A URL to the license for this module.
LicenseUri = 'https://stash.sdl.com/users/asarafian/repos/sdldevtools/browse/LICENSE.TXT'
# A URL to the main website for this project.
ProjectUri = 'https://stash.sdl.com/users/asarafian/repos/sdldevtools/'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'https://stash.sdl.com/users/asarafian/repos/sdldevtools/browse/CHANGELOG.md'
} # 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 = ''
}
| beutepa/ISHBootstrap | Automation/Modules/SDLDevTools/0.3/SDLDevTools.psd1 | PowerShell | apache-2.0 | 4,817 |
<#
.SYNOPSIS
Get-AMInfectionStatusStack.ps1
Returns frequency count of the following fields:
ComputerStatus, CriticallyFailedDetections, PendingFullScan,
PendingManualSteps, PendingOfflineScan, PendingReboot,
RecentlyCleanedDetections, SchemaVersion
Requires:
Process data matching *AMInfectionStatus.tsv in pwd logparser.exe in path
.NOTES
DATADIR AMHealthStatus
#>
if (Get-Command logparser.exe) {
$lpquery = @"
SELECT count (
ComputerStatus,
CriticallyFailedDetections,
PendingFullScan,
PendingManualSteps,
PendingOfflineScan,
PendingReboot,
RecentlyCleanedDetections,
SchemaVersion) AS cnt,
ComputerStatus,
CriticallyFailedDetections,
PendingFullScan,
PendingManualSteps,
PendingOfflineScan,
PendingReboot,
RecentlyCleanedDetections,
SchemaVersion
FROM
*AMInfectionStatus.tsv
GROUP BY
ComputerStatus,
CriticallyFailedDetections,
PendingFullScan,
PendingManualSteps,
PendingOfflineScan,
PendingReboot,
RecentlyCleanedDetections,
SchemaVersion
ORDER BY
CNT ASC
"@
& logparser -stats:off -i:csv -dtlines:0 -fixedsep:on -rtp:-1 "$lpquery"
} else {
$ScriptName = [System.IO.Path]::GetFileName($MyInvocation.ScriptName)
"${ScriptName} requires logparser.exe in the path."
}
| jvaldezjr1/Kansa | Analysis/config/Get-AMInfectionStatus.ps1 | PowerShell | apache-2.0 | 1,440 |
###
# ==++==
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
#
###
<#
Overrides the default Write-Debug so that the output gets routed back thru the
$request.Debug() function
#>
function Write-Debug {
param(
[Parameter(Mandatory=$true)][string] $message,
[parameter(ValueFromRemainingArguments=$true)]
[object[]]
$args= @()
)
if( -not $request ) {
if( -not $args ) {
Microsoft.PowerShell.Utility\write-verbose $message
return
}
$msg = [system.string]::format($message, $args)
Microsoft.PowerShell.Utility\write-verbose $msg
return
}
if( -not $args ) {
$null = $request.Debug($message);
return
}
$null = $request.Debug($message,$args);
}
function Write-Error {
param(
[Parameter(Mandatory=$true)][string] $Message,
[Parameter()][string] $Category,
[Parameter()][string] $ErrorId,
[Parameter()][string] $TargetObject
)
$null = $request.Warning($Message);
}
<#
Overrides the default Write-Verbose so that the output gets routed back thru the
$request.Verbose() function
#>
function Write-Progress {
param(
[CmdletBinding()]
[Parameter(Position=0)]
[string]
$Activity,
# This parameter is not supported by request object
[Parameter(Position=1)]
[ValidateNotNullOrEmpty()]
[string]
$Status,
[Parameter(Position=2)]
[ValidateRange(0,[int]::MaxValue)]
[int]
$Id,
[Parameter()]
[int]
$PercentComplete=-1,
# This parameter is not supported by request object
[Parameter()]
[int]
$SecondsRemaining=-1,
# This parameter is not supported by request object
[Parameter()]
[string]
$CurrentOperation,
[Parameter()]
[ValidateRange(-1,[int]::MaxValue)]
[int]
$ParentID=-1,
[Parameter()]
[switch]
$Completed,
# This parameter is not supported by request object
[Parameter()]
[int]
$SourceID,
[object[]]
$args= @()
)
$params = @{}
if ($PSBoundParameters.ContainsKey("Activity")) {
$params.Add("Activity", $PSBoundParameters["Activity"])
}
if ($PSBoundParameters.ContainsKey("Status")) {
$params.Add("Status", $PSBoundParameters["Status"])
}
if ($PSBoundParameters.ContainsKey("PercentComplete")) {
$params.Add("PercentComplete", $PSBoundParameters["PercentComplete"])
}
if ($PSBoundParameters.ContainsKey("Id")) {
$params.Add("Id", $PSBoundParameters["Id"])
}
if ($PSBoundParameters.ContainsKey("ParentID")) {
$params.Add("ParentID", $PSBoundParameters["ParentID"])
}
if ($PSBoundParameters.ContainsKey("Completed")) {
$params.Add("Completed", $PSBoundParameters["Completed"])
}
if( -not $request ) {
if( -not $args ) {
Microsoft.PowerShell.Utility\Write-Progress @params
return
}
$params["Activity"] = [system.string]::format($Activity, $args)
Microsoft.PowerShell.Utility\Write-Progress @params
return
}
if( -not $args ) {
$request.Progress($Activity, $Status, $Id, $PercentComplete, $SecondsRemaining, $CurrentOperation, $ParentID, $Completed)
}
}
function Write-Verbose{
param(
[Parameter(Mandatory=$true)][string] $message,
[parameter(ValueFromRemainingArguments=$true)]
[object[]]
$args= @()
)
if( -not $request ) {
if( -not $args ) {
Microsoft.PowerShell.Utility\write-verbose $message
return
}
$msg = [system.string]::format($message, $args)
Microsoft.PowerShell.Utility\write-verbose $msg
return
}
if( -not $args ) {
$null = $request.Verbose($message);
return
}
$null = $request.Verbose($message,$args);
}
<#
Overrides the default Write-Warning so that the output gets routed back thru the
$request.Warning() function
#>
function Write-Warning{
param(
[Parameter(Mandatory=$true)][string] $message,
[parameter(ValueFromRemainingArguments=$true)]
[object[]]
$args= @()
)
if( -not $request ) {
if( -not $args ) {
Microsoft.PowerShell.Utility\write-warning $message
return
}
$msg = [system.string]::format($message, $args)
Microsoft.PowerShell.Utility\write-warning $msg
return
}
if( -not $args ) {
$null = $request.Warning($message);
return
}
$null = $request.Warning($message,$args);
}
<#
Creates a new instance of a PackageSource object
#>
function New-PackageSource {
param(
[Parameter(Mandatory=$true)][string] $name,
[Parameter(Mandatory=$true)][string] $location,
[Parameter(Mandatory=$true)][bool] $trusted,
[Parameter(Mandatory=$true)][bool] $registered,
[bool] $valid = $false,
[System.Collections.Hashtable] $details = $null
)
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.PackageSource -ArgumentList $name,$location,$trusted,$registered,$valid,$details
}
<#
Creates a new instance of a SoftwareIdentity object
#>
function New-SoftwareIdentity {
param(
[Parameter(Mandatory=$true)][string] $fastPackageReference,
[Parameter(Mandatory=$true)][string] $name,
[Parameter(Mandatory=$true)][string] $version,
[Parameter(Mandatory=$true)][string] $versionScheme,
[Parameter(Mandatory=$true)][string] $source,
[string] $summary,
[string] $searchKey = $null,
[string] $fullPath = $null,
[string] $filename = $null,
[System.Collections.Hashtable] $details = $null,
[System.Collections.ArrayList] $entities = $null,
[System.Collections.ArrayList] $links = $null,
[bool] $fromTrustedSource = $false,
[System.Collections.ArrayList] $dependencies = $null,
[string] $tagId = $null,
[string] $culture = $null,
[string] $destination = $null
)
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.SoftwareIdentity -ArgumentList $fastPackageReference, $name, $version, $versionScheme, $source, $summary, $searchKey, $fullPath, $filename , $details , $entities, $links, $fromTrustedSource, $dependencies, $tagId, $culture, $destination
}
<#
Creates a new instance of a SoftwareIdentity object based on an xml string
#>
function New-SoftwareIdentityFromXml {
param(
[Parameter(Mandatory=$true)][string] $xmlSwidtag,
[bool] $commitImmediately = $false
)
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.SoftwareIdentity -ArgumentList $xmlSwidtag, $commitImmediately
}
<#
Creates a new instance of a DynamicOption object
#>
function New-DynamicOption {
param(
[Parameter(Mandatory=$true)][Microsoft.PackageManagement.MetaProvider.PowerShell.OptionCategory] $category,
[Parameter(Mandatory=$true)][string] $name,
[Parameter(Mandatory=$true)][Microsoft.PackageManagement.MetaProvider.PowerShell.OptionType] $expectedType,
[Parameter(Mandatory=$true)][bool] $isRequired,
[System.Collections.ArrayList] $permittedValues = $null
)
if( -not $permittedValues ) {
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.DynamicOption -ArgumentList $category,$name, $expectedType, $isRequired
}
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.DynamicOption -ArgumentList $category,$name, $expectedType, $isRequired, $permittedValues.ToArray()
}
<#
Creates a new instance of a Feature object
#>
function New-Feature {
param(
[Parameter(Mandatory=$true)][string] $name,
[System.Collections.ArrayList] $values = $null
)
if( -not $values ) {
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.Feature -ArgumentList $name
}
return New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.Feature -ArgumentList $name, $values.ToArray()
}
<#
Duplicates the $request object and overrides the client-supplied data with the specified values.
#>
function New-Request {
param(
[System.Collections.Hashtable] $options = $null,
[System.Collections.ArrayList] $sources = $null,
[PSCredential] $credential = $null
)
return $request.CloneRequest( $options, $sources, $credential )
}
function New-Entity {
param(
[Parameter(Mandatory=$true)][string] $name,
[Parameter(Mandatory=$true,ParameterSetName="role")][string] $role,
[Parameter(Mandatory=$true,ParameterSetName="roles")][System.Collections.ArrayList]$roles,
[string] $regId = $null,
[string] $thumbprint= $null
)
$o = New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.Entity
$o.Name = $name
# support role as a NMTOKENS string or an array of strings
if( $role ) {
$o.Role = $role
}
if( $roles ) {
$o.Roles = $roles
}
$o.regId = $regId
$o.thumbprint = $thumbprint
return $o
}
function New-Link {
param(
[Parameter(Mandatory=$true)][string] $HRef,
[Parameter(Mandatory=$true)][string] $relationship,
[string] $mediaType = $null,
[string] $ownership = $null,
[string] $use= $null,
[string] $appliesToMedia= $null,
[string] $artifact = $null
)
$o = New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.Link
$o.HRef = $HRef
$o.Relationship =$relationship
$o.MediaType =$mediaType
$o.Ownership =$ownership
$o.Use = $use
$o.AppliesToMedia = $appliesToMedia
$o.Artifact = $artifact
return $o
}
function New-Dependency {
param(
[Parameter(Mandatory=$true)][string] $providerName,
[Parameter(Mandatory=$true)][string] $packageName,
[string] $version= $null,
[string] $source = $null,
[string] $appliesTo = $null
)
$o = New-Object -TypeName Microsoft.PackageManagement.MetaProvider.PowerShell.Dependency
$o.ProviderName = $providerName
$o.PackageName =$packageName
$o.Version =$version
$o.Source =$source
$o.AppliesTo = $appliesTo
return $o
} | bingbing8/PowerShell | src/Modules/Shared/PackageManagement/PackageProviderFunctions.psm1 | PowerShell | mit | 10,269 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
Describe "Get-PSBreakpoint" -Tags "CI" {
$scriptName = "Get-PSBreakpoint.Tests.ps1"
$fullScriptPath = Join-Path -Path $PSScriptRoot -ChildPath $scriptName
AfterEach {
Get-PSBreakpoint -Script $fullScriptPath | Remove-PSBreakpoint
}
It "should be able to get PSBreakpoint with using Id switch" {
Set-PSBreakpoint -Script $fullScriptPath -Line 1
{ Get-PSBreakpoint -Script $fullScriptPath } | Should -Not -Throw
$Id = (Get-PSBreakpoint -Script $fullScriptPath).Id
# if breakpoints have been set by other tests, the number may or may not be 0
# so we can't check against a specific number
# however, we can be sure that we're getting an int and that the int is
# greater or equal to 0
([int]$Id) -ge 0 | Should -BeTrue
}
It "should be able to get PSBreakpoint with using Variable switch" {
Set-PSBreakpoint -Script $fullScriptPath -Variable "$scriptName"
{ Get-PSBreakpoint -Variable "$scriptName" -Script $fullScriptPath } | Should -Not -Throw
$Id = (Get-PSBreakpoint -Variable "$scriptName" -Script $fullScriptPath).Variable
$Id | Should -Be $scriptName
}
}
| JamesWTruher/PowerShell-1 | test/powershell/Modules/Microsoft.PowerShell.Utility/Get-PSBreakpoint.Tests.ps1 | PowerShell | mit | 1,276 |
function Install-ChocolateyInstallPackage {
<#
.SYNOPSIS
Installs a package
.DESCRIPTION
This will run an installer (local file) on your machine.
.PARAMETER PackageName
The name of the package - this is arbitrary, call it whatever you want.
It's recommended you call it the same as your nuget package id.
.PARAMETER FileType
This is the extension of the file. This should be either exe or msi.
.PARAMETER SilentArgs
OPTIONAL - These are the parameters to pass to the native installer.
Try any of these to get the silent installer - /s /S /q /Q /quiet /silent /SILENT /VERYSILENT
With msi it is always /quiet.
If you don't pass anything it will invoke the installer with out any arguments. That means a nonsilent installer.
Please include the notSilent tag in your chocolatey nuget package if you are not setting up a silent package.
.PARAMETER File
The full path to the native installer to run
.EXAMPLE
Install-ChocolateyInstallPackage '__NAME__' 'EXE_OR_MSI' 'SILENT_ARGS' 'FilePath'
.OUTPUTS
None
.NOTES
This helper reduces the number of lines one would have to write to run an installer to 1 line.
There is no error handling built into this method.
.LINK
Install-ChocolateyPackage
#>
param(
[string] $packageName,
[string] $fileType = 'exe',
[string] $silentArgs = '',
[string] $file,
$validExitCodes = @(0)
)
Write-Debug "Running 'Install-ChocolateyInstallPackage' for $packageName with file:`'$file`', args: `'$silentArgs`', fileType: `'$fileType`', validExitCodes: `'$validExitCodes`' ";
$installMessage = "Installing $packageName..."
write-host $installMessage
$ignoreFile = $file + '.ignore'
try {
'' | out-file $ignoreFile
} catch {
Write-Warning "Unable to generate `'$ignoreFile`'"
}
$additionalInstallArgs = $env:chocolateyInstallArguments;
if ($additionalInstallArgs -eq $null) { $additionalInstallArgs = ''; }
$overrideArguments = $env:chocolateyInstallOverride;
if ($fileType -like 'msi') {
$msiArgs = "/i `"$file`""
if ($overrideArguments) {
$msiArgs = "$msiArgs $additionalInstallArgs";
write-host "Overriding package arguments with `'$additionalInstallArgs`'";
} else {
$msiArgs = "$msiArgs $silentArgs $additionalInstallArgs";
}
Start-ChocolateyProcessAsAdmin "$msiArgs" 'msiexec' -validExitCodes $validExitCodes
#Start-Process -FilePath msiexec -ArgumentList $msiArgs -Wait
}
if ($fileType -like 'exe') {
if ($overrideArguments) {
Start-ChocolateyProcessAsAdmin "$additionalInstallArgs" $file -validExitCodes $validExitCodes
write-host "Overriding package arguments with `'$additionalInstallArgs`'";
} else {
Start-ChocolateyProcessAsAdmin "$silentArgs $additionalInstallArgs" $file -validExitCodes $validExitCodes
}
}
if($fileType -like 'msu') {
if ($overrideArguments) {
$msuArgs = "$file $additionalInstallArgs"
} else {
$msuArgs = "$file $silentArgs $additionalInstallArgs"
}
Start-ChocolateyProcessAsAdmin "$msuArgs" 'wusa.exe' -validExitCodes $validExitCodes
}
write-host "$packageName has been installed."
}
| chocolatey/chocolatey | src/helpers/functions/Install-ChocolateyInstallPackage.ps1 | PowerShell | apache-2.0 | 3,201 |
Properties {
if ([string]::IsNullOrWhitespace($Version)) {
$Version = "0.0.0"
}
$ModuleName = "Psst"
$Authors = "Jake Bruun"
$ProjectDir = "$PSScriptRoot"
$SrcDir = "$ProjectDir\src"
$TestDir = "$ProjectDir\src"
$TestResults = "PesterTestResults.xml"
$ReleaseDir = "$ProjectDir\bin\release"
$OutputDir = "$ReleaseDir\$ModuleName"
$ExamplesDir = "$ReleaseDir\examples"
$Exclude = @("*.Tests.ps1")
$TemplateCache = "$env:LOCALAPPDATA\$ModuleName\$Version"
$ReleaseNotes = "https://github.com/Cobster/psst/blob/master/ReleaseNotes.md"
$SettingsPath = "$env:LOCALAPPDATA\$ModuleName\SecuredBuildSettings.clixml"
$NoBuildOutputErrorMessage = "There is no build output. Run psake build."
$CodeCoverage = $true
# Git
$GitLastCommit = git rev-parse HEAD
$GitHash = $GitLastCommit.Substring(0,7)
# Publishing
$NuGetApiKey = $null
$PublishRepository = $null
# Define the options for artifact archival
$ZipArtifactsOptions = @{
InputFilePath = @("$OutputDir","$ReleaseDir\$TestResults")
OutputFilePath = "$ReleaseDir"
OutputFileFormat = "$ModuleName-$Version-$GitHash.zip"
}
}
. $PSScriptRoot\psake\tasks.ps1 | Cobster/psst | default.ps1 | PowerShell | mit | 1,273 |
$checksums = join-path -path $PSScriptRoot -childpath "\checksums.txt"
if ([System.IO.File]::Exists($checksums)) {
del $checksums
}
$installerpath = join-path -path $PSScriptRoot -childpath "..\..\Installer_advinst\Installer_advinst-SetupFiles"
Get-ChildItem $installerpath -Filter *.msi |
Foreach-Object {
Get-FileHash $_ SHA512 | Format-List | Out-File -Append -File $checksums
}
| roots84/DNS-Swapper | DNS-Swapper/tools/get-checksums.ps1 | PowerShell | mit | 387 |
[CmdletBinding()]
param ()
begin {
}
process {
$instanceName ="SPDistributedCacheService Name=AppFabricCachingService"
$serviceInstance = Get-SPServiceInstance | ? {($_.service.tostring()) -eq $instanceName -and ($_.server.name) -eq $env:computername}
if ($serviceInstance)
{
$serviceInstance.Provision()
}
else
{
Write-Error "Distributed Cache service instance waas not found. Verify that $($env:computername) is added to Distributed Cache cluster before starting the service instance."
}
} | egor-yudkin/PS-SharePoint | DistributedCacheMgmt/Start-DistributedCacheHost.ps1 | PowerShell | mit | 565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.