full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/Invoke-ScriptBlockWithRetry.ps1
|
Invoke-ScriptBlockWithRetry.ps1
|
<#
.SYNOPSIS
Executes a ScriptBlock with Retry
.DESCRIPTION
Wraps a ScriptBlock in a try/catch to allow for retrying
based on specific exceptions as defined in the retry policy passed.
To create a retry policy object see New-RetryPolicy cmdlet.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Linear -MilliSeconds 1000 -Retries 3
PS> Invoke-ScriptBlockWithRetry -Context { dir Z:\ } -RetryPolicy $policy
Invokes the provided ScriptBlock and will attempt to retry on an exception if it
meets the criteria defined in the policy. The number of retries as well as the
wait time between retries is also defined in the policy. In this case a linear
retry [1000, 2000, 4000] will the determine the wait time. The provided context
will be attempted 3 times according to the policy defined.
.NOTES
This cmdlet requires terminating errors to be raised. If your global $ErrorActionPreference is set to 'Continue'
or 'SilentlyContinue' errors will not be catched. There are a couple of ways to fix this:
1. Set your global variable to 'Stop':
PS> $ErrorActionPreference = 'Stop'
2. Set this preference on the script block commands. i.e. from the example the context to invoke is:
{ dir Z:\ }
Change this to stop on non-terminating errors as follows:
{ dir Z:\ -ErrorAction Stop}
See New-RetryPolicy cmdlet for details on policy creation as well as all
available options.
#>
function Invoke-ScriptBlockWithRetry {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
# Context to execute
[ScriptBlock] $Context,
[Parameter(Mandatory)]
[ValidateScript({ $_.PSTypeNames[0] -eq $script:RetryPolicyTypeName })]
# Retry policy determines wait time, whether wait follows any pattern, and the types of exceptions to under which will retry
$RetryPolicy
)
$ErrorActionPreference = "Stop"
$continueRetrying = $true
$retryLogicWorkingSet = $RetryPolicy.WorkingSet.Clone()
while ($continueRetrying) {
try {
. $Context
$continueRetrying = $false
}
catch {
$e = $_
if ($e.GetType().Name -eq 'ActionPreferenceStopException') {
$e = $e.ErrorRecord
}
$invokeRetryLogic = $false
if ($RetryPolicy.ExceptionActivity.Count -eq 0 -and
$RetryPolicy.ExceptionCategory.Count -eq 0 -and
$RetryPolicy.ExceptionErrorId.Count -eq 0) {
# Retry on any error
$invokeRetryLogic = $true
}
$invokeRetryLogic = $invokeRetryLogic -or ($RetryPolicy.ExceptionActivity -contains $e.CategoryInfo.Activity)
$invokeRetryLogic = $invokeRetryLogic -or ($RetryPolicy.ExceptionCategory -contains $e.CategoryInfo.Category)
$invokeRetryLogic = $invokeRetryLogic -or ($RetryPolicy.ExceptionErrorId -contains $e.FullyQualifiedErrorId)
if ($invokeRetryLogic) {
try {
. $RetryPolicy.RetryLogic -WorkingSet $retryLogicWorkingSet
}
catch {
$e2 = $_
$continueRetrying = $false
if($e2.GetType().Name -eq 'ActionPreferenceStopException') {
$e2 = $e2.ErrorRecord
}
if ($e2.FullyQualifiedErrorId -ne $script:RetryLogicLimitErrorId) {
Write-Error -Message ("Error during RetryLogicEvaluation: {0}" -f $e2) -ErrorId 'InvalidRetryLogicEvaluation'
}
else {
Write-Verbose "Reached Retry Limit: $e2"
throw $e
}
}
}
else {
Write-Warning 'Retry Logic was not invoked as exception did not passed proper validation'
$continueRetrying = $false
throw $e
}
}
}
}
Set-Alias RetryBlock Invoke-ScriptBlockWithRetry
|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/New-RetryPolicy.ps1
|
New-RetryPolicy.ps1
|
<#
.SYNOPSIS
Creates a custom Retry Policy for use with Invoke-ScriptBlockWithRetry
cmdlet
.DESCRIPTION
Creates a custom Retry Policy for use with Invoke-ScriptBlockWithRetry.
Resulting object contains the required information to detect and retry
appropriately.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Constant -Milliseconds 500 -Retries 5
Creates a retry policy object that will wait a constant time of 500 milliseconds and will allow for 5
retries before throwing a 'RetryLogicLimitReached' exception.
PS> $workSet = $policy.WorkingSet.Clone()
PS> . $policy.RetryLogic -WorkingSet $workSet
Ilustrates the usage of the retry policy to invoke with a constant wait of 500 milliseconds. This
example can be used 5 times before obtaining 'RetryLogicLimitReached' exception.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Linear -Milliseconds 1000 -Retries 3
Creates a retry policy object that will wait a linear time of 1 second, then 2 seconds, then 3 seconds.
It will allow for 3 attempts before throwing 'RetryLogicLimitReached' exception.
PS> $workSet = $policy.WorkingSet.Clone()
PS> . $policy.RetryLogic -WorkingSet $workSet
Ilustrates the usage of the retry policy to invoke with a linear increment of 1 second. This example
can be used 3 times before throwing 'RetryLogicLimitReached' exception.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Exponential -Milliseconds 100 -Retries 3
Creates a retry policy object that will wait an exponential time of 100 milliseconds and will allow
for 3 executions before throwing 'RetryLogicLimitReached' exception.
The wait sequence in this case is [100ms, 10s, 100 000s]
PS> $workSet = $policy.WorkingSet.Clone()
PS> . $policy.RetryLogic -WorkingSet $workSet
Ilustrates the usage of the retry policy to invoke with an exponential increment of 100 milliseconds.
This example can be used 3 times before throwing 'RetryLogicLimitReached' exception.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Random -Milliseconds 5000 -Retries 3
Creates a retry policy object that will wait a random time between 0 and 5000 milliseconds and will
allow for 3 attempts before throwing 'RetryLogicLimitReached' exception.
PS> $workSet = $policy.WorkingSet.Clone()
PS> . $policy.RetryLogic -WorkingSet $workSet
Ilustrates the usage of the retry policy to invoke with a random increment of 100 milliseconds. This example
can be used 3 times before throwing 'RetryLogicLimitReached' exception.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Constant -Milliseconds 1000 -Retries 3 -ExceptionActivity 'Write-Error', 'Test-Path'
Creates a retry policy object, with constant wait of 1 second and allows 3 retries before throwing
'RetryLogicLimitReached'. It records the Exeption.CategoryInfo.Activity to trigger a retry evaluation.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Constant -Milliseconds 1000 -Retries 3 -ExceptionCategory 'NotSpecified'
Creates a retry policy object, with constant wait of 1 second and allows 3 retries before throwing
'RetryLogicLimitReached'. It records the Exeption.CategoryInfo.Category to trigger a retry evaluation.
.EXAMPLE
PS> $policy = New-RetryPolicy -Policy Constant -Milliseconds 1000 -Retries 3 -ExceptionErrorId 'MyCustomErrorId'
Creates a retry policy object, with constant wait of 1 second and allows 3 retries before throwing
'RetryLogicLimitReached'. It records the Exeption.FullyQualifiedErrorId to trigger a retry evaluation.
.EXAMPLE
PS> $customRetryLogic = {
param([HashTable]$WorkingSet)
$ErrorActionPreference = 'Stop'
if($WorkingSet['RetryCount'] -ge $WorkingSet['RetryMax']) {
Write-Error -Message 'Max RetryReached' -ErrorId 'RetryLogicLimitReached'
}
Start-Sleep -Milliseconds 500
$WorkingSet['RetryCount'] = $WorkingSet['RetryCount'] + 1
}
PS> $workingSet = @{
RetryCount = 4
RetryMax = 8
}
PS> $policy = New-RetryPolicy -CustomRetryLogic $customRetryLogic -WorkingSet $workingSet
This example shows how to create a custom retry logic including the required elements such as $WorkingSet required
parameter. Additionally the developer can design and rely on any value on this hashtable provided that the
developer will add those values to $workingSet hash table. The use of a hash table is optional, for example the global
scope can be used for this, however $WorkingSet parameter should still be provided and the cmdlet will inject an empty
hash table.
Note as well that the FullyQualifiedErrorId of the ErrorRecord or the ActionPreferenceStopException should be always
'RetryLogicLimitReached' for Invoke-ScriptBlockWithRetry to work properly.
.NOTES
To request additional policy implementations open a new issue in GitHub.
WorkingSet parameter was introduced to reduce polution on the user scope as
well as to allow to reuse newly create Retry Policy objects since Execution Retries
(from Invoke-ScriptBlockWithRetry) will clone this working set and thus start clean every
time this cmdlet is called with a reused policy object.
#>
function New-RetryPolicy {
[CmdletBinding(DefaultParameterSetName = "PreDefined")]
param(
[Parameter(Mandatory, ParameterSetName = "PreDefined")]
[ValidateSet("Constant", "Linear", "Exponential", "Random")]
# Pre-defined Retry Policy to use
[string] $Policy = "",
[Parameter(Mandatory, ParameterSetName = "PreDefined")]
[ValidateScript({ $_ -gt 0})]
# Delay base between attempts
[int] $Milliseconds = 0,
[Parameter(Mandatory, ParameterSetName = "PreDefined")]
[ValidateScript({$_ -gt 0})]
# Number of retries
[int] $Retries = 0,
[Parameter(Mandatory, ParameterSetName = "UserDefined")]
[ValidateScript({ ValidateCustomRetryLogic -ValidationTarget $_})]
# User defined retry policy, parameter -WorkingSet [HashTable] will be passed upon evaluating, so this must be supported
[ScriptBlock] $CustomRetryLogic = {},
[Parameter(ParameterSetName = "UserDefined")]
# Defines any working set memory to hold any state
[HashTable] $WorkingSet = @{},
[Parameter(ParameterSetName = "PreDefined")]
[Parameter(ParameterSetName = "UserDefined")]
[ValidateNotNullOrEmpty()]
# Specific Exception.CategoryInfo.Activity to match for retry
[string[]] $ExceptionActivity = @(),
[Parameter(ParameterSetName = "PreDefined")]
[Parameter(ParameterSetName = "UserDefined")]
[ValidateNotNullOrEmpty()]
# Specific Exception.CategoryInfo.Category to match for retry
[string[]] $ExceptionCategory = @(),
[Parameter(ParameterSetName = "PreDefined")]
[Parameter(ParameterSetName = "UserDefined")]
[ValidateNotNullOrEmpty()]
# Specific Exception.FullyQualifiedErrorId to match for retry
[string[]] $ExceptionErrorId = @()
)
$ErrorActionPreference = "Stop"
$policyDraft = @{}
if ($Policy -ne "" -and $Retries -gt 0) {
$policyDraft['WorkingSet'] = @{
Retries = $Retries
RetryCount = 0
Milliseconds = $Milliseconds
BaseMilliseconds = $Milliseconds
}
# Create retry algorithm here
switch ($Policy) {
"Constant" {
$policyDraft['RetryLogic'] = {
param([HashTable] $WorkingSet)
$ErrorActionPreference = "Stop"
if ($WorkingSet['RetryCount'] -eq $null) {
$WorkingSet['RetryCount'] = 0
}
if ($WorkingSet['RetryCount'] -ge $WorkingSet['Retries']) {
Write-Error -Message ("[Constant] RetryCount[{0}] reached the limit of allowed Retries[{1}]" -f $WorkingSet['RetryCount'], $WorkingSet['Retries']) `
-ErrorId 'RetryLogicLimitReached'
}
Write-Verbose ("[Constant] About to sleep {0} Milliseconds" -f $WorkingSet['Milliseconds'])
Start-Sleep -Milliseconds $WorkingSet['Milliseconds']
$WorkingSet['RetryCount'] = $WorkingSet['RetryCount'] + 1
}
}
"Linear" {
$policyDraft['RetryLogic'] = {
param([HashTable] $WorkingSet)
$ErrorActionPreference = "Stop"
if ($WorkingSet['RetryCount'] -eq $null) {
$WorkingSet['RetryCount'] = 0
}
if ($WorkingSet['RetryCount'] -ge $WorkingSet['Retries']) {
Write-Error -Message ("[Linear] RetryCount[{0}] reached the limit of allowed Retries[{1}]" -f $WorkingSet['RetryCount'], $WorkingSet['Retries']) `
-ErrorId 'RetryLogicLimitReached'
}
Write-Verbose ("[Linear] About to sleep {0} Milliseconds" -f $WorkingSet['Milliseconds'])
Start-Sleep -Milliseconds $WorkingSet['Milliseconds']
# HashTables are passed as reference, so this will update the caller variable
$WorkingSet['Milliseconds'] = $WorkingSet['Milliseconds'] + $WorkingSet['BaseMilliseconds']
$WorkingSet['RetryCount'] = $WorkingSet['RetryCount'] + 1
}
}
"Exponential" {
$policyDraft['RetryLogic'] = {
param([HashTable] $WorkingSet)
$ErrorActionPreference = "Stop"
if ($WorkingSet['RetryCount'] -eq $null) {
$WorkingSet['RetryCount'] = 0
}
if ($WorkingSet['RetryCount'] -ge $WorkingSet['Retries']) {
Write-Error -Message ("[Exponential] RetryCount[{0}] reached the limit of allowed Retries[{1}]" -f $WorkingSet['RetryCount'], $WorkingSet['Retries']) `
-ErrorId 'RetryLogicLimitReached'
}
Write-Verbose ("[Exponential] About to sleep {0} Milliseconds" -f $WorkingSet['Milliseconds'])
Start-Sleep -Milliseconds $WorkingSet['Milliseconds']
# HashTables are passed as reference, so this will update the caller variable
$WorkingSet['Milliseconds'] = $WorkingSet['Milliseconds'] + $WorkingSet['Milliseconds']
$WorkingSet['RetryCount'] = $WorkingSet['RetryCount'] + 1
}
}
"Random" {
$policyDraft['RetryLogic'] = {
param([HashTable] $WorkingSet)
$ErrorActionPreference = "Stop"
if ($WorkingSet['RetryCount'] -eq $null) {
$WorkingSet['RetryCount'] = 0
}
if ($WorkingSet['RetryCount'] -ge $WorkingSet['Retries']) {
Write-Error -Message ("[Random] RetryCount[{0}] reached the limit of allowed Retries[{1}]" -f $WorkingSet['RetryCount'], $WorkingSet['Retries']) `
-ErrorId 'RetryLogicLimitReached'
}
Write-Verbose ("[Random] About to sleep {0} Milliseconds" -f $WorkingSet['Milliseconds'])
Start-Sleep -Milliseconds $WorkingSet['Milliseconds']
# HashTables are passed as reference, so this will update the caller variable
$WorkingSet['Milliseconds'] = Get-Random -Maximum $WorkingSet['Milliseconds']
$WorkingSet['RetryCount'] = $WorkingSet['RetryCount'] + 1
}
}
default {
throw "Non-implemented Retry Logic"
}
}
}
else {
$policyDraft['RetryLogic'] = $CustomRetryLogic
$policyDraft['WorkingSet'] = $WorkingSet
}
$policyDraft['ExceptionActivity'] = $ExceptionActivity
$policyDraft['ExceptionCategory'] = $ExceptionCategory
$policyDraft['ExceptionErrorId'] = $ExceptionErrorId
$retryPolicy = [PSCustomObject] $policyDraft
$retryPolicy.PSTypeNames.Insert(0, $script:RetryPolicyTypeName)
Write-Output $retryPolicy
}
# Initialization code
function ValidateCustomRetryLogic {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
# ScriptBlock to validate
[ScriptBlock] $ValidationTarget
)
if ($ValidationTarget.Ast.ParamBlock.Parameters.Count -ne 1) {
throw "Invalid ScriptBlock: Target ScriptBlock does not accept just 1 parameter"
}
if ($ValidationTarget.Ast.ParamBlock.Parameters[0].StaticType.ToString() -ne 'System.Collections.Hashtable') {
throw "Invalid ScriptBlock: Parameter of target ScriptBlock is not of type 'System.Collections.Hashtable'"
}
if ($ValidationTarget.Ast.ParamBlock.Parameters[0].Name.ToString() -ne '$WorkingSet') {
throw "Invalid ScriptBlock: Parameter of target ScriptBlock must be of name '`$WorkingSet'"
}
return $true
}
|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/New-ConsoleColorSet.ps1
|
New-ConsoleColorSet.ps1
|
<#
.SYNOPSIS
Creates a color set object. Foreground and background.
.DESCRIPTION
Creates a pair foreground and background color which
express a given console format color to use with
Out-ColorFormat cmdlet.
.EXAMPLE
PS> New-ConsoleColorSet -ForegroundColor Yellow
Returns an object which express a foreground color as Yellow
.EXAMPLE
PS> New-ConsoleColorSet -BackgroundColor Black
Returns an object which express a background color as Black
.EXAMPLE
PS> New-ConsoleColorSet -ForegroundColor Yellow -BackgroundColor Black
Returns an object which express Yellow foreground and black background colors
#>
function New-ConsoleColorSet {
[CmdletBinding()]
param(
[Parameter()]
[System.ConsoleColor] $ForegroundColor,
[Parameter()]
[System.ConsoleColor] $BackgroundColor
)
$consoleColorSetTable = @{}
if ($PsBoundParameters.Keys -contains 'ForegroundColor') {
$consoleColorSetTable['ForegroundColor'] = $ForegroundColor
}
if ($PsBoundParameters.Keys -contains 'BackgroundColor') {
$consoleColorSetTable['BackgroundColor'] = $BackgroundColor
}
$consoleColorSet = [PSCustomObject] $consoleColorSetTable
$consoleColorSet.PSTypeNames.Insert(0, $script:consoleColorSetTypeName)
Write-Output $consoleColorSet
}
|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/Set-ConsoleTransparency.ps1
|
Set-ConsoleTransparency.ps1
|
<#
.SYNOPSIS
Sets console transparency
.DESCRIPTION
Adjust the console transparency to a given level
.EXAMPLE
PS> Set-ConsoleTransparency
Sets console transparency to default level of 220
.EXAMPLE
PS> Set-ConsoleTransparency -Off
Disables console transparency
.EXAMPLE
PS> Set-ConsoleTransparency -Level 200
Sets console transparency to the given level
.EXAMPLE
PS> Set-ConsoleTransparency -Persist
Sets console transparency to the predefined level and persist its value for other sessions
.EXAMPLE
#>
function Set-ConsoleTransparency {
[CmdletBinding(DefaultParameterSetName = "Level")]
param(
[Parameter(ParameterSetName = "Level")]
[ValidateRange(0, 255)]
# Set transparency level
[int] $Level = 220,
[Parameter(ParameterSetName = "Off")]
# Disables transparency
[switch] $Off = $false,
[Parameter(ParameterSetName = "Level")]
[Parameter(ParameterSetName = "Off")]
# Whether to apply this change for future sessions or not
[switch] $Persist = $false
)
if ($Off) {
$Level = 255
if ($Persist) {
Invoke-ScriptBlockWithRetry -Context { Remove-Item $script:localSetConsoleTransparencyConfig } -RetryPolicy $script:consoleTransparencyRetryPolicy
}
}
if ($Persist -and -not $Off) {
$config = [PSCustomObject] @{ Level = $Level }
$saveFileDefinition = {
$config | ConvertTo-Json -Compress | Out-File $script:localSetConsoleTransparencyConfig
}
Invoke-ScriptBlockWithRetry -Context $saveFileDefinition -RetryPolicy $script:consoleTransparencyRetryPolicy
}
$hwnd = (Get-Process -Id $PID).MainWindowHandle
if ([xUtilityTransparency.Win32Methods]::transparencyLevel -ne 0) {
[xUtilityTransparency.Win32Methods]::SetWindowTransparent($hwnd, 255)
}
[xUtilityTransparency.Win32Methods]::SetWindowTransparent($hwnd, $level)
}
Add-Type -Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace xUtilityTransparency
{
public static class Win32Methods
{
internal const int GWL_EXSTYLE = -20;
internal const int WS_EX_LAYERED = 0x80000;
internal const int LWA_ALPHA = 0x2;
internal const int LWA_COLORKEY = 0x1;
public static int transparencyLevel = 0;
[DllImport("user32.dll")]
internal static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public static void SetWindowTransparent(IntPtr hWnd, byte level)
{
SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) ^ WS_EX_LAYERED);
SetLayeredWindowAttributes(hWnd, 0, level, LWA_ALPHA);
transparencyLevel = level;
}
}
}
"@
# Initialization code
$script:localSetConsoleTransparencyPath = Join-Path -Path $script:moduleWorkPath -ChildPath "Set-ConsoleTransparency"
$script:consoleTransparencyRetryPolicy = New-RetryPolicy -Policy $script:consoleTransparencyPolicyName -Milliseconds $script:consoleTransparencyWaitTime -Retries $script:consoleTransparencyRetries
if (-not (Test-Path $script:localSetConsoleTransparencyPath)) {
New-Item -ItemType 'Directory' -Path $script:localSetConsoleTransparencyPath | Write-Verbose
}
$script:localSetConsoleTransparencyConfig = Join-Path -Path $script:localSetConsoleTransparencyPath -ChildPath "config.json"
if ((Test-Path $script:localSetConsoleTransparencyConfig)) {
$fileRetrieval = {
(Get-Content $script:localSetConsoleTransparencyConfig) | Out-String | ConvertFrom-Json | Write-Output
}
$transparencyConfig = Invoke-ScriptBlockWithRetry -Context $fileRetrieval -RetryPolicy $script:consoleTransparencyRetryPolicy
$hwnd = (Get-Process -Id $PID).MainWindowHandle
[xUtilityTransparency.Win32Methods]::SetWindowTransparent($hwnd, $transparencyConfig.Level)
}
|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/Add-ExpiringCacheItem.ps1
|
Add-ExpiringCacheItem.ps1
|
<#
.SYNOPSIS
PowerShell implementation for Expiring Cache
.DESCRIPTION
Takes a ScriptBlock as execution and expiration policy.
ScriptBlock is stored along with its expiration policy.
Upon access, expiration policy is assessed. On expiration
the given ScriptBlock is executed and the value is retrieved.
This value is stored in the cache which is returned until its
expiration.
.EXAMPLE
PS> Add-ExpiringCacheItem -Key '5sec' -ItemDefinition { Write-Output (Get-Date) } -Expiration '0:0:5'
Adds a script block that is executed every time the cached item expires under the given key
.EXAMPLE
PS> Add-ExpiringCacheItem -Key '5sec' -ItemDefinition { Write-Output (Get-Date) } -Expiration '0:0:5' -Force
Adds a script block that is executed every time the cached item expires under the given key. If an
existing key already exists it gets overwritten
#>
function Add-ExpiringCacheItem {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
# A key to reference this item in the cache
[string] $Key = "",
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
# Execution context
[ScriptBlock] $ItemDefinition,
[Parameter(Mandatory)]
# Expiration policy
[TimeSpan] $Expiration,
[Parameter()]
# Whether to override any existing item with same key
[switch] $Force = $false
)
$ErrorActionPreference = "Stop"
if ($script:expiringCacheObjects.Contains($Key) -and -not $Force) {
Write-Error "Cache already contains an object with key '$Key'"
}
$script:expiringCacheObjects[$Key] = [PSCustomObject] @{
Expiration = $Expiration
ItemDefinition = $ItemDefinition
Item = $null
LastRefresh = [DateTime] "January 1, 1"
}
}
|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/Out-ColorFormat.ps1
|
Out-ColorFormat.ps1
|
<#
.SYNOPSIS
Display specific words or rows in given colors
.DESCRIPTION
Takes a string as input and displays the given words in
the specified color. Or rows in a series of given colors
.EXAMPLE
PS> $cs = @()
PS> $cs += (New-ConsoleColorSet -ForegroundColor Green)
PS> $cs += (New-ConsoleColorSet -ForegroundColor Yellow)
PS> $cs += (New-ConsoleColorSet -ForegroundColor Red)
PS> $cs += (New-ConsoleColorSet -ForegroundColor White)
PS> dir E:\ | Out-String | % { $_ -split "`r`n" } | ? {$_ -ne ""}| Out-ColorFormat -RowColorSet $cs
Displays the contents of E: in the specified set of row color formants
.EXAMPLE
PS> $colorDict = @{}
PS> $colorDict['AM'] = New-ConsoleColorSet -ForegroundColor Black -BackgroundColor White
PS> $colorDict['PM'] = New-ConsoleColorSet -ForegroundColor White -BackgroundColor Black
PS> $colorDict['dev'] = New-ConsoleColorSet -ForegroundColor Green
PS> $colorDict['repos'] = New-ConsoleColorSet -ForegroundColor Cyan
PS> dir E:\ | Out-String |%{ $_ -split "`r`n" }|?{$_ -ne ""}| Out-ColorFormat -WordColorSet $cdict
Displays the contents of E: and replaces the format of the words AM, PM, dev, repos with the
ones specified on the dictionary
#>
function Out-ColorFormat {
[CmdletBinding(DefaultParameterSetName = "Word")]
param(
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Word")]
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Row")]
[string] $RawLine = "",
[Parameter(Mandatory, ParameterSetName = "Row")]
[ValidateScript({ ValidateRowColorSet -ValidateObject $_ })]
[PSCustomObject[]] $RowColorSet,
[Parameter(Mandatory, ParameterSetName = "Word")]
[ValidateScript({ ValidateWordColorSet -ValidateObject $_ })]
[HashTable] $WordColorSet
)
begin {
$rowIndex = 0
}
process {
$line = $_
if ($PsBoundParameters['RawLine']) {
$line = $RawLine
}
if ($PsBoundParameters['RowColorSet'] -ne $null) {
$whProperties = @{
Object = $line
}
if ($RowColorSet[$rowIndex].ForegroundColor -ne $null) {
$whProperties['ForegroundColor'] = $RowColorSet[$rowIndex].ForegroundColor
}
if ($RowColorSet[$rowIndex].BackgroundColor -ne $null) {
$whProperties['BackgroundColor'] = $RowColorSet[$rowIndex].BackgroundColor
}
Write-Host @whProperties
$rowIndex = $rowIndex + 1
if ($rowIndex -ge $RowColorSet.Count) {
$rowIndex = 0
}
}
else {
while ($line -ne "") {
# For the given string, get the lowest index of the match words
$lowestColorIndex = $line.Length
$lowestColorWord = ""
$WordColorSet.Keys | ForEach-Object {
$colorWord = $_
$tentativeIndex = $line.IndexOf($colorWord)
if ($tentativeIndex -ne -1 -and $tentativeIndex -lt $lowestColorIndex) {
$lowestColorIndex = $tentativeIndex
$lowestColorWord = $colorWord
}
elseif ($tentativeIndex -ne 1 -and
$tentativeIndex -eq $lowestColorIndex -and
$colorWord.Length -gt $lowestColorWord.Length) {
$lowestColorIndex = $tentativeIndex
$lowestColorWord = $colorWord
}
}
if ($lowestColorWord -eq "") {
Write-Verbose "`n[Out-ColorFormat] Couldn't find a match for the dictionary"
Write-Host $line -NoNewLine
$line = ""
}
else {
Write-Verbose "`n[Out-ColorFormat] Found '$lowestColorWord' at position '$lowestColorIndex'"
# Print normally everything before the first indexof
Write-Host -Object $line.Substring(0, $lowestColorIndex) -NoNewLine
# Print the matching word in the given format
$printData = @{
Object = $lowestColorWord
NoNewLine = $true
}
if ($WordColorSet[$lowestColorWord].ForegroundColor -ne $null) {
$printData['ForegroundColor'] = $WordColorSet[$lowestColorWord].ForegroundColor
}
if ($WordColorSet[$lowestColorWord].BackgroundColor -ne $null) {
$printData['BackgroundColor'] = $WordColorSet[$lowestColorWord].BackgroundColor
}
Write-Host @printData
# Repeat for the remaining string
$line = $line.Substring($lowestColorIndex + $lowestColorWord.Length)
}
}
# New Line and Carriage Return
Write-Host ""
}
}
}
function ValidateRowColorSet {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[PSCustomObject[]] $ValidateObject
)
$ValidateObject | ForEach-Object {
$lineColorSet = $_
if ($lineColorSet.PSTypeNames[0] -ne $script:consoleColorSetTypeName) {
throw ("Object of type [{0}] does not correspond to required type {1}" -f
$lineColorSet.PSTypeNames[0], $script:consoleColorSetTypeName)
}
}
return $true
}
function ValidateWordColorSet {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[HashTable] $ValidateObject
)
if ($ValidateObject.Keys -eq 0) {
throw "WordColorSet cannot be empty"
}
$colorSets = @()
$ValidateObject.Keys | ForEach-Object {
$colorSets += $ValidateObject[$_]
}
return (ValidateRowColorSet -ValidateObject $colorSets)
}
|
PowerShellCorpus/PowerShellGallery/xUtility/1.0.15/Main/Set-WindowSize.ps1
|
Set-WindowSize.ps1
|
<#
.SYNOPSIS
Sets the current console window to a specified size
.DESCRIPTION
Sets the current console window to a specified size.
Alternatively it can be maximized.
.EXAMPLE
PS> Set-WindowSize -Height 60 -Width 130
Sets the console window to the given dimensions
.EXAMPLE
PS> Set-WindowSize -Maximize
Sets the console window to the maximum size available
.NOTES
When downsizing the contents of the buffer are flushed. If there's content wider thant the
target content, it will be lost
#>
function Set-WindowSize {
[CmdletBinding(DefaultParameterSetName = "MaxSize")]
param(
[Parameter(Mandatory, ParameterSetName = "CustomSize")]
[ValidateScript({ $_ -gt 0})]
# Target Height
[int] $Height = 50,
[Parameter(Mandatory, ParameterSetName = "CustomSize")]
[ValidateScript({ $_ -gt 0})]
# Target Width
[int] $Width = 120,
[Parameter(ParameterSetName = "MaxSize")]
# Maximize the window
[switch] $Maximize = $false
)
$maxHeight = $Host.UI.RawUI.MaxPhysicalWindowSize.Height
$maxWidth = $Host.UI.RawUI.MaxPhysicalWindowSize.Width
if ($Maximize) {
$Height = $maxHeight
$Width = $maxWidth - 2
}
$consoleBuffer = $Host.UI.RawUI.BufferSize
$consoleWindow = $Host.UI.RawUI.WindowSize
$consoleWindow.Height = ($Height)
$consoleWindow.Width = ($Width)
#$consoleBuffer.Height = (9999)
$consoleBuffer.Height = (9000)
$consoleBuffer.Width = ($Width)
$Host.UI.RawUI.FlushInputBuffer()
$Host.UI.RawUI.set_bufferSize($consoleBuffer)
$Host.UI.RawUI.set_windowSize($consoleWindow)
}
|
PowerShellCorpus/PowerShellGallery/Fmg-KeePass/0.1.0/Export-KeePassBinary.ps1
|
Export-KeePassBinary.ps1
|
function Export-KeePassBinary() {
<#
.SYNOPSIS
Exports a binary file from a KeePass Entry object
.DESCRIPTION
This method will write the binary information associated with
a KeePass entry. Each association is stored with the file's
name and extension e.g. cert.pfx
.PARAMETER Entry
The KeePass Entry object the file is attached to.
.PARAMETER Name
The file name the binary data was stored as.
.PARAMETER DestinationPath
The file path where the exported file should be saved to. The `Dest`
parameter is an alias.
.PARAMETER Force
(Optional) This will force this command to overwrite the file at the
DestinationPath if it exists.
.EXAMPLE
$entry | Export-KeePassBinary -Name "azure.pfx" -DestinationPath "$home/Desktop/azure.pfx"
.EXAMPLE
PS C:\> $key | Open-KeePassPackage "$home/Desktop/passwords.kdbx" -Do {
PS C:\> $entry = $_ | Find-KeePassEntryByTitle "cert:azure"
PS C:\> $entry | Export-KeePassBinary -Name "azure.pfx" -DestinationPath "$home/Desktop/azure.pfx"
PS C:\> Write-Host ($entry.UnprotectPassword())
PS C:\> }
#>
Param(
[Parameter(Mandatory = $true, Position = 2, ValueFromPipeline = $true)]
[NerdyMishka.KeePass.Entry] $Entry,
[Parameter(Mandatory = $true, Position = 0)]
[string] $Name,
[Parameter(Mandatory = $true, Position = 1)]
[Alias("Dest")]
[string] $DestinationPath,
[switch] $Force
)
$result = [NerdyMishka.KeePass.EntryOperations]::ExportBinary($Entry, $DestinationPath, $Name, $Force.ToBool())
if(!$result) {
Write-Error "$Name failed to export";
}
}
|
PowerShellCorpus/PowerShellGallery/Fmg-KeePass/0.1.0/Open-KeePassPackage.ps1
|
Open-KeePassPackage.ps1
|
if((Get-Command New-KeePassKey -ErrorAction SilentlyContinue) -eq $null) {
. "$PSScriptRoot\New-KeePassKey.ps1"
}
function Open-KeePassPackage() {
<#
.SYNOPSIS
Creates a new KeePass master key
.DESCRIPTION
The master key is a composite key that are required to open KeePass
database files. Without it, the file can not be decrypted.
.PARAMETER Path
The file path to the KeePass database file
.PARAMETER Key
The KeePass composite master key, which is created by `New-KeePassKey`
.PARAMETER Password
(Optional) The password for the composite key.
.PARAMETER KeyFile
(Optional) A file of bytes for the composites key.
.PARAMETER Do
(Optional) A script block that binds `$_`, `$db`, and `$Package`
to the block to allow you to interact with the KeePass database
and then dispose it once the block finishes executing.
.EXAMPLE
$db = Open-KeePassPackage "$home/Desktop/passwords.kdbx" -Key $key
.EXAMPLE
PS C:\> $key | Open-KeePassPackage "$home/Desktop/passwords.kdbx" -Do {
PS C:\> $entry = $_ | Find-KeePassEntryByTitle "cert:azure"
PS C:\> $entry | Export-KeePassBinary -Name "azure.pfx" -DestinationPath "$home/Desktop/azure.pfx"
PS C:\> Write-Host ($entry.UnprotectPassword())
PS C:\> }
#>
Param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Path,
[Parameter(ValueFromPipeline = $true)]
[NerdyMishka.KeePass.MasterKey] $Key,
[string] $Password = $null,
[string] $KeyFile = $null ,
[switch] $UserAccount,
[scriptblock] $Do
)
$constructKey = ! ([string]::IsNullOrWhiteSpace($Password) `
-and [string]::IsNullOrWhiteSpace($KeyFile) `
-and $UserAccount.ToBool() -eq $false)
if($Key -eq $null -and !$constructKey) {
throw new ArgumentException("Key, Password, or KeyFile must have a value");
}
if($constructKey) {
$Key = New-KeePassKey -Password $Password -KeyFile $KeyFile -UserAccount:$UserAccount
}
if(! (Test-Path $Path)) {
throw [System.ArgumentException] "Path not found for $Path"
}
$Path = (Resolve-Path $Path).Path;
$Package = [NerdyMishka.KeePass.DbOperations]::OpenDatabase($Key, $Path)
if($Do -ne $null) {
Set-Variable -Name "_" -Value $Package
$db = $Package
#$underscore = New-Object PSVariable @("_", $Package)
$vars = @(
(Get-Variable -Name "db" -Scope 0),
(Get-Variable -Name "Package" -Scope 0),
(Get-Variable -Name "_")
)
$Do.InvokeWithContext(@{}, $vars)
$Package.Dispose();
return;
}
return $Package;
}
|
PowerShellCorpus/PowerShellGallery/Fmg-KeePass/0.1.0/Find-KeePassEntry.ps1
|
Find-KeePassEntry.ps1
|
if((Get-Command New-KeePassKey -ErrorAction SilentlyContinue) -eq $null) {
. "$PSScriptRoot\New-KeePassKey.ps1"
}
function Find-KeePassEntry() {
<#
.SYNOPSIS
Searches for the all the entries in the KeePass database with
that match the given field.
.DESCRIPTION
This method allows for comparisons against the Title, UserName, Url,
and Tags field of each entry in the Database.
It will return all the matches that it finds.
.PARAMETER Package
The object representation of the KeePass database xml file created by
the `Open-KeePassPackage` function
.PARAMETER Name
The name for the field to search against.
.PARAMETER Value
The value to use for the comparison
.PARAMETER CaseInsenstive
If present, the search will be case insensitive.
.PARAMETER Comparison
The type of string comparison that will be used: Equal, StartsWith, EndsWith, Contains
.EXAMPLE
$entries = $Package | Find-KeePassEntry "Url" "http://google.com"
#>
Param(
[Parameter(Mandatory = $true, Position = 2, ValueFromPipeline = $true)]
[NerdyMishka.KeePass.KeePassPackage] $Package,
[Parameter(Mandatory = $true, Position = 0)]
[string] $Name,
[Parameter(Mandatory = $true, Position = 1)]
[string] $Value,
[switch] $CaseInsenstive,
[NerdyMishka.KeePass.StringComparison] $Comparison
)
return ,[NerdyMishka.KeePass.Search]::FindMatchesByField($Package, $Name, $Value, $CaseInsenstive.ToBool(), $Comparison)
}
|
PowerShellCorpus/PowerShellGallery/Fmg-KeePass/0.1.0/Find-KeePassEntryByTitle.ps1
|
Find-KeePassEntryByTitle.ps1
|
if((Get-Command New-KeePassKey -ErrorAction SilentlyContinue) -eq $null) {
. "$PSScriptRoot\New-KeePassKey.ps1"
}
function Find-KeePassEntryByTitle() {
<#
.SYNOPSIS
Searches for the first entry in the KeePass database with
a match on the given title
.DESCRIPTION
This method does a case insensivive equality search against the titles of
all the entries and returns the first match
.PARAMETER Package
The object representation of the KeePass database xml file created by
the `Open-KeePassPackage` function
.PARAMETER Title
The title for the entry.
.EXAMPLE
$entry = $Package | Find-KeePassEntryByTitle "cert:azure"
#>
Param(
[Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true)]
[NerdyMishka.KeePass.KeePassPackage] $Package,
[Parameter(Mandatory = $true, Position = 0)]
[string] $Title
)
return [NerdyMishka.KeePass.Search]::FindByTitle($Package, $Title)
}
|
PowerShellCorpus/PowerShellGallery/Fmg-KeePass/0.1.0/New-KeePassKey.ps1
|
New-KeePassKey.ps1
|
if([Type]::GetType("NerdyMishka.KeePass.Search") -eq $null) {
if($PSVersionTable.PSEdition -eq "Core") {
Write-Error "Not supported ... yet"
} else {
[System.Reflection.Assembly]::LoadFile("$PSScriptRoot\bin\net452\NerdyMishka.BitsAndPieces.dll") | Write-Debug
[System.Reflection.Assembly]::LoadFile("$PSScriptRoot\bin\net452\NerdyMishka.GoDark.dll") | Write-Debug
[System.Reflection.Assembly]::LoadFile("$PSScriptRoot\bin\net452\NerdyMishka.KeePass.Core.dll") | Write-Debug
[System.Reflection.Assembly]::LoadFile("$PSScriptRoot\bin\net452\NerdyMishka.KeePass.Operations.dll") | Write-Debug
}
}
function New-KeePassKey() {
<#
.SYNOPSIS
Creates a new KeePass master key
.DESCRIPTION
The master key is a composite key that are required to open KeePass
database files. Without it, the file can not be decrypted.
.PARAMETER Password
(Optional) The password for the composite key.
.PARAMETER KeyFile
(Optional) A file of bytes for the composites key.
.EXAMPLE
$key = New-KeePassKey -Passsword "your pass phrase"
.EXAMPLE
$key = New-KeePassKey -KeyFile "$home/Desktop/KP.key"
#>
Param(
[string] $Password = $null,
[string] $KeyFile = $null ,
[switch] $UserAccount
)
if([string]::IsNullOrWhiteSpace($Password)) {
$Password = $null;
}
if(![string]::IsNullOrWhiteSpace($KeyFile)) {
if(!(Test-Path $KeyFile)) {
throw [System.ArgumentException] "Could not find KeyFile at $KeyFile";
}
$KeyFile = (Resolve-Path $KeyFile).Path;
}
return ,[NerdyMishka.KeePass.DbOperations]::CreateKey($Password, $KeyFile)
}
|
PowerShellCorpus/PowerShellGallery/PKITools/1.6/HelperFunctions.ps1
|
HelperFunctions.ps1
|
function Get-Domain
{
<#
.Synopsis
Return the current domain
.DESCRIPTION
Use .net to get the current domain
.EXAMPLE
Get-Domain
#>
[CmdletBinding()]
[OutputType([System.DirectoryServices.ActiveDirectory.Domain])]
Param
()
Write-Verbose -Message 'Calling GetCurrentDomain()'
([DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain())
}
function Get-ADPKIEnrollmentServers
{
<#
.Synopsis
Return the Active Directory objects of the Certificate Authorites
.DESCRIPTION
Use .net to get the current domain
.EXAMPLE
Get-PKIEnrollmentServers
#>
[CmdletBinding()]
[OutputType([adsi])]
Param
(
[Parameter(Mandatory,HelpMessage='Domain To Query',Position = 0)]
[string]
$Domain
)
$QueryDN = 'LDAP://CN=Enrollment Services,CN=Public Key Services,CN=Services,CN=Configuration,DC=' + $Domain -replace '\.', ',DC='
Write-Verbose -Message "Querying [$QueryDN]"
$result = [ADSI]$QueryDN
if (-not ($result.Name))
{
Throw "Unable to find any Certificate Authority Enrollment Services Servers on domain : $Domain"
}
$result
}
function Get-ADCertificateTemplate
{
<#
.Synopsis
Return the Active Directory objects of the Certificate Authorites
.DESCRIPTION
Use .net to get the current domain
.EXAMPLE
Get-PKIEnrollmentServers
#>
[CmdletBinding()]
[OutputType([adsi])]
Param
(
[Parameter(Mandatory,HelpMessage='Domain To Query',Position = 0)]
[string]
$Domain,
[Parameter(Mandatory,HelpMessage='Template Name',Position = 1)]
[string]
$TemplateName
)
$QueryDN = "LDAP://CN=$TemplateName,CN=Certificate Templates,CN=Public Key Services,CN=Services,CN=Configuration,DC=" + $Domain -replace '\.', ',DC='
Write-Verbose -Message "Querying [$QueryDN]"
$result = [ADSI]$QueryDN
if (-not ($result.Name))
{
Throw "Unable to find any Certificate Authority Enrollment Services Servers on domain : $Domain"
}
$result
}
function Get-CaLocationString
{
<#
.SYNOPSIS
Gets the Certificate Authority Location String from active directory
.DESCRIPTION
Certificate Authority Location Strings are in the form of ComputerName\CAName This info is contained in Active Directory
.PARAMETER CAName
Name given when installing Active Directory Certificate Services
.PARAMETER ComputerName
Name of the computer with Active Directory Certificate Services Installed
.PARAMETER Domain
Domain to retreve data from
.EXAMPLE
get-CaLocationString -CAName MyCA
Gets only the CA Location String for the CA named MyCA
.EXAMPLE
get-CaLocationString -ComputerName ca.contoso.com
Gets only the CA Location String for server with the DNS name of ca.contoso.com
.EXAMPLE
get-CaLocationString -Domain contoso.com
Gets all CA Location Strings for the domain contoso.com
.NOTES
Location string are used to connect to Certificate Authority database and extract data.
.OUTPUTS
[STRING[]]
#>
[CmdletBinding()]
[OutputType([string])]
Param
(
# Name given when installing Active Directory Certificate Services
[string[]]
$CAName = $null,
# Name of the computer with Active Directory Certificate Services Installed
[string[]]
$ComputerName = $null,
# Domain to Search
[String]
$Domain = (Get-Domain).Name
)
$CAList = Get-CertificatAuthority @PSBoundParameters
foreach ($ca in $CAList)
{
('{0}\{1}' -f $($ca.dNSHostName), $($ca.name))
}
}
|
PowerShellCorpus/PowerShellGallery/PKITools/1.6/Get-IssuedCertificates.ps1
|
Get-IssuedCertificates.ps1
|
function Get-IssuedCertificate
{
<#
.SYNOPSIS
Get Issued Certificate data from one or more certificate athorities.
.DESCRIPTION
Can get various certificate fileds from the Certificate Authority database. Usfull for exporting certificates or checking what is about to expire
.PARAMETER ExpireInDays
Maximum number of days from now that a certificate will expire. (Default: 21900 = 60 years) Can be a negative numbe to check for recent expirations
.PARAMETER CAlocation
Certificate Authority location string "computername\CAName" (Default gets location strings from Current Domain)
.PARAMETER Properties
Fields in the Certificate Authority Database to Export
.PARAMETER CertificateTemplateOid
Filter on Certificate Template OID (use Get-CertificateTemplateOID)
.PARAMETER CommonName
Filter by Issued Common Name
.EXAMPLE
Get-IssuedCertificate -ExpireInDays 14
Gets all Issued Certificates Expireing in the next two weeks
.EXAMPLE
Get-IssuedCertificate -ExpireInDays -7
Gets all Issued Certificates that Expired last week
.EXAMPLE
Get-IssuedCertificate -CAlocation CA1\MyCA
Gets all Certificates Issued by CA1
.EXAMPLE
Get-IssuedCertificate -Properties 'Issued Common Name', 'Certificate Hash'
Gets all Issued Certificates and outputs only the Common name and thumbprint
.EXAMPLE
Get-IssuedCertificate -CommonName S1, S2.contoso.com
Gets Certificats issued to S1 and S2.contoso.com
.EXAMPLE
$DSCCerts = Get-IssuedCertificate -CertificateTemplateOid (Get-CertificateTemplateOID -Name 'DSCTemplate') -Properties 'Issued Common Name', 'Binary Certificate'
foreach ($cert in $DSCCerts)
{
set-content -path "c:\certs\$($cert.'Issued Common Name').cer" -Value $cert.'Binary Certificate' -Encoding Ascii
}
Get all certificates issued useing the DSCTemplate template and save them to the folder c:\certs named for the Common name of the certificate
#>
[CmdletBinding()]
Param (
# Maximum number of days from now that a certificate will expire. (Default: 21900 = 60 years)
[Int]
$ExpireInDays = 21900,
# Certificate Authority location string "computername\CAName" (Default gets location strings from Current Domain)
[String[]]
$CAlocation = (Get-CaLocationString),
# Fields in the Certificate Authority Database to Export
[String[]]
$Properties = (
'Issued Common Name',
'Certificate Expiration Date',
'Certificate Effective Date',
'Certificate Template',
#'Issued Email Address',
'Issued Request ID',
'Certificate Hash',
#'Request Disposition',
'Request Disposition Message',
'Requester Name',
'Binary Certificate' ),
# Filter on Certificate Template OID (use Get-CertificateTemplateOID)
[AllowNull()]
[String]
$CertificateTemplateOid,
# Filter by Issued Common Name
[AllowNull()]
[String]
$CommonName,
# Credential to with permissions to query ADSC
[AllowNull()]
[System.Management.Automation.Credential()][PSCredential]
$Credential
)
#endregion
$ScriptBlock = {
try
{
$CaView = New-Object -ComObject CertificateAuthority.View
}
catch
{
throw "Unable to create Certificate Authority View. $ENV:COMPUTERNAME Not not have ADSC Installed"
}
$null = $CaView.OpenConnection($using:Location)
$CaView.SetResultColumnCount($using:Properties.Count)
#region SetOutput Colum
foreach ($item in $using:Properties)
{
$index = $CaView.GetColumnIndex($false, $item)
$CaView.SetResultColumn($index)
}
#endregion
#region Filters
$CVR_SEEK_EQ = 1
$CVR_SEEK_LT = 2
$CVR_SEEK_GT = 16
#region filter expiration Date
$index = $CaView.GetColumnIndex($false, 'Certificate Expiration Date')
$now = Get-Date
$expirationdate = $now.AddDays($using:ExpireInDays)
if ($using:ExpireInDays -gt 0)
{
$CaView.SetRestriction($index,$CVR_SEEK_GT,0,$now)
$CaView.SetRestriction($index,$CVR_SEEK_LT,0,$expirationdate)
}
else
{
$CaView.SetRestriction($index,$CVR_SEEK_LT,0,$now)
$CaView.SetRestriction($index,$CVR_SEEK_GT,0,$expirationdate)
}
#endregion filter expiration date
#region Filter Template
if ($using:CertificateTemplateOid)
{
$index = $CaView.GetColumnIndex($false, 'Certificate Template')
$CaView.SetRestriction($index,$CVR_SEEK_EQ,0,$using:CertificateTemplateOid)
}
#endregion
#region Filter Issued Common Name
if ($using:CommonName)
{
$index = $CaView.GetColumnIndex($false, 'Issued Common Name')
$CaView.SetRestriction($index,$CVR_SEEK_EQ,0,$using:CommonName)
}
#endregion
#region Filter Only issued certificates
# 20 - issued certificates
$CaView.SetRestriction($CaView.GetColumnIndex($false, 'Request Disposition'),$CVR_SEEK_EQ,0,20)
#endregion
#endregion
#region output each retuned row
$CV_OUT_BASE64HEADER = 0
$CV_OUT_BASE64 = 1
$RowObj = $CaView.OpenView()
while ($RowObj.Next() -ne -1)
{
$Cert = New-Object -TypeName PsObject
$ColObj = $RowObj.EnumCertViewColumn()
$null = $ColObj.Next()
do
{
$displayName = $ColObj.GetDisplayName()
# format Binary Certificate in a savable format.
if ($displayName -eq 'Binary Certificate')
{
$Cert | Add-Member -MemberType NoteProperty -Name $displayName -Value $($ColObj.GetValue($CV_OUT_BASE64HEADER)) -Force
}
else
{
$Cert | Add-Member -MemberType NoteProperty -Name $displayName -Value $($ColObj.GetValue($CV_OUT_BASE64)) -Force
}
}
until ($ColObj.Next() -eq -1)
Clear-Variable -Name ColObj
$Cert
}
#endregion
}
foreach ($Location in $CAlocation)
{
$ComputerName = $Location -split '\\' | Select-Object -First 1
$Params = @{
'ScriptBlock' = $ScriptBlock
'ComputerName' = $ComputerName
}
if ($Credential)
{
$Params.Add('Credential',$Credential)
}
Invoke-Command @Params
}
}
|
PowerShellCorpus/PowerShellGallery/PKITools/1.6/Get-CertificateAuthority.ps1
|
Get-CertificateAuthority.ps1
|
function Get-CertificatAuthority
{
<#
.Synopsis
Get list of Certificate Authorities from Active directory
.DESCRIPTION
Queries Active Directory for Certificate Authorities with Enrollment Services enabled
.EXAMPLE
Get-CertificatAuthority
.EXAMPLE
Get-CertificatAuthority -CaName 'MyCA'
.EXAMPLE
Get-CertificatAuthority -ComputerName 'CA01' -Domain 'Contoso.com'
.OUTPUTS
System.DirectoryServices.DirectoryEntry
#>
[CmdletBinding()]
[OutputType([adsi])]
Param
(
# Name given when installing Active Directory Certificate Services
[string[]]
$CAName = $null,
# Name of the computer with Active Directory Certificate Services Installed
[string[]]
$ComputerName = $null,
# Domain to Search
[String]
$Domain = (Get-Domain).Name
)
Write-Verbose $Domain
## If the DN path does not exist error message set as valid object
$CaEnrolmentServices = Get-ADPKIEnrollmentServers $Domain
$CAList = $CaEnrolmentServices.Children
if($CAName)
{
$CAList = $CAList | Where-Object -Property Name -In -Value $CAName
}
if ($ComputerName)
{
# Make FQDN
[Collections.ArrayList]$List = @()
foreach ($Computer in $ComputerName)
{
if ($Computer -like "*.$Domain")
{
$null = $List.add($Computer)
}
else
{
$null = $List.add("$($Computer).$Domain")
}
} # end foreach
$CAList = $CAList | Where-Object -Property DNSHostName -In -Value $List
}
$CAList
}
|
PowerShellCorpus/PowerShellGallery/PKITools/1.6/Get-CertificateTemplateOID.ps1
|
Get-CertificateTemplateOID.ps1
|
function Get-CertificateTemplateOID
{
<#
.Synopsis
returns a PKI template OID
.DESCRIPTION
Connects to LDAP and retrievs the OID of a given PKI template by template Common Name
.EXAMPLE
Get-CertificateTemplateOID -Name 'DSCTemplate'
.EXAMPLE
Get-CertificateTemplateOID -Name 'DSCTemplate' -Domain contoso.com
.OUTPUTS
System.String
.NOTES
This may require RSAT.
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([String])]
Param
(
# Name of the template
[Parameter(Mandatory,HelpMessage = 'Name of the template')]
[ValidateNotNull()]
[ValidateNotNullOrEmpty()]
[Alias('cn')]
[string]
$Name,
# Domain to search (defaults to curent machines domain)
[string]
$Domain = (Get-Domain).name
)
(Get-ADCertificateTemplate -Domain $domain -TemplateName $Name ).'msPKI-Cert-Template-OID'
}
|
PowerShellCorpus/PowerShellGallery/xDismFeature/1.2.0.0/Example/Example_WithSource.ps1
|
Example_WithSource.ps1
|
Configuration DismWithWrongSource {
Import-DscResource -ModuleName xDismFeature
Node "localhost"
{
xDismFeature DismFeatureWithSource1
{
Ensure = "Present"
Name = "NetFx3"
Source = "asd"
}
}
}
Configuration DismWithoutSource {
Import-DscResource -ModuleName xDismFeature
Node "localhost"
{
xDismFeature DismFeatureWithSource2
{
Ensure = "Present"
Name = "NetFx3"
}
}
}
Configuration DismCorrectSource {
Import-DscResource -ModuleName xDismFeature
Node "localhost"
{
xDismFeature DismFeatureWithSource3
{
Ensure = "Present"
Name = "NetFx3"
Source = "C:\sources\sxs"
}
}
}
DismCorrectSource
DismWithoutSource
DismWithWrongSource
|
PowerShellCorpus/PowerShellGallery/VMware.VumAutomation/6.5.1.5301639/VMware.VumAutomation.ps1
|
VMware.VumAutomation.ps1
|
[VMware.VimAutomation.Sdk.Interop.V1.CoreServiceFactory]::CoreService.OnImportModule(
"VMware.VumAutomation",
(Split-Path $script:MyInvocation.MyCommand.Path));
function global:Get-VumCommand([string] $Name = "*") {
Get-Command -Module VMware.VumAutomation -Name $Name
}
set-alias Attach-Baseline Add-EntityBaseline -Scope Global
set-alias Detach-Baseline Remove-EntityBaseline -Scope Global
set-alias Download-Patch Sync-Patch -Scope Global
set-alias Remediate-Inventory Update-Entity -Scope Global
set-alias Scan-Inventory Test-Compliance -Scope Global
set-alias Stage-Patch Copy-Patch -Scope Global
# SIG # Begin signature block
# MIIebgYJKoZIhvcNAQcCoIIeXzCCHlsCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU4vsY4U3JckjZo9rHOznbPe6W
# L/mgghlLMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B
# AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG
# A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh
# d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg
# Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV
# UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu
# dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN
# AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q
# WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC
# i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhF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EQMmZD4IBr0nXGvHa/oWU3XJ
# cV9zB7g45BIMxTVpXOgUh7nM2CcNlCCfPR4TFriI1cOiUWYXW9agxdboEz9ZUTPw
# RgXENwLoEirwWedTZh74bDy/385DcifT8eCeBNgg9miZixtWvg3Ra4gbV4GDEdj0
# kxVJLDC7Rul1qJO0t8gWQQcSHW/dNblmoKc+zPI8dYZnrdhcC/1AEbY5NvBi0CSi
# edINLR1wtOtt3P06933mPhulmn58ZEsCELuHRNVeR2spraLdQftNyFlnvfuAYNu+
# sit/wXVu9TPVi1je+iVuO+jN
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/Posh-SYSLOG/2.0.4/Posh-SYSLOG.Tests.ps1
|
Posh-SYSLOG.Tests.ps1
|
Import-Module $PSScriptRoot\Posh-SYSLOG.psm1 -Force
Stop-Job -Name SyslogTest1 -ErrorAction SilentlyContinue
Remove-Job -Name SyslogTest1 -Force -ErrorAction SilentlyContinue
Describe 'Send-SyslogMessage' {
Mock -ModuleName Posh-SYSLOG Get-Date { return (New-Object datetime(2000,1,1)) }
Mock -ModuleName Posh-SYSLOG Get-NetIPAddress {return $null}
Mock -ModuleName Posh-SYSLOG Test-NetConnection {
$Connection = New-Object PSCustomObject
$Connection | Add-Member -MemberType NoteProperty -Name 'SourceAddress' -Value (New-Object PSCustomObject) -Force
$Connection.SourceAddress | Add-Member -MemberType NoteProperty -Name 'IPAddress' -Value ('123.123.123.123') -Force
$Connection.SourceAddress | Add-Member -MemberType NoteProperty -Name 'PrefixOrigin' -Value ('Manual') -Force
return $Connection
}
$ENV:Computername = 'TestHostname'
$ENV:userdnsdomain = $null
$ExpectedTimeStamp = (New-Object datetime(2000,1,1)).ToString('yyyy-MM-ddTHH:mm:ss.ffffffzzz')
function Test-Message ($SendSyslogMessage)
{
$GetSyslogPacket = {
$endpoint = New-Object System.Net.IPEndPoint ([IPAddress]::Any,514)
$udpclient= New-Object System.Net.Sockets.UdpClient 514
$content=$udpclient.Receive([ref]$endpoint)
[Text.Encoding]::ASCII.GetString($content)
}
$null = start-job -Name SyslogTest1 -ScriptBlock $GetSyslogPacket
Start-Sleep 2
Invoke-Expression $SendSyslogMessage
do
{
Start-Sleep 1
}
until ((Get-Job -Name SyslogTest1 | Select-Object -ExpandProperty State) -eq 'Completed')
$UDPResult = Receive-Job SyslogTest1
Remove-Job SyslogTest1
return $UDPResult
}
Context 'Parameter Validation' {
It 'Should not accept a null value for the server' {
{Send-SyslogMessage -Server $null -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth'} | Should Throw 'The argument is null or empty'
}
It 'Should not accept a null value for the message' {
{Send-SyslogMessage -Server '127.0.0.1' -Message $null -Severity 'Alert' -Facility 'auth'} | Should Throw 'The argument is null or empty'
}
It 'Should not accept a null value for the severity' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity $null -Facility 'auth'} | Should Throw 'Cannot convert null to type "Syslog_Severity"'
}
It 'Should not accept a null value for the facility' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility $null} | Should Throw 'Cannot convert null to type "Syslog_Facility"'
}
It 'Should not accept a null value for the hostname' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -Hostname $null} | Should Throw 'The argument is null or empty'
}
It 'Should not accept a null value for the application name' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -ApplicationName $null} | Should Throw 'The argument is null or empty'
}
It 'Should not accept a null value for the timestamp' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -Timestamp $null} | Should Throw 'Cannot convert null to type "System.DateTime"'
}
It 'Should not accept a null value for the UDP port' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -UDPPort $null} | Should Throw 'Cannot validate argument on parameter'
}
It 'Should not accept an invalid value for the UDP port' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -UDPPort 456789789789} | Should Throw 'Error: "Value was either too large or too small for a UInt16.'
}
It 'Should reject ProcessID parameter if -RFC3164 is specified' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -RFC3164 -ProcessID 1} | Should Throw 'Parameter set cannot be resolved using the specified named parameters'
}
It 'Should reject MessageID parameter if -RFC3164 is specified' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -RFC3164 -MessageID 1} | Should Throw 'Parameter set cannot be resolved using the specified named parameters'
}
It 'Should reject StructuredData parameter if -RFC3164 is specified' {
{Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -RFC3164 -StructuredData 1} | Should Throw 'Parameter set cannot be resolved using the specified named parameters'
}
}
Context 'Severity Level Calculations' {
It 'Calculates the correct priority of 0 if Facility is Kern and Severity is Emergency' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Emergency' -Facility 'kern'"
$ExpectedResult = '<0>1 {0} TestHostname PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
It 'Calculates the correct priority of 7 if Facility is Kern and Severity is Debug' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Debug' -Facility 'kern'"
$ExpectedResult = '<7>1 {0} TestHostname PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
It 'Calculates the correct priority of 24 if Facility is daemon and Severity is Emergency' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Emergency' -Facility 'daemon'"
$ExpectedResult = '<24>1 {0} TestHostname PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
It 'Calculates the correct priority of 31 if Facility is daemon and Severity is Debug' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Debug' -Facility 'daemon'"
$ExpectedResult = '<31>1 {0} TestHostname PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
}
Context 'RFC 3164 Message Format' {
It 'Should send RFC5424 formatted message' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -RFC3164"
$ExpectedResult = '<33>Jan 01 00:00:00 TestHostname PowerShell Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
}
Context 'RFC 5424 message format' {
It 'Should send RFC5424 formatted message' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth'"
$ExpectedResult = '<33>1 {0} TestHostname PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
}
Context 'Hostname determination' {
It 'Uses any hostname it is given' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth' -Hostname 'SomeRandomHostNameDude'"
$ExpectedResult = '<33>1 {0} SomeRandomHostNameDude PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
It 'Uses the FQDN if the computer is domain joined' {
$ENV:userdnsdomain = 'contoso.com'
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth'"
$ExpectedResult = '<33>1 {0} TestHostname.contoso.com PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$ENV:userdnsdomain = ''
$TestResult | Should Be $ExpectedResult
}
It 'Uses a Static IP address, on the correct interface that the server is reached on, if no FQDN and not hostname specified' {
Mock -ModuleName Posh-SYSLOG Get-NetIPAddress {return 'value'}
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth'"
$ExpectedResult = '<33>1 {0} 123.123.123.123 PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
It 'Uses the Windows computer name, if no static ip or FQDN' {
Mock -ModuleName Posh-SYSLOG Get-NetIPAddress {return $null}
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth'"
$ExpectedResult = '<33>1 {0} TestHostname PowerShell {1} - - Test Syslog Message' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
}
Context 'Log Message tests' {
It 'truncates long messages correctly' {
$TestCase = "Send-SyslogMessage -Server '127.0.0.1' -Message 'This is a very long syslog message. 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890' -Severity 'Alert' -Facility 'auth'"
$ExpectedResult = '<33>1 {0} TestHostname PowerShell {1} - - This is a very long syslog message. 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234' -f $ExpectedTimeStamp, $PID
$TestResult = Test-Message $TestCase
$TestResult | Should Be $ExpectedResult
}
}
Context 'Function tests' {
It 'does not return any values' {
$TestCase = Send-SyslogMessage -Server '127.0.0.1' -Message 'Test Syslog Message' -Severity 'Alert' -Facility 'auth'
$TestCase | Should be $null
}
}
Context 'Scrypt Analyzer' {
It 'Does not have any issues with the Script Analyser' {
Invoke-ScriptAnalyzer .\Functions\Send-SyslogMessage.ps1 | Should be $null
}
}
}
|
PowerShellCorpus/PowerShellGallery/Posh-SYSLOG/2.0.4/Functions/Send-SyslogMessage.ps1
|
Send-SyslogMessage.ps1
|
#requires -Version 2 -Modules NetTCPIP
enum Syslog_Facility
{
kern
user
mail
daemon
auth
syslog
lpr
news
uucp
clock
authpriv
ftp
ntp
logaudit
logalert
cron
local0
local1
local2
local3
local4
local5
local6
local7
}
enum Syslog_Severity
{
Emergency
Alert
Critical
Error
Warning
Notice
Informational
Debug
}
function Send-SyslogMessage
{
<#
.SYNOPSIS
Sends a SYSLOG message to a server running the SYSLOG daemon
.DESCRIPTION
Sends a message to a SYSLOG server as defined in RFC 5424 and RFC 3164.
.INPUTS
Nothing can be piped directly into this function
.OUTPUTS
Nothing is output
.EXAMPLE
Send-SyslogMessage mySyslogserver "The server is down!" Emergency Mail
Sends a syslog message to mysyslogserver, saying "server is down", severity emergency and facility is mail
.NOTES
NAME: Send-SyslogMessage
AUTHOR: Kieran Jacobsen
.LINK
https://github.com/poshsecurity/Posh-Syslog
.LINK
https://poshsecurity.com
#>
[CMDLetBinding(DefaultParameterSetName = 'RFC5424')]
Param
(
#Destination SYSLOG server that message is to be sent to.
[Parameter(mandatory = $true,
HelpMessage = 'Server to send message to')]
[ValidateNotNullOrEmpty()]
[String]
$Server,
#Our message or content that we want to send to the server. This is option in RFC 5424, the CMDLet still has this as a madatory parameter, to send no message, simply specifiy '-' (as per RFC).
[Parameter(mandatory = $true,
HelpMessage = 'Message to send')]
[ValidateNotNullOrEmpty()]
[String]
$Message,
#Severity level as defined in SYSLOG specification, must be of ENUM type Syslog_Severity
[Parameter(mandatory = $true,
HelpMessage = 'Messsage severity level')]
[ValidateNotNullOrEmpty()]
[Syslog_Severity]
$Severity,
#Facility of message as defined in SYSLOG specification, must be of ENUM type Syslog_Facility
[Parameter(mandatory = $true,
HelpMessage = 'Facility sending message')]
[ValidateNotNullOrEmpty()]
[Syslog_Facility]
$Facility,
#Hostname of machine the mssage is about, if not specified, RFC 5425 selection rules will be followed.
[Parameter(mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]
$Hostname = '',
#Specify the name of the application or script that is sending the mesage. If not specified, will select the ScriptName, or if empty, powershell.exe will be sent. To send Null, specify '-' to meet RFC 5424.
[Parameter(mandatory = $false)]
[ValidateNotNullOrEmpty()]
[String]
$ApplicationName = '',
#ProcessID or PID of generator of message. Will automatically use $PID global variable. If you want to override this and send null, specify '-' to meet RFC 5424 rquirements. This is only sent for RFC 5424 messages.
[Parameter(mandatory = $false,
ParameterSetName = 'RFC5424')]
[ValidateNotNullOrEmpty()]
[String]
$ProcessID = $PID,
#Error message or troubleshooting number associated with the message being sent. If you want to override this and send null, specify '-' to meet RFC 5424 rquirements. This is only sent for RFC 5424 messages.
[Parameter(mandatory = $false,
ParameterSetName = 'RFC5424')]
[ValidateNotNullOrEmpty()]
[String]
$MessageID = '-',
#Key Pairs of structured data as a string as defined in RFC5424. Default will be '-' which means null. This is only sent for RFC 5424 messages.
[Parameter(mandatory = $false,
ParameterSetName = 'RFC5424')]
[ValidateNotNullOrEmpty()]
[String]
$StructuredData = '-',
#Time and date of the message, must be of type DateTime. Correct format will be selected depending on RFC requested. If not specified, will call get-date to get appropriate date time.
[Parameter(mandatory = $false)]
[ValidateNotNullOrEmpty()]
[DateTime]
$Timestamp = (Get-Date),
#SYSLOG UDP port to send message to. Defaults to 514 if not specified.
[Parameter(mandatory = $false)]
[ValidateNotNullOrEmpty()]
[ValidateRange(1,65535)]
[UInt16]
$UDPPort = 514,
#Send an RFC3164 fomatted message instead of RFC5424.
[Parameter(mandatory = $True,
ParameterSetName = 'RFC3164')]
[switch]
$RFC3164
)
# Evaluate the facility and severity based on the enum types
$Facility_Number = $Facility.value__
$Severity_Number = $Severity.value__
Write-Verbose -Message "Syslog Facility, $Facility_Number, Severity is $Severity_Number"
# Calculate the priority
$Priority = ($Facility_Number * 8) + $Severity_Number
Write-Verbose -Message "Priority is $Priority"
<#
Application name or process name, simply find out if a script is calling the CMDLet, else use PowerShell
#>
if ($ApplicationName -eq '')
{
if (($null -ne $myInvocation.ScriptName) -and ($myInvocation.ScriptName -ne ''))
{
$ApplicationName = Split-Path -Leaf -Path $myInvocation.ScriptName
}
else
{
$ApplicationName = 'PowerShell'
}
}
<#
According to RFC 5424, we need to send our hostname as one of these 5 (in order of priority)
1. FQDN
2. Static IP address
3. Hostname - Windows always has one of these, so this is our last resort
4. Dynamic IP address - We will never get to this one
5. the NILVALUE - or this one
Windows should always, in the worst case, have a result at 3, the hostname or computer name of the system this command is run from.
Taking this into account, then our logic, if no hostname is provided should be:
1. Are we domain joined, if so, we have a FQDN
2. Do we have any static ip allocations and can we ping or at least try to ping the SYSLOG server from an interface with a static ip address
The elseif statement first determines if there are any interfaces with a static address, if there are, it does the ping, otherwise it returns false immediately.
This is due to how PowerShell processes -and/-or/etc logic.
3. The name of the computer
#>
if ($Hostname -eq '')
{
if ($null -ne $ENV:userdnsdomain)
{
# Option 1, FQDN
$Hostname = $ENV:Computername + '.' + $ENV:userdnsdomain
}
elseif (($null -ne (Get-NetIPAddress -PrefixOrigin Manual -SuffixOrigin Manual -ErrorAction SilentlyContinue)) -and ((Test-NetConnection -ComputerName $Server -ErrorAction SilentlyContinue).SourceAddress.PrefixOrigin -eq 'Manual'))
{
# Option 2, Static IP address
# ** Changes here as suggested by Brtlvrs **
$Hostname = (Test-NetConnection -ComputerName $Server -ErrorAction SilentlyContinue).SourceAddress.IPAddress
}
else
{
# Option 3
$Hostname = $ENV:Computername
}
}
if ($PSCmdlet.ParameterSetName -eq 'RFC3164')
{
Write-Verbose -Message 'Using RFC 3164 UNIX/BSD message format'
#Get the timestamp
$FormattedTimestamp = (Get-Culture).TextInfo.ToTitleCase($Timestamp.ToString('MMM dd HH:mm:ss'))
# Assemble the full syslog formatted Message
$FullSyslogMessage = '<{0}>{1} {2} {3} {4}' -f $Priority, $FormattedTimestamp, $Hostname, $ApplicationName, $Message
}
else
{
Write-Verbose -Message 'Using RFC 5424 IETF message format'
#Get the timestamp
$FormattedTimestamp = $Timestamp.ToString('yyyy-MM-ddTHH:mm:ss.ffffffzzz')
# Assemble the full syslog formatted Message
$FullSyslogMessage = '<{0}>1 {1} {2} {3} {4} {5} {6} {7}' -f $Priority, $FormattedTimestamp, $Hostname, $ApplicationName, $ProcessID, $MessageID, $StructuredData, $Message
}
Write-Verbose -Message "Message to send will be $FullSyslogMessage"
# create an ASCII Encoding object
$Encoding = [System.Text.Encoding]::ASCII
# Convert into byte array representation
$ByteSyslogMessage = $Encoding.GetBytes($FullSyslogMessage)
# If the message is too long, shorten it
if ($ByteSyslogMessage.Length -gt 1024)
{
$ByteSyslogMessage = $Encoding.GetBytes($FullSyslogMessage.SubString(0, 1024))
}
# Create a UDP Client Object
$UDPCLient = New-Object -TypeName System.Net.Sockets.UdpClient
$UDPCLient.Connect($Server, $UDPPort)
# Send the Message
$null = $UDPCLient.Send($ByteSyslogMessage, $ByteSyslogMessage.Length)
#Close the connection
$UDPCLient.Close()
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/New-KPEntry.ps1
|
New-KPEntry.ps1
|
#.ExternalHelp psKeePass.Help.xml
function New-KPEntry
{
# http://technet.microsoft.com/en-us/library/hh847872.aspx
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
PositionalBinding=$false
#HelpUri = 'http://www.microsoft.com/',
#ConfirmImpact='Medium'
)]
#[OutputType([String])]
param(
[Parameter(Mandatory=$true, Position = 1, HelpMessage="Use path to KeePass database.")]
[string]$KeyPassFile,
[Parameter(Mandatory=$false,HelpMessage='Use MasterPassword to KeePass database.')]
[Security.SecureString]$MasterPassword=(Get-KPSecurePassword -Alias Default).MasterPassword,
[Parameter(Mandatory=$false,HelpMessage='Use to set Title the new entry.')]
[String]$EntryTitle,
[Parameter(Mandatory=$False,HelpMessage='Use to set Username the new entry.')]
[String]$EntryUserName,
[Parameter(Mandatory=$False, ParameterSetName="EntryPassword",HelpMessage='Use to set Password the new entry.')]
[String]$EntryPassword,
[Parameter(Mandatory=$False, ParameterSetName="AutoPassword",HelpMessage='Use to define the password length.')]
[int]$EntryPasswordLenght=20,
[Parameter(Mandatory=$False, ParameterSetName="AutoPassword",HelpMessage='Use to generate password.')]
[Switch]$EntryPasswordComplex,
[Parameter(Mandatory=$False,HelpMessage='Use to Url the new entry.')]
[String]$EntryUrl,
[Parameter(Mandatory=$False,HelpMessage='Use to set Tags the new entry.')]
[String[]]$Tags,
[Parameter(Mandatory=$False,HelpMessage='Use to set Notes the new entry.')]
[String]$EntryNotes,
[Parameter(Mandatory=$False,HelpMessage='Use to set logical path to the new entry.')]
[String]$GroupPath,
[Parameter(Mandatory=$False,HelpMessage='Use to output the new entry.')]
[Switch]$PassThru
)
BEGIN
{
$currentMethod = (Get-PSCallStack)[0].Command
if (-not $MasterPassword)
{
do
{
$MasterPassword = Read-Host -Prompt "Type the Master Password to KeepPass Database `n$($KeyPassFile)" -AsSecureString
}While(-not $MasterPassword)
}
if (Test-Path $KeyPassFile)
{
if (-not $ConnectionInfo)
{
$connectionInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
$connectionInfo.Path = $KeyPassFile
New-KPParamHistory -Function $currentMethod -Parameter KeyPassFile -Content $KeyPassFile
}
}
else
{
Write-Host File $KeyPassFile not found. -ForegroundColor Red
break;
}
$kpDatabase = new-object KeePassLib.PwDatabase
$compositeKey = new-object KeePassLib.Keys.CompositeKey
#$m_pKey.AddUserKey((New-Object KeePassLib.Keys.KcpUserAccount))
$compositeKey.AddUserKey((New-Object KeePassLib.Keys.KcpPassword($MasterPassword | ConvertTo-KPPlainText)));
$StatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger
try
{
$kpDatabase.Open($connectionInfo,$compositeKey,$StatusLogger)
}
catch [KeePassLib.Keys.InvalidCompositeKeyException]
{
Write-Host Incorrect password. $($_.Exception.Message) -ForegroundColor Red
break;
}
catch [Exception]
{
Write-Host $_.Exception.Message
Write-KPLog -message $_ -Level EXCEPTION
break;
}
function Get-PwGroup ($RootGroup,[String]$GroupPath)
{
$Tree = $GroupPath -split '\\'
if ($Tree)
{
#$pwGroup = $RootGroup.Groups
$pwGroup = $RootGroup
foreach ($groupName in $Tree)
{
if (-not [String]::IsNullOrEmpty($groupName))
{
if ($groupName -in $pwGroup.Name)
{
$pwGroup = $pwGroup | ? {$_.Name -eq $groupName}
$out = $pwGroup
$pwGroup = $pwGroup.Groups
$isValidGroup = $True
}
else
{
$isValidGroup = $False
break
}
}
}
if ($isValidGroup)
{
#return [Array]$Tree | ? { -not [String]::IsNullOrEmpty($_) }
return $out
}
else
{
return $null
}
}
else
{
return $RootGroup
}
}
}
PROCESS
{
try
{
$rootGroup = $kpDatabase.RootGroup
$PwGroup = Get-PwGroup $rootGroup $GroupPath
# The $True arguments allow new UUID and timestamps to be created automatically:
$PwEntry = New-Object -TypeName KeePassLib.PwEntry( $PwGroup[0], $True, $True )
if (-not $EntryPassword)
{
$EntryPassword = Get-KPRandomPassword -Length $EntryPasswordLenght -Complex:$EntryPasswordComplex.IsPresent
}
$EntryNotes += "`n#New entry by psKeePass"
# Protected strings are encrypted in memory:
$pTitle = New-Object KeePassLib.Security.ProtectedString($True, $EntryTitle)
$pUser = New-Object KeePassLib.Security.ProtectedString($True, $EntryUserName)
$pPW = New-Object KeePassLib.Security.ProtectedString($True, $EntryPassword)
$pURL = New-Object KeePassLib.Security.ProtectedString($True, $EntryUrl)
$pNotes = New-Object KeePassLib.Security.ProtectedString($True, $EntryNotes)
$PwEntry.Strings.Set("Title", $pTitle)
$PwEntry.Strings.Set("UserName", $pUser)
$PwEntry.Strings.Set("Password", $pPW)
$PwEntry.Strings.Set("URL", $pURL)
$PwEntry.Strings.Set("Notes", $pNotes)
$Tags | % { $null = $PwEntry.AddTag($_) }
$PwGroup[0].AddEntry($PwEntry, $True)
# Notice that the database is automatically saved here!
#$StatusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger
$kpDatabase.Save($StatusLogger)
if ($PassThru.IsPresent)
{
Get-KPEntry -ConnectionInfo $connectionInfo -CompositeKey $compositeKey -Uuid $PwEntry.Uuid
}
}
catch [Exception]
{
Write-Host $_.Exception.Message
Write-KPLog -message $_ -Level EXCEPTION
}
}
END
{
if ($kpDatabase.IsOpen)
{
$kpDatabase.Close()
}
}
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/Remove-KPEntry.ps1
|
Remove-KPEntry.ps1
|
#.ExternalHelp psKeePass.Help.xml
function Remove-KPEntry
{
# http://technet.microsoft.com/en-us/library/hh847872.aspx
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
PositionalBinding=$false
#HelpUri = 'http://www.microsoft.com/',
#ConfirmImpact='Medium'
)]
#[OutputType([String])]
param(
[Parameter(Mandatory=$false,ValueFromPipeline=$True,DontShow)]
[KeePassLib.PwEntry]$InputObject,
[Parameter(Mandatory=$False)]
[Switch]$Permanent,
[Parameter(Mandatory=$False)]
[Switch]$PassThru
)
BEGIN
{
# http://stackoverflow.com/questions/20690347/c-sharp-delete-group-from-keepass-database
$kpDatabase = new-object KeePassLib.PwDatabase
$statusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger
}
PROCESS
{
#Write-Output $InputObject
if ($InputObject)
{
$InputObject | % {
try
{
if ($_ -is [KeePassLib.PwEntry] )
{
try
{
$PwEntry = $_
$connectionInfo = $PwEntry.connectionInfo
$compositeKey = $PwEntry.compositeKey
$kpDatabase.open($connectionInfo,$compositeKey,$statusLogger)
$pwDeletedObject = New-Object KeePassLib.PwDeletedObject
$pwDeletedObject.Uuid = $PwEntry.Uuid
$pwDeletedObject.DeletionTime = Get-Date
$kpDatabase.DeletedObjects.Add($pwDeletedObject)
$kpDatabase.MergeIn($kpDatabase,[KeePassLib.PwMergeMethod]::Synchronize,$statusLogger)
if ($kpDatabase.RecycleBinEnabled -and (-not $Permanent.IsPresent))
{
$pwGroupRecycleBin = $kpDatabase.RootGroup.FindGroup($kpDatabase.RecycleBinUuid,$true)
$pwGroupRecycleBin.AddEntry($PwEntry, $true, $true)
}
$PwEntry.Touch($true,$true)
$kpDatabase.Save($statusLogger)
$kpDatabase.Close()
}
catch [Exception]
{
Write-KPLog -message $_ -Level EXCEPTION
Write-Host $($_.Exception.Message) -ForegroundColor Red
}
}
else
{
Write-Host InputObjec is not KeePassLib.PwEntry. -ForegroundColor Red
break
}
if ($PassThru.IsPresent)
{
Get-KPEntry -ConnectionInfo $connectionInfo -CompositeKey $compositeKey -Uuid $PwEntry.Uuid
}
}
catch [Exception]
{
Write-KPLog -message $_ -Level EXCEPTION
Write-Host $($_.Exception.Message) -ForegroundColor Red
continue
}
}#InputObject
}
}
END
{
}
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/TabExpansion.ps1
|
TabExpansion.ps1
|
try
{
Import-Module -Name TabExpansionPlusPlus -ea Ignore
if (Get-Command Register-ArgumentCompleter -Module TabExpansionPlusPlus -ea Ignore)
{
# http://www.powertheshell.com/dynamicargumentcompletion/
# https://github.com/lzybkr/TabExpansionPlusPlus
$cmdlets = @('Get-KPEntry','New-KPEntry')
$cmdlets | % {
#Register-ArgumentCompleter -CommandName $_ -ParameterName "KeyPassFile" -ScriptBlock {
# param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
# Import-Module (Join-Path $PSScriptRoot common\common.psm1) -Prefix KP
# $path = Get-KPParamHistory -Function Get-KPEntry -Parameter KeyPassFile
# if ($path)
# {
# $path | % { New-CompletionResult -CompletionText "'$($_.Content)'" -ListItemText $($_.Content) }
# }
#}
Register-ArgumentCompleter -CommandName $_ -ParameterName "MasterPassword" -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)
Import-Module (Join-Path $PSScriptRoot common\common.psm1) -Prefix KP
$path = Get-KPSecurePassword
if ($path)
{
$path | % { New-CompletionResult -CompletionText ("(Get-KPSecurePassword -Alias $($_.Alias)).MasterPassword") -ListItemText $_.Alias -NoQuotes }
}
}
}
}
elseif (Get-Command Register-ArgumentCompleter -Module Microsoft.PowerShell.Core -ea Ignore)
{
#https://technet.microsoft.com/en-us/library/mt631420.aspx
$cmdlets = @('Get-KPEntry','New-KPEntry')
$cmdlets | % {
#Microsoft.PowerShell.Core\Register-ArgumentCompleter -CommandName $_ -ParameterName "KeyPassFile" -ScriptBlock { Get-KPParamHistory -Function $_ -Parameter KeyPassFile | % {"'$($_.Content)'"} }
Microsoft.PowerShell.Core\Register-ArgumentCompleter -CommandName $_ -ParameterName "MasterPassword" -ScriptBlock { Get-KPSecurePassword | % {"(Get-KPSecurePassword -Alias $($_.Alias)).MasterPassword"} }
}
}
}
catch
{
Write-KPLog -message $_ -Level EXCEPTION
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/Get-KPEntry.ps1
|
Get-KPEntry.ps1
|
#.ExternalHelp psKeePass.Help.xml
function Get-KPEntry
{
# http://technet.microsoft.com/en-us/library/hh847872.aspx
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
PositionalBinding=$false
#HelpUri = 'http://www.microsoft.com/',
#ConfirmImpact='Medium'
)]
#[OutputType([String])]
param(
[Parameter(Mandatory=$False, Position = 1, HelpMessage="Use managedServer name.")]
[string]$KeyPassFile,
[Parameter(Mandatory=$False, HelpMessage="Use filter EntryKeys.", ParameterSetName='EntryKeys')]
[EntryKeys[]]$Key,
[Parameter(Mandatory=$False, HelpMessage="Use filter Value.", ParameterSetName='EntryKeys')]
[string]$Value,
[Parameter(Mandatory=$False, HelpMessage="Use to filter by GroupPath.")]
[string]$GroupPath,
[Parameter(Mandatory=$False, HelpMessage="Use KeePassLib.PwUuid object.", ParameterSetName='Uuid')]
[KeePassLib.PwUuid]$Uuid,
[Parameter(Mandatory=$False)]
[Security.SecureString]$MasterPassword=(Get-KPSecurePassword -Alias Default).MasterPassword,
[Parameter(Mandatory=$False, HelpMessage="Use managedServer name.")]
[Switch]$ForcePlainText,
[Parameter(Mandatory=$False, HelpMessage="Use managedServer name.")]
[Switch]$IncludeRecycleBin,
[Parameter(Mandatory=$False,DontShow)]
[KeePassLib.Keys.CompositeKey]$CompositeKey,
[Parameter(Mandatory=$False,DontShow)]
[KeePassLib.Serialization.IOConnectionInfo]$ConnectionInfo
)
BEGIN
{
# http://keepass.info/help/v2_dev/scr_sc_index.html#getentrystring
# http://it-by-doing.blogspot.com.br/2014/10/accessing-keepass-with-powershell.html
function Get-ParentGroups ($item)
{
if ($item)
{
try
{
$item = $item.ParentGroup
$pGroups = New-Object -TypeName System.Collections.ArrayList
While($item)
{
$pGroups.Add($item)
$item = $item.ParentGroup
}
return $pGroups
}
catch [Exception]
{
return $null
}
}
}
$currentMethod = (Get-PSCallStack)[0].Command
if (-not $MasterPassword)
{
do
{
$MasterPassword = Read-Host -Prompt "Type the Master Password to KeepPass Database `n$($KeyPassFile)" -AsSecureString
}While(-not $MasterPassword)
}
$kpDatabase = new-object KeePassLib.PwDatabase
$statusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger
if (-not $CompositeKey)
{
$compositeKey = new-object KeePassLib.Keys.CompositeKey
#$m_pKey.AddUserKey((New-Object KeePassLib.Keys.KcpUserAccount))
$compositeKey.AddUserKey((New-Object KeePassLib.Keys.KcpPassword($MasterPassword | ConvertTo-KPPlainText)));
}
if (-not $ConnectionInfo)
{
if (Test-Path $KeyPassFile)
{
$connectionInfo = New-Object KeePassLib.Serialization.IOConnectionInfo
$connectionInfo.Path = $KeyPassFile
New-KPParamHistory -Function $currentMethod -Parameter KeyPassFile -Content $KeyPassFile
}
else
{
Write-Host File $KeyPassFile not found. -ForegroundColor Red
break;
}
}
try
{
$kpDatabase.Open($connectionInfo,$compositeKey,$statusLogger)
if ($Uuid)
{
$kpItems = $kpDatabase.RootGroup.FindEntry($Uuid,$true)
}
else
{
$kpItems = $kpDatabase.RootGroup.GetObjects($true, $true)
if (-not $IncludeRecycleBin.IsPresent)
{
$kpItems = $kpItems | ? {
$pGroups = Get-ParentGroups $_
$pGroups.Uuid -notcontains $kpDatabase.RecycleBinUuid
#$_.ParentGroup.Uuid -ne $kpDatabase.RecycleBinUuid
}
}
}
}
catch [KeePassLib.Keys.InvalidCompositeKeyException]
{
Write-Host Incorrect password. $($_.Exception.Message) -ForegroundColor Red
break;
}
catch [Exception]
{
Write-Host $_.Exception.Message -ForegroundColor Red
Write-KPLog -message $_ -Level EXCEPTION
break;
}
try
{
$kpDatabase.Close()
}
catch [Exception]
{
Write-Host $_.Exception.Message -ForegroundColor Red
Write-KPLog -message $_ -Level EXCEPTION
}
if ([String]::IsNullOrEmpty($key))
{
$Key = [System.Enum]::GetValues('EntryKeys')
}
if (-not $Value)
{
$Value = '*'
}
}#BEGIN
PROCESS
{
# GroupPath option
if ($kpItems)
{
$kpItems | % {
$pNames = (Get-ParentGroups $_).name
[Array]::Reverse($pNames)
$gPath = $pNames -join '\'
try
{
Add-Member -InputObject $_ -MemberType NoteProperty -Name GroupPath -Value "\$($gPath)"
}
catch [Exception]
{
Write-KPLog -message $_ -Level EXCEPTION
}
}
if ($GroupPath)
{
$kpItems = $kpItems | ? {$_.GroupPath -like $GroupPath}
}
}
foreach($kpItem in $kpItems)
{
foreach ($k in $key)
{
$val = $kpItem.Strings.ReadSafe($K)
if ( $val -and ($val -like $Value) )
{
$item = Format-KpPwEntry -PwEntry $kpItem -CompositeKey $CompositeKey -ConnectionInfo $ConnectionInfo -ForcePlainText:$ForcePlainText.IsPresent
if ($item)
{
Set-KPStandardMembers -MyObject $item -DefaultProperties UserName,Password,Title,GroupPath
Write-Output $item
}
break
}#if
$secPassword = $null
}
}
}#PROCESS
END
{}#END
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/Set-KPEntry.ps1
|
Set-KPEntry.ps1
|
#.ExternalHelp psKeePass.Help.xml
function Set-KPEntry
{
# http://technet.microsoft.com/en-us/library/hh847872.aspx
[CmdletBinding(DefaultParameterSetName='Parameter Set 1',
SupportsShouldProcess=$true,
PositionalBinding=$false
#HelpUri = 'http://www.microsoft.com/',
#ConfirmImpact='Medium'
)]
#[OutputType([String])]
param(
[Parameter(Mandatory=$false,ValueFromPipeline=$True,DontShow)]
[KeePassLib.PwEntry]$InputObject,
[Parameter(Mandatory=$False)]
[String]$EntryTitle,
[Parameter(Mandatory=$False)]
[String]$EntryUserName,
[Parameter(Mandatory=$False, ParameterSetName="EntryPassword")]
[Security.SecureString]$EntryPassword,
[Parameter(Mandatory=$False, ParameterSetName="AutoPassword",HelpMessage='Use to define the password length.')]
[Switch]$AutoResetPassword,
[Parameter(Mandatory=$False, ParameterSetName="AutoPassword",HelpMessage='Use to define the password length.')]
[int]$EntryPasswordLenght=20,
[Parameter(Mandatory=$False, ParameterSetName="AutoPassword",HelpMessage='Use to generate password.')]
[Switch]$EntryPasswordComplex,
[Parameter(Mandatory=$False)]
[String]$EntryUrl,
[Parameter(Mandatory=$False,HelpMessage='Use to Add new Tags.')]
[String[]]$AddTags,
[Parameter(Mandatory=$False,HelpMessage='Use to Remove Tags.')]
[String[]]$RemoveTags,
[Parameter(Mandatory=$False)]
[String]$EntryNotes,
[Parameter(Mandatory=$False,HelpMessage='Use to move entry to group.')]
[String]$GroupPath,
[Parameter(Mandatory=$False)]
[Switch]$PassThru
)
BEGIN
{
function Get-PwGroup ($RootGroup,[String]$GroupPath)
{
$Tree = $GroupPath -split '\\'
if ($Tree)
{
#$pwGroup = $RootGroup.Groups
$pwGroup = $RootGroup
foreach ($groupName in $Tree)
{
if (-not [String]::IsNullOrEmpty($groupName))
{
if ($groupName -in $pwGroup.Name)
{
$pwGroup = $pwGroup | ? {$_.Name -eq $groupName}
$out = $pwGroup
$pwGroup = $pwGroup.Groups
$isValidGroup = $True
}
else
{
$isValidGroup = $False
break
}
}
}
if ($isValidGroup)
{
#return [Array]$Tree | ? { -not [String]::IsNullOrEmpty($_) }
return $out
}
else
{
return $null
}
}
else
{
return $RootGroup
}
}
}
PROCESS
{
if ($InputObject)
{
$InputObject | % {
try
{
if ($_ -is [KeePassLib.PwEntry] )
{
$PwEntry = $_
$connectionInfo = $PwEntry.connectionInfo
$compositeKey = $PwEntry.compositeKey
#$kpDatabase = $PwEntry.kpDatabase
$kpDatabase = new-object KeePassLib.PwDatabase
$statusLogger = New-Object KeePassLib.Interfaces.NullStatusLogger
$kpDatabase.open($connectionInfo,$compositeKey,$statusLogger)
$PwEntry = $kpDatabase.RootGroup.FindEntry($PwEntry.Uuid,$true)
}
else
{
Write-Host InputObjec is not KeePassLib.PwEntry. -ForegroundColor Red
break
}
# Protected strings are encrypted in memory:
if ( $EntryTitle -and ($PwEntry.Strings.ReadSafe('Title') -ne $EntryTitle) )
{
$pTitle = New-Object KeePassLib.Security.ProtectedString($True, $EntryTitle)
$PwEntry.Strings.Set("Title", $pTitle)
}
if ( $EntryUserName -and ($PwEntry.Strings.ReadSafe('UserName') -ne $EntryUserName) )
{
$pUser = New-Object KeePassLib.Security.ProtectedString($True, $EntryUserName)
$PwEntry.Strings.Set("UserName", $pUser)
}
if ($AutoResetPassword.IsPresent)
{
$pPW = New-Object KeePassLib.Security.ProtectedString($True, (Get-KPRandomPassword -Length $EntryPasswordLenght -Complex:$EntryPasswordComplex.IsPresent ))
$PwEntry.Strings.Set("Password", $pPW)
}
if ( $EntryPassword -and ($PwEntry.Strings.ReadSafe('Password') -ne (ConvertTo-PlainText -SecureString $EntryPassword)) )
{
$pPW = New-Object KeePassLib.Security.ProtectedString($True, (ConvertTo-PlainText -SecureString $EntryPassword))
$PwEntry.Strings.Set("Password", $pPW)
}
if ( $EntryUrl -and ($PwEntry.Strings.ReadSafe('URL') -ne $EntryUrl) )
{
$pURL = New-Object KeePassLib.Security.ProtectedString($True, $EntryUrl)
$PwEntry.Strings.Set("URL", $pURL)
}
if ( $EntryNotes -and ($PwEntry.Strings.ReadSafe('Notes') -ne $EntryNotes) )
{
$pNotes = New-Object KeePassLib.Security.ProtectedString($True, $EntryNotes)
$PwEntry.Strings.Set("Notes", $pNotes)
}
if ($AddTags)
{
$AddTags | % {
if ($PwEntry.Tags -notcontains $_)
{
$null = $PwEntry.AddTag($_)
}
}
}
if ($RemoveTags)
{
$RemoveTags | % {
if ($PwEntry.Tags -contains $_)
{
$null = $PwEntry.RemoveTag($_)
}
}
}
#if ( $GroupPath -and ($PwEntry.Strings.ReadSafe('Notes') -ne $GroupPath) )
if ( $GroupPath -and ($GroupPath -ne $PwEntry.GroupPath) )
{
try
{
$rootGroup = $kpDatabase.RootGroup
$oldPwGroup = $PwEntry.ParentGroup
$PwGroup = Get-PwGroup $rootGroup $GroupPath
if ($PwGroup)
{
$null = $kpDatabase.MergeIn($kpDatabase,[KeePassLib.PwMergeMethod]::Synchronize,$statusLogger)
$null = $PwGroup[0].AddEntry($PwEntry, $True, $True)
$null = $oldPwGroup.Entries.Remove($PwEntry)
}
else
{
Write-Host "Group Path $($GroupPath) is invalid." -ForegroundColor Cyan
}
}
catch [Exception]
{
Write-KPLog -message $_ -Level EXCEPTION
Write-Host $($_.Exception.Message) -ForegroundColor Red
}
}
if ($kpDatabase.IsOpen)
{
$null = $kpDatabase.MergeIn($kpDatabase,[KeePassLib.PwMergeMethod]::Synchronize,$statusLogger)
$null = $PwEntry.Touch($true,$true)
$kpDatabase.Save($statusLogger)
$kpDatabase.Close()
}
if ($PassThru.IsPresent)
{
Get-KPEntry -ConnectionInfo $connectionInfo -CompositeKey $compositeKey -Uuid $PwEntry.Uuid
}
}
catch [Exception]
{
Write-KPLog -message $_ -Level EXCEPTION
Write-Host $($_.Exception.Message) -ForegroundColor Red
continue
}
}#InputObject
}
}
END
{
}
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/common/Write-Log.ps1
|
Write-Log.ps1
|
#region Log File Management
$logLocalAppDir = Join-Path $Script:mInfo.ModuleBase logs
$logName = "$($Script:mInfo.Name).log"
$logFullName = Join-Path $logLocalAppDir $logName
$MaxLogFileSizeMB = 5 # After a log file reaches this size it will archive the existing and create a new one
trap
[Exception]
{
Write-Log
"error: $($_.Exception.GetType().Name) - $($_.Exception.Message)"
}
function LogFileCheck
{
if (Test-Path $logFullName) #
{
if (((gci $logFullName).length/1MB) -gt $MaxLogFileSizeMB) # Check size of log file - to stop unweildy size, archive existing file if over limit and create fresh.
{
$NewLogFile = $LogName.replace(".log", " ARCHIVED $(Get-Date -Format dd-MM-yyy-hh-mm-ss).log")
$log = Rename-Item $logFullName (Join-Path $LogLocalAppDir $NewLogFile) -PassThru
Write-Host "Log $($log.fullname)" -ForegroundColor Cyan
}
}
else
{
if (!(Test-Path $LogLocalAppDir))
{
mkdir $LogLocalAppDir | Out-Null
}
New-Item $logFullName -type file
}
}
function Write-Log # Send to log file
{
param(
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[System.String]$message,
[ValidateSet('INFO','WARNING','ERROR','EXCEPTION','SECURITY')]
[System.String]$Level="INFO"
)
if (-not $WhatIfPreference.IsPresent -and $message)
{
foreach($obj in $input)
{
$pipeline += $obj
}
if (![String]::IsNullOrEmpty($pipeline))
{
$message = $pipeline
}
try
{
$toOutput = "$(get-date) $($env:USERDOMAIN)\$($env:USERNAME) $($Level):$($message)" | Out-File $logFullName -append -NoClobber -ErrorAction SilentlyContinue -Encoding default
}
catch{}
}
}
LogFileCheck
#endregion Log File Management
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/common/generic.ps1
|
generic.ps1
|
#Convert a text from the DOS format to the UNIX format.
#The format is different in the last character of each line.
#The DOS format ends with a carriage return (Cr) line feed (Lf)
#character whereas the UNIX format uses the line feed (Lf) character.
function ConvertTo-Unix
{
begin
{}
process
{
($_ | Out-String) -replace "`r`n","`n"
}
end
{}
}
#Convert a text from the UNIX format to the DOS format.
#The format is different in the last character of each line.
#The DOS format ends with a carriage return (Cr) line feed (Lf)
#character whereas the UNIX format uses the line feed (Lf) character.
function ConvertFrom-Unix
{
begin
{}
process
{
($_ | Out-String) -replace "`n","`r`n"
}
end
{}
}
function Set-StandardMembers
{
# http://stackoverflow.com/questions/1369542/can-you-set-an-objects-defaultdisplaypropertyset-in-a-powershell-v2-script/1891215#1891215
Param([PSObject]$MyObject,[String[]]$DefaultProperties)
try
{
$defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$DefaultProperties)
$PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
$MyObject | Add-Member MemberSet PSStandardMembers $PSStandardMembers -Force
}
catch [Exception]
{
Write-Log -message $_ -Level EXCEPTION
Write-Debug $_.Exception.Message
}
}
# Teste Write permissions
function Test-Write {
[CmdletBinding()]
param (
[parameter()] [ValidateScript({[IO.Directory]::Exists($_.FullName)})]
[IO.DirectoryInfo] $Path
)
try {
$testPath = Join-Path $Path ([IO.Path]::GetRandomFileName())
[IO.File]::Create($testPath, 1, 'DeleteOnClose') > $null
# Or...
<# New-Item -Path $testPath -ItemType File -ErrorAction Stop > $null #>
return $true
} catch {
return $false
} finally {
Remove-Item $testPath -ErrorAction SilentlyContinue -WhatIf:$false
}
}
#.ExternalHelp ..\psKeePass.Help.xml
function New-ParamHistory
{
[CmdletBinding()]
param (
[parameter(Mandatory=$true)]
[String]$Function,
[parameter(Mandatory=$true)]
[String]$Parameter,
[parameter(Mandatory=$true)]
[String]$Content
)
try
{
[Array]$paramHistory = Get-ParamHistory | select -First 5
if (-not ($paramHistory | ? {($_.Parameter -eq $Parameter) -and ($_.Content -eq $Content)}) )
{
$item = "" | Select Function,Parameter,Content,DateTime
$item.Function = $Function
$item.Parameter = $Parameter
$item.Content = $Content
$item.DateTime = (Get-Date).DateTime
$paramHistory += $item
$null = New-Item -Path (Join-Path -Path $Script:parent_appdata -ChildPath enviroment) -Name history.json -ItemType File -Value ($paramHistory | ConvertTo-Json) -Force
}
}
catch [Exception]
{
Write-Log -message $_ -Level EXCEPTION
}
}
#.ExternalHelp ..\psKeePass.Help.xml
function Get-ParamHistory
{
[CmdletBinding()]
param (
[parameter(Mandatory=$False)]
[String]$Function,
[parameter(Mandatory=$False)]
[String]$Parameter
)
try
{
$path = (Join-Path -Path $Script:parent_appdata -ChildPath enviroment/history.json)
if (Test-Path -LiteralPath $path)
{
$output = Get-Content $path | ConvertFrom-Json
$output = $output | sort -Property DateTime -Descending
if ($Function)
{
$output = $output | ? {$_.Function -like $Function}
}
if ($Parameter)
{
$output = $output | ? {$_.Parameter -like $Parameter}
}
return $output
}
else
{
return $null
}
}
catch [Exception]
{
Write-Log -message $_ -Level EXCEPTION
}
}
Function Get-RandomPassword
{
Param($Length = 15, [Switch]$Complex)
$chars = $letters = 65..90 + 97..122
if ($Complex.IsPresent)
{
$chars += $punc = 33..33 + 35..38 + 40..43 + 45..46
$chars += $digits = 48..57
}
# Thanks to
# https://blogs.technet.com/b/heyscriptingguy/archive/2012/01/07/use-pow
$password = get-random -count $length -input ($chars) | % `
-begin { $aa = $null } `
-process {$aa += [char]$_} `
-end {$aa}
return $password
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/common/specific.ps1
|
specific.ps1
|
#.ExternalHelp ..\psKeePass.Help.xml
function Format-PwEntry
{
Param
(
[Parameter(Mandatory=$false,ValueFromPipeline=$True)]
$PwEntry,
[Switch]$ForcePlainText,
$CompositeKey,
$ConnectionInfo
)
$PwEntry.Strings | % {
try
{
$val = $null
$val = $PwEntry.Strings.ReadSafe($_.Key)
if (-not [String]::IsNullOrEmpty($val))
{
if ( ($_.Key -eq "Password") )
{
try
{
$secPassword = $val | ConvertTo-SecureString -AsPlainText -Force -ErrorAction stop
if (-not $ForcePlainText.IsPresent)
{
$val = $secPassword
}
}
catch [Exception]
{
#$val = $_.Exception.Message
$val = $null
}
}
}
else
{
$val = $null
}
}
catch [Exception]
{
$val = $null
}
try
{
Add-Member -InputObject $PwEntry -MemberType NoteProperty -Name $_.Key -Value $val
}
catch [exception]
{
Write-Log -message $_ -Level EXCEPTION
}
}# $kpItem.Strings
try
{
if ($PwEntry.UserName -and $secPassword)
{
$psCred = New-Object System.Management.Automation.PSCredential ($PwEntry.UserName, $secPassword)
Add-Member -InputObject $PwEntry -MemberType NoteProperty -Name PsCredential -Value $psCred
Add-Member -InputObject $PwEntry -MemberType NoteProperty -Name User -Value $PwEntry.UserName
}
#Add-Member -InputObject $kpItem -MemberType NoteProperty -Name GroupPath -Value (Get-ParentGroup $kpItem)
Add-Member -InputObject $PwEntry -MemberType NoteProperty -Name compositeKey -Value $compositeKey
Add-Member -InputObject $PwEntry -MemberType NoteProperty -Name connectionInfo -Value $connectionInfo
$getHistory = {
Param([bool]$ForcePlainText=$false)
if ($this.History)
{
if ($ForcePlainText)
{
$item = $this.History | % {Format-PwEntry -PwEntry $_ -CompositeKey $this.CompositeKey -ConnectionInfo $this.ConnectionInfo -ForcePlainText:$true}
}
else
{
$item = $this.History | % {Format-PwEntry -PwEntry $_ -CompositeKey $this.CompositeKey -ConnectionInfo $this.ConnectionInfo}
}
}
Set-StandardMembers -MyObject $item -DefaultProperties LastAccessTime,UserName,Password,Title
return $item
}
Add-Member -InputObject $PwEntry -MemberType ScriptMethod -Name getHistory -Value $getHistory
}
catch [Exception]
{
Write-Log -message $_ -Level EXCEPTION
}
return $PwEntry
}
|
PowerShellCorpus/PowerShellGallery/psKeePass/0.0.0.7/common/Credential.ps1
|
Credential.ps1
|
#region PSTip Storing of credentials
# http://www.powershellmagazine.com/2012/10/30/pstip-storing-of-credentials/
#.ExternalHelp ..\psKeePass.Help.xml
function New-SecurePassword
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 1)]
[string]$Alias,
[Parameter(Mandatory = $false)]
#[String]$Path = (Join-Path -Path $env:LOCALAPPDATA -ChildPath "$($Script:mInfo.Name)\security"),
[String]$Path = (Join-Path -Path $Script:parent_appdata -ChildPath security),
[Switch]$Force
)
if ((Get-SecurePassword -Alias $Alias) -and (-not $Force.IsPresent))
{
Write-Host "Aborted. This SecurePassword Alias '$($Alias)' already exists. Use '-Force' switch to overwrite." -ForegroundColor Cyan
return
}
# get credentials for given username
$cred = Read-Host -AsSecureString -Prompt "Type Master Password to KeePass Database.`nStore at $(Join-Path -Path $Path -ChildPath $Alias)"
# and save encrypted text to a file
if ($cred)
{
if (-not (Test-Path $Path))
{
$null = New-Item -Path $Path -ItemType directory -Force
}
$credentials = "" | select MasterPassword
$credentials.MasterPassword = $cred | ConvertFrom-SecureString
$credentials | ConvertTo-Json | Out-File -FilePath (Join-Path -Path $Path -ChildPath $Alias)
Remove-Variable -Name cred
Remove-Variable -Name credentials
return Get-SecurePassword -Alias $Alias
}
}
#.ExternalHelp ..\psKeePass.Help.xml
function Get-SecurePassword
{
[CmdletBinding()]
param(
#[Parameter(Mandatory = $false)]
#[string]$UserName,
[Parameter(Mandatory = $false,Position = 1)]
[string]$Alias = $null,
[Parameter(Mandatory = $false)]
#[String]$Path = (Join-Path -Path $Script:mInfo.ModuleBase -ChildPath security)
[String]$Path = (Join-Path -Path $Script:parent_appdata -ChildPath security)
)
try
{
#$credentials_files = Get-ChildItem -Path $Path -Filter $Alias -ErrorAction SilentlyContinue
if ($Alias)
{
$credentials_files = Get-ChildItem -Path $Path -ErrorAction SilentlyContinue | ? { $_.Name -like $Alias }
}
else
{
$credentials_files = Get-ChildItem -Path $Path -ErrorAction SilentlyContinue
}
}
catch [Exception]
{
Write-Log -message $_ -Level EXCEPTION
Write-Host $_.Exception.Message -ForegroundColor Red
return $null
}
$credentials_files | % {
try
{
$credentials = (Get-Content -Path $_.FullName) -join "`n" | ConvertFrom-Json
$credentials.MasterPassword = $credentials.MasterPassword | ConvertTo-SecureString
Add-Member -InputObject $credentials -Name Alias -MemberType NoteProperty -Value $_.Name
Add-Member -InputObject $credentials -Name CreationTime -MemberType NoteProperty -Value $_.CreationTime
Write-Output $credentials
Remove-Variable -Name credentials
}
catch
{
Write-Log -message $_ -Level EXCEPTION
Write-Host $_.Exception.Message -ForegroundColor Red
}
}
}
#.ExternalHelp ..\psKeePass.Help.xml
function Remove-SecurePassword
{
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName=$True, Position = 1)]
[string]$Alias = $null,
[Parameter(Mandatory = $false)]
#[String]$Path = (Join-Path -Path $Script:mInfo.ModuleBase -ChildPath security)
[String]$Path = (Join-Path -Path $Script:parent_appdata -ChildPath security)
)
Get-ChildItem -Path $Path -Filter $Alias | Remove-Item
}
#.ExternalHelp ..\psKeePass.Help.xml
function Show-SecurePassword
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$False,ValueFromPipeline=$True)]
[System.Management.Automation.PSObject]$InputObject
)
BEGIN{}
PROCESS
{
# Just to see password in clear text
$InputObject | % {
$_.MasterPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_.MasterPassword))
Write-Output $_
}
}
END{}
}
# Taking a secure password and converting to plain text
function ConvertTo-PlainText
{
Param(
[Parameter(Mandatory=$False,ValueFromPipeline=$True)]
[security.securestring]$SecureString
)
$marshal = [Runtime.InteropServices.Marshal]
$marshal::PtrToStringAuto( $marshal::SecureStringToBSTR($SecureString) )
}
#endregion PSTip Storing of credentials
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Misc/New-DnsServerSecondaryZone.ps1
|
New-DnsServerSecondaryZone.ps1
|
$Properties = @{
Name = New-xDscResourceProperty -Name Name -Type String -Attribute Key `
-Description 'Name of the secondary zone'
DnsServer = New-xDscResourceProperty -Name MasterServerIPAddress -Type String[] -Attribute Required `
-Description 'IP address of secondary DNS servers'
Ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write -ValidateSet 'Present','Absent' `
-Description 'Should this resource be present or absent'
}
New-xDscResource -Name MSFT_xDnsServerSecondaryZone -Property $Properties.Values -Path . -ModuleName xDnsServer -FriendlyName xDnsServerSecondaryZone -Force
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Misc/New-DnsServerZoneTransfer.ps1
|
New-DnsServerZoneTransfer.ps1
|
$Properties = @{
Name = New-xDscResourceProperty -Name Name -Type String -Attribute Key `
-Description 'Name of the secondary zone'
Type = New-xDscResourceProperty -Name Type -Type String -Attribute Required -ValidateSet 'Any', 'Named', 'Specific' `
-Description 'Type of transfer allowed'
SecondaryServer = New-xDscResourceProperty -Name SecondaryServerIPAddress -Type String[] -Attribute Write `
-Description 'IP address of DNS servers where zone information can be sent'
Ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write -ValidateSet 'Present','Absent' `
-Description 'Should this resource be present or absent'
}
New-xDscResource -Name MSFT_xDnsServerZoneTransfer -Property $Properties.Values -Path . -ModuleName xDnsServer -FriendlyName xDnsServerZoneTransfer -Force
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Tests/Unit/MSFT_xDnsRecord.Tests.ps1
|
MSFT_xDnsRecord.Tests.ps1
|
$Global:DSCModuleName = 'xDnsServer' # Example xNetworking
$Global:DSCResourceName = 'MSFT_xDnsRecord' # Example MSFT_xFirewall
#region HEADER
[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))
if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'))
}
else
{
& git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $Global:DSCModuleName `
-DSCResourceName $Global:DSCResourceName `
-TestType Unit
#endregion
# Begin Testing
try
{
#region Pester Tests
InModuleScope $Global:DSCResourceName {
#region Pester Test Initialization
$testPresentParams = @{
Name = "test"
Zone = "contoso.com"
Target = "192.168.0.1"
Type = "ARecord"
Ensure = "Present"
}
$testAbsentParams = @{
Name = $testPresentParams.Name
Zone = $testPresentParams.Zone
Target = $testPresentParams.Target
Type = $testPresentParams.Type
Ensure = "Absent"
}
$fakeDnsServerResourceRecord = @{
HostName = $testPresentParams.Name;
RecordType = 'A'
TimeToLive = '01:00:00'
RecordData = @{
IPv4Address = @{
IPAddressToString = $testPresentParams.Target
}
}
}
#endregion
#region Function Get-TargetResource
Describe "$($Global:DSCResourceName)\Get-TargetResource" {
It "Returns Ensure is Present when DNS record exists" {
Mock Get-DnsServerResourceRecord { return $fakeDnsServerResourceRecord }
(Get-TargetResource @testPresentParams).Ensure | Should Be 'Present'
}
It "Returns Ensure is Absent when DNS record does not exist" {
Mock Get-DnsServerResourceRecord { return $null }
(Get-TargetResource @testPresentParams).Ensure | Should Be 'Absent'
}
}
#endregion
#region Function Test-TargetResource
Describe "$($Global:DSCResourceName)\Test-TargetResource" {
It "Fails when no DNS record exists and Ensure is Present" {
Mock Get-TargetResource { return $testAbsentParams }
Test-TargetResource @testPresentParams | Should Be $false
}
It "Fails when a record exists, target does not match and Ensure is Present" {
Mock Get-TargetResource {
return @{
Name = $testPresentParams.Name
Zone = $testPresentParams.Zone
Target = "192.168.0.10"
Ensure = $testPresentParams.Ensure
}
}
Test-TargetResource @testPresentParams | Should Be $false
}
It "Fails when round-robin record exists, target does not match and Ensure is Present (Issue #23)" {
Mock Get-TargetResource {
return @{
Name = $testPresentParams.Name
Zone = $testPresentParams.Zone
Target = @("192.168.0.10","192.168.0.11")
Ensure = $testPresentParams.Ensure
}
}
Test-TargetResource @testPresentParams | Should Be $false
}
It "Fails when a record exists and Ensure is Absent" {
Mock Get-TargetResource { return $testPresentParams }
Test-TargetResource @testAbsentParams | Should Be $false
}
It "Fails when round-robin record exists, and Ensure is Absent (Issue #23)" {
Mock Get-TargetResource {
return @{
Name = $testPresentParams.Name
Zone = $testPresentParams.Zone
Target = @("192.168.0.1","192.168.0.2")
Ensure = $testPresentParams.Ensure
}
}
Test-TargetResource @testAbsentParams | Should Be $false
}
It "Passes when record exists, target matches and Ensure is Present" {
Mock Get-TargetResource { return $testPresentParams }
Test-TargetResource @testPresentParams | Should Be $true
}
It "Passes when round-robin record exists, target matches and Ensure is Present (Issue #23)" {
Mock Get-TargetResource {
return @{
Name = $testPresentParams.Name
Zone = $testPresentParams.Zone
Target = @("192.168.0.1","192.168.0.2")
Ensure = $testPresentParams.Ensure
}
}
Test-TargetResource @testPresentParams | Should Be $true
}
It "Passes when record does not exist and Ensure is Absent" {
Mock Get-TargetResource { return $testAbsentParams }
Test-TargetResource @testAbsentParams | Should Be $true
}
}
#endregion
#region Function Set-TargetResource
Describe "$($Global:DSCResourceName)\Set-TargetResource" {
It "Calls Add-DnsServerResourceRecord in the set method when Ensure is Present" {
Mock Add-DnsServerResourceRecord { return $null }
Set-TargetResource @testPresentParams
Assert-MockCalled Add-DnsServerResourceRecord -Scope It
}
It "Calls Remove-DnsServerResourceRecord in the set method when Ensure is Absent" {
Mock Remove-DnsServerResourceRecord { return $null }
Set-TargetResource @testAbsentParams
Assert-MockCalled Remove-DnsServerResourceRecord -Scope It
}
}
#endregion
} #end InModuleScope
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Tests/Unit/MSFT_xDnsServerForwarder.Tests.ps1
|
MSFT_xDnsServerForwarder.Tests.ps1
|
$Global:DSCModuleName = 'xDnsServer'
$Global:DSCResourceName = 'MSFT_xDnsServerForwarder'
#region HEADER
[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))
if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'))
}
else
{
& git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $Global:DSCModuleName `
-DSCResourceName $Global:DSCResourceName `
-TestType Unit
#endregion
# Begin Testing
try
{
#region Pester Tests
InModuleScope $Global:DSCResourceName {
#region Pester Test Initialization
$forwarders = '192.168.0.1','192.168.0.2'
$testParams = @{
IsSingleInstance = 'Yes'
IPAddresses = $forwarders
}
$fakeCimInstance = @{
Forwarders = $forwarders
}
#endregion
#region Function Get-TargetResource
Describe "$($Global:DSCResourceName)\Get-TargetResource" {
It 'Returns a "System.Collections.Hashtable" object type' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstance}
$targetResource = Get-TargetResource @testParams
$targetResource -is [System.Collections.Hashtable] | Should Be $true
}
It "Returns IPAddresses = $($testParams.IPAddresses) when forwarders exist" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstance}
$targetResource = Get-TargetResource @testParams
$targetResource.IPAddresses | Should Be $testParams.IPAddresses
}
It "Returns an empty IPAddresses when forwarders don't exist" {
Mock -CommandName Get-CimInstance -MockWith {}
$targetResource = Get-TargetResource @testParams
$targetResource.IPAddresses | Should Be $null
}
}
#endregion
#region Function Test-TargetResource
Describe "$($Global:DSCResourceName)\Test-TargetResource" {
It 'Returns a "System.Boolean" object type' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstance}
$targetResource = Test-TargetResource @testParams
$targetResource -is [System.Boolean] | Should Be $true
}
It 'Passes when forwarders match' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstance}
Test-TargetResource @testParams | Should Be $true
}
It "Fails when forwarders don't match" {
Mock -CommandName Get-CimInstance -MockWith {}
Test-TargetResource @testParams | Should Be $false
}
}
#endregion
#region Function Set-TargetResource
Describe "$($Global:DSCResourceName)\Set-TargetResource" {
It "Calls Set-CimInstance once" {
Mock -CommandName Set-CimInstance -MockWith {}
Set-TargetResource @testParams
Assert-MockCalled -CommandName Set-CimInstance -Times 1 -Exactly -Scope It
}
}
} #end InModuleScope
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Tests/Unit/MSFT_xDnsServerZoneTransfer.Tests.ps1
|
MSFT_xDnsServerZoneTransfer.Tests.ps1
|
$Global:DSCModuleName = 'xDnsServer'
$Global:DSCResourceName = 'MSFT_xDnsServerZoneTransfer'
#region HEADER
[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))
if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'))
}
else
{
& git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $Global:DSCModuleName `
-DSCResourceName $Global:DSCResourceName `
-TestType Unit
#endregion
# Begin Testing
try
{
#region Pester Tests
InModuleScope $Global:DSCResourceName {
#region Pester Test Initialization
$testName = 'example.com';
$testType = 'Any';
$testSecondaryServer = '192.168.0.1','192.168.0.2';
$testParams = @{
Name = $testName;
Type = $testType;
}
$testParamsAny = @{
Name = $testName;
Type = 'Any';
SecondaryServer = '';
}
$testParamsSpecific = @{
Name = $testName;
Type = 'Specific';
SecondaryServer = $testSecondaryServer;
}
$testParamsSpecificDifferent = @{
Name = $testName;
Type = 'Specific';
SecondaryServer = '192.168.0.1','192.168.0.2','192.168.0.3';
}
$fakeCimInstanceAny = @{
Name = $testName;
SecureSecondaries = $XferId2Name.IndexOf('Any');
SecondaryServers = '';
}
$fakeCimInstanceNamed = @{
Name = $testName;
SecureSecondaries = $XferId2Name.IndexOf('Named');
SecondaryServers = '';
}
$fakeCimInstanceSpecific = @{
Name = $testName;
SecureSecondaries = $XferId2Name.IndexOf('Specific');
SecondaryServers = $testSecondaryServer;
}
#endregion
#region Function Get-TargetResource
Describe "$($Global:DSCResourceName)\Get-TargetResource" {
It 'Returns a "System.Collections.Hashtable" object type' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceAny}
$targetResource = Get-TargetResource @testParams
$targetResource -is [System.Collections.Hashtable] | Should Be $true
}
It "Returns SecondaryServer = $($testParams.SecondaryServer) when zone transfers set to specific" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceSpecific}
$targetResource = Get-TargetResource @testParams
$targetResource.SecondaryServers | Should Be $testParams.SecondaryServers
}
}
#endregion
#region Function Test-TargetResource
Describe "$($Global:DSCResourceName)\Test-TargetResource" {
It 'Returns a "System.Boolean" object type' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceAny}
$targetResource = Test-TargetResource @testParamsAny
$targetResource -is [System.Boolean] | Should Be $true
}
It 'Passes when Zone Transfer Type matches' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceAny}
Test-TargetResource @testParamsAny | Should Be $true
}
It "Fails when Zone Transfer Type does not match" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceNamed}
Test-TargetResource @testParamsAny | Should Be $false
}
It 'Passes when Zone Transfer Secondaries matches' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceSpecific}
Test-TargetResource @testParamsSpecific | Should Be $true
}
It 'Passes when Zone Transfer Secondaries does not match' {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceSpecific}
Test-TargetResource @testParamsSpecificDifferent | Should Be $false
}
}
#endregion
#region Function Set-TargetResource
Describe "$($Global:DSCResourceName)\Set-TargetResource" {
function Invoke-CimMethod { [CmdletBinding()]
param ( $InputObject, $MethodName, $Arguments )
}
Mock -CommandName Invoke-CimMethod -MockWith {}
Mock -CommandName Restart-Service -MockWith {}
It "Calls Invoke-CimMethod not called when Zone Transfer Type matches" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceAny}
Set-TargetResource @testParamsAny
Assert-MockCalled -CommandName Invoke-CimMethod -Times 0 -Exactly -Scope It
}
It "Calls Invoke-CimMethod called once when Zone Transfer Type does not match" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceNamed}
Set-TargetResource @testParamsAny
Assert-MockCalled -CommandName Invoke-CimMethod -Times 1 -Exactly -Scope It
}
It "Calls Invoke-CimMethod not called when Zone Transfer Secondaries matches" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceSpecific}
Set-TargetResource @testParamsSpecific
Assert-MockCalled -CommandName Invoke-CimMethod -Times 0 -Exactly -Scope It
}
It "Calls Invoke-CimMethod called once when Zone Transfer Secondaries does not match" {
Mock -CommandName Get-CimInstance -MockWith {return $fakeCimInstanceSpecific}
Set-TargetResource @testParamsSpecificDifferent
Assert-MockCalled -CommandName Invoke-CimMethod -Times 1 -Exactly -Scope It
}
}
} #end InModuleScope
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Tests/Unit/MSFT_xDnsServerPrimaryZone.Tests.ps1
|
MSFT_xDnsServerPrimaryZone.Tests.ps1
|
$Global:DSCModuleName = 'xDnsServer'
$Global:DSCResourceName = 'MSFT_xDnsServerPrimaryZone'
#region HEADER
[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))
if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'))
}
else
{
& git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $Global:DSCModuleName `
-DSCResourceName $Global:DSCResourceName `
-TestType Unit
#endregion
# Begin Testing
try
{
#region Pester Tests
InModuleScope $Global:DSCResourceName {
#region Pester Test Initialization
$testZoneName = 'example.com';
$testZoneFile = 'example.com.dns';
$testDynamicUpdate = 'None';
$testParams = @{ Name = $testZoneName; }
$fakeDnsFileZone = [PSCustomObject] @{
DistinguishedName = $null;
ZoneName = $testZoneName;
ZoneType = 'Primary';
DynamicUpdate = $testDynamicUpdate;
ReplicationScope = 'None';
DirectoryPartitionName = $null;
ZoneFile = $testZoneFile;
}
#endregion
#region Function Get-TargetResource
Describe 'Validates Get-TargetResource Method' {
function Get-DnsServerZone { }
Mock -CommandName 'Assert-Module' -MockWith { }
It 'Returns a "System.Collections.Hashtable" object type' {
$targetResource = Get-TargetResource @testParams;
$targetResource -is [System.Collections.Hashtable] | Should Be $true;
}
It 'Returns "Present" when DNS zone exists and "Ensure" = "Present"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
$targetResource = Get-TargetResource @testParams -ZoneFile 'example.com.dns';
$targetResource.Ensure | Should Be 'Present';
}
It 'Returns "Absent" when DNS zone does not exists and "Ensure" = "Present"' {
Mock -CommandName Get-DnsServerZone -MockWith { }
$targetResource = Get-TargetResource @testParams -ZoneFile 'example.com.dns';
$targetResource.Ensure | Should Be 'Absent';
}
It 'Returns "Present" when DNS zone exists and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
$targetResource = Get-TargetResource @testParams -ZoneFile 'example.com.dns' -Ensure Absent;
$targetResource.Ensure | Should Be 'Present';
}
It 'Returns "Absent" when DNS zone does not exist and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { }
$targetResource = Get-TargetResource @testParams -ZoneFile 'example.com.dns' -Ensure Absent;
$targetResource.Ensure | Should Be 'Absent';
}
}
#endregion
#region Function Test-TargetResource
Describe 'Validates Test-TargetResource Method' {
function Get-DnsServerZone { }
It 'Returns a "System.Boolean" object type' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
$targetResource = Test-TargetResource @testParams;
$targetResource -is [System.Boolean] | Should Be $true;
}
It 'Passes when DNS zone exists and "Ensure" = "Present"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
Test-TargetResource @testParams -Ensure Present | Should Be $true;
}
It 'Passes when DNS zone does not exist and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { }
Test-TargetResource @testParams -Ensure Absent | Should Be $true;
}
It 'Passes when DNS zone "DynamicUpdate" is correct' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
Test-TargetResource @testParams -Ensure Present -DynamicUpdate $testDynamicUpdate | Should Be $true;
}
It 'Fails when DNS zone exists and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
Test-TargetResource @testParams -Ensure Absent | Should Be $false;
}
It 'Fails when DNS zone does not exist and "Ensure" = "Present"' {
Mock -CommandName Get-DnsServerZone -MockWith { }
Test-TargetResource @testParams -Ensure Present | Should Be $false;
}
It 'Fails when DNS zone "DynamicUpdate" is incorrect' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
Test-TargetResource @testParams -Ensure Present -DynamicUpdate 'NonsecureAndSecure' -ZoneFile $testZoneFile | Should Be $false;
}
It 'Fails when DNS zone "ZoneFile" is incorrect' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone; }
Test-TargetResource @testParams -Ensure Present -DynamicUpdate $testDynamicUpdate -ZoneFile 'nonexistent.com.dns' | Should Be $false;
}
}
#endregion
#region Function Set-TargetResource
Describe 'Validates Set-TargetResource Method' {
It 'Calls "Add-DnsServerPrimaryZone" when DNS zone does not exist and "Ensure" = "Present"' {
function Get-DnsServerZone { }
function Add-DnsServerPrimaryZone { param ( $Name ) }
function Set-DnsServerPrimaryZone { [CmdletBinding()] param (
[Parameter(ValueFromPipeline)] $Name,
[Parameter(ValueFromPipeline)] $DynamicUpdate,
[Parameter(ValueFromPipeline)] $ZoneFile ) }
function Remove-DnsServerZone { }
Mock -CommandName Get-DnsServerZone -MockWith { }
Mock -CommandName Add-DnsServerPrimaryZone -ParameterFilter { $Name -eq $testZoneName } -MockWith { }
Set-TargetResource @testParams -Ensure Present -DynamicUpdate $testDynamicUpdate -ZoneFile $testZoneFile;
Assert-MockCalled -CommandName Add-DnsServerPrimaryZone -ParameterFilter { $Name -eq $testZoneName } -Scope It;
}
It 'Calls "Remove-DnsServerZone" when DNS zone does exist and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone }
Mock -CommandName Remove-DnsServerZone -MockWith { }
Set-TargetResource @testParams -Ensure Absent -DynamicUpdate $testDynamicUpdate -ZoneFile $testZoneFile;
Assert-MockCalled -CommandName Remove-DnsServerZone -Scope It;
}
It 'Calls "Set-DnsServerPrimaryZone" when DNS zone "DynamicUpdate" is incorrect' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone }
Mock -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $DynamicUpdate -eq 'NonsecureAndSecure' } -MockWith { }
Set-TargetResource @testParams -Ensure Present -DynamicUpdate 'NonsecureAndSecure' -ZoneFile $testZoneFile;
Assert-MockCalled -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $DynamicUpdate -eq 'NonsecureAndSecure' } -Scope It;
}
It 'Calls "Set-DnsServerPrimaryZone" when DNS zone "ZoneFile" is incorrect' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsFileZone }
Mock -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $ZoneFile -eq 'nonexistent.com.dns' } -MockWith { }
Set-TargetResource @testParams -Ensure Present -DynamicUpdate $testDynamicUpdate -ZoneFile 'nonexistent.com.dns';
Assert-MockCalled -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $ZoneFile -eq 'nonexistent.com.dns' } -Scope It;
}
}
#endregion
} #end InModuleScope
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/xDnsServer/1.7.0.0/Tests/Unit/MSFT_xDnsServerADZone.Tests.ps1
|
MSFT_xDnsServerADZone.Tests.ps1
|
$Global:DSCModuleName = 'xDnsServer'
$Global:DSCResourceName = 'MSFT_xDnsServerADZone'
#region HEADER
[String] $moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))
if ( (-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'))
}
else
{
& git @('-C',(Join-Path -Path $moduleRoot -ChildPath '\DSCResource.Tests\'),'pull')
}
Import-Module (Join-Path -Path $moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $Global:DSCModuleName `
-DSCResourceName $Global:DSCResourceName `
-TestType Unit
#endregion
# Begin Testing
try
{
#region Pester Tests
InModuleScope $Global:DSCResourceName {
#region Pester Test Initialization
$testZoneName = 'example.com';
$testDynamicUpdate = 'Secure';
$testReplicationScope = 'Domain';
$testDirectoryPartitionName = "DomainDnsZones.$testZoneName";
$testParams = @{ Name = $testZoneName; }
$fakeDnsADZone = [PSCustomObject] @{
DistinguishedName = $null;
ZoneName = $testZoneName;
ZoneType = 'Primary';
DynamicUpdate = $testDynamicUpdate;
ReplicationScope = $testReplicationScope;
DirectoryPartitionName = $testDirectoryPartitionName;
ZoneFile = $null;
}
$fakePresentTargetResource = @{
Name = $testZoneName
DynamicUpdate = $testDynamicUpdate
ReplicationScope = $testReplicationScope;
DirectoryPartitionName = $testDirectoryPartitionName;
Ensure = 'Present'
CimSession = @{
Id = 1
Name = 'CimSession1'
InstanceId = 'a23d4d49-f588-407d-9b78-601cd74d8116'
ComputerName = 'localhost'
Protocol = 'WSMAN'
}
}
$fakeAbsentTargetResource = @{ Ensure = 'Absent' }
#endregion
#region Function Get-TargetResource
Describe "$($Global:DSCResourceName)\Get-TargetResource" {
function Get-DnsServerZone { }
Mock -CommandName 'Assert-Module' -MockWith { }
It 'Returns a "System.Collections.Hashtable" object type' {
$targetResource = Get-TargetResource @testParams -ReplicationScope $testReplicationScope;
$targetResource -is [System.Collections.Hashtable] | Should Be $true;
}
It 'Returns "Present" when DNS zone exists and "Ensure" = "Present"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsADZone; }
$targetResource = Get-TargetResource @testParams -ReplicationScope $testReplicationScope;
$targetResource.Ensure | Should Be 'Present';
}
It 'Returns "Absent" when DNS zone does not exists and "Ensure" = "Present"' {
Mock -CommandName Get-DnsServerZone -MockWith { }
$targetResource = Get-TargetResource @testParams -ReplicationScope $testReplicationScope;
$targetResource.Ensure | Should Be 'Absent';
}
It 'Returns "Present" when DNS zone exists and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { return $fakeDnsADZone; }
$targetResource = Get-TargetResource @testParams -ReplicationScope $testReplicationScope -Ensure Absent;
$targetResource.Ensure | Should Be 'Present';
}
It 'Returns "Absent" when DNS zone does not exist and "Ensure" = "Absent"' {
Mock -CommandName Get-DnsServerZone -MockWith { }
$targetResource = Get-TargetResource @testParams -ReplicationScope $testReplicationScope -Ensure Absent;
$targetResource.Ensure | Should Be 'Absent';
}
}
#endregion
#region Function Test-TargetResource
Describe "$($Global:DSCResourceName)\Test-TargetResource" {
function Get-DnsServerZone { }
It 'Returns a "System.Boolean" object type' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
$targetResource = Test-TargetResource @testParams -ReplicationScope $testReplicationScope;
$targetResource -is [System.Boolean] | Should Be $true;
}
It 'Passes when DNS zone exists and "Ensure" = "Present"' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope | Should Be $true;
}
It 'Passes when DNS zone does not exist and "Ensure" = "Absent"' {
Mock -CommandName Get-TargetResource -MockWith { }
Test-TargetResource @testParams -Ensure Absent -ReplicationScope $testReplicationScope | Should Be $true;
}
It 'Passes when DNS zone "DynamicUpdate" is correct' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DynamicUpdate $testDynamicUpdate | Should Be $true;
}
It 'Passes when DNS zone "ReplicationScope" is correct' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope | Should Be $true;
}
It 'Passes when DNS zone "DirectoryPartitionName" is correct' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DirectoryPartitionName $testDirectoryPartitionName | Should Be $true;
}
It 'Fails when DNS zone exists and "Ensure" = "Absent"' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Absent -ReplicationScope $testReplicationScope | Should Be $false;
}
It 'Fails when DNS zone does not exist and "Ensure" = "Present"' {
Mock -CommandName Get-TargetResource -MockWith { }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope | Should Be $false;
}
It 'Fails when DNS zone "DynamicUpdate" is incorrect' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DynamicUpdate 'NonsecureAndSecure' | Should Be $false;
}
It 'Fails when DNS zone "ReplicationScope" is incorrect' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope 'Forest' | Should Be $false;
}
It 'Fails when DNS zone "DirectoryPartitionName" is incorrect' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Test-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DirectoryPartitionName 'IncorrectDirectoryPartitionName' | Should Be $false;
}
}
#endregion
#region Function Set-TargetResource
Describe "$($Global:DSCResourceName)\Set-TargetResource" {
function Get-DnsServerZone { }
function Add-DnsServerPrimaryZone { param ( $Name ) }
function Set-DnsServerPrimaryZone { [CmdletBinding()] param (
$Name,
$DynamicUpdate,
$ReplicationScope,
$DirectoryPartitionName,
$CimSession ) }
function Remove-DnsServerZone { }
It 'Calls "Add-DnsServerPrimaryZone" when DNS zone does not exist and "Ensure" = "Present"' {
Mock -CommandName Get-TargetResource -MockWith { return $fakeAbsentTargetResource }
Mock -CommandName Add-DnsServerPrimaryZone -ParameterFilter { $Name -eq $testZoneName } -MockWith { }
Set-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DynamicUpdate $testDynamicUpdate;
Assert-MockCalled -CommandName Add-DnsServerPrimaryZone -ParameterFilter { $Name -eq $testZoneName } -Scope It;
}
It 'Calls "Remove-DnsServerZone" when DNS zone does exist and "Ensure" = "Absent"' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Mock -CommandName Remove-DnsServerZone -MockWith { }
Set-TargetResource @testParams -Ensure Absent -ReplicationScope $testReplicationScope -DynamicUpdate $testDynamicUpdate;
Assert-MockCalled -CommandName Remove-DnsServerZone -Scope It;
}
It 'Calls "Set-DnsServerPrimaryZone" when DNS zone "DynamicUpdate" is incorrect' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Mock -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $DynamicUpdate -eq 'NonsecureAndSecure' } -MockWith { }
Set-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DynamicUpdate 'NonsecureAndSecure';
Assert-MockCalled -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $DynamicUpdate -eq 'NonsecureAndSecure' } -Scope It;
}
It 'Calls "Set-DnsServerPrimaryZone" when DNS zone "ReplicationScope" is incorrect' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Mock -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $ReplicationScope -eq 'Forest' } -MockWith { }
Set-TargetResource @testParams -Ensure Present -ReplicationScope 'Forest';
Assert-MockCalled -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $ReplicationScope -eq 'Forest' } -Scope It;
}
It 'Calls "Set-DnsServerPrimaryZone" when DNS zone "DirectoryPartitionName" is incorrect' {
Mock -CommandName Get-TargetResource -MockWith { return $fakePresentTargetResource; }
Mock -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $DirectoryPartitionName -eq 'IncorrectDirectoryPartitionName' } -MockWith { }
Set-TargetResource @testParams -Ensure Present -ReplicationScope $testReplicationScope -DirectoryPartitionName 'IncorrectDirectoryPartitionName';
Assert-MockCalled -CommandName Set-DnsServerPrimaryZone -ParameterFilter { $DirectoryPartitionName -eq 'IncorrectDirectoryPartitionName' } -Scope It;
}
}
#endregion
} #end InModuleScope
}
finally
{
#region FOOTER
Restore-TestEnvironment -TestEnvironment $TestEnvironment
#endregion
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Private/Out-DataTable.ps1
|
Out-DataTable.ps1
|
<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
Any object can be piped to Out-DataTable
.OUTPUTS
System.Data.DataTable
.EXAMPLE
$dt = Get-psdrive| Out-DataTable
This example creates a DataTable from the properties of Get-psdrive and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Fixed Issue with Properties
v1.2 - Chad Miller - Added setting column datatype by property as suggested by emp0
v1.3 - Chad Miller - Corrected issue with setting datatype on empty properties
v1.4 - Chad Miller - Corrected issue with DBNull
v1.5 - Chad Miller - Updated example
v1.6 - Chad Miller - Added column datatype logic with default to string
v1.7 - Chad Miller - Fixed issue with IsArray
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
[CmdletBinding()]
param ([Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
[PSObject[]]$InputObject)
Begin
{
function Get-Type
{
param ($type)
$types = @(
'System.Boolean',
'System.Byte[]',
'System.Byte',
'System.Char',
'System.Datetime',
'System.Decimal',
'System.Double',
'System.Guid',
'System.Int16',
'System.Int32',
'System.Int64',
'System.Single',
'System.UInt16',
'System.UInt32',
'System.UInt64')
if ($types -contains $type)
{
Write-Output "$type"
}
else
{
Write-Output 'System.String'
}
} #Get-Type
$dt = new-object Data.datatable
$First = $true
}
Process
{
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
foreach ($property in $object.PsObject.get_properties())
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $property.Name.ToString()
if ($property.value)
{
if ($property.value -isnot [System.DBNull])
{
$Col.DataType = [System.Type]::GetType("$(Get-Type $property.TypeNameOfValue)")
}
}
$DT.Columns.Add($Col)
}
if ($property.Gettype().IsArray)
{
$DR.Item($property.Name) = $property.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1
}
else
{
$DR.Item($property.Name) = $property.value
}
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output @(, ($dt))
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/New-WPFMessageBox.ps1
|
New-WPFMessageBox.ps1
|
function New-WPFMessageBox
{
<#
.SYNOPSIS
The New-WPFMessageBox functio will show a message box to the user
.DESCRIPTION
The New-WPFMessageBox functio will show a message box to the user
.PARAMETER Message
Specifies the message to show
.PARAMETER Title
Specifies the title of the message box
.PARAMETER Buttons
Specifies which button to add. Just press tab to see the choices
.PARAMETER Icon
Specifies the icon to show. Just press tab to see the choices
.EXAMPLE
PS C:\> New-WPFMessageBox -Message "Hello World" -Title "First Message" -Buttons "RetryCancel" -Icon "Asterix"
.NOTES
Author: Francois-Xavier Cat
Twitter:@LazyWinAdm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
[OutputType([System.Windows.Forms.DialogResult])]
param
(
[Parameter(Mandatory = $true)]
[String]$Message,
[String]$Title,
[System.Windows.Forms.MessageBoxButtons]$Buttons = "OK",
[System.Windows.Forms.MessageBoxIcon]$Icon = "None"
)
BEGIN
{
Add-Type -AssemblyName System.Windows.Forms
}
PROCESS
{
if ($PSCmdlet.ShouldProcess("MessageBox", "Show a new message box"))
{
[System.Windows.Forms.MessageBox]::Show($Message, $Title, $Buttons, $Icon)
}
}
} #New-MessageBox
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Set-WPFWindow.ps1
|
Set-WPFWindow.ps1
|
function Set-WPFWindow
{
<#
.SYNOPSIS
Function to set properties on the Window Control
.DESCRIPTION
Function to set properties on the Window Control
.PARAMETER Window
Specifies the Window Control
.PARAMETER Title
Specifies the Title to set on the Window
.EXAMPLE
PS C:\> Set-WPFWindow -Window $Window -Title 'Super GUI'
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM (
[parameter(Mandatory)]
[Alias('Form')]
[System.Windows.Window]
$Window,
[String]$Title
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSBoundParameters['Title'])
{
$Window.Title = $Title
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Remove-WPFDataGridtem.ps1
|
Remove-WPFDataGridtem.ps1
|
function Remove-WPFDataGridItem
{
<#
.SYNOPSIS
This function remove a row to a DataGrid
.DESCRIPTION
This function remove a row to a DataGrid
.PARAMETER DataGridView
Specifies the DataGridView Control to use
.PARAMETER SelectedItems
Specifies that the selectedItems will be removed
.EXAMPLE
Remove-WFDataGridItem -DataGrid $datagrid1 -selectedItems
Remove all selected items
.NOTES
Francois-Xavier Cat
www.lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[System.Windows.Controls.DataGrid]$DataGrid,
[switch]$SelectedItems
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF($PSBoundParameters['SelectedItems'])
{
while ($dataGrid.SelectedItems.count -gt 0)
{
$dataGrid.ItemsSource.Table.Rows.RemoveAt($dataGrid.SelectedIndex)
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/New-WPFOpenFileDialog.ps1
|
New-WPFOpenFileDialog.ps1
|
function New-WPFOpenFileDialog
{
<#
.SYNOPSIS
The New-WFOpenFileDialog function will ask the user to select one of multiple files.
The function will return the literal path of the file(s) selected
.DESCRIPTION
The New-WFOpenFileDialog function will ask the user to select one of multiple files.
The function will return the literal path of the file(s) selected
.PARAMETER WindowsTitle
Specifies the Title of the window.
.PARAMETER Path
Specifies the Path where the dialog will open.
.PARAMETER Filter
Specifies the extension filter.Default is "All files (*.*)|*.*"
Other example:
"Text files (*.txt)|*.txt|All files (*.*)|*.*";
"Photos files (*.jpg)|*.png|All files (*.*)|*.*";
.PARAMETER AllowMultiSelect
Allow the user to select multiple files.
.EXAMPLE
PS C:\> New-WPFOpenFileDialog -WindowsTitle 'Upload' -Path 'c:\"
.NOTES
Author: Francois-Xavier Cat
Twitter:@LazyWinAdm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[Alias('Title')]
[String]$WindowsTitle,
[Parameter(Mandatory = $true)]
[String]$Path,
[String]$Filter = "All files (*.*)|*.*",
[switch]$AllowMultiSelect
)
BEGIN
{
Add-Type -AssemblyName System.Windows.Forms
}
PROCESS
{
# Create Object and add properties
$OpenFileDialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $Path
$OpenFileDialog.CheckPathExists = $true
$OpenFileDialog.CheckFileExists = $true
$OpenFileDialog.Title = $WindowTitle
IF ($PSBoundParameters["Filter"]) { $OpenFileDialog.Filter = $Filter }
IF ($PSBoundParameters["AllowMultiSelect"]) { $OpenFileDialog.MultiSelect = $true }
IF ($PSCmdlet.ShouldProcess('OpenFileDialog','Will prompt to select a file'))
{
# Show the Dialog
$OpenFileDialog.ShowHelp = $True
[void]$OpenFileDialog.ShowDialog()
}
}
END
{
# Return the selected file
IF ($PSBoundParameters["AllowMultiSelect"]) { $OpenFileDialog.Filenames }
# Return the selected files
IF (-not $PSBoundParameters["AllowMultiSelect"]) { $OpenFileDialog.Filename }
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/New-WPFSpeakerBeep.ps1
|
New-WPFSpeakerBeep.ps1
|
function New-WPFSpeakerBeep
{
<#
.SYNOPSIS
The New-WPFSpeakerBeep function plays the sound of a beep of a specified frequency and duration through the console speaker.
.DESCRIPTION
The New-WPFSpeakerBeep function plays the sound of a beep of a specified frequency and duration through the console speaker.
.PARAMETER Frequency
The frequency of the beep, ranging from 37 to 32767 hertz.
.PARAMETER Duration
The duration of the beep measured in milliseconds.
.EXAMPLE
PS C:\> New-WPFSpeakerBeep -Frequency 500 -Duration 300
.NOTES
Author: Francois-Xavier Cat
Twitter:@LazyWinAdm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[ValidateRange(37, 32767)]
[int32]$Frequency = 800,
[int32]$Duration = 200
)
PROCESS
{
if ($PSCmdlet.ShouldProcess("System Console Beep", "Create a beep with a Frequency of $Frequency hertz and a duration of $Duration ms"))
{
[System.Console]::Beep($Frequency, $Duration)
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Enable-WPFButton.ps1
|
Enable-WPFButton.ps1
|
function Enable-WPFButton
{
<#
.SYNOPSIS
Function to Enable a Button control
.DESCRIPTION
Function to Enable a Button control
.PARAMETER Button
Specifies the Button Control
.EXAMPLE
PS C:\> Enable-WPFButton -Button $Button1
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM ([System.Windows.Controls.Button]
$Button)
$Button.IsEnabled = $true
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Update-WPFDataGrid.ps1
|
Update-WPFDataGrid.ps1
|
function Update-WPFDataGrid
{
<#
.SYNOPSIS
Function to refresh the content of a DataGrid control
.DESCRIPTION
Function to refresh the content of a DataGrid control
.PARAMETER DataGrid
Specifies the DataGrid control to update
.NOTES
Author: Francois-Xavier Cat
Twitter:@LazyWinAdm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[System.Windows.Controls.DataGrid]$DataGrid
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSCmdlet.ShouldProcess($DataGrid,"Refresh the content"))
{
$DataGrid.items.Refresh()
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Import-WPFDataGrid.ps1
|
Import-WPFDataGrid.ps1
|
function Import-WPFDataGrid
{
<#
.SYNOPSIS
Function to load multiple items into a DataGrid control.
.DESCRIPTION
Function to load multiple items into a DataGrid control.
The object that you are passing to the Item parameter will be converted to a Datatable object
.PARAMETER DataGrid
Specifies the DataGrid Control
.PARAMETER Item
Specifies the object(s) you wish to load into the ComboBox's items collection.
.EXAMPLE
Import-WFDataGrid -DataGrid $DataGrid1 -Item (Get-Process)
.NOTES
Francois-Xavier Cat
www.lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
[System.Windows.Controls.DataGrid]$DataGrid,
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
$Item
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
if ($item -isnot [System.Data.DataTable])
{
$Item = $Item |Out-DataTable
}
$DataTableView = New-Object System.Data.DataView -ArgumentList $Item
$DataGrid.ItemsSource = $DataTableView
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Clear-WPFDataGrid.ps1
|
Clear-WPFDataGrid.ps1
|
function Clear-WPFDataGrid
{
<#
.SYNOPSIS
This function will clear the content of a DataGrid control
.DESCRIPTION
This function will clear the content of a DataGrid control
.PARAMETER RichTextBox
A description of the DataGrid parameter.
.EXAMPLE
Clear-WPFDataGrid -DataGrid $DataGrid
.NOTES
Francois-Xavier Cat
@lazywinadm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[System.Windows.Controls.DataGrid]$DataGrid
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSCmdlet.ShouldProcess($DataGrid, "Clear the Richtextbox control"))
{
#Clear the RichTextBox
$DataGrid.ItemsSource = $null
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Remove-WPFComboBoxItem.ps1
|
Remove-WPFComboBoxItem.ps1
|
function Remove-WPFComboBoxItem
{
<#
.SYNOPSIS
Function to Remove items from a ComboBox
.DESCRIPTION
Function to Remove items from a ComboBox
System.windows.controls.combobox
https://msdn.microsoft.com/en-us/library/system.windows.controls.combobox(v=vs.110).aspx
.PARAMETER ComboBox
Specifies the ComboBox control
.PARAMETER SelectedItem
Specifies the Selected item(s)
.EXAMPLE
Remove-WPFComboBoxItem -ComboBox $Combobox1 -SelectedItem
Will remove all the selected item in the ComboBox $Combobox1
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
[System.Windows.Controls.ComboBox]$ComboBox,
[switch]$SelectedItem
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSBoundParameters['SelectedItem'])
{
Foreach ($item in $ComboBox.SelectedItem)
{
$ComboBox.Items.RemoveAt($comboBox.SelectedIndex)
#$ComboBox.Items.Remove($comboBox.SelectedItem)
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Disable-WPFButton.ps1
|
Disable-WPFButton.ps1
|
function Disable-WPFButton
{
<#
.SYNOPSIS
Function to disable a Button control
.DESCRIPTION
Function to disable a Button control
.PARAMETER Button
Specifies the Button Control
.EXAMPLE
PS C:\> Disable-WPFButton -Button $Button1
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM ([System.Windows.Controls.Button]
$Button)
$Button.IsEnabled = $false
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Set-WPFProgressBar.ps1
|
Set-WPFProgressBar.ps1
|
function Set-WPFProgressBar
{
<#
.SYNOPSIS
Function to change ProgressBar Control
.DESCRIPTION
Function to change ProgressBar Control
.PARAMETER ProgressBar
Specifies the ProgressBar control
.PARAMETER Value
Specifies the Percentage of progress
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
System.Windows.Controls.ProgressBar
#>
[CmdletBinding()]
param
(
[System.Windows.Controls.ProgressBar]$ProgressBar,
[ValidateRange(0, 100)]
$Value
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
$ProgressBar.Value = $Value
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/New-WPFOpenFolderDialog.ps1
|
New-WPFOpenFolderDialog.ps1
|
function New-WPFOpenFolderDialog
{
<#
.SYNOPSIS
The New-WPFOpenFolderDialog function will ask the user to select one folder.
.DESCRIPTION
The New-WPFOpenFolderDialog function will ask the user to select one folder.
.PARAMETER Description
Specifies a message to help the user select a folder
.PARAMETER RootFolder
Specifies the folder where to look. All the SpecialFolder are listed using tab. Default is "Desktop".
.PARAMETER ShowNewFolderButton
Specifies if the "New Folder" button should be displayed. Default is True.
.EXAMPLE
PS C:\> New-WPFOpenFolderDialog -Description "Please select a folder" -RootFolder "Desktop"
.NOTES
Author: Francois-Xavier Cat
Twitter:@LazyWinAdm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Alias('Message')]
[String]$Description = "Please select a folder",
[Alias('Path')]
[Environment+SpecialFolder]$RootFolder = "Desktop",
[Alias('NewFolderButton', 'NewFolder')]
[bool]$ShowNewFolderButton = $true
)
BEGIN
{
Add-Type -AssemblyName System.Windows.Forms
}
PROCESS
{
IF ($PSCmdlet.ShouldProcess('OpenFolderDialog', 'Will prompt to select a folder'))
{
# Create an object and properties
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
$FolderBrowser.Description = $Description
$FolderBrowser.RootFolder = $RootFolder
$FolderBrowser.ShowNewFolderButton = $ShowNewFolderButton
# Show the Dialog
[void]$FolderBrowser.ShowDialog()
}
}
END
{
# Return the selected folder
$FolderBrowser.SelectedPath
}
} #New-OpenFolderDialog
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Add-WPFDataGridRow.ps1
|
Add-WPFDataGridRow.ps1
|
function Add-WPFDataGridRow
{
<#
.SYNOPSIS
This function add a row to a DataGrid
.DESCRIPTION
This function add a row to a DataGrid
By default it will add an empty row (if -values is not specified)
.PARAMETER DataGrid
Specifies the DataGrid Control to use
.PARAMETER Values
Specities the values to add
.EXAMPLE
Add-WFDataGridRow -DataGrid $datagrid1
Add an empty row
.EXAMPLE
Add-WFDataGridRow -DataGrid $datagrid1 -Values "Francois-Xavier","Cat","fxcat"
Add a row with the values specified.
.EXAMPLE
Add-WFDataGridRow -DataGrid $datagrid1 -Object (Get-Process|select name,id.path)
Add an object to the Datagrid. The column must exist
.NOTES
Francois-Xavier Cat
www.lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
[CmdletBinding(DefaultParameterSetName = 'EmptyRow')]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[System.Windows.Controls.DataGrid]$DataGrid,
[Parameter(ParameterSetName = 'Row')]
[Array]$Values,
[Parameter(ParameterSetName = 'Object')]
$Object
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSCmdlet.ParameterSetName -eq 'EmptyRow')
{
$Row = $DataGrid.ItemsSource.Table.NewRow()
$DataGrid.ItemsSource.Table.Rows.add()
}
ELSEIF ($PSCmdlet.ParameterSetName -eq 'Row')
{
$Row = $DataGrid.ItemsSource.Table.NewRow()
$Row.ItemArray = $Values
$DataGrid.ItemsSource.Table.Rows.add($row)
}
ELSEIF ($PSCmdlet.ParameterSetName -eq 'Object')
{
Foreach ($i in $Object)
{
$Row = $DataGrid.ItemsSource.Table.NewRow()
$RowProps = ($row|gm -MemberType Properties).name
($i|gm -MemberType Properties).name|%{
if ($RowProps -contains $_)
{
$row.$_ = $i.$_
}
}
$DataGrid.ItemsSource.Table.Rows.add($row)
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Get-WPFTextBoxText.ps1
|
Get-WPFTextBoxText.ps1
|
function Get-WPFTextBoxText
{
<#
.SYNOPSIS
Function to get the text from the TextBox Control
.DESCRIPTION
Function to get the text from the TextBox Control
.PARAMETER TextBox
Specifies the TextBox Control
.EXAMPLE
PS C:\> Get-WPFTextBoxText -TextBox $TextBox1
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM ([System.Windows.Controls.TextBox]
$TextBox)
$TextBox.Text
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/New-WPFInputBox.ps1
|
New-WPFInputBox.ps1
|
function New-WPFInputBox
{
<#
.SYNOPSIS
The New-WPFInputBox function will prompt the user for input in a window.
.DESCRIPTION
The New-WPFInputBox function will prompt the user for input in a window.
.PARAMETER Message
Specifies the question you want to ask to the user.
.PARAMETER Title
Specifies the title of the window.
.PARAMETER DefaultInputText
Specifies the default answer text.
.EXAMPLE
PS C:\> New-WPFInputBox -Message 'What is your computer name' -Title 'Computer' -DefaultInputText "$env:ComputerName"
.NOTES
Author: Francois-Xavier Cat
Twitter:@LazyWinAdm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[string]$Message,
[Alias('WindowsTitle')]
[string]$Title,
[Alias('DefaultText')]
[string]$DefaultInputText
)
BEGIN
{
TRY
{
# Load the Assembly
Add-Type -AssemblyName Microsoft.VisualBasic -ErrorAction 'Stop' -ErrorVariable ErrorBeginAddType
}
CATCH
{
Write-Warning -message "[BEGIN] Something wrong happened"
IF ($ErrorBeginAddType) { Write-Warning -message "[BEGIN] Error while loading assembly Microsoft.VisualBasic" }
Write-Error -message $Error[0].Exception.Message
}
}
PROCESS
{
if ($PSCmdlet.ShouldProcess("InputBox", "Show a new Input box with the following message: $Message"))
{
#[Microsoft.VisualBasic.Interaction]::InputBox($Message, $Title, $DefaultInputText, $XPosition, $YPosition)
Write-output $([Microsoft.VisualBasic.Interaction]::InputBox($Message, $Title, $DefaultInputText))
}
}
} #New-InputBox
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Clear-WPFListBox.ps1
|
Clear-WPFListBox.ps1
|
function Clear-WPFListBox
{
<#
.SYNOPSIS
function to clear the content of a Listbox
.DESCRIPTION
function to clear the content of a Listbox
.PARAMETER ListBox
Specifies the ListBox control to clear
.EXAMPLE
PS C:\> Clear-WPFListBox -ListBox $ListBox01
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
[System.Windows.Controls.ListBox]
$ListBox
)
# Clear ListBox
$ListBox.Items.Clear()
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Show-WPFWindow.ps1
|
Show-WPFWindow.ps1
|
function Show-WPFWindow
{
<#
.SYNOPSIS
Function to show the Window
.DESCRIPTION
Function to show the Window
.PARAMETER Window
Specifies the Window to Show
.EXAMPLE
PS C:\> Show-WPFWindow -Window $Window
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
<#
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory)]
[Alias("Form")]
[System.Windows.Window]
$Window)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
$Window.ShowDialog() | out-null
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Add-WPFListBoxItem.ps1
|
Add-WPFListBoxItem.ps1
|
function Add-WPFListBoxItem
{
<#
.SYNOPSIS
Function to add items from a Listbox
.DESCRIPTION
Function to add items from a Listbox.
System.windows.controls.listbox
https://msdn.microsoft.com/en-us/library/system.windows.controls.listbox(v=vs.110).aspx
.PARAMETER ListBox
Specifies the Listbox control
.PARAMETER Items
Specifies the items to add in the Listbox
.PARAMETER Append
Specifies that the Listbox
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
[System.Windows.Controls.ListBox]
$ListBox,
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
$Item #,
#[Switch]$Append=$true
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
<#
IF (-not $PSBoundParameters['Append'])
{
# Clear ListBox
$ListBox.items.Clear()
}
#>
# Add Items
FOREACH ($i in $Item)
{
$ListBox.Items.Add($i)
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Remove-WPFListBoxItem.ps1
|
Remove-WPFListBoxItem.ps1
|
function Remove-WPFListBoxItem
{
<#
.SYNOPSIS
Function to remove items from a Listbox
.DESCRIPTION
Function to remove items from a Listbox
System.windows.controls.listbox
https://msdn.microsoft.com/en-us/library/system.windows.controls.listbox(v=vs.110).aspx
.PARAMETER ListBox
Specifies the Listbox control
.PARAMETER SelectedItem
Specifies that all the selected items will be remove from the Listbox
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[System.Windows.Controls.ListBox]$ListBox,
[Switch]$SelectedItem
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSBoundParameters['SelectedItem'])
{
while ($ListBox.SelectedItems.count -gt 0)
{
$ListBox.Items.RemoveAt($ListBox.SelectedIndex)
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Enable-WPFTextBox.ps1
|
Enable-WPFTextBox.ps1
|
function Enable-WPFTextBox
{
<#
.SYNOPSIS
Function to Enable a TextBox Control
.DESCRIPTION
Function to Enable a TextBox Control
.PARAMETER TextBox
Specifies the TextBox Control
.EXAMPLE
PS C:\> Enable-WPFTextBox -Textbox $TextBox1
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM ([System.Windows.Controls.TextBox]
$TextBox)
$Textbox.IsEnabled = $True
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Clear-WPFRichTextBox.ps1
|
Clear-WPFRichTextBox.ps1
|
function Clear-WPFRichTextBox
{
<#
.SYNOPSIS
This function will clear the content of a richtextbox control
.DESCRIPTION
This function will clear the content of a richtextbox control
.PARAMETER RichTextBox
Specifies the RichTextBox control
.EXAMPLE
Clear-WPFRichTextBox -RichTextBox $RichTextBox1
.NOTES
Francois-Xavier Cat
@lazywinadm
www.lazywinadmin.com
github.com/lazywinadmin
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[System.Windows.Controls.RichTextBox]$RichTextBox
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSCmdlet.ShouldProcess($RichTextBox, "Clear the Richtextbox control"))
{
#Clear the RichTextBox
$RichTextBox.Document.Blocks.Clear()
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Set-WPFTextBoxText.ps1
|
Set-WPFTextBoxText.ps1
|
function Set-WPFTextBoxText
{
<#
.SYNOPSIS
function to set the Text property on a TextBox control
.DESCRIPTION
function to set the Text property on a TextBox control
.PARAMETER TextBox
Specifies the TExtBox Control
.PARAMETER Text
Specifies the Text property value
.EXAMPLE
PS C:\> Set-WPFTextBoxText -TextBox $TextBox1 -Text 'Some text here'
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM (
[Parameter(Mandatory)]
[System.Windows.Controls.TextBox]
$TextBox,
[String]$Text)
$TextBox.Text = $Text
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Set-WPFWindowVariable.ps1
|
Set-WPFWindowVariable.ps1
|
Function Set-WPFWindowVariable
{
<#
.SYNOPSIS
Function to generate the Control Variables
.DESCRIPTION
Function to generate the Control Variables
.PARAMETER Window
Specifies the Window
.PARAMETER XAML
Specifies the XAML used
.PARAMETER Prefix
Specifies the Prefix of each Variable, default is WPF
.EXAMPLE
PS C:\> Set-WPFWindowVariable -Window $Window -XAML $XAML -Prefix 'WPF'
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
[CmdletBinding()]
PARAM (
[parameter(Mandatory)]
[alias("Form")]
[System.Windows.Window]
$Window,
[parameter(Mandatory)]
[XML]$XAML,
$Prefix = "WPF")
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
# Retrieve the Control in the XAML
$GUI = $XAML.SelectNodes("//*[@Name]")
}
PROCESS
{
IF ($PSBoundParameters['Prefix'])
{
Foreach ($item in $GUI)
{
Set-Variable -Name "$Prefix$($item.Name)" -Value $Window.FindName($item.Name) -Scope global
}
}
ELSE
{
Foreach ($item in $GUI)
{
Set-Variable -Name "($item.Name)" -Value $Window.FindName($item.Name) -Scope global
}
}
} #Process
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Set-WPFListBox.ps1
|
Set-WPFListBox.ps1
|
function Set-WPFListBox
{
<#
.SYNOPSIS
Function to edit the behavior of a ListBox Control
.DESCRIPTION
Function to edit the behavior of a ListBox Control
.PARAMETER ListBox
Specifies the ListBox control
.PARAMETER ScrollToCaret
Specifies that you want the listbox to go to the bottom of the list
.PARAMETER SelectionMode
Specifies the selection mode. Default is Single
Extended: The user can select multiple consecutive items while holding down the SHIFT key.
Multiple: The user can select multiple items without holding down a modifier key.
Single: The user can select only one item at a time.
https://msdn.microsoft.com/en-us/library/system.windows.controls.selectionmode(v=vs.110).aspx
.EXAMPLE
PS C:\> Set-WPFListBox -ListBox $ListBox -ScrollToCaret
Go to the bottom of the listbox $listbox
.EXAMPLE
PS C:\> Set-WPFListBox -ListBox $ListBox -SelectionMode Extended
Change the SelectionMode to Extended.
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
Syystem.Windows.Controls.ListBox
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Windows.Controls.ListBox]$ListBox,
[switch]$ScrollToCaret,
[System.Windows.Controls.Selectionmode]$SelectionMode
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
IF ($PSBoundParameters['ScrollToCaret'])
{
$listBox.SelectedIndex = $listBox.Items.Count - 1
$ListBox.ScrollIntoView($listBox.SelectedItem)
}
IF ($PSBoundParameters['SelectionMode'])
{
$ListBox.SelectionMode = $SelectionMode
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Disable-WPFTextBox.ps1
|
Disable-WPFTextBox.ps1
|
function Disable-WPFTextBox
{
<#
.SYNOPSIS
Function to disable a TextBox Control
.DESCRIPTION
Function to disable a TextBox Control
.PARAMETER TextBox
Specifies the TextBox Control
.EXAMPLE
PS C:\> Disable-WPFTextBox -Textbox $TextBox1
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
PARAM ([System.Windows.Controls.TextBox]
$TextBox)
$Textbox.IsEnabled = $false
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Add-WPFComboBoxItem.ps1
|
Add-WPFComboBoxItem.ps1
|
function Add-WPFComboBoxItem
{
<#
.SYNOPSIS
Function to add items from a ComboBox
.DESCRIPTION
Function to add items from a ComboBox
System.windows.controls.combobox
https://msdn.microsoft.com/en-us/library/system.windows.controls.combobox(v=vs.110).aspx
.PARAMETER ComboBox
Specifies the ComboBox control
.PARAMETER Item
Specifies the item to add
.EXAMPLE
Add-WPFComboBoxItem -ComboBox $Combobox1 -item (Get-Service).ServiceName
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
[System.Windows.Controls.ComboBox]
$ComboBox,
[ValidateNotNull()]
[Parameter(Mandatory = $true)]
$Item
)
BEGIN
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
PROCESS
{
# Add Items
FOREACH ($i in $Item)
{
#$ComboBox.Items.Add($i)
$ComboBox.Items.Add($i) | Out-Null
}
}
}
|
PowerShellCorpus/PowerShellGallery/WPFPS/1.0.0.0/Public/Get-WPFListBoxItem.ps1
|
Get-WPFListBoxItem.ps1
|
function Get-WPFListBoxItem
{
<#
.SYNOPSIS
Function to retrieve items from a ListBox Control
.DESCRIPTION
Function to retrieve items from a ListBox Control
.PARAMETER ListBox
Specifies the ListBox control
.PARAMETER Selected
Retrieve only the selected items
.PARAMETER All
Retrieve All items
.EXAMPLE
PS C:\> Get-WPFListBoxItem -ListBox $ListBox1 -Selected
Retrieve the selected Item(s)
.EXAMPLE
PS C:\> Get-WPFListBoxItem -ListBox $ListBox1
Retrieve all the items
.NOTES
Francois-Xavier Cat
lazywinadmin.com
@lazywinadm
github.com/lazywinadmin
#>
[CmdletBinding(DefaultParameterSetName = 'All')]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNull()]
[System.Windows.Controls.ListBox]
$ListBox,
[Parameter(ParameterSetName = 'Selected',
Mandatory = $false)]
[Switch]$Selected,
[Parameter(ParameterSetName = 'All')]
$All
)
begin
{
Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase
}
process
{
IF ($PSBoundParameters['Selected'])
{
$ListBox.SelectedItems
}
IF ($PSBoundParameters['All'])
{
$ListBox.Items
}
}
}
|
PowerShellCorpus/PowerShellGallery/AzureStackVaaS/2.0.0/Automation/LaunchVaaSTests.ps1
|
LaunchVaaSTests.ps1
|
##-----------------------------------------------------------------------
## <copyright file="LaunchVaaSTests.ps1" company="Microsoft Corp.">
## Copyright (c) Microsoft Corp. All rights reserved.
## </copyright>
##-----------------------------------------------------------------------
<#
.SYNOPSIS
Launches a VaaS Test Pass based off of the supplied parameters.
.DESCRIPTION
Launches a VaaS Test Pass based off of the supplied parameters using the AzureStackVaaS PowerShell cmdlets.
.PARAMETER VaaSSolutionName
VaaSSolutionName
.PARAMETER VaaSTestPassName
VaaSTestPassName
.PARAMETER VaaSTestCategory
VaaSTestCategory - Integration, Functional, or Reliability
.PARAMETER VaaSOnPremAgentName
Name of the agent for executing tests on premise. If not specified, the local machine name will be used.
.PARAMETER VaaSAccountCreds
VaaSAccountCreds - PSCredential type
.PARAMETER VaaSApplicationId
VaaSApplicationId
.PARAMETER VaaSAccountTenantId
VaaSAccountTenantId
.PARAMETER VaaSPackageUri
Optional. Overrides default VaaS package storage location
.PARAMETER VaaSPortalUri
Optional. Specifies VaaS Portal Endpoint.
.PARAMETER VaaSApplicationUri
Optional. Specifies Application Endpoint.
.PARAMETER VaaSBaseServiceUri
Optional. Specifies VaaS Service Endpoint.
.PARAMETER VaaSServiceResourceId
Optional. Specifies VaaS Service Resource Id.
.PARAMETER AadTenantId
AadTenantId
.PARAMETER ServiceAdminCreds
ServiceAdminCreds
.PARAMETER TenantAdminCreds
TenantAdminCreds
.PARAMETER ExternalFqdn
External FQDN for the environment
.PARAMETER Region
Optional. Sets the value for region in cases where this value cannot be gathered. Default value is "local"
.PARAMETER NumberOfNodes
Optional. Sets the value for NumberOfNodes in cases where this value cannot be gathered. Default value is 4
.PARAMETER LogFilePath
Path to log files from tests. If the DoNotWait switch is specified, use cmdlet Get-AzureStackVaaSTestLaunchLogs
to obtain log files.
.PARAMETER MaxDurationInHrs
Specifies how long execution of this script should take before cancelling any pending tests and returning
the failure exit code (0)
.PARAMETER DoNotWait
The DoNotWait switch bypasses the test execution monitor loop that normally executes once tests are scheduled.
.PARAMETER UseVaaSSPNAuth
The UseVaaSSPNAuth switch specifies that SPN credentials are supplied via parameter VaaSAccountCreds.
Note that parameters VaaSApplicationId and VaaSApplicationUri are not applicable when specifying the UseVaaSSPNAuth switch.
.EXAMPLE
Create account credentials object:
$VaaSAccountCreds = New-Object System.Management.Automation.PSCredential (“vaasUserId@vaasTenant.onmicrosoft.com”, ConvertTo-SecureString “Password” -AsPlainText -Force)
Launch VaaS Test Pass using account credentials:
.\LaunchVaaSTests.ps1 -VaaSTestCategory Functional -VaaSAccountCreds $VaaSAccountCreds -VaaSAccountTenantId <VaaSAccountTenantId>
-AadTenantId <AadTenantId> -ServiceAdminCreds <ServiceAdminCreds> -TenantAdminCreds <TenantAdminCreds> -ExternalFqdn <ExternalFqdn>
-MaxDurationInHrs 48
.LINK
https://www.powershellgallery.com/packages/AzureStackVaaS
#>
param(
[Parameter(Mandatory=$false)][string]$VaaSSolutionName=$null,
[Parameter(Mandatory=$false)][string]$VaaSTestPassName=$null,
[Parameter(Mandatory=$true)][ValidateSet("Integration","Functional","Reliability","CI")][string]$VaaSTestCategory,
[Parameter(Mandatory=$false)][string]$VaaSOnPremAgentName=$null,
[Parameter(Mandatory=$true)][ValidateNotNull()][PSCredential]$VaaSAccountCreds,
[Parameter(Mandatory=$false)][string]$VaaSApplicationId=$null,
[Parameter(Mandatory=$true)][ValidateNotNull()][string]$VaaSAccountTenantId,
[Parameter(Mandatory=$false)][string]$VaaSTestManifestSource=$null,
[Parameter(Mandatory=$false)][string]$VaaSPackageUri=$null,
[Parameter(Mandatory=$false)][string]$VaaSPortalUri=$null,
[Parameter(Mandatory=$false)][string]$VaaSApplicationUri=$null,
[Parameter(Mandatory=$false)][string]$VaaSBaseServiceUri=$null,
[Parameter(Mandatory=$false)][string]$VaaSServiceResourceId=$null,
[Parameter(Mandatory=$true)][ValidateNotNull()][string]$AadTenantId,
[Parameter(Mandatory=$true)][ValidateNotNull()][PSCredential]$ServiceAdminCreds,
[Parameter(Mandatory=$true)][ValidateNotNull()][PSCredential]$TenantAdminCreds,
[Parameter(Mandatory=$true)][string]$ExternalFqdn,
[Parameter(Mandatory=$false)][string]$Region="local",
[Parameter(Mandatory=$false)][int]$NumberOfNodes=4,
[Parameter(Mandatory=$false)][string]$LogFilePath=$null,
[Parameter(Mandatory=$true)][int]$MaxDurationInHrs,
[Parameter(Mandatory=$false)][switch]$DoNotWait,
[Parameter(Mandatory=$false)][switch]$UseVaaSSPNAuth
)
[System.Reflection.Assembly]::LoadWithPartialName("mscorlib") | Out-Null
try
{
Add-Type -TypeDefinition @"
public struct LaunchData
{
public System.DateTime durationTimeout;
public string[] logPaths;
public string onPremAgentDirectory;
public int testResult;
public int titleCounter;
public string vaaSPackageDirectory;
}
"@
}
catch
{
Write-Host "Add-Type may already be added for this PowerShell Session ..."
}
finally
{
$launcherData = New-Object LaunchData
}
Add-Type -TypeDefinition @"
public struct EnvInfo
{
public string DeploymentID;
public string StampVersion;
public string Prefix;
public string CompanyName;
public string ServerSku;
public string Topology;
public string Timezone;
public string HardwareOEM;
public string RegionName;
public string DomainNetBIOSName;
public string DomainFQDN;
public string Timeserver;
public int NumberOfNodes;
}
"@
$envInfo = New-Object EnvInfo
New-Variable -Name BaseURIVaaSStorage -Value "https://vaastestpacksprodeastus.blob.core.windows.net" -Option Constant
New-Variable -Name BaseURIVaaSPortal -Value "https://azurestackvalidation.com" -Option Constant
New-Variable -Name GetStampInfoUri -Value "https://ASAppGateway:4443/ServiceTypeId/4dde37cc-6ee0-4d75-9444-7061e156507f/CloudDefinition/GetStampInformation" -Option Constant
New-Variable -Name IsProductionRun -Value $true
New-Variable -Name DefaultRetryCount -Value 60 -Option Constant
New-Variable -Name ProjectType -Value "TestPasses" -Option Constant
function CreateVaaSDirectory
{
if (!(Test-Path -Path "$($launcherData.vaaSPackageDirectory)" -PathType Container))
{
Write-Verbose "Creating vaaSPackageDirectory ..."
New-Item -ItemType Directory -Path $launcherData.vaaSPackageDirectory | Out-Null
}
else
{
Write-Warning "Path $($launcherData.vaaSPackageDirectory) already exists ..."
}
}
function CreateVaaSLogDirectory
{
if (!(Test-Path -Path "$LogFilePath" -PathType Container))
{
Write-Verbose "Creating VaaS Log Directory ..."
New-Item -ItemType Directory -Path $LogFilePath | Out-Null
}
}
function CreateVaaSSolution
{
DisplayTitle -Title "Creating VaaS Solution"
Write-Host "Creating VaaS Solution with name $VaaSSolutionName ..."
return (New-AzureStackVaaSSolution -Name $VaaSSolutionName -Force -ErrorAction Stop)
}
function CreateVaaSTestPass
{
DisplayTitle -Title "Creating VaaS Test Pass"
Write-Host "Creating VaaS Test Pass with name $VaaSTestPassName ..."
$tpParams = @{'SolutionName' = $VaaSSolutionName;'Name' = $VaaSTestPassName}
if($envInfo.StampVersion -ne "")
{
$tpParams.Add('Build',$envInfo.StampVersion)
}
if($envInfo.ServerSku -ne "")
{
$tpParams.Add('ServerSku',$envInfo.ServerSku)
}
if($envInfo.Topology -ne "")
{
$tpParams.Add('Topology',$envInfo.Topology)
}
if($envInfo.RegionName -ne "")
{
$tpParams.Add('RegionName',$envInfo.RegionName)
}
if($envInfo.NumberOfNodes -ne "")
{
$tpParams.Add('NumberOfNodes',$envInfo.NumberOfNodes)
}
return (New-AzureStackVaaSTestPass @tpParams -Force -ErrorAction Stop)
}
function InstallVaaSPSModules
{
DisplayTitle -Title "Installing Azure Stack VaaS PowerShell Module"
if($VaaSPackageUri -imatch "$BaseURIVaaSStorage/packages")
{
Write-Host "Installing from PowerShell Gallery ..."
Install-Module -Name AzureStackVaaS -Scope AllUsers -AllowClobber -Force -ErrorVariable InstallError -ErrorAction SilentlyContinue
if($InstallError)
{
Write-Warning "Couldn't install Azure Stack VaaS PowerShell module..."
}
return
}
$vaasPSModulesUri = "$VaaSPackageUri/AzureStackVaaS.zip"
Write-Host "Downloading latest Azure Stack VaaS PowerShell Module from:"
Write-Host $vaasPSModulesUri
try
{
Invoke-WebRequest -Uri $vaasPSModulesUri -outfile "$($launcherData.vaaSPackageDirectory)\AzureStackVaaS.zip"
}
catch
{
Write-Warning "Unable to download file from $vaasPSModulesUri"
Write-Warning "Attempting retry in 30 seconds ..."
Start-Sleep -s 30 | Out-Null
try
{
Invoke-WebRequest -Uri $vaasPSModulesUri -outfile "$($launcherData.vaaSPackageDirectory)\AzureStackVaaS.zip"
}
catch
{
Write-Warning "Unable to download file on retry from:`r`n$vaasPSModulesUri"
return
}
}
$psModulePath = $env:ProgramFiles + '\WindowsPowerShell\Modules'
Write-Host "Extracting latest Azure Stack VaaS PowerShell Module to:`r`n$psModulePath"
Expand-Archive -Path "$($launcherData.vaaSPackageDirectory)\AzureStackVaaS.zip" -DestinationPath "$psModulePath" -Force -ErrorAction SilentlyContinue -ErrorVariable ExpandError
if($ExpandError)
{
if($ExpandError[0].CategoryInfo.Reason -imatch 'UnauthorizedAccessException')
{
Write-Warning "A PowerShell lock currently exists on the Azure Stack VaaS PowerShell."
Write-Warning "To update binaries, please close the applicable PowerShell window or ISE."
}
}
}
function InstallVaaSOnPremAgent
{
DisplayTitle -Title "Installing VaaS OnPrem Agent"
Write-Host "Stopping any running VaaS OnPrem Agent(s) ..."
StopVaaSOnPremAgentProcess
Write-Host "Downloading latest VaaS OnPrem Agent from:"
$vaasOnPremAgentUri = "$VaaSPackageUri/Microsoft.VaaSOnPrem.TaskEngineHost.2.0.0.nupkg"
Write-Host $vaasOnPremAgentUri
New-Item -ItemType Directory -Force -Path $launcherData.vaaSPackageDirectory | Out-Null
try
{
Invoke-WebRequest -Uri $vaasOnPremAgentUri -outfile "$($launcherData.vaaSPackageDirectory)\OnPremAgent.zip"
}
catch
{
Write-Warning "Unable to download file from $vaasOnPremAgentUri"
Write-Warning "Attempting retry in 30 seconds ..."
Start-Sleep -s 30 | Out-Null
Invoke-WebRequest -Uri $vaasOnPremAgentUri -outfile "$($launcherData.vaaSPackageDirectory)\OnPremAgent.zip"
}
Write-Host "Extracting latest VaaS OnPrem Agent to:"
Write-Host $launcherData.vaaSPackageDirectory
Expand-Archive -Path "$($launcherData.vaaSPackageDirectory)\OnPremAgent.zip" -DestinationPath "$($launcherData.vaaSPackageDirectory)\OnPremAgent" -Force
}
function InstallVaaSPreReq
{
DisplayTitle -Title "Installing VaaS Prerequisites"
Push-Location $launcherData.onPremAgentDirectory
$result = @()
$ArmEndpoint = GetServiceArmEndpoint
try
{
Import-Module .\VaaSPreReqs.psm1 -Force
Set-VaaSPreReqContext -LogFilePath $LogFilePath
$result = Install-VaaSPrerequisites -AadTenantId $AadTenantId -ServiceAdminCreds $ServiceAdminCreds -ArmEndpoint $ArmEndpoint -Region $($envInfo.RegionName)
}
catch
{
Pop-Location
Write-Error "VaaS Prerequisite installation failed. Check logs for details."
TerminateScript $_.Exception.Message
}
if($result[$result.count-1] -ne 0)
{
Pop-Location
TerminateScript "VaaS Prerequisite installation failed. Check logs for details."
}
Write-Host "VaaS Prerequisite installation succeeded. Check logs for details."
Pop-Location
}
function InitializeLaunchData
{
$launcherData.vaaSPackageDirectory = $env:Temp + "\VaaS"
$launcherData.onPremAgentDirectory = $launcherData.vaaSPackageDirectory + "\OnPremAgent\lib\net46"
$launcherData.durationTimeout = (Get-Date).AddHours($MaxDurationInHrs)
$launcherData.logPaths = @()
$launcherData.testResult = 0
$launcherData.titleCounter = 0
}
function ValidateAndResolveAuthMethodParameters
{
if(($VaaSPortalUri -eq "") -and ($VaaSBaseServiceUri -eq "") -and ($VaaSServiceResourceId -eq ""))
{
$script:IsProductionRun = $true
}
elseif(($VaaSPortalUri -ne "") -and ($VaaSBaseServiceUri -ne "") -and ($VaaSServiceResourceId -ne ""))
{
$script:IsProductionRun = $false
}
else
{
throw [System.ArgumentException] "Parameters VaaSPortalUri, VaaSBaseServiceUri, and VaaSServiceResourceId must be either all specified, or none specified ..."
}
if(($IsProductionRun) -or ($UseVaaSSPNAuth))
{
if(($VaaSApplicationId -ne "") -or ($VaaSApplicationUri -ne ""))
{
throw [System.ArgumentException] "Parameters VaaSApplicationId and/or VaaSApplicationUri should not be specified when launching a production level run or when using SPN credentials ..."
}
}
elseif(!$UseVaaSSPNAuth)
{
Write-Host "Verifying that parameters VaaSApplicationId and VaaSApplicationUri are present as`r`nthe UseVaaSSPNAuth switch was not specified..."
if(($VaaSApplicationId -eq "") -or ($VaaSApplicationUri -eq ""))
{
throw [System.ArgumentException] "Parameters VaaSApplicationId and VaaSApplicationUri must both be specified when using non-SPN credentials are supplied ..."
}
}
}
function ValidateAndResolveTestParameters
{
$vaasGroupManifest = "$PSScriptRoot\TestGroupManifests\$VaaSTestCategory.json"
if (!(Test-Path -Path "$vaasGroupManifest" -PathType Leaf))
{
throw [System.IO.FileNotFoundException] "The required test manifest file for executing $VaaSTestCategory tests was not found at location:`r`n$vaasGroupManifest"
}
if($VaaSTestManifestSource -eq "")
{
$script:VaaSTestManifestSource = $BaseURIVaaSStorage
Write-Host "VaaS Test Manifest source updated to:`r`n$VaaSTestManifestSource"
}
if($VaaSPackageUri -eq "")
{
$script:VaaSPackageUri = "$BaseURIVaaSStorage/packages"
Write-Host "VaaS Package endpoint updated to:`r`n$VaaSPackageUri"
}
if($VaaSPortalUri -eq "")
{
$script:VaaSPortalUri = $BaseURIVaaSPortal
Write-Host "VaaS Portal endpoint updated to:`r`n$VaaSPortalUri"
}
}
function ValidateAndResolveEnvironmentParameters
{
if($VaaSOnPremAgentName -eq "")
{
$script:VaaSOnPremAgentName = (Get-WmiObject win32_computersystem).DNSHostName + "." + (Get-WmiObject win32_computersystem).Domain
Write-Host "Defaulting to VaaS OnPrem agent name $VaaSOnPremAgentName, as an agent name was not provided ..."
}
GetStampInformation
if($VaaSTestPassName -eq "")
{
$script:VaaSTestPassName = "TP" + $(Get-Date -Format yyMMddHHmm)
Write-Host "Defaulting to VaaS test pass name $VaaSTestPassName, as a test pass name was not provided ..."
}
if($VaaSSolutionName -eq "")
{
$script:VaaSSolutionName = "AzureStack-VaaS"
Write-Host "Defaulting to VaaS solution name $VaaSSolutionName, as a solution name was not provided ..."
}
}
function ValidateAndResolveParameters
{
DisplayTitle -Title "Validating and Resolving Parameters"
ValidateAndResolveAuthMethodParameters
ValidateAndResolveTestParameters
ValidateAndResolveEnvironmentParameters
}
function ConfigureGroupManifestFile
{
DisplayTitle -Title "Configuring VaaS Group Manifest File"
$vaasGroupManifest = "$PSScriptRoot\TestGroupManifests\$VaaSTestCategory.json"
$vaasGroupManifestData = Get-Content $vaasGroupManifest
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[VaaSTestManifestSource]", $VaaSTestManifestSource)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[ExternalFqdn]", $ExternalFqdn)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[TenantId]", $AadTenantId)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[AdminArmEndpoint]", "https://adminmanagement.$ExternalFqdn/")
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[TenantArmEndpoint]", "https://management.$ExternalFqdn/")
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[ServiceAdminUser]", $ServiceAdminCreds.UserName)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[ServiceAdminPassword]", $ServiceAdminCreds.GetNetworkCredential().password)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[TenantAdminUser]", $TenantAdminCreds.UserName)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[TenantAdminPassword]", $TenantAdminCreds.GetNetworkCredential().password)
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[NumberOfNodes]", $envInfo.NumberOfNodes.ToString())
$vaasGroupManifestData = $vaasGroupManifestData.Replace("[RegionName]", $envInfo.RegionName)
$vaasGroupManifest = $vaasGroupManifest.Replace(".json", "_Resolved.json")
$vaasGroupManifestData | Set-Content $vaasGroupManifest -Force
Write-Host "Group Manifest $vaasGroupManifest created ..."
return $vaasGroupManifest
}
function CancelActiveTests
{
param(
[parameter(Mandatory=$true)][Object[]]$testLaunchManifests
)
foreach($testLaunchManifest in $testLaunchManifests)
{
Write-Host "Getting information for test: $($testLaunchManifest.TestLaunchName) ..."
$testManifest = Get-AzureStackVaaSTestLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -Name $testLaunchManifest.TestLaunchName -ErrorAction Ignore -ErrorVariable GetTestError
Write-Host "Test state: $($testManifest.State) ..."
if (($testManifest.State -eq 'Accepted') -or ($testManifest.State -eq 'Running'))
{
Write-Host "Attempting to stop test $($testLaunchManifest.TestLaunchName) ..."
Stop-AzureStackVaaSTestLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -Name $testLaunchManifest.TestLaunchName -Force -ErrorAction Ignore -ErrorVariable StopTestError
if($StopTestError)
{
Write-Warning "Unable to Stop Test $($testLaunchManifest.TestLaunchName) due to $($StopTestError[0].CategoryInfo.Reason). Retrying ..."
Start-Sleep -s 5 | Out-Null
Stop-AzureStackVaaSTestLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -Name $testLaunchManifest.TestLaunchName -Force -ErrorAction Continue
}
}
}
}
function StartVaaSOnPremAgent
{
DisplayTitle -Title "Starting VaaS OnPrem Agent"
Write-Host "Verifying that 'login.windows.net' can be resolved ..."
Resolve-DnsName login.windows.net -ErrorVariable ResolutionError -ErrorAction SilentlyContinue | Out-Null
if($ResolutionError)
{
Write-Error "Terminating script as 'login.windows.net' cannot be resolved ..."
throw $ResolutionError[0].Exception
}
$agentArgs = @("-t $VaaSAccountTenantId","-p $($VaaSAccountCreds.GetNetworkCredential().password)","-n $VaaSOnPremAgentName")
if($UseVaaSSPNAuth)
{
$agentArgs += "-c $(($VaaSAccountCreds).UserName)"
}
else
{
$agentArgs += "-u $(($VaaSAccountCreds).UserName)"
if($VaaSApplicationId -ne "")
{
$agentArgs += "-c $VaaSApplicationId"
}
}
if($VaaSBaseServiceUri -ne "")
{
$agentArgs += "-l $VaaSBaseServiceUri"
}
if($VaaSServiceResourceId -ne "")
{
$agentArgs += "-r $VaaSServiceResourceId"
}
if($VaaSApplicationUri -ne "")
{
$agentArgs += "-z $VaaSApplicationUri"
}
Write-Host "Checking to see if Agent $VaaSOnPremAgentName already exists ..."
$agentInstance = Get-AzureStackVaaSOnPremAgent -Name $VaaSOnPremAgentName -ErrorAction SilentlyContinue -ErrorVariable GetAgentError | Out-Null
if($GetAgentError)
{
Write-Host "Did not find Agent $VaaSOnPremAgentName. Starting agent ..."
}
else
{
RemoveVaaSOnPremAgent -agentName $VaaSOnPremAgentName
}
Push-Location $launcherData.onPremAgentDirectory
Start-Process -FilePath "Microsoft.VaaSOnPrem.TaskEngineHost.exe" -ArgumentList $agentArgs -WindowStyle Minimized -Verb runas
$agentArgs = [string]::Empty
Pop-Location
Write-Host "VaaS OnPrem Agent started ..."
Write-Host "Waiting for OnPrem Agent to register ..."
Write-Host "Verifying OnPrem Agent status ..."
VerifyVaaSOnPremAgentStatus -agentName $VaaSOnPremAgentName
return $VaaSOnPremAgentName
}
function VerifyVaaSOnPremAgentStatus
{
param(
[parameter(Mandatory=$true)][ValidateNotNull()][string]$agentName
)
Start-Sleep -s 10 | Out-Null
$agentInstance = Get-AzureStackVaaSOnPremAgent -Name $agentName -ErrorAction Ignore -ErrorVariable GetAgentError
if($GetAgentError)
{
Write-Verbose "Unable to get agent $VaaSOnPremAgentName, retrying after 30 seconds ..."
Start-Sleep -s 30 | Out-Null
$agentInstance = Get-AzureStackVaaSOnPremAgent -Name $agentName -ErrorAction Ignore -ErrorVariable GetAgentError
if($GetAgentError)
{
$launcherData.testResult = 1
$launcherData.testResult
ShutdownVaaSOnPremAgent
RemoveVaaSOnPremAgent
exit $launcherData.testResult
}
}
if($agentInstance.ApproximatePendingTests -gt 0)
{
Write-Warning "Agent has $($agentInstance.ApproximatePendingTests) pending tests ..."
}
Write-Host "Agent ready for launching tests ..."
}
function ShutdownVaaSOnPremAgent
{
$agentInstance = Get-AzureStackVaaSOnPremAgent -Name $VaaSOnPremAgentName -ErrorAction Ignore -ErrorVariable ShutdownAgentError
if($ShutdownAgentError)
{
Write-Verbose "Unable to get agent $VaaSOnPremAgentName"
return
}
[DateTime]$shutdownTimeout = (Get-Date).AddMinutes(5)
while($agentInstance.ApproximatePendingTests -gt 0)
{
if((Get-Date) -gt $shutdownTimeout)
{
Write-Warning "Tests are still being processed by agent after 5 minutes, forcing Agent shutdown ..."
break
}
Start-Sleep -Seconds 20 | Out-Null
$agentInstance = Get-AzureStackVaaSOnPremAgent -Name $VaaSOnPremAgentName
Write-Host "Waiting for $($agentInstance.ApproximatePendingTests) test(s) to complete before shutting down Agent ..."
}
StopVaaSOnPremAgentProcess
}
function StopVaaSOnPremAgentProcess
{
$process = Get-Process -ProcessName "Microsoft.VaaSOnPrem.TaskEngineHost" -ErrorAction Ignore
foreach ($proc in $process)
{
Stop-Process $proc -Force -ErrorAction Ignore
}
}
function RemoveVaaSOnPremAgent
{
param(
[parameter(Mandatory=$true)][ValidateNotNull()][string]$agentName
)
Write-Host "Attempting to remove Agent $agentName ..."
Remove-AzureStackVaaSOnPremAgent -Name $agentName -ErrorAction SilentlyContinue -ErrorVariable RemoveAgentError -Force | Out-Null
if($RemoveAgentError)
{
Write-Warning "Unable to remove Agent $agentName due to ..."
$errorMsg = ""
if ($RemoveAgentError.Exception.InnerException.Message -ne $null)
{
$errorMsg = $RemoveAgentError.Exception.InnerException.Message.ToString()
}
else
{
$errorMsg = $RemoveAgentError.Exception.ToString()
}
Write-Warning $errorMsg
}
else
{
Write-Host "Agent $agentName was removed successfully ..."
}
}
function GetStampInformation
{
$params = $null
try
{
Write-Host "Attempting to get stamp information via:`r`n$GetStampInfoUri"
$params = Invoke-RestMethod -Method Get -Uri $GetStampInfoUri
}
catch
{
Write-Warning "Unable to get stamp infomation. Retrying in 15 seconds ..."
Start-Sleep -Seconds 15
try
{
$params = Invoke-RestMethod -Method Get -Uri $GetStampInfoUri
}
catch
{
Write-Warning "Unable to get stamp infomation on retry"
}
}
finally
{
if($params)
{
$envInfo.DeploymentID = $params.DeploymentID
$envInfo.StampVersion = $params.StampVersion
$envInfo.Prefix = $params.Prefix
$envInfo.CompanyName = $params.CompanyName
$envInfo.ServerSku = $params.ServerSku
$envInfo.Topology = $params.Topology
$envInfo.Timezone = $params.Timezone
$envInfo.HardwareOEM = $params.HardwareOEM
$envInfo.RegionName = $params.RegionName
$envInfo.DomainNetBIOSName = $params.DomainNetBIOSName
$envInfo.DomainFQDN = $params.DomainFQDN
$envInfo.Timeserver = $params.Timeserver
$envInfo.NumberOfNodes = $params.NumberOfNodes
}
if($envInfo.NumberOfNodes -eq "")
{
Write-Host "Defaulting Number Of Nodes to the value of parameter NumberOfNodes ($NumberOfNodes) as environment information is not available ..."
$envInfo.NumberOfNodes = $NumberOfNodes
}
if(($envInfo.RegionName -eq "") -or ($envInfo.RegionName -eq $null))
{
Write-Host "Defaulting Region Name to the value of parameter Region ($Region) as environment information is not available ..."
$envInfo.RegionName = $Region
}
}
}
function GetServiceArmEndpoint
{
return "https://adminmanagement.$ExternalFqdn"
}
function GenerateVaaSReport
{
Write-Host "Generating VaaS Report"
Write-Host "Current directory: $(Get-Location)"
Write-Host "Setting directory to $PSScriptRoot"
Set-Location $PSScriptRoot
Write-Host "Current directory now set to: $(Get-Location)"
$retryCount = $DefaultRetryCount
while($retryCount -gt 0)
{
try
{
New-AzureStackVaaSTestPassReport -SolutionName $VaaSSolutionName -Name $VaaSTestPassName -Force
break
}
catch
{
Write-Warning "Exception thrown while attempting to call New-AzureStackVaaSTestPassReport:`r`n$($_.Exception.Message)"
}
$retryCount--
if ($retryCount -eq 0)
{
Write-Error "Retries exhausted. Unable to generate test pass report ..."
return
}
Write-Host "Attempting to generate report again in 5 seconds" $Logfile
Start-Sleep -seconds 5 | Out-Null
}
}
function DownloadLogs
{
param(
[parameter(Mandatory=$true)][string]$testLaunchName,
[parameter(Mandatory=$true)][string]$testName
)
[string]$logFullName = $LogFilePath + "\" + $testLaunchName + ".zip"
Start-Sleep -s 2 | Out-Null
Get-AzureStackVaaSTestLaunchLogs -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -TestLaunchName $testLaunchName -Path $logFullName -ErrorAction SilentlyContinue -ErrorVariable downloadError
if($downloadError)
{
if($downloadError[0].CategoryInfo.Reason -imatch 'AggregateException')
{
Write-Warning "Unable to download logs for test $testLaunchName to $logFullName"
Write-Warning "Command used to download logs:"
Write-Warning "Get-AzureStackVaaSTestLaunchLogs -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -TestLaunchName $testLaunchName -Path $logFullName"
Write-Host ""
Start-Sleep -s 2 | Out-Null
return
}
}
$launcherData.logPaths += "Logs for test $testName [$testLaunchName] downloaded to $logFullName"
Write-Host $launcherData.logPaths[-1]
Write-Host ""
}
function TestMonitor
{
param(
[parameter(Mandatory=$false)][int]$refreshRate=20,
[parameter(Mandatory=$false)][int]$refreshInterval=600,
[parameter(Mandatory=$true)][Object[]]$testLaunchManifests
)
DisplayTitle -title "Test Pass Monitor"
Start-Sleep -Seconds 2 | Out-Null
$launcherData.durationTimeout = (Get-Date).AddHours($MaxDurationInHrs)
$prevTestManifests = $null
$nextInterval = (Get-Date).AddSeconds(-1)
while($true)
{
if((Get-Date) -gt $launcherData.durationTimeout)
{
$launcherData.testResult = 1
Write-Warning "Cancelling all remaining tests as timeout has been reached ..."
CancelActiveTests -testLaunchManifests $testLaunchManifests
return
}
try
{
$testManifests = @()
foreach($testLaunchManifest in $testLaunchManifests)
{
$testManifests += Get-AzureStackVaaSTestLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -Name $testLaunchManifest.TestLaunchName -ErrorAction SilentlyContinue -ErrorVariable GetTestError
if($GetTestError)
{
Write-Warning "Could not get information for test $($testLaunchManifest.TestLaunchName); Reason - $($GetTestError[0].CategoryInfo.Reason)"
}
}
if($testManifests.count -ne $testLaunchManifests.count)
{
Write-Warning "Attempting to gather test pass information in $refreshRate seconds..."
Write-Warning "Number of tests launched: $($testLaunchManifests.count); Number of tests status was gathered: $($testManifests.count)"
Start-Sleep -Seconds $refreshRate | Out-Null
continue
}
$testPassActive = $false
foreach ($testManifest in $testManifests)
{
if (($testManifest.State -eq 'Accepted') -or ($testManifest.State -eq 'Running'))
{
$testPassActive = $true
break
}
}
# Check to see if there are any updates
if($prevTestManifests)
{
foreach ($prevTestManifest in $prevTestManifests)
{
#output table, reset nextInterval, and continue
$testManifest = $testManifests | where {$_.TestLaunchName -eq $prevTestManifest.TestLaunchName}
if($prevTestManifest.State -ne $testManifest.State)
{
Write-Host "[$(Get-Date -Format 'MM-dd-yy hh:mm:ss')] Checking Test Pass Status ..."
Write-Host "Test Pass URL $VaaSPortalUri/$VaaSAccountTenantId/en-US/TestPass/Manage/Summary?solutionName=$VaaSSolutionName&projectName=$VaaSTestPassName"
Find-AzureStackVaaSTestLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -ErrorAction SilentlyContinue -ErrorVariable GetTestError | ft -ErrorAction Ignore @{Expression={$_.TestName};Label="Test Name"},@{Expression={$_.CreatedTimeUtc};Label="Created"},@{Expression={if($_.StartedTimeUtc -eq "1/1/0001 12:00:00 AM"){""}else{$_.StartedTimeUtc}};Label="Started"},State,AgentName
if($GetTestError)
{
Write-Warning "Could not get test pass information; Reason - $($GetTestError[0].CategoryInfo.Reason)"
}
$nextInterval = (Get-Date).AddSeconds($refreshInterval)
$prevTestManifests = $testManifests
if( ($testManifest.State -eq "Succeeded") -or ($testManifest.State -eq "Failed") -or ($testManifest.State -eq "Cancelled") )
{
DownloadLogs -testLaunchName $testManifest.TestLaunchName -testName $testManifest.TestName
}
continue
}
}
}
else
{
Write-Host "[$(Get-Date -Format 'MM-dd-yy hh:mm')] Checking Test Pass Status ..."
Write-Host "Test Pass URL $VaaSPortalUri/$VaaSAccountTenantId/en-US/TestPass/Manage/Summary?solutionName=$VaaSSolutionName&projectName=$VaaSTestPassName"
Find-AzureStackVaaSTestLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -ErrorAction SilentlyContinue -ErrorVariable GetTestError | ft -ErrorAction Ignore @{Expression={$_.TestName};Label="Test Name"},@{Expression={$_.CreatedTimeUtc};Label="Created"},@{Expression={if($_.StartedTimeUtc -eq "1/1/0001 12:00:00 AM"){""}else{$_.StartedTimeUtc}};Label="Started"},State,AgentName
if($GetTestError)
{
Write-Warning "Could not get test pass information; Reason - $($GetTestError[0].CategoryInfo.Reason)"
}
$prevTestManifests = $testManifests
}
if (!$testPassActive)
{
DisplayTitle -title "Test pass completed. Final Result Summary"
$statusTable = $testManifests | ft @{Expression={$_.TestName};Label="Test Name"},@{Expression={$_.CreatedTimeUtc};Label="Created"},@{Expression={if($_.StartedTimeUtc -eq "1/1/0001 12:00:00 AM"){""}else{$_.StartedTimeUtc}};Label="Started"},State,AgentName | Out-String
Write-Host "Test Pass Status:"
Write-Host "$statusTable"
foreach($logPath in $launcherData.logPaths)
{
Write-Host $logPath
}
foreach ($testManifest in $testManifests)
{
if( ($testManifest.State -eq "Failed") -or ($testManifest.State -eq "Cancelled") )
{
$launcherData.testResult = 1
break
}
}
return
}
# If the time interval has been reached, output table, and reset nextInterval
if($nextInterval -lt (Get-Date))
{
Write-Host "[$(Get-Date -Format 'MM-dd-yy hh:mm:ss')] Checking Test Pass Status ..."
$nextInterval = (Get-Date).AddSeconds($refreshInterval)
}
$prevTestManifests = $testManifests
}
catch
{
Write-Warning "Exception occurred while calling Find-AzureStackVaaSTestLaunch. Retrying ..."
}
Start-Sleep -Seconds $refreshRate | Out-Null
}
}
function DisplaySessionInfo
{
Write-Host "Current User: $([Security.Principal.WindowsIdentity]::GetCurrent().Name)"
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if ($currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator ))
{
Write-Host "Current session is running as an Administrator ..."
}
else
{
Write-Warning "Current session is running is not running as an Administrator ..."
}
}
function DisplayTitle
{
param(
[parameter(Mandatory=$true)][string]$title,
[parameter(Mandatory=$false)][int]$seconds=1
)
$launcherData.titleCounter++
Write-Host ""
Write-Host "----------------------------------------------------" -ForegroundColor Green
Write-Host " $($launcherData.titleCounter). $title" -ForegroundColor Green
Write-Host "----------------------------------------------------" -ForegroundColor Green
Start-Sleep -s $seconds | Out-Null
}
Function TerminateScript
{
Param(
[Parameter(Mandatory=$True)][String]$Message
)
Write-Error $Message
$lastExitCode = 1
$lastExitCode
exit
}
function Main
{
DisplayTitle -title "Adding AzureStack VaaS Account"
if($IsProductionRun)
{
Write-Host "Production Run ..."
if($UseVaaSSPNAuth)
{
Write-Host "Using SPN Authentication"
Add-AzureStackVaaSAccount -Credential $VaaSAccountCreds -ServicePrincipal -TenantId $VaaSAccountTenantId -ErrorAction Stop
}
else
{
Write-Host "Using User Authentication"
Add-AzureStackVaaSAccount -Credential $VaaSAccountCreds -TenantId $VaaSAccountTenantId -ErrorAction Stop
}
}
else
{
if($UseVaaSSPNAuth)
{
Write-Host "Using SPN Authentication"
Add-AzureStackVaaSAccount -Credential $VaaSAccountCreds -ServicePrincipal -TenantId $VaaSAccountTenantId -TenantServiceBaseUri $VaaSBaseServiceUri -TenantServiceResourceId $VaaSServiceResourceId -ErrorAction Stop
}
else
{
Write-Host "Using User Authentication"
Add-AzureStackVaaSAccount -Credential $VaaSAccountCreds -ApplicationId $VaaSApplicationId -ApplicationUri $VaaSApplicationUri -TenantId $VaaSAccountTenantId -TenantServiceBaseUri $VaaSBaseServiceUri -TenantServiceResourceId $VaaSServiceResourceId -ErrorAction Stop
}
}
StartVaaSOnPremAgent
$vaasSolution = CreateVaaSSolution
$vaasTestPass = CreateVaaSTestPass
$vaasGroupManifest = ConfigureGroupManifestFile
try
{
DisplayTitle -Title "VaaS test pass launch"
Write-Host "Launching test pass $VaaSTestPassName on Solution $VaaSSolutionName against Agent $VaaSOnPremAgentName"
$testLaunchManifests = New-AzureStackVaaSTestGroupLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -AgentName $VaaSOnPremAgentName -TestInventoryFilePath $vaasGroupManifest
}
catch
{
Write-Warning "Unable to launch tests. Attempting retry in 30 seconds ..."
Start-Sleep -s 30 | Out-Null
$testLaunchManifests = New-AzureStackVaaSTestGroupLaunch -SolutionName $VaaSSolutionName -ProjectName $VaaSTestPassName -ProjectType $ProjectType -AgentName $VaaSOnPremAgentName -TestInventoryFilePath $vaasGroupManifest -ErrorAction Stop
}
if(!$testLaunchManifests)
{
throw [System.AggregateException] "No test manifest data was returned after launching test group ..."
}
Write-Host "You can also monitor your test pass using VaaS Portal at:" -ForegroundColor Green -BackgroundColor Black
Write-Host "$VaaSPortalUri/$VaaSAccountTenantId/en-US/TestPass/Manage/Summary?solutionName=$VaaSSolutionName&projectName=$VaaSTestPassName" -ForegroundColor Green -BackgroundColor Black
if($DoNotWait)
{
return
}
TestMonitor -testLaunchManifests $testLaunchManifests
GenerateVaaSReport
}
Set-PSDebug -Strict
$windowTitle = $host.ui.RawUI.WindowTitle
if($LogFilePath -eq "")
{
$script:LogFilePath = "$PSScriptRoot\Logs"
Write-Host "Defaulting to VaaS log file path $LogFilePath, as a log file path was not provided ..."
}
CreateVaaSLogDirectory
$logFileName = "$LogFilePath\LaunchVaaSTests_$(Get-Date -Format yyyyMMdd-HHmmss).log"
Start-Transcript -Path $logFileName -IncludeInvocationHeader
Write-Output "`r`n"
DisplaySessionInfo
try
{
Write-Output "PsBoundParameters: "
foreach($keyValue in $PsBoundParameters.GetEnumerator())
{
Write-Output "$($keyValue.Key)=$($keyValue.Value)"
}
Write-Output ""
InitializeLaunchData
ValidateAndResolveParameters
InstallVaaSOnPremAgent
InstallVaaSPreReq
$host.ui.RawUI.WindowTitle = "VaaS"
CreateVaaSDirectory
InstallVaaSPSModules
Import-Module AzureStackVaaS -Force -ErrorAction Stop
Write-Host "`r`nAzureStackVaaS module version loaded: $((Get-Module -Name AzureStackVaaS).Version.ToString())`r`n"
Import-Module 'AzureRM'
Disable-AzureRmDataCollection -WarningAction Ignore
Main
}
catch
{
$_ | Format-List * -Force | Out-Default;
$_.InvocationInfo | Format-List * | Out-Default
$Exception = $_.Exception
for ($i = 0; $Exception; $i++, ($Exception = $_.InnerException))
{
"$i" * 80
$Exception | Format-List * -Force | Out-Default
}
$launcherData.testResult = 1
}
finally
{
Remove-Module AzureStackVaaS -Force -ErrorAction Ignore
ShutdownVaaSOnPremAgent
RemoveVaaSOnPremAgent -agentName $VaaSOnPremAgentName
Stop-Transcript
$host.ui.RawUI.WindowTitle = $windowTitle
Pop-Location
exit $launcherData.testResult
}
# SIG # Begin signature block
# MIIdnQYJKoZIhvcNAQcCoIIdjjCCHYoCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU5omKahA35kNLC51omllsla/4
# jNegghhlMIIEwzCCA6ugAwIBAgITMwAAAMhHIp2jDcrAWAAAAAAAyDANBgkqhkiG
# 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw
# HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTYwOTA3MTc1ODU0
# WhcNMTgwOTA3MTc1ODU0WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp
# bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw
# b3JhdGlvbjENMAsGA1UECxMETU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TK5BNZ+zP0RA91cyckridd
# 54lVrg6lkipMVxgy+VyNMYOpsXqdUVXyx8lTC4eXrAR7iDhuTvQgFgjf3XCgWboS
# ekCncNGUOzP2iinuiRLkzebV7eFKGuOUiKrsseog4zQqaPRgekvOKDYiHklyXJH0
# rpycDU5js2XG8J9KrR5NuDnv/f9fGDuYqItqT+QOULTLVrYxun+1kVXgnpUnbRo2
# CQ==
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/xSystemSecurity/1.2.0.0/Tests/Unit/MSFT_xFileSystemAccessRule.tests.ps1
|
MSFT_xFileSystemAccessRule.tests.ps1
|
$script:DSCModuleName = 'xSystemSecurity'
$script:DSCResourceName = 'MSFT_xFileSystemAccessRule'
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}
Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:DSCModuleName `
-DSCResourceName $script:DSCResourceName `
-TestType Unit
Import-Module (Join-Path $script:moduleRoot "\DSCResources\$script:DSCResourceName\$script:DSCResourceName.psm1") -Force
try
{
Describe "xFileSystemAccessRule" {
InModuleScope -ModuleName $script:DSCResourceName {
Mock Set-Acl {}
Mock Test-Path { return $true }
Context "No permissions exist for a user, but should" {
$testParams = @{
Path = "$($env:SystemDrive)\TestFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Rights = @("Read","Synchronize")
}
Mock Get-Acl {
return @{
Access = @()
} | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
| Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
}
It "should return absent from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Absent"
}
It "should return false from the test method" {
Test-TargetResource @testParams | Should Be $false
}
It "should add the permission in the set method" {
Set-TargetResource @testParams
Assert-MockCalled -CommandName Set-Acl
}
}
Context "A permission exists and should, but the rights are incorrect" {
$testParams = @{
Path = "$($env:SystemDrive)\TestFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Rights = @("Read","Synchronize")
}
Mock Get-Acl {
return @{
Access = @(
@{
IdentityReference = $testParams.Identity
FileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl
}
)
} | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
| Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
}
It "should return present from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Present"
}
It "should return false from the test method" {
Test-TargetResource @testParams | Should Be $false
}
It "should add the permission in the set method" {
Set-TargetResource @testParams
Assert-MockCalled -CommandName Set-Acl
}
}
Context "A permission exists and should, including correct rights" {
$testParams = @{
Path = "$($env:SystemDrive)\TestFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Rights = @("Read","Synchronize")
}
Mock Get-Acl {
return @{
Access = @(
@{
IdentityReference = $testParams.Identity
FileSystemRights = [System.Security.AccessControl.FileSystemRights]$testParams.Rights
}
)
} | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
| Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
}
It "should return present from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Present"
}
It "should return true from the test method" {
Test-TargetResource @testParams | Should Be $true
}
}
Context "A permission exists that shouldn't" {
$testParams = @{
Path = "$($env:SystemDrive)\TestFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Ensure = "Absent"
}
Mock Get-Acl {
return @{
Access = @(
@{
IdentityReference = $testParams.Identity
FileSystemRights = [System.Security.AccessControl.FileSystemRights]::FullControl
}
)
} | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
| Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
}
It "should return present from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Present"
}
It "should return false from the test method" {
Test-TargetResource @testParams | Should Be $false
}
It "should add the permission in the set method" {
Set-TargetResource @testParams
Assert-MockCalled -CommandName Set-Acl
}
}
Context "A permission doesn't exist and shouldn't" {
$testParams = @{
Path = "$($env:SystemDrive)\TestFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Ensure = "Absent"
}
Mock Get-Acl {
return @{
Access = @()
} | Add-Member -MemberType ScriptMethod -Name "SetAccessRule" -Value {} -PassThru `
| Add-Member -MemberType ScriptMethod -Name "RemoveAccessRule" -Value {} -PassThru
}
It "should return absent from the get method" {
(Get-TargetResource @testParams).Ensure | Should Be "Absent"
}
It "should return true from the test method" {
Test-TargetResource @testParams | Should Be $true
}
}
Mock Test-Path { return $false }
Context "A path doesn't exist" {
$testParams = @{
Path = "$($env:SystemDrive)\TestFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Rights = @("Read","Synchronize")
}
It "should throw from the get method" {
{ Get-TargetResource @testParams } | Should Throw
}
It "should throw from the test method" {
{ Test-TargetResource @testParams } | Should Throw
}
It "should throw from the set method" {
{ Set-TargetResource @testParams } | Should Throw
}
}
}
}
}
finally
{
Restore-TestEnvironment -TestEnvironment $TestEnvironment
}
|
PowerShellCorpus/PowerShellGallery/xSystemSecurity/1.2.0.0/Tests/Integration/MSFT_xFileSystemAccessRule.integration.tests.ps1
|
MSFT_xFileSystemAccessRule.integration.tests.ps1
|
$script:DSCModuleName = 'xSystemSecurity'
$script:DSCResourceName = 'MSFT_xFileSystemAccessRule'
[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or `
(-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) )
{
& git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\'))
}
Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force
$TestEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:DSCModuleName `
-DSCResourceName $script:DSCResourceName `
-TestType Integration
try
{
$ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).config.ps1"
. $ConfigFile
New-Item -Path "$env:SystemDrive\SampleFolder" -ItemType Directory
Describe "$($script:DSCResourceName)_Integration" {
It 'New rule - Should compile without throwing' {
{
Invoke-Expression -Command "$($script:DSCResourceName)_NewRule -OutputPath `$TestEnvironment.WorkingFolder"
} | Should not throw
}
It "New rule - Should apply without throwing" {
{
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder `
-ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'New rule - Should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
It 'New rule - Should have set the resource and all the parameters should match' {
Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true
}
It 'Update rule - Should compile without throwing' {
{
Invoke-Expression -Command "$($script:DSCResourceName)_UpdateRule -OutputPath `$TestEnvironment.WorkingFolder"
} | Should not throw
}
It "Update rule - Should apply without throwing" {
{
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder `
-ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'Update rule - Should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
It 'Remove rule - Should have set the resource and all the parameters should match' {
Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true
}
It 'Remove rule - Should compile without throwing' {
{
Invoke-Expression -Command "$($script:DSCResourceName)_RemoveRule -OutputPath `$TestEnvironment.WorkingFolder"
} | Should not throw
}
It "Remove rule - Should apply without throwing" {
{
Start-DscConfiguration -Path $TestEnvironment.WorkingFolder `
-ComputerName localhost -Wait -Verbose -Force
} | Should not throw
}
It 'Remove rule - Should be able to call Get-DscConfiguration without throwing' {
{ Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not throw
}
It 'New rule - Should have set the resource and all the parameters should match' {
Test-DscConfiguration -Path $TestEnvironment.WorkingFolder | Should Be $true
}
Remove-Item -Path "$env:SystemDrive\SampleFolder" -Recurse -Force -Confirm:$false
}
}
finally
{
Restore-TestEnvironment -TestEnvironment $TestEnvironment
}
|
PowerShellCorpus/PowerShellGallery/xSystemSecurity/1.2.0.0/Tests/Integration/MSFT_xFileSystemAccessRule.config.ps1
|
MSFT_xFileSystemAccessRule.config.ps1
|
configuration MSFT_xFileSystemAccessRule_NewRule {
Import-DscResource -ModuleName 'xSystemSecurity'
node localhost {
xFileSystemAccessRule Integration_Test {
Path = "$($env:SystemDrive)\SampleFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Rights = @("Read","Synchronize")
}
}
}
configuration MSFT_xFileSystemAccessRule_UpdateRule {
Import-DscResource -ModuleName 'xSystemSecurity'
node localhost {
xFileSystemAccessRule Integration_Test {
Path = "$($env:SystemDrive)\SampleFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Rights = @("FullControl")
}
}
}
configuration MSFT_xFileSystemAccessRule_RemoveRule {
Import-DscResource -ModuleName 'xSystemSecurity'
node localhost {
xFileSystemAccessRule Integration_Test {
Path = "$($env:SystemDrive)\SampleFolder"
Identity = "NT AUTHORITY\NETWORK SERVICE"
Ensure = "Absent"
}
}
}
|
PowerShellCorpus/PowerShellGallery/OledbSql/1.0.3/tests/OledbSql.Tests.ps1
|
OledbSql.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module (Join-Path $here '..\OledbSql.psd1')
# Find the latest version of the ACE data provider, for the connection string.
$ProviderVersion = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Foreach {
if ($_.SOURCES_NAME -match '^Microsoft\.ACE\.OLEDB\.([\d\.]+)$') {
[decimal]$Matches[1]
}
} | Sort | Select -Last 1
$connectionString = 'Provider=Microsoft.ACE.OLEDB.{0};Data Source={1};Extended Properties="Text;HDR=Yes;FMT=Delimited;"' -f $ProviderVersion, $here
Describe 'New-OledbConnection' {
It 'Create and open an OLEDB Connection.' {
$connection = New-OledbConnection $connectionString
$connection.Open()
$connection.State | Should Be 'Open'
$connection.Close()
}
}
Describe 'Invoke-OledbSql' {
Context 'Create an OLEDB Connection, then read from a CSV file.' {
$result = Invoke-OledbSql -Connection $connectionString -Sql 'select * from [test#csv]' | Select -First 1
It 'Return the value of the first column.' {
$result.'test#csv.test' | Should Be 'Success1'
}
It 'Return the value of the second column, which has the same name as the first and was de-duplicated.' {
$result.'test#csv.test1' | Should Be 'Success2'
}
}
}
|
PowerShellCorpus/PowerShellGallery/Posh-Sysmon/0.7.5/Filters.ps1
|
Filters.ps1
|
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonImageLoadFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonImageLoadFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ProcessGuid', 'ProcessId', 'Image',
'ImageLoaded', 'Hashes', 'Signed',
'Signature')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process
{
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'ImageLoad'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch($psCmdlet.ParameterSetName)
{
'Path'
{
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath'
{
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End { }
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonDriverLoadFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonDriverLoadFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ImageLoaded',
'Hashes', 'Signed', 'Signature')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'DriverLoad'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch($psCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonNetworkConnectFilter
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonNetworkConnectFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ProcessGuid', 'ProcessId', 'Image',
'User', 'Protocol', 'Initiated', 'SourceIsIpv6',
'SourceIp', 'SourceHostname', 'SourcePort',
'SourcePortName', 'DestinationIsIpv6',
'DestinationIp', 'DestinationHostname',
'DestinationPort', 'DestinationPortName')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'NetworkConnect'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch($psCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonFileCreateFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonFileCreateFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ProcessGuid', 'ProcessId', 'Image',
'TargetFilename', 'CreationUtcTime',
'PreviousCreationUtcTime')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
switch($psCmdlet.ParameterSetName) {
'Path' {
New-RuleFilter -Path $Path -EventType FileCreateTime -Condition $Condition -EventField $FieldString -Value $Value -OnMatch $OnMatch
}
'LiteralPath' {
New-RuleFilter -LiteralPath $LiteralPath -EventType FileCreateTime -Condition $Condition -EventField $FieldString -Value $Value -OnMatch $OnMatch
}
}
}
End {}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonProcessCreateFilter
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonProcessCreateFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ProcessGuid', 'ProcessId', 'Image',
'CommandLine', 'User', 'LogonGuid', 'LogonId',
'TerminalSessionId', 'IntegrityLevel',
'Hashes', 'ParentProcessGuid', 'ParentProcessId',
'ParentImage', 'ParentCommandLine')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'ProcessCreate'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch($psCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End { }
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonProcessTerminateFilter
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonProcessTerminateFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ProcessGuid', 'ProcessId')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process
{
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'ProcessTerminate'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch($psCmdlet.ParameterSetName)
{
'Path'
{
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath'
{
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonCreateRemoteThreadFilter
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonCreateRemoteThreadFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('SourceImage', 'TargetImage')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin { }
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'CreateRemoteThread'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch($psCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
<#
.SYNOPSIS
Create a new filter for the logging of when a running process opens another.
.DESCRIPTION
Create a new filter for the logging of when a running process opens another.
.EXAMPLE
C:\PS> New-SysmonProcessAccessFilter -Path .\testver31.xml -OnMatch include -Condition Contains -EventField TargetImage lsass.exe
Log any process trying to open lsass.exe.
#>
function New-SysmonProcessAccessFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonProcessAccessFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'SourceProcessGUID',
'SourceProcessId', 'SourceThreadId', 'SourceImage',
'TargetProcessGUID', 'TargetProcessId', 'TargetImage',
'GrantedAccess','CallTrace')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'ProcessAccess'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch ($PSCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
<#
.SYNOPSIS
Create a new filter for the logging of file raw access read actions.
.DESCRIPTION
Create a new filter for the logging of file raw access read actions.
.EXAMPLE
C:\PS> New-SysmonRawAccessReadFilter -Path .\testver31.xml -OnMatch include -Condition Contains -EventField Image NTDS.dit
Log any raw access read of the file NTDS.dit.
#>
function New-SysmonRawAccessReadFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonRawAccessReadFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('UtcTime', 'ProcessGuid', 'ProcessId',
'Image', 'Device')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'RawAccessRead'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch ($PSCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
<#
.SYNOPSIS
Create a new filter for the logging file creation.
.DESCRIPTION
Create a new filter for the logging file creation.
.EXAMPLE
#>
function New-SysmonFileCreateFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonFileCreateFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('TargetFilename', 'ProcessGuid', 'ProcessId',
'Image')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'FileCreate'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch ($PSCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
<#
.SYNOPSIS
Create a new filter for the logging of the saving of data on a file stream.
.DESCRIPTION
Create a new filter for the logging of the saving of data on a file stream.
#>
function New-SysmonFileCreateStreamHashFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonFileCreateStreamHashFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('TargetFilename', 'ProcessGuid', 'ProcessId',
'Image')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'FileCreateStreamHash'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch ($PSCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
<#
.SYNOPSIS
Create a new filter for the actions against the registry.
.DESCRIPTION
Create a new filter for actions against the registry. Supports filtering
by aby of the following event types:
* CreateKey
* DeleteKey
* RenameKey
* CreateValue
* DeleteValue
* RenameValue
* SetValue
Hives in TargetObject are referenced as:
* \REGISTRY\MACHINE\HARDWARE
* \REGISTRY\USER\Security ID number
* \REGISTRY\MACHINE\SECURITY
* \REGISTRY\USER\.DEFAULT
* \REGISTRY\MACHINE\SYSTEM
* \REGISTRY\MACHINE\SOFTWARE
* \REGISTRY\MACHINE\SAM
.EXAMPLE
C:\PS> New-SysmonRegistryFilter -Path .\32config.xml -OnMatch include -Condition Contains -EventField TargetObject 'RunOnce'
Capture persistance attemp by creating a registry entry in the RunOnce keys.
#>
function New-SysmonRegistryFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonRegistryFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({ Test-Path -Path $_ })]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('TargetObject', 'ProcessGuid', 'ProcessId',
'Image', 'EventType')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {
# Event types used to validate right type and string case
$EventTypeMap = @{
CreateKey = 'CreateKey'
DeleteKey = 'DeleteKey'
RenameKey = 'RenameKey'
CreateValue = 'CreateValue'
DeleteValue = 'DeleteValue'
RenameValue = 'RenameValue'
SetValue = 'SetValue'
}
$Etypes = $EventTypeMap.Keys
}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
if ($EventField -in 'EventType') {
if ($Value -in $Etypes) {
$Value = $EventTypeMap[$Value]
} else {
Write-Error -Message "Not a supported EventType. Supported Event types $($Etypes -join ', ')"
return
}
}
$cmdoptions = @{
'EventType' = 'RegistryEvent'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch ($PSCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
<#
.SYNOPSIS
Create a new filter for when a Named Pipe is created or connected.
.DESCRIPTION
Create a new filter for when a Named Pipe is created or connected.
Useful for watching malware inter process communication.
#>
function New-SysmonPipeFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonPipeFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('Pipe', 'ProcessGuid', 'ProcessId',
'Image')]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string[]]
$Value
)
Begin {}
Process {
$FieldString = $MyInvocation.MyCommand.Module.PrivateData[$EventField]
$cmdoptions = @{
'EventType' = 'PipeEvent'
'Condition' = $Condition
'EventField' = $FieldString
'Value' = $Value
'OnMatch' = $OnMatch
}
switch ($PSCmdlet.ParameterSetName) {
'Path' {
$cmdOptions.Add('Path',$Path)
New-RuleFilter @cmdOptions
}
'LiteralPath' {
$cmdOptions.Add('LiteralPath',$LiteralPath)
New-RuleFilter @cmdOptions
}
}
}
End {}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function Remove-SysmonRuleFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Remove-SysmonRuleFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type to update.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad',
'CreateRemoteThread', 'RawAccessRead', 'ProcessAccess',
'FileCreateStreamHash', 'RegistryEvent', 'FileCreate',
'FileCreateStreamHash', 'RegistryEvent', 'FileCreate',
'PipeEvent')]
[string]
$EventType,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch,
# Condition for filtering against and event field.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[ValidateSet('Is', 'IsNot', 'Contains', 'Excludes', 'Image',
'BeginWith', 'EndWith', 'LessThan', 'MoreThan')]
[string]
$Condition,
# Event field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[string]
$EventField,
# Value of Event Field to filter on.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=5)]
[string[]]
$Value
)
Begin{}
Process {
$EvtType = $null
# Check if the file is a valid XML file and if not raise and error.
try {
switch($psCmdlet.ParameterSetName) {
'Path' {
[xml]$Config = Get-Content -Path $Path
$FileLocation = (Resolve-Path -Path $Path).Path
}
'LiteralPath' {
[xml]$Config = Get-Content -LiteralPath $LiteralPath
$FileLocation = (Resolve-Path -LiteralPath $LiteralPath).Path
}
}
}
catch [Management.Automation.PSInvalidCastException] {
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null) {
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
$Rules = $Config.SelectSingleNode('//Sysmon/EventFiltering')
# Select the proper condition string.
switch ($Condition) {
'Is' {$ConditionString = 'is'}
'IsNot' {$ConditionString = 'is not'}
'Contains' {$ConditionString = 'contains'}
'Excludes' {$ConditionString = 'excludes'}
'Image' {$ConditionString = 'image'}
'BeginWith' {$ConditionString = 'begin with'}
'EndWith' {$ConditionString = 'end with'}
'LessThan' {$ConditionString = 'less than'}
'MoreThan' {$ConditionString = 'more than'}
Default {$ConditionString = 'is'}
}
# Check if the event type exists if not create it.
if ($Rules -eq '') {
Write-Error -Message 'Rule element does not exist. This appears to not be a valid config file'
return
} else {
$EvtType = $MyInvocation.MyCommand.Module.PrivateData[$EventType]
$EventRule = $Rules.SelectNodes("//EventFiltering/$($EvtType)")
}
if($EventRule -eq $null) {
Write-Warning -Message "No rule for $($EvtType) was found."
return
}
if($EventRule -eq $null) {
Write-Error -Message "No rule for $($EvtType) was found."
return
} else {
if ($EventRule.count -eq $null -or $EventRule.Count -eq 1) {
if ($EventRule.onmatch -eq $OnMatch) {
$Filters = $EventRule.SelectNodes('*')
if ($Filters.count -gt 0) {
foreach($val in $Value) {
foreach($Filter in $Filters) {
if ($Filter.Name -eq $EventField) {
if (($Filter.condition -eq $null) -and ($Condition -eq 'is') -and ($Filter.'#text' -eq $val)) {
[void]$Filter.ParentNode.RemoveChild($Filter)
Write-Verbose -Message "Filter for field $($EventField) with condition $($Condition) and value of $($val) removed."
} elseif (($Filter.condition -eq $Condition) -and ($Filter.'#text' -eq $val)) {
[void]$Filter.ParentNode.RemoveChild($Filter)
Write-Verbose -Message "Filter for field $($EventField) with condition $($Condition) and value of $($val) removed."
}
}
}
}
Get-RuleWithFilter($EventRule)
}
}
} else {
Write-Verbose -Message 'Mutiple nodes.'
foreach ($rule in $EventRule) {
if ($rule.onmatch -eq $OnMatch) {
$Filters = $rule.SelectNodes('*')
if ($Filters.count -gt 0) {
foreach($val in $Value) {
foreach($Filter in $Filters) {
if ($Filter.Name -eq $EventField) {
if (($Filter.condition -eq $null) -and ($Condition -eq 'is') -and ($Filter.'#text' -eq $val)) {
[void]$Filter.ParentNode.RemoveChild($Filter)
Write-Verbose -Message "Filter for field $($EventField) with condition $($Condition) and value of $($val) removed."
} elseif (($Filter.condition -eq $Condition) -and ($Filter.'#text' -eq $val)) {
[void]$Filter.ParentNode.RemoveChild($Filter)
Write-Verbose -Message "Filter for field $($EventField) with condition $($Condition) and value of $($val) removed."
}
}
}
}
Get-RuleWithFilter($rule)
}
}
}
}
}
$config.Save($FileLocation)
}
End{}
}
<#
.SYNOPSIS
Get the configured filters for a specified Event Type Rule in a Sysmon configuration file.
.DESCRIPTION
Get the configured filters for a specified Event Type Rule in a Sysmon configuration file.
.EXAMPLE
C:\PS> Get-SysmonRuleFilter -Path C:\sysmon.xml -EventType ProcessCreate
Get the filter under the ProcessCreate Rule.
#>
function Get-SysmonRuleFilter {
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Get-SysmonRuleFilter.md')]
Param (
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type rule to get filter for.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=1)]
[ValidateSet('NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad',
'CreateRemoteThread','RawAccessRead', 'ProcessAccess',
'FileCreateStreamHash', 'RegistryEvent', 'FileCreate',
'PipeEvent')]
[string]
$EventType,
# Event type on match action.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('include', 'exclude')]
[string]
$OnMatch
)
Begin{}
Process {
$EvtType = $null
# Check if the file is a valid XML file and if not raise and error.
try {
switch($psCmdlet.ParameterSetName){
'Path'{
[xml]$Config = Get-Content -Path $Path
$FileLocation = (Resolve-Path -Path $Path).Path
}
'LiteralPath' {
[xml]$Config = Get-Content -LiteralPath $LiteralPath
$FileLocation = (Resolve-Path -LiteralPath $LiteralPath).Path
}
}
}
catch [System.Management.Automation.PSInvalidCastException] {
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null){
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
$Rules = $Config.SelectSingleNode('//Sysmon/EventFiltering')
if ($Rules -eq '') {
Write-Error -Message 'Rule element does not exist. This appears to not be a valid config file'
return
} else {
$EvtType = $MyInvocation.MyCommand.Module.PrivateData[$EventType]
$EventRule = $Rules.SelectNodes("//EventFiltering/$($EvtType)")
}
if($EventRule -eq $null) {
Write-Error -Message "No rule for $($EvtType) was found."
return
} else {
if ($EventRule.count -eq $null -or $EventRule.Count -eq 1) {
Write-Verbose -Message 'Single Node'
if ($EventRule.onmatch -eq $OnMatch) {
$Filters = $EventRule.SelectNodes('*')
if ($Filters.ChildNodes.Count -gt 0) {
foreach($Filter in $Filters) {
$FilterObjProps = @{}
$FilterObjProps['EventField'] = $Filter.Name
$FilterObjProps['Condition'] = &{if($Filter.condition -eq $null){'is'}else{$Filter.condition}}
$FilterObjProps['Value'] = $Filter.'#text'
$FilterObjProps['EventType'] = $EvtType
$FilterObjProps['OnMatch'] = $OnMatch
$FilterObj = [pscustomobject]$FilterObjProps
$FilterObj.pstypenames.insert(0,'Sysmon.Rule.Filter')
$FilterObj
}
}
}
}
else
{
Write-Verbose -Message 'Mutiple nodes.'
foreach ($rule in $EventRule)
{
if ($rule.onmatch -eq $OnMatch)
{
$Filters = $rule.SelectNodes('*')
if ($Filters.ChildNodes.Count -gt 0)
{
foreach($Filter in $Filters)
{
$FilterObjProps = @{}
$FilterObjProps['EventField'] = $Filter.Name
$FilterObjProps['Condition'] = &{if($Filter.condition -eq $null){'is'}else{$Filter.condition}}
$FilterObjProps['Value'] = $Filter.'#text'
$FilterObjProps['EventType'] = $EvtType
$FilterObjProps['OnMatch'] = $OnMatch
$FilterObj = [pscustomobject]$FilterObjProps
$FilterObj.pstypenames.insert(0,'Sysmon.Rule.Filter')
$FilterObj
}
}
}
}
}
}
}
End{}
}
<#
.Synopsis
Searches for specified SysMon Events and retunrs the Event Data as a custom object.
.DESCRIPTION
Searches for specified SysMon Events and retunrs the Event Data as a custom object.
.EXAMPLE
Get-SysMonEventData -EventId 1 -MaxEvents 10 -EndTime (Get-Date) -StartTime (Get-Date).AddDays(-1)
All process creation events in the last 24hr
.EXAMPLE
Get-SysMonEventData -EventId 3 -MaxEvents 20 -Path .\export.evtx
last 20 network connection events from a exported SysMon log.
#>
function Get-SysmonEventData {
[CmdletBinding(DefaultParameterSetName='ID',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Get-SysmonEventData.md')]
Param (
# Sysmon Event ID of records to show
[Parameter(Mandatory=$true,
ParameterSetName='ID',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateSet(1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,255)]
[Int32[]]
$EventId,
# EventType that a Rule can be written against.
[Parameter(Mandatory=$false,
ParameterSetName='Type',
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string[]]
[ValidateSet('NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad',
'CreateRemoteThread', 'RawAccessRead', 'ProcessAccess', 'Error',
'FileCreateStreamHash', 'RegistryValueSet', 'RegistryRename',
'RegistryAddOrDelete', 'FileCreate','ConfigChange','PipeCreated',
'PipeConnected')]
$EventType,
# Specifies the maximum number of events that Get-WinEvent returns. Enter an integer. The default is to return all the events in the logs or files.
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[int]
$MaxEvents,
# Specifies a path to one or more exported SysMon events in evtx format.
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
HelpMessage='Path to one or more locations.')]
[Alias('PSPath')]
[ValidateNotNullOrEmpty()]
[string[]]
$Path,
# Start Date to get all event going forward.
[Parameter(Mandatory=$false)]
[datetime]
$StartTime,
# End data for searching events.
[Parameter(Mandatory=$false)]
[datetime]
$EndTime
)
Begin
{
$EventTypeMap = @{
ProcessCreate = 1
FileCreateTime = 2
NetworkConnect = 3
ProcessTerminate = 5
DriverLoad = 6
ImageLoad = 7
CreateRemoteThread = 8
RawAccessRead = 9
ProcessAccess = 10
FileCreate = 11
RegistryAddOrDelete = 12
RegistryValueSet = 13
RegistryRename = 14
FileCreateStreamHash = 15
ConfigChange = 16
PipeCreated = 17
PipeConnected = 18
Error = 255
}
$EventIdtoType = @{
'1' = 'ProcessCreate'
'2' = 'FileCreateTime'
'3' = 'NetworkConnect'
'5' = 'ProcessTerminate'
'6' = 'DriverLoad'
'7' = 'ImageLoad'
'8' = 'CreateRemoteThread'
'9' = 'RawAccessRead'
'10' = 'ProcessAccess'
'11' = 'FileCreate'
'12' = 'RegistryAddOrDelete'
'13' = 'RegistryValueSet'
'14' = 'RegistryRename'
'15' = 'FileCreateStreamHash'
'16' = 'ConfigChange'
'17' = 'PipeCreated'
'18' = 'PipeConnected'
'255' = 'Error'
}
}
Process
{
# Hash for filtering
$HashFilter = @{LogName='Microsoft-Windows-Sysmon/Operational'}
# Hash for command paramteters
$ParamHash = @{}
if ($MaxEvents -gt 0)
{
$ParamHash.Add('MaxEvents', $MaxEvents)
}
if ($Path -gt 0)
{
$ParamHash.Add('Path', $Path)
}
switch ($PSCmdlet.ParameterSetName) {
'ID' { $HashFilter.Add('Id', $EventId) }
'Type' {
$EventIds = @()
foreach ($etype in $EventType)
{
$EventIds += $EventTypeMap[$etype]
}
$HashFilter.Add('Id', $EventIds)
}
}
if ($StartTime)
{
$HashFilter.Add('StartTime', $StartTime)
}
if ($EndTime)
{
$HashFilter.Add('EndTime', $EndTime)
}
$ParamHash.Add('FilterHashTable',$HashFilter)
Get-WinEvent @ParamHash | ForEach-Object {
[xml]$evtxml = $_.toxml()
$ProcInfo = [ordered]@{}
$ProcInfo['EventId'] = $evtxml.Event.System.EventID
$ProcInfo['EventType'] = $EventIdtoType[$evtxml.Event.System.EventID]
$ProcInfo['Computer'] = $evtxml.Event.System.Computer
$evtxml.Event.EventData.Data | ForEach-Object {
$ProcInfo[$_.name] = $_.'#text'
}
New-Object psobject -Property $ProcInfo
}
}
End {}
}
|
PowerShellCorpus/PowerShellGallery/Posh-Sysmon/0.7.5/Config.ps1
|
Config.ps1
|
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function New-SysmonConfiguration
{
[CmdletBinding(HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/New-SysmonConfiguration.md')]
Param
(
# Path to write XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[String]
$Path,
# Specify one or more hash algorithms used for image identification
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('ALL', 'MD5', 'SHA1', 'SHA256', 'IMPHASH')]
[string[]]
$HashingAlgorithm,
# Log Network Connections
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[Switch]
$NetworkConnect,
# Log process loading of modules.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=3)]
[Switch]
$DriverLoad,
# Log process loading of modules.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=4)]
[Switch]
$ImageLoad,
# Log create remote thread actions.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=5)]
[Switch]
$CreateRemoteThread,
# Log file creation time modifications.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=6)]
[Switch]
$FileCreateTime,
# Log process creation.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=7)]
[Switch]
$ProcessCreate,
# Log process termination.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=8)]
[Switch]
$ProcessTerminate,
# Log when a running process opens another process.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=9)]
[Switch]
$ProcessAccess,
# Log raw access reads of files.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=10)]
[Switch]
$RawAccessRead,
# Check for signature certificate revocation.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=11 )]
[Switch]
$CheckRevocation,
# Log Registry events.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=12 )]
[Switch]
$RegistryEvent,
# Log File Creation events.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=13 )]
[Switch]
$FileCreate,
# Log File Stream creations events.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=14 )]
[Switch]
$FileCreateStreamHash,
# Log NamedPipes connection and creations events.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true,
Position=15 )]
[Switch]
$PipeEvent,
# Comment for purpose of the configuration file.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true)]
[String]
$Comment,
# Schema Vesion for the configuration file, default is 3.3.
[Parameter(Mandatory=$False,
ValueFromPipelineByPropertyName=$true)]
[ValidateSet('2.0','3.0', '3.1', '3.2','3.3')]
[String]
$SchemaVersion = '3.3'
)
Begin{}
Process
{
if ($HashingAlgorithm -contains 'ALL')
{
$Hash = '*'
}
else
{
$Hash = $HashingAlgorithm -join ','
}
$Config = ($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path))
# get an XMLTextWriter to create the XML
$XmlWriter = New-Object System.XMl.XmlTextWriter($Config,$Null)
# choose a pretty formatting:
$xmlWriter.Formatting = 'Indented'
$xmlWriter.Indentation = 1
# write the header
if ($Comment)
{
$xmlWriter.WriteComment($Comment)
}
$xmlWriter.WriteStartElement('Sysmon')
$XmlWriter.WriteAttributeString('schemaversion', $SchemaVersion)
Write-Verbose -Message "Enabling hashing algorithms : $($Hash)"
$xmlWriter.WriteElementString('HashAlgorithms',$Hash)
# Enable checking revocation.
if ($CheckRevocation)
{
if ($SchemaVersion -in @('3.1','3.2','3.3'))
{
Write-Verbose -message 'Enabling CheckRevocation.'
$xmlWriter.WriteElementString('CheckRevocation','')
}
else
{
Write-Warning -Message 'CheckRevocation was not enabled because it is not supported in this SchemaVersion.'
}
}
# Create empty EventFiltering section.
$xmlWriter.WriteStartElement('EventFiltering')
if ($NetworkConnect)
{
Write-Verbose -Message 'Enabling network connection logging for all connections by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('NetworkConnect')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($DriverLoad)
{
Write-Verbose -Message 'Enabling logging all driver loading by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('DriverLoad ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($ImageLoad)
{
Write-Verbose -Message 'Enabling logging all image loading by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('ImageLoad ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($CreateRemoteThread)
{
Write-Verbose -Message 'Enabling logging all CreateRemoteThread API actions by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('CreateRemoteThread ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($ProcessCreate)
{
Write-Verbose -Message 'Enabling logging all process creation by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('ProcessCreate ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($ProcessTerminate)
{
Write-Verbose -Message 'Enabling logging all process termination by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('ProcessTerminate ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($FileCreateTime)
{
Write-Verbose -Message 'Enabling logging all process creation by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('FileCreateTime ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($ProcessAccess)
{
Write-Verbose -Message 'Enabling logging all process access by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('ProcessAccess ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
if ($RawAccessRead)
{
Write-Verbose -Message 'Enabling logging all process access by setting no filter and onmatch to exclude.'
$xmlWriter.WriteStartElement('RawAccessRead ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
# Log registry events.
if ($RegistryEvent)
{
if ($SchemaVersion -in @('3.2','3.3'))
{
Write-Verbose -message 'Enabling RegistryEvent.'
$xmlWriter.WriteStartElement('RegistryEvent ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
else
{
Write-Warning -Message 'RegistryEvent was not enabled because it is not supported in this SchemaVersion.'
}
}
# Log file create events.
if ($FileCreate)
{
if ($SchemaVersion -in @('3.2','3.3'))
{
Write-Verbose -message 'Enabling FileCreate.'
$xmlWriter.WriteStartElement('FileCreate ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
else
{
Write-Warning -Message 'FileCreate was not enabled because it is not supported in this SchemaVersion.'
}
}
# Log file create events.
if ($FileCreateStreamHash)
{
if ($SchemaVersion -in @('3.2','3.3'))
{
Write-Verbose -message 'Enabling FileCreateStreamHash.'
$xmlWriter.WriteStartElement('FileCreateStreamHash ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
else
{
Write-Warning -Message 'FileCreateStreamHash was not enabled because it is not supported in this SchemaVersion.'
}
}
# NamedPipes create and connect events.
if ($PipeEvent)
{
if ($SchemaVersion -in @('3.2','3.3'))
{
Write-Verbose -message 'Enabling PipeEvent.'
$xmlWriter.WriteStartElement('PipeEvent ')
$XmlWriter.WriteAttributeString('onmatch', 'exclude')
$xmlWriter.WriteFullEndElement()
}
else
{
Write-Warning -Message 'PipeEvent was not enabled because it is not supported in this SchemaVersion.'
}
}
# End Element of EventFiltering
$xmlWriter.WriteFullEndElement()
# Sysmon
$xmlWriter.WriteEndElement()
# finalize the document:
#$xmlWriter.WriteEndDocument()
$xmlWriter.Flush()
$xmlWriter.Close()
Write-Verbose -Message "Config file created as $($Config)"
write-verbose -Message "Configuration is for Sysmon $($sysmonVerMap[$SchemaVersion])"
}
End
{
}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function Get-SysmonHashingAlgorithm
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Get-SysmonHashingAlgorithm.md')]
Param
(
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[string]$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
[string]$LiteralPath
)
Begin{}
Process
{
# Check if the file is a valid XML file and if not raise and error.
try
{
switch($psCmdlet.ParameterSetName)
{
'Path' {[xml]$Config = Get-Content -Path $Path}
'LiteralPath' {[xml]$Config = Get-Content -LiteralPath $LiteralPath}
}
}
catch [System.Management.Automation.PSInvalidCastException]
{
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null)
{
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
if ($Config.Sysmon.schemaversion -notin $SysMonSupportedVersions)
{
Write-Error -Message 'This version of Sysmon Rule file is not supported.'
return
}
$ObjOptions = @{}
if ($Config.Sysmon.SelectSingleNode('//HashAlgorithms'))
{
$ObjOptions['Hashing'] = $config.Sysmon.HashAlgorithms
}
else
{
$ObjOptions['Hashing'] = ''
}
#$ObjOptions['Comment'] = $Config.'#comment'
$ConfigObj = [pscustomobject]$ObjOptions
$ConfigObj.pstypenames.insert(0,'Sysmon.HashingAlgorithm')
$ConfigObj
}
End{}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function Get-SysmonRule
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Get-SysmonRule.md')]
Param
(
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[string]$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
[string]$LiteralPath,
# Event type to parse rules for.
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('ALL', 'NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad', 'ProcessAccess',
'RawAccessRead','ProcessAccess', 'FileCreateStreamHash',
'RegistryEvent', 'FileCreate', 'PipeEvent')]
[string[]]
$EventType = @('ALL')
)
Begin{}
Process
{
# Check if the file is a valid XML file and if not raise and error.
try
{
switch($psCmdlet.ParameterSetName)
{
'Path' {[xml]$Config = Get-Content -Path $Path}
'LiteralPath' {[xml]$Config = Get-Content -LiteralPath $LiteralPath}
}
}
catch [System.Management.Automation.PSInvalidCastException]
{
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null)
{
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
if ($Config.Sysmon.schemaversion -notin $SysMonSupportedVersions)
{
Write-Error -Message 'This version of Sysmon Rule file is not supported.'
return
}
# Collect all individual rules if they exist.
$Rules = $Config.Sysmon.EventFiltering
if ($EventType -contains 'ALL')
{
$TypesToParse = @('NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad','CreateRemoteThread',
'ProcessAccess', 'RawAccessRead', 'FileCreateStreamHash',
'RegistryEvent', 'FileCreate', 'PipeEvent')
}
else
{
$TypesToParse = $EventType
}
foreach($Type in $TypesToParse)
{
$EvtType = $MyInvocation.MyCommand.Module.PrivateData[$Type]
$RuleData = $Rules.SelectNodes("//EventFiltering/$($EvtType)")
if($RuleData -ne $null)
{
Write-Verbose -Message "$($EvtType) Rule Found."
Get-RuleWithFilter($RuleData)
}
}
}
End{}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function Set-SysmonHashingAlgorithm
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Set-SysmonHashingAlgorithm.md')]
Param
(
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Specify one or more hash algorithms used for image identification
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('ALL', 'MD5', 'SHA1', 'SHA256', 'IMPHASH')]
[string[]]
$HashingAlgorithm
)
Begin{}
Process
{
# Check if the file is a valid XML file and if not raise and error.
try
{
switch($psCmdlet.ParameterSetName)
{
'Path'
{
[xml]$Config = Get-Content -Path $Path
$FileLocation = (Resolve-Path -Path $Path).Path
}
'LiteralPath'
{
[xml]$Config = Get-Content -LiteralPath $LiteralPath
$FileLocation = (Resolve-Path -LiteralPath $LiteralPath).Path
}
}
}
catch [System.Management.Automation.PSInvalidCastException]
{
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null)
{
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
if ($Config.Sysmon.schemaversion -notin $SysMonSupportedVersions)
{
Write-Error -Message 'This version of Sysmon Rule file is not supported.'
return
}
Write-Verbose -Message 'Updating Hashing option.'
if ($HashingAlgorithm -contains 'ALL')
{
$Hash = '*'
}
else
{
$Hash = $HashingAlgorithm -join ','
}
# Check if Hashing Alorithm node exists.
if($Config.SelectSingleNode('//Sysmon/HashAlgorithms') -ne $null)
{
$Config.Sysmon.HashAlgorithms = $Hash
}
else
{
$HashElement = $Config.CreateElement('HashAlgorithms')
[void]$Config.Sysmon.Configuration.AppendChild($HashElement)
$Config.Sysmon.Configuration.Hashing = $Hash
}
Write-Verbose -Message 'Hashing option has been updated.'
Write-Verbose -Message "Option have been set on $($FileLocation)"
$Config.Save($FileLocation)
}
End{}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function Set-SysmonRule
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Set-SysmonRule.md')]
Param
(
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type to update.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad', 'CreateRemoteThread',
'ProcessAccess', 'RawAccessRead', 'FileCreateStreamHash',
'RegistryEvent', 'FileCreate')]
[string[]]
$EventType,
# Action for event type rule and filters.
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Include', 'Exclude')]
[String]
$OnMatch = 'Exclude',
# Action to take for Schema 3.0 files.
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true)]
[ValidateSet('Modify', 'Add')]
[String]
$Action = 'Modify'
)
Begin{}
Process
{
# if no elemrnt create one either if it is schema 2.0 or 3.0.
# If one is present we modify that one if Schema 2.0 and if Schema 3.0 and action modify.
# If Schema 3.0 and action add we check if only is present and that it is not the same OnMatch
# as being specified if it is we do nothing if not we add.
# Check if the file is a valid XML file and if not raise and error.
try
{
switch($psCmdlet.ParameterSetName)
{
'Path'
{
[xml]$Config = Get-Content -Path $Path
$FileLocation = (Resolve-Path -Path $Path).Path
}
'LiteralPath'
{
[xml]$Config = Get-Content -LiteralPath $LiteralPath
$FileLocation = (Resolve-Path -LiteralPath $LiteralPath).Path
}
}
}
catch [Management.Automation.PSInvalidCastException]
{
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null)
{
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
if ($Config.Sysmon.schemaversion -notin $SysMonSupportedVersions)
{
Write-Error -Message 'This version of Sysmon Rule file is not supported.'
return
}
$Rules = $config.SelectSingleNode('//Sysmon/EventFiltering')
foreach($Type in $EventType)
{
$EvtType = $MyInvocation.MyCommand.Module.PrivateData[$Type]
$RuleData = $Rules.SelectSingleNode("//EventFiltering/$($EvtType)")
$elements = $Rules."$($EvtType)" | Select-Object -property onmatch -Unique
if($RuleData -ne $null)
{
if ($Rules."$($EvtType)".count -eq $null)
{
if (($Config.Sysmon.schemaversion -eq '2.0') -or ($Config.Sysmon.schemaversion -in @('3.0', '3.1', '3.2','3.3') -and $Action -eq 'Modify'))
{
Write-Verbose -Message "Setting as default action for $($EvtType) the rule on match of $($OnMatch)."
$RuleData.SetAttribute('onmatch',($OnMatch.ToLower()))
Write-Verbose -Message 'Action has been set.'
}
elseif ($Config.Sysmon.schemaversion -in @('3.0', '3.1', '3.2','3.3') -and $Action -eq 'Add')
{
if ($RuleData.onmatch -ne $OnMatch)
{
Write-Verbose -Message "Creating rule for event type with action of $($OnMatch)"
$TypeElement = $config.CreateElement($EvtType)
$TypeElement.SetAttribute('onmatch',($OnMatch.ToLower()))
$RuleData = $Rules.AppendChild($TypeElement)
Write-Verbose -Message 'Action has been set.'
}
else
{
Write-Verbose -Message 'A rule with the specified onmatch action already exists.'
}
}
}
elseif ($Config.Sysmon.schemaversion -in ('3.0', '3.1', '3.2','3.3') -and $elements.count -eq 2)
{
Write-Verbose -Message 'A rule with the specified onmatch action already exists.'
}
else
{
Write-Error -Message 'This XML file does not conform to the schema.'
return
}
}
else
{
Write-Verbose -Message "No rule for $($EvtType) was found."
Write-Verbose -Message "Creating rule for event type with action of $($OnMatch)"
$TypeElement = $config.CreateElement($EvtType)
$TypeElement.SetAttribute('onmatch',($OnMatch.ToLower()))
$RuleData = $Rules.AppendChild($TypeElement)
Write-Verbose -Message 'Action has been set.'
}
Get-RuleWithFilter($RuleData)
}
$config.Save($FileLocation)
}
End{}
}
# .ExternalHelp Posh-SysMon.psm1-Help.xml
function Remove-SysmonRule
{
[CmdletBinding(DefaultParameterSetName = 'Path',
HelpUri = 'https://github.com/darkoperator/Posh-Sysmon/blob/master/docs/Remove-SysmonRule.md')]
Param
(
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='Path',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
$Path,
# Path to XML config file.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
ParameterSetName='LiteralPath',
Position=0)]
[ValidateScript({Test-Path -Path $_})]
[Alias('PSPath')]
$LiteralPath,
# Event type to remove. It is case sensitive.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=1)]
[ValidateSet('NetworkConnect', 'ProcessCreate', 'FileCreateTime',
'ProcessTerminate', 'ImageLoad', 'DriverLoad', 'CreateRemoteThread',
'ProcessAccess', 'RawAccessRead', 'FileCreateStreamHash',
'RegistryEvent', 'FileCreate')]
[string[]]
$EventType,
# Action for event type rule and filters.
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=2)]
[ValidateSet('Include', 'Exclude')]
[String]
$OnMatch = 'Exclude'
)
Begin{}
Process
{
# Check if the file is a valid XML file and if not raise and error.
try
{
switch($psCmdlet.ParameterSetName)
{
'Path'
{
[xml]$Config = Get-Content -Path $Path
$FileLocation = (Resolve-Path -Path $Path).Path
}
'LiteralPath'
{
[xml]$Config = Get-Content -LiteralPath $LiteralPath
$FileLocation = (Resolve-Path -LiteralPath $LiteralPath).Path
}
}
}
catch [Management.Automation.PSInvalidCastException]
{
Write-Error -Message 'Specified file does not appear to be a XML file.'
return
}
# Validate the XML file is a valid Sysmon file.
if ($Config.SelectSingleNode('//Sysmon') -eq $null)
{
Write-Error -Message 'XML file is not a valid Sysmon config file.'
return
}
if ($Config.Sysmon.schemaversion -notin $SysMonSupportedVersions)
{
Write-Error -Message 'This version of Sysmon Rule file is not supported.'
return
}
$Rules = $config.SelectSingleNode('//Sysmon/EventFiltering')
foreach ($rule in $rules.ChildNodes)
{
if ($rule.name -in $EventType -and $rule.onmatch -eq $OnMatch)
{
[void]$rule.ParentNode.RemoveChild($rule)
Write-Verbose -Message "Removed rule for $($EventType)."
}
}
$config.Save($FileLocation)
}
End{}
}
|
PowerShellCorpus/PowerShellGallery/PSAlphaFS/2.0.0.1/PSAlphaFS.tests.ps1
|
PSAlphaFS.tests.ps1
|
#
# This is a PowerShell Unit Test file.
# You need a unit test framework such as Pester to run PowerShell Unit tests.
# You can download Pester from http://go.microsoft.com/fwlink/?LinkID=534084
#
Describe "Get-Function" {
Context "Function Exists" {
It "Should Return" {
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSAlphaFS/2.0.0.1/build.ps1
|
build.ps1
|
Publish-Module -Path "C:\Github\Public\dev\PSAlphaFS" -NuGetApiKey mykey
|
PowerShellCorpus/PowerShellGallery/PSAlphaFS/2.0.0.1/Helpers/PSAlphaFSHelpers.ps1
|
PSAlphaFSHelpers.ps1
|
Function GetDotNetVer {
#https://gallery.technet.microsoft.com/scriptcenter/Detect-NET-Framework-120ec923
#modified to work with this module
[cmdletbinding()]
param()
$dotNetRegistry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP'
$dotNet4Registry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
$dotNet4Builds =
@{
30319 = '4.0'
378389 = '4.5'
378675 = '4.5.1'
378758 = '4.5.1'
379893 = '4.5.2'
380042 = '4.5'
393295 = '4.6'
393297 = '4.6'
394254 = '4.6.1'
394271 = '4.6.1'
394802 = '4.6.2'
394806 = '4.6.2'
}
if($regKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', 'Default')) {
if ($netRegKey = $regKey.OpenSubKey($dotNetRegistry)) {
foreach ($versionKeyName in $netRegKey.GetSubKeyNames()) {
if ($versionKeyName -match '^v[123]') {
$versionKey = $netRegKey.OpenSubKey($versionKeyName)
$version = [version]($versionKey.GetValue('Version', ''))
'{0}.{1}' -f $version.Major,$version.minor
}
}
}
if ($net4RegKey = $regKey.OpenSubKey($dotNet4Registry)) {
if(-not ($net4Release = $net4RegKey.GetValue('Release'))) {
$net4Release = 30319
}
$dotNet4Builds[$net4Release]
}
}#open reg key
}#end function
$installed_dotnetversion = GetDotNetVer -ErrorAction SilentlyContinue | sort -Descending | Select-Object -First 1
$libpath_parent = join-path (Split-Path $PSScriptRoot -Parent) -ChildPath lib
if([string]::IsNullOrEmpty($installed_dotnetversion)) {
$libpath = Join-Path $libpath_parent -ChildPath 'net40\AlphaFS.dll'
}
else {
switch($installed_dotnetversion) {
'3.5' {$libpath = Join-Path $libpath_parent -ChildPath 'net35\AlphaFS.dll';break}
'4.0' {$libpath = Join-Path $libpath_parent -ChildPath 'net40\AlphaFS.dll';break}
'4.5.0' {$libpath = Join-Path $libpath_parent -ChildPath 'net45\AlphaFS.dll';break}
'4.5.1' {$libpath = Join-Path $libpath_parent -ChildPath 'net451\AlphaFS.dll';break}
'4.5.2' {$libpath = Join-Path $libpath_parent -ChildPath 'net452\AlphaFS.dll';break}
'4.6.1' {$libpath = Join-Path $libpath_parent -ChildPath 'net452\AlphaFS.dll';break}
'4.6.2' {$libpath = Join-Path $libpath_parent -ChildPath 'net452\AlphaFS.dll';break}
default {$libpath = Join-Path $libpath_parent -ChildPath 'net40\AlphaFS.dll'}
}
}# if installed_dotnetversion
# Load the AlphaFS assembly
Add-Type -Path $libpath
Function FormatDriveLetter ([string]$DriveLetter) {
#Format driveletter
if($DriveLetter -notmatch '[aA-zZ]:\\') {
$DriveLetter = "$DriveLetter`:\"
}
return $DriveLetter
}
Function CheckMappedDriveExists ([string]$DriveLetter, [String]$NetworkShare) {
$DriveLetterFormatted = FormatDriveLetter $DriveLetter
$isDrivePresent = [Alphaleonis.Win32.Filesystem.DriveInfo]::GetDrives() | Where-Object { ($_.DriveType -eq 'Network') -and ($_.DriveLetter -eq $DriveLetterFormatted) -and ($_.UncPath -eq $NetworkShare) }
if ($isDrivePresent) {
Write-Verbose "MappedDrive ['$DriveLetterFormatted'] for NetworkShare ['$NetworkShare'] exists."
return $true
}
else {
Write-Verbose "MappedDrive ['$DriveLetterFormatted'] for NetworkShare ['$NetworkShare'] does not exist."
return $false
}
}
# function to match file extensions
function CompareExtension([string[]]$Extension, $Filename) {
foreach ($p in $Extension) {
$wc = New-Object System.Management.Automation.WildcardPattern -ArgumentList ($p, [System.Management.Automation.WildcardOptions]::IgnoreCase)
if ($wc.IsMatch($Filename)) {return $true}
}
}
Function newlongitemhelper {
#[cmdletbinding()]
param
(
[string]$Filename,
[String]$itemtype,
$value,
[String]$Encoding,
[Switch]$Force
)
$FilePath = $Filename
$Leaf = $PathFSObject::GetFileName($FilePath)
$Parent = $PathFSObject::GetDirectoryName($FilePath)
$isFile = if($PathFSObject::HasExtension($Leaf) ){$true}else {$false}
# Create the parent
if (-not ($DirObject::Exists($Parent)) ) {
$DirObject::CreateDirectory($Parent) | Out-Null
}
if($ItemType -eq 'File') {
# check if there is an existing folder with the same name as the file we are trying to create
if($DirObject::Exists($FilePath)) {
Write-Warning ("New-LongItem: A Directory with the same name '{0}' already exists." -f $FilePath)
return
}
#Create a file
if($FileObject::Exists($FilePath)) {
if($Force) {
if ($Value) {
$FileObject::WriteAllLines($FilePath, $value, [System.Text.Encoding]::$Encoding, $PathFSFormatObject::FullPath)
}
Else {
$FileObject::Create($FilePath, $PathFSFormatObject::FullPath) | Out-Null
}
New-Object Alphaleonis.Win32.Filesystem.FileInfo -ArgumentList $FilePath, $PathFSFormatObject::FullPath
}
Else {
Write-Warning ("New-LongItem: The file '{0}' already exists. Use '-Force' to overwrite" -f $FilePath)
}
}# file exists
Else {
if ($Value) {
$FileObject::WriteAllLines($FilePath, $value, [System.Text.Encoding]::$Encoding, $PathFSFormatObject::FullPath)
}
Else {
$FileObject::Create($FilePath, $PathFSFormatObject::FullPath) | Out-Null
}
New-Object Alphaleonis.Win32.Filesystem.FileInfo -ArgumentList $FilePath, $PathFSFormatObject::FullPath
}# if file dosent exist
}# if itemtype is file
Elseif($ItemType -eq 'Directory') {
if($FileObject::Exists($FilePath)) {
Write-Warning ("New-LongItem: A file with the same name '{0}' already exists." -f $FilePath)
return
}
if($DirObject::Exists($FilePath)) {
if($Force) {
$DirObject::CreateDirectory($FilePath)
}
Else {
Write-Warning ("New-LongItem: The Directory '{0}' already exists. Use '-Force' to overwrite" -f $FilePath)
}
}# folder exists
Else {
$DirObject::CreateDirectory($FilePath)
}
}# itemtype is directory
Elseif($ItemType -eq 'HardLink') {
if($Value) {
if(-not [Alphaleonis.Win32.Filesystem.Path]::IsPathRooted($value)) {
$value = $PathFSObject::Combine($PWD, $value.TrimStart('.\'))
}
$ExistingFile_Leaf = $PathFSObject::GetFileName($value)
$ExistingFile_info = New-Object Alphaleonis.Win32.Filesystem.FileInfo -ArgumentList $Value
$ExistingDirectory_info = New-Object Alphaleonis.Win32.Filesystem.DirectoryInfo -ArgumentList $Value
if(-not $ExistingFile_info.Exists) {
if($ExistingDirectory_info.Exists) {
Write-Warning ("New-LongItem: The Hardlink to be created cannot be a folder '{0}'" -f $FilePath)
return
}
Else {
Write-warning ("New-LongItem:`tHardLink Link Target '{0}' does not exist" -f $Value)
return
}
}#if the target does not exist
if($FileObject::Exists($FilePath)) {
if($Force) {
$FileObject::Delete($FilePath, $true, $PathFSFormatObject::FullPath)
$FileObject::CreateHardlink($FilePath, $value)
}
Else {
Write-Warning ("New-LongItem: The Hardlink '{0}' already exists. Use -Force to overwrite" -f $FilePath)
return
}
}# file exists
else {
Write-Verbose ("New-LongItem:`tCreating Symbolic Link ['{0}'] for ['{1}']" -f $FilePath,$Value)
$FileObject::CreateHardlink($FilePath, $value)
}
}
Else {
Write-Warning ("New-LongItem: Please provide the target for The Hardlink '{0}' " -f $FilePath)
}# if no value is provided
}# if Hardlink
Elseif($ItemType -eq 'SymbolicLink') {
if($Value) {
if(-not [Alphaleonis.Win32.Filesystem.Path]::IsPathRooted($value)) {
$value = $PathFSObject::Combine($PWD, $value.TrimStart('.\'))
}
$ExistingFile_Leaf = $PathFSObject::GetFileName($value)
$ExistingFile_info = New-Object Alphaleonis.Win32.Filesystem.FileInfo -ArgumentList $Value
$ExistingDirectory_info = New-Object Alphaleonis.Win32.Filesystem.DirectoryInfo -ArgumentList $Value
if( (-not $ExistingFile_info.Exists) -and (-not $ExistingDirectory_info.Exists) ) {
Write-warning ("New-LongItem:`tSymbolic Link Target '{0}' does not exist" -f $Value)
return
}
$isFile_Real = if($ExistingFile_info.EntryInfo.IsDirectory){$false}else {$true}
if($isFile_Real) {
$linktarget = $linktype::File
}
Else {
$linktarget = $linktype::Directory
}
$checkfortarget_file = $FileObject::Exists($FilePath)
$checkfortarget_dir = $DirObject::Exists($FilePath)
if($checkfortarget_file -or $checkfortarget_dir) {
if($Force) {
try {
$FileObject::Delete($FilePath, $true, $PathFSFormatObject::FullPath)
}
Catch {
try {
$DirObject::Delete($FilePath, $true, $PathFSFormatObject::FullPath)
}
catch {
throw $_
}
}
$FileObject::CreateSymbolicLink($FilePath, $value, $linktarget)
}
Else {
Write-Warning ("New-LongItem: The SymbolicLink '{0}' already exists.Use -Force to overwrite" -f $FilePath)
return
}
}# file exists
else {
Write-Verbose ("New-LongItem:`tCreating Symbolic Link ['{0}'] for ['{1}']" -f $FilePath,$Value)
$FileObject::CreateSymbolicLink($FilePath, $value, $linktarget)
}
}
Else {
Write-Warning ("New-LongItem: Please provide the target for The SymbolicLink '{0}' " -f $FilePath)
}# if no value is provided
}# if itemtype is symboliclink
Else {
#best effort to create a file or directory
if($isFile) {
# check if there is an existing folder with the same name as the file we are trying to create
if($DirObject::Exists($FilePath)) {
Write-Warning ("New-LongItem: A Directory with the same name '{0}' already exists." -f $FilePath)
return
}
#Create a file
if($FileObject::Exists($FilePath)) {
if($Force) {
if ($Value) {
$FileObject::WriteAllLines($FilePath, $value, [System.Text.Encoding]::$Encoding, $PathFSFormatObject::FullPath)
}
Else {
$FileObject::Create($FilePath, $PathFSFormatObject::FullPath) | Out-Null
}
New-Object Alphaleonis.Win32.Filesystem.FileInfo -ArgumentList $FilePath, $PathFSFormatObject::FullPath
}
Else {
Write-Warning ("New-LongItem: The file '{0}' already exists. Use '-Force' to overwrite" -f $FilePath)
}
}# file exists
Else {
if ($Value) {
$FileObject::WriteAllLines($FilePath, $value, [System.Text.Encoding]::$Encoding, $PathFSFormatObject::FullPath)
}
Else {
$FileObject::Create($FilePath, $PathFSFormatObject::FullPath) | Out-Null
}
New-Object Alphaleonis.Win32.Filesystem.FileInfo -ArgumentList $FilePath, $PathFSFormatObject::FullPath
}# if file dosent exist
}# if file
else {
if($FileObject::Exists($FilePath)) {
Write-Warning ("New-LongItem: A file with the same name '{0}' already exists." -f $FilePath)
return
}
if($DirObject::Exists($FilePath)) {
if($Force) {
$DirObject::CreateDirectory($FilePath)
}
Else {
Write-Warning ("New-LongItem: The Directory '{0}' already exists. Use '-Force' to overwrite" -f $FilePath)
}
}# folder exists
Else {
$DirObject::CreateDirectory($FilePath)
}
}# if not file but a folder
}#if itemtype is not specified
}
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/SupplierSpecific_Functions/Get-UKPowerCutsNieNetworks.ps1
|
Get-UKPowerCutsNieNetworks.ps1
|
function Get-UKPowerCutsWesternPower {
Param (
[Parameter(Mandatory=$true)][ValidatePattern("^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$")] $PostCode,
[bool]$ViewAll
)
$AllObjects = @()
$WebSite = ('https://powercheck.nienetworks.co.uk/TabularFaults.html')
$ie = new-object -ComObject "InternetExplorer.Application"
$ie.navigate($WebSite)
while($ie.busy) {Start-Sleep 1}
$doc = $ie.Document.body
$tables = @($doc.getElementsByTagName('TABLE'))
#$Table = (Get-WebRequestTable $WebSite -TableNumber 0 -IeExperience)
ForEach ($f in $Table) {
$c = ($f.'Areas Affected').replace(" ","")
$d = $Postcode.replace(" ","")
if ($f.'Areas Affected' -match ","){
$ff = $f.'Areas Affected' -split(",")
ForEach ($fff in $ff) {
$obj = [PSCustomObject]@{
AreasAffected = $fff
TimeofIncident = $f.'Time of Incident'
NumberPropertiesWithoutPower = $f.'Number properties without power'
EstimatedRestorationTime = $f.'Estimated Restoration Time'
}
$g = $fff.replace(" ","")
if ($ViewAll -eq "True"){
$AllObjects += $obj
} else {
if ($d -match $g) {
$AllObjects += $obj
}
}
}
} else {
$obj = [PSCustomObject]@{
AreasAffected = $f.'Areas Affected'
TimeofIncident = $f.'Time of Incident'
NumberPropertiesWithoutPower = $f.'Number properties without power'
EstimatedRestorationTime = $f.'Estimated Restoration Time'
}
if ($ViewAll -eq "True"){
$AllObjects += $obj
} else {
if ($d -match $c) {
$AllObjects += $obj
}
}
}
}
$AllObjects
}
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/SupplierSpecific_Functions/Get-UKPowerCutsWesternPower.ps1
|
Get-UKPowerCutsWesternPower.ps1
|
function Get-UKPowerCutsWesternPower {
Param (
[Parameter(Mandatory=$true)][ValidatePattern("^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$")] $PostCode,
[bool]$ViewAll
)
$WebSite = ('https://www.westernpower.co.uk/Power-outages/Power-cuts-in-your-area/Power-Cut-outages-list.aspx')
$AllObjects = @()
$Table = (Get-WebRequestTable $WebSite -TableNumber 0)
ForEach ($f in $TAble) {
$c = ($f.'Areas Affected').replace(" ","")
$d = $Postcode.replace(" ","")
if ($f.'Areas Affected' -match ","){
$ff = $f.'Areas Affected' -split(",")
ForEach ($fff in $ff) {
$obj = [PSCustomObject]@{
AreasAffected = $fff
TimeofIncident = $f.'Time of Incident'
NumberPropertiesWithoutPower = $f.'Number properties without power'
EstimatedRestorationTime = $f.'Estimated Restoration Time'
}
$g = $fff.replace(" ","")
if ($ViewAll -eq "True"){
$AllObjects += $obj
} else {
if ($d -match $g) {
$AllObjects += $obj
}
}
}
} else {
$obj = [PSCustomObject]@{
AreasAffected = $f.'Areas Affected'
TimeofIncident = $f.'Time of Incident'
NumberPropertiesWithoutPower = $f.'Number properties without power'
EstimatedRestorationTime = $f.'Estimated Restoration Time'
}
if ($ViewAll -eq "True"){
$AllObjects += $obj
} else {
if ($d -match $c) {
$AllObjects += $obj
}
}
}
}
If ($AllObjects.count -eq 0) {
Write-Output "There are no power cuts for your area."
} else {
Write-Output "There are power cuts for your area".
$AllObjects
}
}
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/SupplierSpecific_Functions/Get-UKPowerCutsScottishAndSouthern.ps1
|
Get-UKPowerCutsScottishAndSouthern.ps1
|
function Get-UKPowerCutsScottishAndSouthern {
Param (
[Parameter(Mandatory = $true)][ValidatePattern("^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$")] $PostCode,
[switch]$ViewAll
)
$r = $NULL
#$PostCode = "SL8 5EE"
$AllObjects = @()
$Allproperties = @()
$FinalObject = @()
$object = @{}
$props = @{}
$props2 = @{}
$WebSite = ('https://www.ssepd.co.uk/Powertrack/')
$WebRequest = Invoke-WebRequest $WebSite
$divs = $WebRequest.ParsedHtml.body.getElementsByTagName('div') |
Where-Object {$_.getAttributeNode('class').Value -eq 'power-track-summary clearfix'}
$rows = $divs.getElementsByClassName('accordion-group')
ForEach ($row in $rows) {
$props = @{}
$c = @()
$MaxPElements = ($row.getElementsByTagName('P') | ? {$_.outerhtml -match "content"} | measure).count
For ($i = 0; $i -lt $MaxPElements ; $i += 2) {
$PropName = $row.getElementsByTagName('P')[$i].outertext.Replace(' ', '')
$PropValue = $row.getElementsByTagName('P')[$i].nextsibling.nextsibling.outertext
$props += @{"$PropName" = "$PropValue"}
}
$e = $row.getElementsByClassName('affected-areas row')
$codes = $e[0].getElementsByClassName('col-xs-12 col-sm-3 col-md-2')
ForEach ($code in $codes) { $c += $code.innertext.trim() + "," }
$props += @{"AffectedPostCodes" = $c.trimend(',')}
$object = new-object psobject -Property $props
$AllObjects += $object
}
#$AllObjects | select -Property Faultreference, * -ErrorAction SilentlyContinue
ForEach ($o in $AllObjects) {
$props2 = @{}
ForEach ($p in $o.psobject.Properties) {
if ($p -notmatch "AffectedPostCodes") {
$props2 += @{$p.name = $p.value}
$Allproperties += $p.name
$Allproperties += "AffectdPostCode"
}
}
ForEach ($k in $o.AffectedPostCodes) {
$props3 = @{}
$props3 = $props2
$props3 += @{"AffectdPostCode" = $k}
$object2 = new-object psobject -Property $props3
if ($ViewAll) {
$FinalObject += $object2
}
else {
if ($object2.AffectdPostCode.replace(" ", "") -match $PostCode.replace(" ", "")) {
$FinalObject += $object2
}
}
}
}
#$FinalObject | ft -Property *
$uni = $Allproperties | select -Unique
#$FinalObject | select $uni
If ($FinalObject.count -eq 0 -and !$viewall) {
Write-Output "There are no power cuts for your area."
}
elseif ($FinalObject.count -ne 0 -and !$viewall) {
Write-Output "There are power cuts for your area."
$FinalObject
}
else {
$FinalObject | ft $uni
}
}
#Get-UKPowerCutsChecker -PostCode "sl8 5ee" -ViewAll
#Get-UKPowerCutsScottishAndSouthern -PostCode "sl8 5ee" -ViewAll
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/SupplierSpecific_Functions/Get-UKPowerCutsSPEnergyNetworks.ps1
|
Get-UKPowerCutsSPEnergyNetworks.ps1
|
function Get-UKPowerCutsSPEnergyNetworks {
Param (
[Parameter(Mandatory=$true)][ValidatePattern("^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$")] $PostCode,
[bool]$ViewAll = $false
)
$PostCodeNoSpace = $PostCode -replace ' ',''
$WebSite = ("https://www.spenergynetworks.co.uk/pages/postcode_results.aspx?post=$PostCodeNoSpace")
$WebRequest = Invoke-WebRequest $WebSite
if ($WebRequest.ParsedHtml.body.getElementsByClassName('spacer-top-10')[0].outertext -eq "No faults detected") {
Write-Output "There are no power cuts for your area"
} else {
Write-Output "There are power cuts for your area, check 'SP Energy Networks' website for details."
}
}
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/SupplierSpecific_Functions/Get-UKPowerCutsUKPowerNetworks.ps1
|
Get-UKPowerCutsUKPowerNetworks.ps1
|
function Get-UKPowerCutsUKPowerNetworks {
Param (
[Parameter(Mandatory=$true)][ValidatePattern("^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$")] $PostCode,
[bool]$ViewAll
)
$WebSite = "http://www.ukpowernetworks.co.uk/internet/en/power-cuts/list-of-powercuts/"
$Table = (Get-WebRequestTable $WebSite -TableNumber 0 -IeExperience)
$AllObjects = @()
ForEach ($f in $Table) {
if ($f.'Potentially affected postcodes'){
$c = ($f.'Potentially affected postcodes').replace(" ","")
$d = $Postcode.replace(" ","")
if ($f.'Potentially affected postcodes' -match ","){
$ff = $f.'Potentially affected postcodes' -split(",")
ForEach ($fff in $ff) {
$obj = [PSCustomObject]@{
AreasAffected = $fff
TimeofIncident = $f.'This power cut was reported at'
EstimatedRestorationTime = $f.'Estimated time for power to be restored'
ReferenceNumber = $f.'Reference number'
}
$g = $fff.replace(" ","")
if ($ViewAll -eq "True"){
$AllObjects += $obj
} else {
if ($d -match $g) {
$AllObjects += $obj
}
}
}
} else {
$obj = [PSCustomObject]@{
AreasAffected = $f.'Potentially affected postcodes'
TimeofIncident = $f.'This power cut was reported at'
EstimatedRestorationTime = $f.'Estimated time for power to be restored'
ReferenceNumber = $f.'Reference number'
}
if ($ViewAll -eq "True"){
$AllObjects += $obj
} else {
if ($d -match $c) {
$AllObjects += $obj
}
}
}
}
}
$AllObjects
}
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/Main_Functions/Get-UKPowerCutsChecker.ps1
|
Get-UKPowerCutsChecker.ps1
|
function Get-UKPowerCutsChecker {
<#
.SYNOPSIS
"Get-UKPowerCutsChecker" function has been created to give an information about power outages.
"Get-UKPowerCutsChecker" is the main function of the module.
.DESCRIPTION
"Get-UKPowerCutsChecker" allows you to check if there is any power cut for your post code, or if there are any power cuts for your power supplier.
Valid post code need to be provided in order to see output.
Verbose mode will additional show informarmation who has been identified as a power supplier for given post code.
Currently 2 suppliers are included:
"Western Power Disctribution"
"UK Power Networks"
.OUTPUTS
Output so far is an object, at this point of time I think anyone will create a unique action is script returns an outage.
.EXAMPLE
Command to check if there is any ongoing power cut for some Coventry area:
Get-UKPowerCutsChecker -PostCode "cv4 8hs"
.EXAMPLE
Command to list all ongoing power cuts for London, Cabot Square area:
Get-UKPowerCutsChecker -PostCode "e14 4qr" -ViewAll
.LINK
https://paweljarosz.wordpress.com/2017/04/13/search-power-cuts-in-the-uk-using-powershell
.NOTES
Written By: Pawel Jarosz
Website: http://paweljarosz.wordpress.com
GitHub: https://github.com/zaicnupagadi
Technet: https://gallery.technet.microsoft.com/scriptcenter/site/mydashboard
PowerShellGallery: https://www.powershellgallery.com/packages/ukpowercutchecker
Change Log
V1.0.3, 23/05/2017 - Still dirty as hell but added ScottishAndSouthern supplier
V1.0.2, 13/04/2017 - Version with two power suppliers, creating proper function for ScottishAndSouthern.
V1.0.1, 11/04/2017 - Initial version, dity and full of bugs :)
#>
Param (
[Parameter(Mandatory=$true)][ValidatePattern("^([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])\ [0-9][ABD-HJLNP-UW-Z]{2}|(GIR\ 0AA)|(SAN\ TA1)|(BFPO\ (C\/O\ )?[0-9]{1,4})|((ASCN|BBND|[BFS]IQQ|PCRN|STHL|TDCU|TKCA)\ 1ZZ))$")] $PostCode,
[switch]$ViewAll
)
$web = (Invoke-WebRequest http://www.powercut105.com/FindOperator?Postcode=$PostCode#dno)
$a = ($web.tostring() -split "[`r`n]" | select-string "lblSupplier").ToString()
$b = $a.Replace('bold;">','#').replace("</span>","#")
$prog = [regex]::match($b,'#([^#]+)#')
$PowerSupplier = $prog.Groups[1].Value
Write-Verbose -Message "Power supplier has been identified as '$PowerSupplier'"
if (!($ViewAll)){
$params = @{
PostCode = $PostCode
}
} else {
$params = @{
PostCode = $PostCode
ViewAll = $ViewAll
}
}
switch ($PowerSupplier)
{
"Postcode not found" {"Postcode not found"}
"Western Power Distribution" {Get-UKPowerCutsWesternPower @params}
"UK Power Networks" {Get-UKPowerCutsUKPowerNetworks @params}
"SP Energy Networks" {Get-UKPowerCutsSPEnergyNetworks @params}
"Scottish and Southern Electricity Networks" {Get-UKPowerCutsScottishAndSouthern @params}
default {"Power supplier couldn't be identified - please report the problem to the Author."}
}
}
|
PowerShellCorpus/PowerShellGallery/ukpowercutchecker/1.0.8/Public/Helper_Functions/Get-WebRequestTable.ps1
|
Get-WebRequestTable.ps1
|
Function Get-WebRequestTable {
param(
[Parameter(Mandatory = $true)]
[String] $WebSite,
[Parameter(Mandatory = $true)]
[int] $TableNumber,
[switch] $IeExperience
)
## Extract the tables out of the web request
If ($IeExperience) {
$ie = new-object -ComObject "InternetExplorer.Application"
$ie.navigate($WebSite)
while($ie.busy) {Start-Sleep 1}
$doc = $ie.Document.body
$tables = @($doc.getElementsByTagName('TABLE'))
} else {
$WebRequest = Invoke-WebRequest $WebSite
$tables = @($WebRequest.ParsedHtml.getElementsByTagName("TABLE"))
}
$table = $tables[$TableNumber]
$titles = @()
$rows = @($table.Rows)
## Go through all of the rows in the table
foreach($row in $rows)
{
$cells = @($row.Cells)
## If we've found a table header, remember its titles
if($cells[0].tagName -eq "TH")
{
$titles = @($cells | ForEach-Object { ("" + $_.InnerText).Trim() })
continue
}
## If we haven't found any table headers, make up names "P1", "P2", etc.
if(-not $titles)
{
$titles = @(1..($cells.Count + 2) | ForEach-Object { "P$_" })
}
## Now go through the cells in the the row. For each, try to find the
## title that represents that column and create a hashtable mapping those
## titles to content
$resultObject = [Ordered] @{}
for($counter = 0; $counter -lt $cells.Count; $counter++)
{
$title = $titles[$counter]
if(-not $title) { continue }
$resultObject[$title] = ("" + $cells[$counter].InnerText).Trim()
}
## And finally cast that hashtable to a PSCustomObject
[PSCustomObject] $resultObject
}
if ($ie){
$ie.Quit()
}
}
|
PowerShellCorpus/PowerShellGallery/OVF.SharePoint/1.0.0.3/Diagnostics/Simple/OVF.SharePoint.Tests.ps1
|
OVF.SharePoint.Tests.ps1
|
#Functions
function Test-OPSValServiceState{
param(
$serviceName,
$computerName = "."
)
if(($computerName -eq ".") -or ($computerName -eq "$env:computername") -or ($computerName -eq "localhost") -or ($computerName -eq "$env:computername.$env:USERDNSDOMAIN")){
$service = Get-Service -Name $serviceName
}
else{
$service = Get-Service -Name $serviceName -ComputerName $computerName
}
return $service
}
function Test-OPSValWebAppPoolState{
param(
$computerName = "."
)
if(($computerName -eq ".") -or ($computerName -eq "$env:computername") -or ($computerName -eq "localhost") -or ($computerName -eq "$env:computername.$env:USERDNSDOMAIN")){
$iisPool = Get-ChildItem -Path IIS:\AppPools | Where-Object{($_.Name -ne "SharePoint Web Services Root") -and ($_.State -ne "Started")}
}
else{
$template = 'Import-Module WebAdministration;Get-ChildItem -Path IIS:\AppPools | Where-Object{($_.Name -ne "SharePoint Web Services Root") -and ($_.State -ne "Started")}'
$sb = [ScriptBlock]::Create($template)
$session = New-PSSession -ComputerName $computerName
$iisPool = Invoke-Command -Session $session -ScriptBlock $sb
Remove-PSSession -Session $session
}
return $iispool
}
#Modules
Import-Module Pester
Import-Module OperationValidation
Add-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue
Import-Module WebAdministration
Describe "Operational Validation of SharePoint 2013" {
Context "Windows Services" {
#Windows Service Area
$serviceName = "W3SVC"
$computerName = "localhost"
It "Service $serviceName State should be running" {
$service = Test-OPSValServiceState -serviceName $serviceName -ComputerName $computerName
$service.Status | Should be running
}
$serviceName = "SPSearchHostController"
It "Service $serviceName State should be running" {
$service = Test-OPSValServiceState -serviceName $serviceName -ComputerName $computerName
$service.Status | Should be running
}
$serviceName = "OSearch15"
It "Service $serviceName State should be running" {
$service = Test-OPSValServiceState -serviceName $serviceName -ComputerName $computerName
$service.Status | Should be running
}
$serviceName = "SPTimerV4"
It "Service $serviceName State should be running" {
$service = Test-OPSValServiceState -serviceName $serviceName -ComputerName $computerName
$service.Status | Should be running
}
$serviceName = "SPTraceV4"
It "Service $serviceName State should be running" {
$service = Test-OPSValServiceState -serviceName $serviceName -ComputerName $computerName
$service.Status | Should be running
}
$serviceName = "AppFabricCachingService"
It "Service $serviceName State should be running" {
$service = Test-OPSValServiceState -serviceName $serviceName -ComputerName $computerName
$service.Status | Should be running
}
}
Context "WebApp Pools"{
#Web App Pools Area
It "Web Application Pools in IIS should be running" {
$iispool = Test-OPSValWebAppPoolState
($iisPool | Measure-Object).Count | Should be 0
}
}
Context "URLCheck" {
#Url Areas
$url = "https://sharepoint-test.mydomain.com"
It "WebSite $url should be running and login working" {
$request = Invoke-WebRequest -Uri $url -UseDefaultCredentials
$request.StatusCode | Should be 200
}
$url = "https://server:centralAdminPort/"
It "The Central Administration on $url should be running and login working" {
$request = Invoke-WebRequest -Uri $url -UseDefaultCredentials
$request.StatusCode | Should be 200
}
}
Context "SP Sites Test"{
#SharePoint Site Tests
$webAppUrl = "https://sharepoint-test.domain.com/"
It "The SharePoint Sites should have no Errors"{
$webApp = Get-SPWebApplication -Identity $webAppUrl
$sites = Get-SPSite -WebApplication $webApp -Limit All
$result = $sites | Test-SPSite
$sitesWithErrors = $null
$sitesWithErrors = $result | Where-Object{$_.FailedErrorCount -gt 0}
if(-not([String]::IsNullOrEmpty($sitesWithErrors))){
$testResult = "Failed"
}
else{
$testResult = "Succeeded"
}
$testResult | Should be Succeeded
}
}
Context "SP Upgrade Status"{
#SharePoint DB Tests
It "The SharePoint Databases should have no Upgrades pending"{
$dbs = Get-SPDatabase
$dbsWithUpgradeNeeded = $dbs | Where-Object{$_.NeedsUpgrade -eq $true}
if($dbsWithUpgradeNeeded){
Write-Warning "DBs needing Upgrade:"
Write-Host ($dbsWithUpgradeNeeded | Out-String)
}
$dbsWithUpgradeNeeded | Should be $null
}
}
}
|
PowerShellCorpus/PowerShellGallery/OVF.SharePoint/1.0.0.3/Diagnostics/Simple/OVF.SharePoint.EnterpriseSearch.Tests.ps1
|
OVF.SharePoint.EnterpriseSearch.Tests.ps1
|
function New-HostTemplate{
# Template object for the host array:
$hostTemplate = New-Object -TypeName PSObject
$hostTemplate | Add-Member -MemberType NoteProperty -Name hostName -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name components -Value 0
$hostTemplate | Add-Member -MemberType NoteProperty -Name cpc -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name qpc -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name pAdmin -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name sAdmin -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name apc -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name crawler -Value $null
$hostTemplate | Add-Member -MemberType NoteProperty -Name index -Value $null
return $hostTemplate
}
function New-HATemplate{
# Template object for the HA group array:
$haTemplate = New-Object -TypeName PSObject
$haTemplate | Add-Member -MemberType NoteProperty -Name entity -Value $null
$haTemplate | Add-Member -MemberType NoteProperty -Name partition -Value -1
$haTemplate | Add-Member -MemberType NoteProperty -Name primary -Value $null
$haTemplate | Add-Member -MemberType NoteProperty -Name docs -Value 0
$haTemplate | Add-Member -MemberType NoteProperty -Name components -Value 0
$haTemplate | Add-Member -MemberType NoteProperty -Name componentsOk -Value 0
return $haTemplate
}
function New-ComponentTemplate{
# Template object for the component/server table:
$compTemplate = New-Object -TypeName PSObject
$compTemplate | Add-Member -MemberType NoteProperty -Name Component -Value $null
$compTemplate | Add-Member -MemberType NoteProperty -Name Server -Value $null
$compTemplate | Add-Member -MemberType NoteProperty -Name Partition -Value $null
$compTemplate | Add-Member -MemberType NoteProperty -Name State -Value $null
return $compTemplate
}
function New-ComponentHAList{
param(
$searchComponent
)
if ($searchComponent.ServerName)
{
$hostName = $searchComponent.ServerName
}
else
{
$hostName = "Unknown server"
}
$partition = $searchComponent.IndexPartitionOrdinal
$newHostFound = $true
$newHaFound = $true
$entity = $null
foreach ($searchHost in ($script:hostArray))
{
if ($searchHost.hostName -eq $hostName)
{
$newHostFound = $false
}
}
if ($newHostFound)
{
# Add the host to $script:hostArray
$hostTemp = New-HostTemplate
$hostTemp.hostName = $hostName
$script:hostArray += $hostTemp
$script:searchHosts += 1
}
# Fill in component specific data in $script:hostArray
foreach ($searchHost in ($script:hostArray))
{
if ($searchHost.hostName -eq $hostName)
{
$partition = -1
if ($searchComponent.Name -match "Query")
{
$entity = "QueryProcessingComponent"
$searchHost.qpc = "QueryProcessing "
$searchHost.components += 1
}
elseif ($searchComponent.Name -match "Content")
{
$entity = "ContentProcessingComponent"
$searchHost.cpc = "ContentProcessing "
$searchHost.components += 1
}
elseif ($searchComponent.Name -match "Analytics")
{
$entity = "AnalyticsProcessingComponent"
$searchHost.apc = "AnalyticsProcessing "
$searchHost.components += 1
}
elseif ($searchComponent.Name -match "Admin")
{
$entity = "AdminComponent"
if ($searchComponent.Name -eq $script:primaryAdmin)
{
$searchHost.pAdmin = "Admin(Primary) "
}
else
{
$searchHost.sAdmin = "Admin "
}
$searchHost.components += 1
}
elseif ($searchComponent.Name -match "Crawl")
{
$entity = "CrawlComponent"
$searchHost.crawler = "Crawler "
$searchHost.components += 1
}
elseif ($searchComponent.Name -match "Index")
{
$entity = "IndexComponent"
$partition = $searchComponent.IndexPartitionOrdinal
$searchHost.index = "IndexPartition($partition) "
$searchHost.components += 1
}
}
}
# Fill in component specific data in $script:haArray
foreach ($haEntity in ($script:haArray))
{
if ($haEntity.entity -eq $entity)
{
if ($entity -eq "IndexComponent")
{
if ($haEntity.partition -eq $partition)
{
$newHaFound = $false
}
}
else
{
$newHaFound = $false
}
}
}
if ($newHaFound)
{
# Add the HA entities to $script:haArray
$haTemp = New-HATemplate
$haTemp.entity = $entity
$haTemp.components = 1
if ($partition -ne -1)
{
$haTemp.partition = $partition
}
$script:haArray += $haTemp
}
else
{
foreach ($haEntity in ($script:haArray))
{
if ($haEntity.entity -eq $entity)
{
if (($entity -eq "IndexComponent") )
{
if ($haEntity.partition -eq $partition)
{
$haEntity.components += 1
}
}
else
{
$haEntity.components += 1
if (($haEntity.entity -eq "AdminComponent") -and ($searchComponent.Name -eq $script:primaryAdmin))
{
$haEntity.primary = $script:primaryAdmin
}
}
}
}
}
}
function Get-IndexerEvents{
$indexerComps = $script:escss | Where-Object{$_.Name -match "Index" -or $_.Name -match "Content" -or $_.Name -match "Admin" -and $_.Name -notmatch "Cell" -and $_.State -notmatch "Unknown" -and $_.State -notmatch "Registering"}
foreach ($component in $indexerComps)
{
[array]$events += Get-SPEnterpriseSearchStatus -SearchApplication $script:essa -HealthReport -Component $component.Name
return $events
}
}
function Test-AnalyticsStatus{
$analyticsStatus = Get-SPEnterpriseSearchStatus -SearchApplication $script:essa -JobStatus
foreach ($analyticsEntry in $analyticsStatus)
{
# Output additional diagnostics from the dictionary
foreach ($de in ($analyticsEntry.Details))
{
# Skip entries that is listed as Not Available
if ( ($de.Value -ne "Not available") -and ($de.Key -ne "Activity") -and ($de.Key -ne "Status") )
{
if ($de.Key -match "Last successful start time")
{
$dLast = Get-Date $de.Value
$dNow = Get-Date
$daysSinceLastSuccess = $dNow.DayOfYear - $dLast.DayOfYear
if ($daysSinceLastSuccess -gt 3)
{
[array]$analytcsJobNotRunCount += 1
}
}
}
}
}
return $analytcsJobNotRunCount
}
Add-PSSnapin Microsoft.SharePoint.Powershell
$script:essa = Get-SPEnterpriseSearchServiceApplication
$script:esccs = Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $script:essa
$script:est = Get-SPEnterpriseSearchTopology -SearchApplication $script:essa -Active
$script:esc = Get-SPEnterpriseSearchComponent -SearchTopology $script:est
$script:ess = Get-SPEnterpriseSearchStatus -SearchApplication $script:essa -JobStatus
$script:eshc = Get-SPEnterpriseSearchHostController
$script:escss = Get-SPEnterpriseSearchStatus -SearchApplication $script:essa
$script:hostArray = @()
$script:haArray = @()
$script:compArray = @()
$script:topologyCompList = Get-SPEnterpriseSearchComponent -SearchTopology $script:est
foreach ($component in ($script:esccs)){
if ( ($component.Name -match "Admin") -and ($component.State -ne "Unknown") ){
if (Get-SPEnterpriseSearchStatus -SearchApplication $script:essa -Primary -Component $($component.Name)){
$script:primaryAdmin = $component.Name
}
}
}
foreach ($searchComponent in ($script:topologyCompList))
{
New-ComponentHAList -searchComponent $searchComponent
}
$componentEvents = Get-IndexerEvents
Describe "Operational Validation of SharePoint 2013 Search Topology"{
It "Enterprise Search Service Application should be Online"{
$script:essa.Status | Should be "Online"
}
It "All Enterprise Search Components should be Online"{
$offlineComponents = ($script:escss | Where-Object{$_.State -ne "Active"} | Measure-Object).Count
$offlineComponents | Should be 0
}
It "Indexer, Content Processor and Admin Component should not have Errors"{
$errorEventCount = ($componentEvents | Where-Object{$_.Level -eq "Error"} | Measure-Object).Count
$errorEventCount | Should be 0
}
It "Indexer, Content Processor and Admin Component should not have Warnings"{
$warningEventCount = ($componentEvents | Where-Object{$_.Level -eq "Warning"} | Measure-Object).Count
$warningEventCount | Should be 0
}
It "No Component should be on a High Document Count"{
$docsHighCount = ($script:haArray | Where-Object{$_.docs -gt 9000000} | Measure-Object).Count
$docsHighCount | Should be 0
}
It "No Component should exceed the Healthy Document Count"{
$docsExceededCount = ($script:haArray | Where-Object{$_.docs -gt 10000000}| Measure-Object).Count
$docsExceededCount | Should be 0
}
It "All Host Controllers should have the same Repository Version"{
$hostControllerCount = ($script:eshc | Measure-Object).Count
if($hostControllerCount -eq 1){
$sameVersion = $true
}
elseif($hostControllerCount -gt 1){
$highestVersion = 0
foreach($hostController in $script:eshc){
if($hostController.Version -gt $highestVersion){
$highestVersion = $hostController.Version
}
}
$hostControllerWithLowerVersionCount = ($script:eshc | Where-Object{$_.Version -lt $highestVersion} | Measure-Object).Count
if($hostControllerWithLowerVersionCount = 0){
$sameVersion = $true
}
else{
$sameVersion = $false
}
}
$sameVersion | Should be true
}
It "All Analytics Jobs should have Succesfully Run in the last three Days"{
$jobsNotRunCount = Test-AnalyticsStatus
$jobsNotRunCount | Should be 0
}
It "Enterprise Search Service Application should not be Paused"{
$essaStatus = $script:essa.Ispaused()
$essaStatus | Should be 0
}
It "All Content Sources should have been successfully crawled in the last 3 days"{
$contentSources = Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $global:essa
$crawlNotCompletedCount = 0
foreach($contentSource in $contentSources){
$crawlLastCompleted = $contentSource.CrawlCompleted
$timeDifference = (Get-Date) - $crawlLastCompleted
if($timeDifference.Days -ge 3){
$crawlNotCompletedCount++
}
}
$crawlNotCompletedCount | Should be 0
}
}
|
PowerShellCorpus/PowerShellGallery/AzureRM.EventHub/0.4.0/AzureRmProfileStartup.ps1
|
AzureRmProfileStartup.ps1
|
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
@{
"Login-AzureRmAccount" = "Add-AzureRmAccount";
"Select-AzureRmSubscription" = "Set-AzureRmContext";
"Save-AzureRmProfile" = "Save-AzureRmContext";
"Select-AzureRmProfile" = "Import-AzureRmContext";
"Resolve-Error" = "Resolve-AzureRmError";
}.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias"
# SIG # Begin signature block
# MIIkFwYJKoZIhvcNAQcCoIIkCDCCJAQCA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b25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xJjAkBgNVBAMT
# HU1pY3Jvc29mdCBUaW1lLVN0YW1wIFBDQSAyMDEwAhMzAAAAtEM6HP62ulKJAAAA
# AAC0MA0GCWCGSAFlAwQCAQUAoIIBMjAaBgkqhkiG9w0BCQMxDQYLKoZIhvcNAQkQ
# AQQwLwYJKoZIhvcNAQkEMSIEIC8qZpn8SU+2O2ajlzUvAaitssf6p0W4ZOkjnawI
# ElUAMIHiBgsqhkiG9w0BCRACDDGB0jCBzzCBzDCBsQQUB8CVl64uTm7J03X22YlR
# mIsgbTowgZgwgYCkfjB8MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv
# bjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0
# aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EgMjAxMAITMwAA
# ALRDOhz+trpSiQAAAAAAtDAWBBT1xWWOfslnqPz0dT7PaHUsSYFjfzANBgkqhkiG
# 9w0BAQsFAASCAQDXID6ZUKZXXUal5Jb934cMHRVE2vUF/enYC/uftvnfCwKrzHFN
# at/r1rxaxVovdPPEMtAXbBevy+iZ/K2w+O3IPJFwvrff39T0tEItZxxS2b+C9q1d
# 3i4tKUSRVg1uOJDc+2GnWRangitndZB/npFD10pBbWAJuE8JNMDguwdP8IbZbr0/
# PfQ2qJTUrsx4ayfHshDyJD7wy6QKfnZm9zA3PKBIJON+4dIR8GgU/GY1aKdpvRjj
# TIMa5T+J3iImInOqSiT0RgaAjPCZT+MWaWq6Y9iTXSuRVSKHKByPvMcFrkZJ6exL
# RwIUbAeI541Xy5cnLvkfvWY68F9r6WLZiKuI
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/AzureRM.EventHub/0.2.0/AzureRmProfileStartup.ps1
|
AzureRmProfileStartup.ps1
|
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
@{
"Login-AzureRmAccount" = "Add-AzureRmAccount";
"Select-AzureRmSubscription" = "Set-AzureRmContext";
"Save-AzureRmProfile" = "Save-AzureRmContext";
"Select-AzureRmProfile" = "Import-AzureRmContext";
}.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias"
# SIG # Begin signature block
# MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDApggZz05Qnk0e
# yiuUwG/hQa3nA5NWg0bjPekKbmwN+aCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR
# pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL
# MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v
# bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb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YwDQYJ
# KoZIhvcNAQELBQAEggEAbIJqXcLAUEe/JME4tB+bSD9Oc28kzEVBGlSJv02aBsEK
# LjN6+y3KW1MKXq9AbBHYR2Kx09NWT4FhRVlvCINX14VXGoudeLEN9HwbU/fm6YIT
# am27sATWgpUjjaK+3wZ+YRxGjlQ0QLsnYy00BvDLGvzZLq+hlDfaAn+QhzepoGS7
# L9Etu8JRKLUEl3pUo9+gOWJZy0RzVRG1pd+9K1GDCvxeZDFTmIWx4oYqylxo5YJM
# lrbqTBCQ/YOci1DkIkdErc36VBeQouSXpoCk33Rolhv2YaJDbMUJ3FI3ktGQNG9J
# gxNo/i5isKTaBQ3jV7FQp1cRVzWAWTPJtxJXNv8NBg==
# SIG # End signature block
|
PowerShellCorpus/PowerShellGallery/PoshNuGet/0.1.40/deploy.ps1
|
deploy.ps1
|
<#
.Author
Trevor Sullivan <trevor@trevorsullivan.net>
.Description
Publishes the PowerShell module to the PowerShell Gallery.
This PowerShell script is invoked by AppVeyor after the "Deploy" phase has completed successfully.
#>
function Patch-ModuleManifest {
[CmdletBinding()]
param (
[string] $Path
, [string] $BuildNumber
)
if (!$Path) {
$Path = Get-ChildItem -Path $env:APPVEYOR_BUILD_FOLDER -Include *.psd1;
if (!$Path) { throw 'Could not find a module manifest file'; }
}
$ManifestContent = Get-Content -Path $Path -Raw;
$ManifestContent = $ManifestContent -replace '(?<=ModuleVersion\s+=\s+'')(?<ModuleVersion>.*)(?='')', ('${{ModuleVersion}}.{0}' -f $BuildNumber);
Set-Content -Path $Path -Value $ManifestContent;
$ManifestContent -match '(?<=ModuleVersion\s+=\s+'')(?<ModuleVersion>.*)(?='')';
Write-Verbose -Message ('Module Version patched: ' + $Matches.ModuleVersion);
}
function Main {
[CmdletBinding()]
param ()
$VerbosePreference = 'continue';
### Skip the build if the Git tag does not match "release"
Write-Output -InputObject "Git tag is: $env:APPVEYOR_REPO_TAG_NAME";
if ($env:APPVEYOR_REPO_TAG_NAME -notmatch 'release') {
# throw 'The release tag was not found on this commit. Skipping deployment.';
# return;
} else {
Write-Verbose -Message ('The release tag ({0}) was found on this commit. Starting deployment.' -f $env:APPVEYOR_REPO_TAG_NAME);
}
'AppVeyor Build Folder: {0}' -f $env:APPVEYOR_BUILD_FOLDER;
Write-Verbose -Message 'Calling Find-Package command to download nuget-anycpu.exe'
Find-Package -ForceBootstrap -Name zzzzzz -ErrorAction Ignore;
Patch-ModuleManifest -Path $env:APPVEYOR_BUILD_FOLDER\PoshNuGet.psd1 -BuildNumber $env:APPVEYOR_BUILD_NUMBER;
Write-Verbose -Message ('Publishing module {0} to Gallery!' -f $env:APPVEYOR_BUILD_FOLDER);
Publish-Module -Path $env:APPVEYOR_BUILD_FOLDER -NuGetApiKey $env:psapikey;
Write-Verbose -Message 'Finished publishing module!'
}
### Invoke Main function
Main;
|
PowerShellCorpus/PowerShellGallery/RackspaceCloudOffice/0.4.1/New-Release.ps1
|
New-Release.ps1
|
function Main {
$module = Test-ModuleManifest .\RackspaceCloudOffice.psd1
[string] $version = $module.Version
$d = New-TemporaryDirectory
try {
$moduleDir = New-Item -ItemType Directory -Path (Join-Path $d $module.Name)
Copy-Item *.psd1 $moduleDir
Copy-Item *.psm1 $moduleDir
New-ZipFile $d ".\RackspaceCloudOffice-$version.zip"
}
finally {
Remove-Item -Recurse $d
}
}
function New-TemporaryDirectory {
$parent = [System.IO.Path]::GetTempPath()
$name = [System.IO.Path]::GetRandomFileName()
New-Item -ItemType Directory -Path (Join-Path $parent $name) -Force
}
Add-Type -Assembly System.IO.Compression.FileSystem
function New-ZipFile {
param(
[string]$DirPath,
[string]$ZipPath
)
With-WorkingDirectory {
[System.IO.Compression.ZipFile]::CreateFromDirectory($DirPath, $ZipPath)
}
}
function With-WorkingDirectory {
param(
[scriptblock]$Code
)
$previous = [Environment]::CurrentDirectory
try {
$current = Get-Location -PSProvider FileSystem | select -ExpandProperty Path
[Environment]::CurrentDirectory = $current
& $Code
}
finally {
[Environment]::CurrentDirectory = $previous
}
}
Main
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/build.ps1
|
build.ps1
|
[cmdletbinding()]
param(
[string[]]$Task = 'default' # This task is defined in psakeBuild. We are just setting a default here.
)
# Verify that we have PackageManagement module installed
if (!(Get-Command Install-Module)) {
throw 'PackageManagement is not installed. You need V5 or https://www.microsoft.com/en-us/download/details.aspx?id=51451'
}
# Verify that our testing utilities are installed.
if (!(Get-Module -Name Pester -ListAvailable)) {
Install-Module -Name Pester
}
if (!(Get-Module -Name psake -ListAvailable)) {
Install-Module -Name Psake
}
if (!(Get-Module -Name PSDeploy -ListAvailable)) {
Install-Module -Name PSDeploy
}
if (!(Get-Module -Name PSScriptAnalyzer -ListAvailable)) {
Install-Module -Name PSScriptAnalyzer
}
# Run our test
Invoke-psake -buildFile "$PSScriptRoot\test\psakeBuild.ps1" -taskList $Task -parameters @{"root"=$PSScriptRoot}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Test/PowerRails.psdeploy.ps1
|
PowerRails.psdeploy.ps1
|
# Upload to powershell gallery
Deploy 'Upload to gallery' {
# Get config file
$root = Split-Path $PSScriptRoot -Parent
try {
$config = get-content "$root\config.json" | ConvertFrom-Json
$moduleFolder = Join-Path "$root\dist" $config.name
# Create and empty out dist file
if (!(Test-Path $moduleFolder)) {
New-Item -Path "$moduleFolder" -ItemType:Directory | Out-Null
}
Remove-Item -Path "$moduleFolder\*" -Recurse
# Copy files over
Copy-Item -Path "$root\PowerRails*" -Destination $moduleFolder
Copy-Item -Path "$root\build.ps1" -Destination $moduleFolder
Copy-Item -Path "$root\Public" -Destination $moduleFolder -Recurse
Copy-Item -Path "$root\Private" -Destination $moduleFolder -Recurse
Copy-Item -Path "$root\Resources" -Destination $moduleFolder -Recurse
Copy-Item -Path "$root\Test" -Destination $moduleFolder -Recurse
# Publish module
Publish-Module -path $moduleFolder -NuGetApiKey $config.apikey
} catch {
write-error "Unable to deploy: $_"
}
}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Test/psakeBuild.ps1
|
psakeBuild.ps1
|
properties {
$powerrailsModule = Join-Path $root "PowerRails.psm1"
}
# Default task includes Analyzing and Testing of script
task default -depends Analyze, Test
# Analyze by running Invoke-ScriptAnalyzer. Check script against best known practices
task Analyze {
$saResults = Invoke-ScriptAnalyzer -Path "$root\Public" -Severity @('Error', 'Warning') -Recurse -ExcludeRule "PSAvoidUsingWriteHost","PSUseDeclaredVarsMoreThanAssignments" -Verbose:$false
$saResults += Invoke-ScriptAnalyzer -Path "$root\Private" -Severity @('Error', 'Warning') -Recurse -Verbose:$false
if ($saResults) {
$saResults | Format-Table
Write-Error -Message 'One or more Script Analyzer errors/warnings where found. Build cannot continue!'
}
}
# Run our test to make sure everything is in line
task Test {
$testResults = Invoke-Pester -Path "$root\test\PowerRails.test.ps1"
if ($testResults.FailedCount -gt 0) {
$testResults | Format-List
Write-Error -Message 'One or more Pester tests failed. Build cannot continue!'
}
}
# Run a deployment script after appropriate tests are passed
task Deploy -depends Analyze, Test {
Invoke-PSDeploy -Path "$root\test\PowerRails.psdeploy.ps1" -Force -Verbose:$VerbosePreference
}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Test/PowerRails.test.ps1
|
PowerRails.test.ps1
|
# Determine our script root
$root = Split-Path $PSScriptRoot -Parent
# Load module via definition
Import-Module $root\PowerRails.psd1 -Force
# Run our module tests
InModuleScope PowerRails {
# Check that modules are installed
Describe 'Load PowerRails' {
It 'PowerRails modules is loaded' {
$powerRailsModule = get-module PowerRails -all
$powerRailsModule | Should Be $true
}
}
Describe 'New-PowerRailsItem - Validate resource files' {
# Check and grab resources
$requiredFiles = @('build.ps1', 'psakeBuild.ps1', 'Template.ps1', 'Template.psm1', 'Template.psd1', 'Template.psdeploy.ps1', 'Template.tests.ps1')
$testFolder = get-item $PSScriptRoot
$parentFolder = $testFolder.parent.FullName + '\Resources\'
foreach ($file in $requiredFiles) {
$checkFile = $parentFolder + $file
It "Check for required resource file: $checkFile" {
Test-Path $checkFile | Should Be $true
}
}
}
Describe 'Module - Runs successfully' {
# Define name and where our module will be created
$TestPath = 'TestDrive:\'
$newModuleName = 'TestModule'
$moduleFullPath = $TestPath + $newModuleName
$moduleFile = $moduleFullPath +"\$newModuleName.psd1"
It "Generate module: $newModuleName" {
{ New-PowerRailsItem -Name $newModuleName -Path $TestPath } | Should Not throw
}
It "Created module folder" {
test-path $moduleFullPath | Should Be $true
}
# Verify that the resources were copied over
$exclude = @('template.ps1') # Script specific file
foreach ($file in $requiredFiles) {
if ($exclude -notcontains $file) {
$newName = $file.replace('Template', $newModuleName)
$checkFile = $moduleFullPath +"\"+ $newName
It "Check generated file: $checkFile" {
Test-Path $checkFile | Should Be $true
}
}
}
}
Describe 'Script - Runs successfully' {
# Define name and where our script will be created
$TestPath = 'TestDrive:\'
$newScriptName = 'TestScript'
$scriptFullPath = $TestPath + $newScriptName
It "Generate script: $scriptFullPath" {
{ New-PowerRailsItem -Name $newScriptName -Type 'script' -Path $TestPath } | Should Not throw
}
It "Created script folder" {
test-path $scriptFullPath | Should Be $true
}
# Verify that the resources were copied over
$exclude = @('template.psm1', 'template.psd1') # module specific file
foreach ($file in $requiredFiles) {
if ($exclude -notcontains $file) {
$newName = $file.replace('Template', $newScriptName)
$checkFile = $scriptFullPath +"\"+ $newName
It "Check generated file: $checkFile" {
Test-Path $checkFile | Should Be $true
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Public/New-PowerRailsItem.ps1
|
New-PowerRailsItem.ps1
|
function New-PowerRailsItem {
<#
.SYNOPSIS
Scaffold a powershell module or script based on best practices.
.DESCRIPTION
Scaffold a powershell module or script based on best practices.
A folder will be created with required files to get you going.
.PARAMETER name
Name of your module or script.
.PARAMETER type
Type of structure you want scaffolded. Script or module. Defaults to module.
.PARAMETER path
Path where you want the new folder to be created. Defaults to current path.
.PARAMETER useTabs
A switch parameter to change 2 space tabs into a tab character.
.EXAMPLE
Create a new module
New-PowerRailsItem -name 'MyAwesomeModule' -type 'module' -path 'c:\scripts'
Create a new script
New-PowerRailsItem -name 'MyStandAloneScript' -type 'script' -path 'c:\code'
#>
[CmdletBinding(SupportsShouldProcess = $true)]
Param(
[Parameter(Mandatory=$true)][string]$name,
[ValidateSet('script', 'module')][string]$type='module',
[string]$path=(Get-Location).path,
[switch]$useTabs
)
Begin {
$ErrorActionPreference = "STOP"
# Import utility functions and variables
. "$PSScriptRoot\utilities.ps1"
# Collect some info to use in our generated files
$date = get-Date
$author = $Env:username
$modulePath = "{0}\{1}" -f $path, $name
# Write our starting output
write-PowerRailsStatus -line "Generating new module: $name" -type 'header'
}
Process {
try {
# Create directory if needed
if (!(test-path $modulePath)) {
Write-PowerRailsStatus -line "Generating module path: $modulePath"
new-item -name $name -path $Path -type 'Directory' | Out-Null
}
# Determine folders and files needed
# TODO : Removed '.editorconfig', from the list since powershell online gallery doesn't support it. Add back when bug is fixed
if ($type -eq 'module') {
$requiredFiles = @('build.ps1', 'psakeBuild.ps1', 'Template.psm1', 'Template.psd1', 'Template.psdeploy.ps1', 'Template.tests.ps1')
$fileExtension = 'psm1'
} else {
$requiredFiles = @('build.ps1', 'psakeBuild.ps1', 'Template.ps1', 'Template.psdeploy.ps1', 'Template.tests.ps1')
$fileExtension = 'ps1'
}
$testFolder = get-item $PSScriptRoot
$parentFolder = $testFolder.parent.FullName + '\Resources\'
# Create each file based on our resources
foreach ($file in $requiredFiles) {
$filePath = Join-Path $parentFolder $file # Our resource template
$content = get-Content $filePath # Content from the template file
$newFile = Join-Path $modulePath $file # Our new file
# Replace spaces with tabs when switch is passed
if ($useTabs) {
$content = $content.Replace($spaces, $tabs)
}
# Perform the proper action for each file
switch ($file) {
'build.ps1' {
# Generate file
Write-PowerRailsStatus "Generating $newFile"
$content | out-file $newFile -Encoding 'UTF8'
}
'.editorconfig' {
# Fill in indent style and size
Write-PowerRailsStatus "Generating $newFile"
# determine values for editorconfig
if ($useTabs) {
$style = 'tab'
} else {
$style = 'space'
}
# fill in required values
$content = $content.replace('$indent_style', $style)
# Generate file
$content | out-file $newFile -encoding 'UTF8'
}
'psakeBuild.ps1' {
# Replace name in content and output to new file
Write-PowerRailsStatus "Generating $newFile"
$content = $content.replace('$name', $Name)
$content = $content.replace('$fileType', $fileExtension)
# Generate file
$content | out-file $newFile -encoding 'UTF8'
}
'Template.psd1' {
# Generate file name
$newFileName = $newFile.replace('Template', $name)
Write-PowerRailsStatus "Generating $newFileName"
# Rename name and author
$content = $content.replace('$Name', $Name)
$content = $content.replace('$author', $Author)
# Output file
$content | out-file $newFileName -encoding 'UTF8'
}
'Template.psm1' {
# Generate file name
$newFileName = $newFile.replace('Template', $name)
Write-PowerRailsStatus "Generating $newFileName"
# Rename name, author & date
$content = $content.replace('$name', $Name)
$content = $content.replace('$author', $Author)
$content = $content.replace('$date', $date)
# Output file
$content | out-file $newFileName -encoding 'UTF8'
}
'Template.ps1' {
# Generate file name
$newFileName = $newFile.replace('Template', $name)
Write-PowerRailsStatus "Generating $newFileName"
# Rename name, author & date
$content = $content.replace('$name', $Name)
$content = $content.replace('$author', $Author)
$content = $content.replace('$date', $date)
# Output file
$content | out-file $newFileName -encoding 'UTF8'
}
'Template.tests.ps1' {
# Generate file name
$newFileName = $newFile.replace('Template', $name)
Write-PowerRailsStatus "Generating $newFileName"
# Construct our module path so that we import it in our tests
$fileName = $Name + ".$fileExtension"
$content = $content.replace('$name', $name)
$content = $content.replace('$fileName', $fileName)
# Output file
$content | out-file $newFileName -encoding 'UTF8'
}
'Template.psdeploy.ps1' {
# Generate file name
$newFileName = $newFile.replace('Template', $name)
Write-PowerRailsStatus "Generating $newFileName"
# Replace variables name
$content = $content.replace('$module', $name)
# Output file
$content | out-file $newFileName -encoding 'UTF8'
}
}
}
} catch {
$errorMessage = $_.toString()
Write-PowerRailsStatus -line $errorMessage -type 'error'
}
}
End {
# Empty
}
}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Public/Utilities.ps1
|
Utilities.ps1
|
function Write-PowerRailsStatus {
<#
.SYNOPSIS
Write PowerRails progress to host.
.DESCRIPTION
Write PowerRails progress to host. This function just makes the output a little prettier.
.PARAMETER line
The text that you want to appear in your console
.PARAMETER type
The type of output you want. This changes the display of line accordingly.
Validate entries are header, info, task, success, error & warning.
.PARAMETER depth
Controls how deep the text is indented. For display purposes.
.PARAMETER spaces
Constrol what is used as the indentation characters.
.EXAMPLE
Write-PowerRailsStatus -line 'Hello world!' -type 'header'
#>
param(
[Parameter(Mandatory=$true)][string]$line,
[ValidateSet('header', 'info', 'task', 'success', 'error', 'warning')][string]$type='info',
[int]$depth=1,
$spaces=" ",
$tabs = " "
)
# Determine starting point.
$seperator = $spaces * $depth
# Switch between type that is required
switch ($type) {
'header' {
Write-Host $line
Write-Host ("=" * $line.length) -ForegroundColor:Green
Write-Host "`n"
}
'info' {
Write-Host "$seperator * " -ForegroundColor:DarkGray -NoNewline
Write-Host $line "`n"
}
'task' {
# This option exists so that we can attach some cool animations to the output for something that is long running.
Write-Host "$seperator" -ForegroundColor:DarkGray -NoNewline
Write-Host $line -NoNewline
}
'success' {
Write-Host "$seperator Success! - " -ForegroundColor:Green -NoNewline
Write-Host $line "`n"
}
'warning' {
Write-Host "$seperator ! " -ForegroundColor:Yellow -NoNewline
Write-Host $line "`n"
}
'error' {
Write-Host "$seperator X " -ForegroundColor:Red -NoNewline
Write-Host $line "`n"
}
default {
Write-Host $seperator $line
}
}
}
# Helpers for generator
$spaces = " "
$tabs = " "
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Resources/Template.psdeploy.ps1
|
Template.psdeploy.ps1
|
# Deploy the script to the c:\scripts directory
Deploy 'Copy to scripts folder' {
By Filesystem {
FromSource '.\'
To "c:\scripts\$module"
Tagged Prod
}
}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Resources/Template.ps1
|
Template.ps1
|
<#
.SYNOPSIS
Write a synopsis here
.DESCRIPTION
Write a description here
.EXAMPLE
C:\PS> ./$name.ps1
.NOTES
Author: $author
CreateDate: $date
#>
# Generated command for testing. Can be removed
Write-Output "Reporting from $name!"
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Resources/psakeBuild.ps1
|
psakeBuild.ps1
|
properties {
$script = "$PSScriptRoot\$name.$fileType"
}
# Default task includes Analyzing and Testing of script
task default -depends Analyze, Test
# Analyze by running Invoke-ScriptAnalyzer. Check script against best known practices
task Analyze {
$saResults = Invoke-ScriptAnalyzer -Path $script -Severity @('Error', 'Warning') -Recurse -Verbose:$false
if ($saResults) {
$saResults | Format-Table
Write-Error -Message 'One or more Script Analyzer errors/warnings where found. Build cannot continue!'
}
}
# Run our test to make sure everything is in line
task Test {
$testResults = Invoke-Pester -Path $PSScriptRoot -PassThru
if ($testResults.FailedCount -gt 0) {
$testResults | Format-List
Write-Error -Message 'One or more Pester tests failed. Build cannot continue!'
}
}
# Run a deployment script after appropriate tests are passed
task Deploy -depends Analyze, Test {
Invoke-PSDeploy -Path '.\$name.psdeploy.ps1' -Force -Verbose:$VerbosePreference
}
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Resources/build.ps1
|
build.ps1
|
[cmdletbinding()]
param(
[string[]]$Task = 'default' # This task is defined in psakeBuild. We are just setting a default here.
)
# Verify that we have PackageManagement module installed
if(!(Get-Command Install-Module)) {
throw 'PackageManagement is not installed. You need V5 or https://www.microsoft.com/en-us/download/details.aspx?id=51451'
}
# Verify that our testing utilities are installed.
if (!(Get-Module -Name Pester -ListAvailable)) {
Install-Module -Name Pester
}
if (!(Get-Module -Name psake -ListAvailable)) {
Install-Module -Name Psake
}
if (!(Get-Module -Name PSDeploy -ListAvailable)) {
Install-Module -Name PSDeploy
}
if (!(Get-Module -Name PSScriptAnalyzer -ListAvailable)) {
Install-Module -Name PSScriptAnalyzer
}
# Run our test
Invoke-psake -buildFile "$PSScriptRoot\psakeBuild.ps1" -taskList $Task -Verbose:$VerbosePreference
|
PowerShellCorpus/PowerShellGallery/PowerRails/0.0.9/Resources/Template.tests.ps1
|
Template.tests.ps1
|
# Pester testing. https://github.com/pester/Pester/wiki
$myScript = "$PSScriptRoot\$fileName"
Describe 'Unit Tests' {
Context 'Basic Validation' {
it 'Should run successfully' {
if ($myScript -like '*ps1') {
$run = invoke-expression $myScript
} else {
import-module $myScript
$runCommand = test-$name
}
$runCommand | Should Match "Reporting from"
}
}
}
|
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/EditorCommands.ps1
|
EditorCommands.ps1
|
# Example Editor Commands for Reference
# Register-EditorCommand `
# -Name 'VSCodeExtensions.OpenEditorProfile' `
# -DisplayName 'Open Editor Profile' `
# -SuppressOutput `
# -ScriptBlock {
# param([Microsoft.PowerShell.EditorServices.Extensions.EditorContext]$context)
# If (!(Test-Path -Path $Profile)) { New-Item -Path $Profile -ItemType File }
# $psEditor.Workspace.OpenFile($Profile)
# }
# Register-EditorCommand `
# -Name 'VSCodeExtensions.OpenProfileList' `
# -DisplayName 'Open Profile from List (Current User)' `
# -SuppressOutput `
# -ScriptBlock {
# param([Microsoft.PowerShell.EditorServices.Extensions.EditorContext]$context)
# $Current = Split-Path -Path $profile -Leaf
# $List = @($Current,'Microsoft.VSCode_profile.ps1','Microsoft.PowerShell_profile.ps1','Microsoft.PowerShellISE_profile.ps1','Profile.ps1') | Select-Object -Unique
# $Choices = [System.Management.Automation.Host.ChoiceDescription[]] @($List)
# $Selection = $host.ui.PromptForChoice('Please Select a Profile', '(Current User)', $choices,'0')
# $Name = $List[$Selection]
# $ProfileDir = Split-Path $Profile -Parent
# $ProfileName = Join-Path -Path $ProfileDir -ChildPath $Name
# If (!(Test-Path -Path $ProfileName)) { New-Item -Path $ProfileName -ItemType File }
# $psEditor.Workspace.OpenFile($ProfileName)
# }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.