full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/Load.ps1
|
Load.ps1
|
$PreLoad = {
Import-Module (Join-Path $PluginPath 'pscolor\src\module\pscolor.psm1') -Global -Force
}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$Unload = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/Plugin.ps1
|
Plugin.ps1
|
# Nothing
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/private/Get-CallerPreference.ps1
|
Get-CallerPreference.ps1
|
function Get-CallerPreference {
<#
.Synopsis
Fetches "Preference" variable values from the caller's scope.
.DESCRIPTION
Script module functions do not automatically inherit their caller's variables, but they can be
obtained through the $PSCmdlet variable in Advanced Functions. This function is a helper function
for any script module Advanced Function; by passing in the values of $ExecutionContext.SessionState
and $PSCmdlet, Get-CallerPreference will set the caller's preference variables locally.
.PARAMETER Cmdlet
The $PSCmdlet object from a script module Advanced Function.
.PARAMETER SessionState
The $ExecutionContext.SessionState object from a script module Advanced Function. This is how the
Get-CallerPreference function sets variables in its callers' scope, even if that caller is in a different
script module.
.PARAMETER Name
Optional array of parameter names to retrieve from the caller's scope. Default is to retrieve all
Preference variables as defined in the about_Preference_Variables help file (as of PowerShell 4.0)
This parameter may also specify names of variables that are not in the about_Preference_Variables
help file, and the function will retrieve and set those as well.
.EXAMPLE
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Imports the default PowerShell preference variables from the caller into the local scope.
.EXAMPLE
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState -Name 'ErrorActionPreference','SomeOtherVariable'
Imports only the ErrorActionPreference and SomeOtherVariable variables into the local scope.
.EXAMPLE
'ErrorActionPreference','SomeOtherVariable' | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
Same as Example 2, but sends variable names to the Name parameter via pipeline input.
.INPUTS
String
.OUTPUTS
None. This function does not produce pipeline output.
.LINK
about_Preference_Variables
#>
[CmdletBinding(DefaultParameterSetName = 'AllVariables')]
param (
[Parameter(Mandatory = $true)]
[ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })]
$Cmdlet,
[Parameter(Mandatory = $true)]
[System.Management.Automation.SessionState]$SessionState,
[Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)]
[string[]]$Name
)
begin {
$filterHash = @{}
}
process {
if ($null -ne $Name)
{
foreach ($string in $Name)
{
$filterHash[$string] = $true
}
}
}
end {
# List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0
$vars = @{
'ErrorView' = $null
'FormatEnumerationLimit' = $null
'LogCommandHealthEvent' = $null
'LogCommandLifecycleEvent' = $null
'LogEngineHealthEvent' = $null
'LogEngineLifecycleEvent' = $null
'LogProviderHealthEvent' = $null
'LogProviderLifecycleEvent' = $null
'MaximumAliasCount' = $null
'MaximumDriveCount' = $null
'MaximumErrorCount' = $null
'MaximumFunctionCount' = $null
'MaximumHistoryCount' = $null
'MaximumVariableCount' = $null
'OFS' = $null
'OutputEncoding' = $null
'ProgressPreference' = $null
'PSDefaultParameterValues' = $null
'PSEmailServer' = $null
'PSModuleAutoLoadingPreference' = $null
'PSSessionApplicationName' = $null
'PSSessionConfigurationName' = $null
'PSSessionOption' = $null
'ErrorActionPreference' = 'ErrorAction'
'DebugPreference' = 'Debug'
'ConfirmPreference' = 'Confirm'
'WhatIfPreference' = 'WhatIf'
'VerbosePreference' = 'Verbose'
'WarningPreference' = 'WarningAction'
}
foreach ($entry in $vars.GetEnumerator()) {
if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and
($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name))) {
$variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key)
if ($null -ne $variable) {
if ($SessionState -eq $ExecutionContext.SessionState) {
Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
}
else {
$SessionState.PSVariable.Set($variable.Name, $variable.Value)
}
}
}
}
if ($PSCmdlet.ParameterSetName -eq 'Filtered') {
foreach ($varName in $filterHash.Keys) {
if (-not $vars.ContainsKey($varName)) {
$variable = $Cmdlet.SessionState.PSVariable.Get($varName)
if ($null -ne $variable)
{
if ($SessionState -eq $ExecutionContext.SessionState)
{
Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
}
else
{
$SessionState.PSVariable.Set($variable.Name, $variable.Value)
}
}
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/private/Write-FileLength.ps1
|
Write-FileLength.ps1
|
# Helper method to write file length in a more human readable format
function Write-FileLength
{
param ($length)
if ($length -eq $null)
{
return ""
}
elseif ($length -ge 1GB)
{
return ($length / 1GB).ToString("F") + 'GB'
}
elseif ($length -ge 1MB)
{
return ($length / 1MB).ToString("F") + 'MB'
}
elseif ($length -ge 1KB)
{
return ($length / 1KB).ToString("F") + 'KB'
}
return $length.ToString() + ' '
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/other/PreLoad.ps1
|
PreLoad.ps1
|
if (-not $Script:ModulePath) {
$ModulePath = Split-Path $script:MyInvocation.MyCommand.Path
}
# This is used for the PSColor functions
$Script:PSColor = @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Cyan'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html)$' }
Executable = @{ Color = 'Red'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg)$' }
Text = @{ Color = 'Yellow'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown)$' }
Compressed = @{ Color = 'Green'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Cyan'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
$script:showHeader=$true
# For each type we will 'colorizing' create an entry to map an action
$script:PSColorTypeMap = @{
'System.IO.DirectoryInfo' = {
if ($script:showHeader) {
Write-Host
Write-Host " Directory: " -noNewLine
Write-Host " $(pwd)`n" -foregroundcolor "Green"
Write-Host "Mode LastWriteTime Length Name"
Write-Host "---- ------------- ------ ----"
$script:showHeader=$false
}
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Directory.Color
}
'System.IO.FileInfo' = {
if ($script:showHeader) {
Write-Host
Write-Host " Directory: " -noNewLine
Write-Host " $(pwd)`n" -foregroundcolor "Green"
Write-Host "Mode LastWriteTime Length Name"
Write-Host "---- ------------- ------ ----"
$script:showHeader=$false
}
if (([regex]::new($Script:PSColor.File.Hidden.Pattern,[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)).IsMatch($_.Name)) {
# Match Hidden
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Hidden.Color
}
elseif (([regex]::new($Script:PSColor.File.Code.Pattern,[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)).IsMatch($_.Name)){
# Match code
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Code.Color
}
elseif (([regex]::new($Script:PSColor.File.Executable.Pattern,[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)).IsMatch($_.Name)){
# Match executable
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Executable.Color
}
elseif (([regex]::new($Script:PSColor.File.Text.Pattern,[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)).IsMatch($_.Name)){
# Match text
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Text.Color
}
elseif (([regex]::new($Script:PSColor.File.Compressed.Pattern,[System.Text.RegularExpressions.RegexOptions]::IgnoreCase)).IsMatch($_.Name)){
# Match compressed
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Compressed.Color
}
else {
# Default
Write-host ("{0,-7} {1,25} {2,10} {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), (Write-FileLength $_.length), $_.name) -foregroundcolor $Script:PSColor.File.Default.Color
}
}
'System.ServiceProcess.ServiceController' = {
if($script:showHeader) {
Write-Host
Write-Host "Status Name DisplayName"
$script:showHeader=$false
}
if ($_.Status -eq 'Stopped') {
Write-host ("{0,-8}" -f 'Stopped') -foregroundcolor $Script:PSColor.Service.Stopped.Color -noNewLine
}
elseif ($_.Status -eq 'Running') {
Write-host ("{0,-8}" -f 'Running') -foregroundcolor $Script:PSColor.Service.Running.Color -noNewLine
}
else {
Write-host ("{0,-8}" -f $_.Status) -foregroundcolor $Script:PSColor.Service.Default.Color -noNewLine
}
Write-host (" {0,-18} {1,-39}" -f (Write-CutString $_.Name 18), (Write-CutString $_.DisplayName 38)) -foregroundcolor "white"
}
'Microsoft.Powershell.Commands.MatchInfo' = {
Write-host $_.RelativePath($pwd) -foregroundcolor $Script:PSColor.Match.Path.Color -noNewLine
Write-host ':' -foregroundcolor $Script:PSColor.Match.Default.Color -noNewLine
Write-host $_.LineNumber -foregroundcolor $Script:PSColor.Match.LineNumber.Color -noNewLine
Write-host ':' -foregroundcolor $Script:PSColor.Match.Default.Color -noNewLine
Write-host $_.Line -foregroundcolor $Script:PSColor.Match.Line.Color
}
'OMP.PluginStatus' = {
if($script:showHeader) {
Write-Host
Write-Host "Name Loaded"
Write-Host "---- ------"
$script:showHeader=$false
}
Write-host ("{0,-18}" -f (Write-CutString $_.Name 18)) -foregroundcolor "white" -noNewLine
if ($_.Loaded) {
Write-host ("{0,-8}" -f $_.Loaded) -foregroundcolor 'Green'
}
else {
Write-host ("{0,-8}" -f $_.Loaded) -foregroundcolor 'Red'
}
}
}
# We define this for later use in out-default to reduce processing a teeny bit
$Script:PSColorTypeMapKeys = ($script:PSColorTypeMap).Keys
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/other/PostLoad.ps1
|
PostLoad.ps1
|
# Nothing
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/public/Add-OMPColorAction.ps1
|
Add-OMPColorAction.ps1
|
Function Add-OMPColorAction {
<#
.SYNOPSIS
Adds a new colorization action to take against a particular output type.
.DESCRIPTION
Adds a new colorization action to take against a particular output type.
.PARAMETER Type
Object type to colorize.
.PARAMETER Action
Action to take against the object type.
.EXAMPLE
PS> Add-OMPColorAction -Type 'System.IO.DirectoryInfo' -Action { Write-FileInfo $_ }
.NOTES
Author: Zachary Loeber
Version History
1.0.0 - Initial release
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true)]
[string]$Type,
[Parameter(Position = 1, Mandatory = $true)]
[ScriptBlock]$Action
)
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
if ($Script:PSColorTypeMapKeys -notcontains $Type) {
try {
$script:PSColorTypeMap[$Type] = $Action
$Script:PSColorTypeMapKeys = ($script:PSColorTypeMap).Keys
}
catch {
throw "Unable to add PSColorType Map for $Type"
}
}
else {
Write-Output "$Type already exists as a setting. Doing nothing."
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/public/Set-OMPPSColor.ps1
|
Set-OMPPSColor.ps1
|
Function Set-OMPPSColor {
<#
.SYNOPSIS
Sets the PSColor settings.
.DESCRIPTION
Sets the PSColor settings.
.PARAMETER Setting
Hash containging the PSColor settings.
.EXAMPLE
PS> Set-OMPPSColor -Setting @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Green'}
Reparse = @{ Color = 'Magenta'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html|Dockerfile|gradle|pp|packergitignore|gitattributes|go|)$' }
Executable = @{ Color = 'Green'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|sh|fsx|)$' }
Text = @{ Color = 'Cyan'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown|properties|json|todo)$' }
Compressed = @{ Color = 'Yellow'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Green'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
Set the PSColor settings to the hash
.NOTES
Author: Zachary Loeber
Version History
1.0.0 - Initial release
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true)]
[hashtable]$Setting
)
$Script:PSColor = $Setting.Clone()
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/public/Write-CutString.ps1
|
Write-CutString.ps1
|
function Write-CutString {
<#
.Synopsis
Helper method for simulating ellipsis in PSColor modified output
.DESCRIPTION
Helper method for simulating ellipsis in PSColor modified output
.PARAMETER Message
Message to modify
.PARAMETER Length
Length to limit output string to before inserting '...'
.EXAMPLE
Write-host ("{0,-18}" -f (Write-CutString $Mystring.Name 18)) -foregroundcolor "white" -noNewLine
.LINK
https://www.github.com/zloeber/OhMyPsh
.NOTES
None
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[string]$Message,
[Parameter(Position = 1)]
[int]$Length
)
if ($message.length -gt $length) {
return $message.SubString(0, $length-3) + '...'
}
return $message
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/public/Out-Default.ps1
|
Out-Default.ps1
|
function Out-Default {
<#
.SYNOPSIS
Proxy Out-Default command required for colorization of console output.
.DESCRIPTION
Proxy Out-Default command required for colorization of console output.
.PARAMETER Transcript
TBD
.PARAMETER InputObject
TBD
#>
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=113362', RemotingCapability='None')]
param(
[switch]
${Transcript},
[Parameter(Position=0, ValueFromPipeline=$true)]
[psobject]
${InputObject})
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Core\Out-Default', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline()
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process {
try {
# Our snazzy hook for colorizing the output...
if ($_ -ne $null) {
if ($Script:PSColorTypeMapKeys -contains ($_.pstypenames)[0]) {
.([scriptblock]::create($Script:PSColorTypeMap[$_.pstypenames[0]]))
$_ = $null
}
else {
$steppablePipeline.Process($_)
}
}
else {
$steppablePipeline.Process($_)
}
} catch {
throw
}
}
end {
try {
write-host ""
$script:showHeader=$true
$steppablePipeline.End()
}
catch {
throw
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/public/Get-OMPColorAction.ps1
|
Get-OMPColorAction.ps1
|
Function Get-OMPColorAction {
<#
.SYNOPSIS
Get one or all of the OMP color actions.
.DESCRIPTION
Get one or all of the OMP color actions.
.PARAMETER Name
Name of the setting
.EXAMPLE
PS> Get-OMPColorAction -Name 'SomeTypeName'
Shows the action assigned to SomeTypeName
.NOTES
Author: Zachary Loeber
Version History
1.0.0 - Initial release
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, ValueFromPipeline = $true)]
[String]$Name
)
Process {
if ([string]::IsNullOrEmpty($Name)) {
$Script:PSColorTypeMap
}
else {
if ($Script:PSColorTypeMapKeys -contains $Name) {
$Script:PSColorTypeMap[$Name]
}
else {
Write-Error "Typename of $Name does not exist!"
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/pscolor/src/module/src/public/Remove-OMPColorAction.ps1
|
Remove-OMPColorAction.ps1
|
Function Remove-OMPColorAction {
<#
.SYNOPSIS
Removes a colorization action.
.DESCRIPTION
Removes a colorization action.
.PARAMETER Name
Type name to remove
.EXAMPLE
PS> Remove-OMPColorAction -Name 'Custom.Type'
.NOTES
Author: Zachary Loeber
Version History
1.0.0 - Initial release
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, Mandatory = $true)]
[string]$Name
)
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
if ($Script:PSColorTypeMapKeys -contains $Name) {
($Script:PSColorTypeMap).Remove($Name)
$Script:PSColorTypeMapKeys = ($script:PSColorTypeMap).Keys
}
else {
Write-Error "Typename of $Name does not exist!"
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/o365/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$Unload = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/o365/src/Connect-ExchangeMFA.ps1
|
Connect-ExchangeMFA.ps1
|
# https://www.powershellgallery.com/packages/Load-ExchangeMFA/1.1/Content/Load-ExchangeMFA.ps1
Function Global:Connect-ExchangeMFA {
function Install-ClickOnce {
[CmdletBinding()]
Param(
$Manifest = "https://cmdletpswmodule.blob.core.windows.net/exopsmodule/Microsoft.Online.CSE.PSModule.Client.application",
#AssertApplicationRequirements
$ElevatePermissions = $true
)
Try {
Add-Type -AssemblyName System.Deployment
Write-Verbose "Start installation of ClockOnce Application $Manifest "
$RemoteURI = [URI]::New( $Manifest , [UriKind]::Absolute)
if (-not $Manifest)
{
throw "Invalid ConnectionUri parameter '$ConnectionUri'"
}
$HostingManager = New-Object System.Deployment.Application.InPlaceHostingManager -ArgumentList $RemoteURI , $False
#register an event to trigger custom event (yep, its a hack)
Register-ObjectEvent -InputObject $HostingManager -EventName GetManifestCompleted -Action {
new-event -SourceIdentifier "ManifestDownloadComplete"
} | Out-Null
#register an event to trigger custom event (yep, its a hack)
Register-ObjectEvent -InputObject $HostingManager -EventName DownloadApplicationCompleted -Action {
new-event -SourceIdentifier "DownloadApplicationCompleted"
} | Out-Null
#get the Manifest
$HostingManager.GetManifestAsync()
#Waitfor up to 5s for our custom event
$event = Wait-Event -SourceIdentifier "ManifestDownloadComplete" -Timeout 5
if ($event ) {
$event | Remove-Event
Write-Verbose "ClickOnce Manifest Download Completed"
$HostingManager.AssertApplicationRequirements($ElevatePermissions)
#todo :: can this fail ?
#Download Application
$HostingManager.DownloadApplicationAsync()
#register and wait for completion event
# $HostingManager.DownloadApplicationCompleted
$event = Wait-Event -SourceIdentifier "DownloadApplicationCompleted" -Timeout 15
if ($event ) {
$event | Remove-Event
Write-Verbose "ClickOnce Application Download Completed"
} else {
Write-error "ClickOnce Application Download did not complete in time (15s)"
}
} else {
Write-error "ClickOnce Manifest Download did not complete in time (5s)"
}
#Clean Up
} finally {
#get rid of our eventhandlers
Get-EventSubscriber|? {$_.SourceObject.ToString() -eq 'System.Deployment.Application.InPlaceHostingManager'} | Unregister-Event
}
}
<# Simple Install Check
#>
function Get-ClickOnce {
[CmdletBinding()]
Param(
$ApplicationName = "Microsoft Exchange Online Powershell Module"
)
$InstalledApplicationNotMSI = Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall | foreach-object {Get-ItemProperty $_.PsPath}
return $InstalledApplicationNotMSI | ? { $_.displayname -match $ApplicationName } | Select-Object -First 1
}
Function Test-ClickOnce {
[CmdletBinding()]
Param(
$ApplicationName = "Microsoft Exchange Online Powershell Module"
)
return ( (Get-ClickOnce -ApplicationName $ApplicationName) -ne $null)
}
<# Simple UnInstall
#>
function Uninstall-ClickOnce {
[CmdletBinding()]
Param(
$ApplicationName = "Microsoft Exchange Online Powershell Module"
)
$app=Get-ClickOnce -ApplicationName $ApplicationName
#Deinstall One to remove all instances
if ($App) {
$selectedUninstallString = $App.UninstallString
#Seperate cmd from parameters (First Space)
$parts = $selectedUninstallString.Split(' ', 2)
Start-Process -FilePath $parts[0] -ArgumentList $parts[1] -Wait
#ToDo : Automatic press of OK
#Start-Sleep 5
#$wshell = new-object -com wscript.shell
#$wshell.sendkeys("`"OK`"~")
$app=Get-ClickOnce -ApplicationName $ApplicationName
if ($app) {
Write-verbose 'De-installation aborted'
#return $false
} else {
Write-verbose 'De-installation completed'
#return $true
}
} else {
#return $null
}
}
Function Load-ExchangeMFAModule {
[CmdletBinding()]
Param ()
$Modules = @(Get-ChildItem -Path "$($env:LOCALAPPDATA)\Apps\2.0" -Filter "Microsoft.Exchange.Management.ExoPowershellModule.manifest" -Recurse )
if ($Modules.Count -ne 1 ) {
throw "No or Multiple Modules found : Count = $($Modules.Count )"
} else {
$ModuleName = Join-path $Modules[0].Directory.FullName "Microsoft.Exchange.Management.ExoPowershellModule.dll"
Write-Verbose "Start Importing MFA Module"
Import-Module -FullyQualifiedName $ModuleName -Force
$ScriptName = Join-path $Modules[0].Directory.FullName "CreateExoPSSession.ps1"
if (Test-Path $ScriptName) {
return $ScriptName
<#
# Load the script to add the additional commandlets (Connect-EXOPSSession)
# DotSourcing does not work from inside a function (. $ScriptName)
#Therefore load the script as a dynamic module instead
$content = Get-Content -Path $ScriptName -Raw -ErrorAction Stop
#BugBug >> $PSScriptRoot is Blank :-(
<#
$PipeLine = $Host.Runspace.CreatePipeline()
$PipeLine.Commands.AddScript(". $scriptName")
$r = $PipeLine.Invoke()
#Err : Pipelines cannot be run concurrently.
$scriptBlock = [scriptblock]::Create($content)
New-Module -ScriptBlock $scriptBlock -Name "Microsoft.Exchange.Management.CreateExoPSSession.ps1" -ReturnResult -ErrorAction SilentlyContinue
#>
} else {
throw "Script not found"
return $null
}
}
}
if ((Test-ClickOnce -ApplicationName "Microsoft Exchange Online Powershell Module" ) -eq $false) {
Install-ClickOnce -Manifest "https://cmdletpswmodule.blob.core.windows.net/exopsmodule/Microsoft.Online.CSE.PSModule.Client.application"
}
#Load the Module
$script = Load-ExchangeMFAModule -Verbose
#Dot Source the associated script
. $Script
#make sure the Exchange session uses the same proxy settings as IE/Edge
$ProxySetting = New-PSSessionOption -ProxyAccessType IEConfig
Import-Module (Connect-EXOPSSession -PSSessionOption $ProxySetting) -Global
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/o365/src/Connect-SkypeOnline.ps1
|
Connect-SkypeOnline.ps1
|
function Global:Connect-SkypeOnline{
[CmdLetBinding()]
param()
try {
Import-Module SkypeOnlineConnector
$proxysettings = New-PSSessionOption -ProxyAccessType IEConfig
$upn = ([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.userprincipalname
$creds = Get-Credential -UserName $upn -Message "Enter password for $upn"
$session = New-CsOnlineSession -Credential $creds -Verbose -SessionOption $proxysettings
Import-Module (Import-PSSession $session -AllowClobber) -Global
}
catch {
throw
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/o365/src/Connect-ExchangeLocal.ps1
|
Connect-ExchangeLocal.ps1
|
Function Global:Connect-ExchangeLocal([string]$Server = "" ) {
try {
$URI = 'http://' + $Server + '/PowerShell/'
# $proxysettings = New-PSSessionOption -ProxyAccessType IEConfig
$upn = ([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.userprincipalname
$creds = Get-Credential -UserName $upn -Message "Enter password for $upn"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $URI -Credential $creds -Authentication Kerberos -AllowRedirection -Verbose #-SessionOption $proxysettings
Import-Module (Import-PSSession $session -AllowClobber) -Global
#Write-Output "`n`n`nDon't forget to 'Remove-PSSession `$session' when you're done"
}
catch {
throw
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/o365/src/Connect-ExchangeOnline.ps1
|
Connect-ExchangeOnline.ps1
|
Function Global:Connect-ExchangeOnline {
[CmdletBinding()]
$proxysettings = New-PSSessionOption -ProxyAccessType IEConfig
$upn = ([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.userprincipalname
$creds = Get-Credential -UserName $upn -Message "Enter password for $upn"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $creds -Authentication Basic -AllowRedirection -SessionOption $proxysettings
$yes = New-Object System.Management.Automation.Host.ChoiceDescription '&Yes',''
$no = New-Object System.Management.Automation.Host.ChoiceDescription '&No',''
$choices = [System.Management.Automation.Host.ChoiceDescription[]]($no,$yes)
$result = $Host.UI.PromptForChoice('Prefix Commands','Do you want to prefix all imported commands with o365 (useful if you are accessing both on premise and cloud environments?',$choices,0)
$AddPrefix = ($result -eq $true)
$ImportParam = @{}
If ( $AddPrefix ) {
$ImportParam.Prefix = 'o365'
}
Import-Module (Import-PSSession $session @ImportParam -AllowClobber) -Global
Write-Output "`n`n`nDon't forget to 'Remove-PSSession `$session' when you're done"
# If the msonline module is available then ask if we want to load it as well
if ((get-module msonline -ListAvailable) -ne $null) {
$result = $Host.UI.PromptForChoice('MSOL','Connect to MSOL as well?',$choices,0)
$MSOL = ($result -eq $true)
if ( $MSOL ) {
import-module msonline -ErrorAction SilentlyContinue
if ((get-module | Where-Object {$_.Name -eq 'msonline'}) -ne $null) {
Connect-MsolService -Credential $creds }
else {
Write-Warning 'Unable to load the MSOnline powershell module!'
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/fileutils/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$Unload = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/fileutils/src/fileutils.ps1
|
fileutils.ps1
|
# Credit Adam Driscoll
# https://github.com/adamdriscoll/PoshInternals/blob/master/PendMoves.ps1
# This can also be installed by installing the module PoshInternals
function Global:Get-PendingFileRenameOperation
{
<#
.Synopsis
Gets the pending file rename operations that will take place on the next restart.
.DESCRIPTION
Gets the pending file rename operations that will take place on the next restart. Move-FileOnReboot and Remove-FileOnReboot
can schedule these rename operations.
.EXAMPLE
Get-PendingFileRenameOperation
#>
$Renames = (Get-ItemProperty "HKLM:\System\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations).PendingFileRenameOperations
$Renames = $Renames.Split([Environment]::NewLine)
for($i = 0; $i -lt $Renames.Length; $i+=2)
{
[PSCustomObject]@{Path=$Renames[$i];Destination=$Renames[$i +1];Delete=[String]::IsNullOrEmpty($Renames[$i + 1])}
}
}
function Global:Move-FileOnReboot
{
<#
.Synopsis
Schedules a file to be moved on reboot.
.DESCRIPTION
Schedules a file to be moved on reboot. This cmdlet can move a file on reboot and optionally
replace an existing file.
.EXAMPLE
Move-FileOnReboot -Path "C:\Windows\System32\kernel32.dll" -Destination "C:\Windows\SysWow64\kernel32.dll" -ReplaceExisting
#>
[CmdletBinding()]
param(
# The source file to move.
[Parameter(Mandatory=$true)]
[IO.FileInfo]$Path,
# The destination to move the file to.
[Parameter(Mandatory=$true)]
[IO.FileInfo]$Destination,
# Specifies whether to replace an existing file.
[Parameter()]
[Switch]$ReplaceExisting
)
Begin {
$Flags = [PoshInternals.MoveFileFlags]::MOVEFILE_DELAY_UNTIL_REBOOT
if ($ReplaceExisting)
{
$flags = $flags -bor [PoshInternals.MoveFileFlags]::MOVEFILE_REPLACE_EXISTING
}
if ([PoshInternals.Kernel32]::MoveFileEx($Path, $Destination, $flags) -eq 0)
{
throw New-Object System.Win32Exception
}
}
}
function Global:Remove-FileOnReboot
{
<#
.Synopsis
Schedules a file to be deleted on reboot.
.DESCRIPTION
Schedules a file to be deleted on reboot.
.EXAMPLE
Remove-FileOnReboot -Path "C:\Windows\System32\kernel32.dll"
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[IO.FileInfo]$Path
)
Begin {
$Flags = [PoshInternals.MoveFileFlags]::MOVEFILE_DELAY_UNTIL_REBOOT
if ([PoshInternals.Kernel32]::MoveFileEx($Path, $null, $Flags) -eq 0)
{
throw New-Object System.Win32Exception
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/psdefaultparams/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {}
$Config = {
# A few example psdefaultparametervalues to start with
$Global:PSDefaultParameterValues.Clear()
#$Global:PSDefaultParameterValues.Add("*:Credential",$Cred) # Uncomment to always have -Credential be populated with $Cred
$Global:PSDefaultParameterValues.Add("Get-ChildItem:Force",$True)
#$Global:PSDefaultParameterValues.Add("Receive-Job:Keep",$True)
$Global:PSDefaultParameterValues.Add("Format-Table:AutoSize",{if ($host.Name -eq "ConsoleHost"){$true}})
#$Global:PSDefaultParameterValues.Add("Send-MailMessage:To","<emailaddress>")
#$Global:PSDefaultParameterValues.Add("Send-MailMessage:SMTPServer","mail.whatever.com")
$Global:PSDefaultParameterValues.Add("Update-Help:Module","*")
$Global:PSDefaultParameterValues.Add("Update-Help:ErrorAction","SilentlyContinue")
$Global:PSDefaultParameterValues.Add("Test-Connection:Quiet",$True)
$Global:PSDefaultParameterValues.Add("Test-Connection:Count","1")
$Global:PSDefaultParameterValues.Add('Get-Help:ShowWindow',$true)
}
$Shutdown = {
Restore-OMPOriginalPSDefaultParameter
}
$Unload = {
Restore-OMPOriginalPSDefaultParameter
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/psdefaultparams/src/Plugin.ps1
|
Plugin.ps1
|
<#
#A quick template function
function Global:Some-Function {
[CmdletBinding( )]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Name
)
Begin {
$Names = @()
}
Process {
$Names += $Name
}
End {
$Names | ForEach-Object {
$_
}
}
}
#>
<# Or an alias perhaps
Set-Alias -Name mycmd -Value cmd -option AllScope -Scope Global
#>
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/powerline/Load.ps1
|
Load.ps1
|
$PreLoad = {
Import-OMPModule 'Powerline'
}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$Unload = {
Remove-OMPModule -Name 'powerline' -PluginSafe
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/powerline/src/Plugin.ps1
|
Plugin.ps1
|
# customize git prompt display settings
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/psreadline/Load.ps1
|
Load.ps1
|
$PreLoad = {
if (-not (Test-OMPProfileSetting -Name 'PSReadlineHistoryPath')) {
try {
Add-OMPProfileSetting -Name 'PSReadlineHistoryPath' -Value (Join-Path (Split-Path $Profile) '.powershell.history')
}
catch {
throw 'Unable to add psreadline profile settting PSReadlineHistoryPath!'
}
if (Test-Path (Get-OMPProfileSetting -Name 'PSReadlineHistoryPath')) {
Write-Output "NOTE: PSReadline history file already exists: $(Join-Path (Split-Path $Profile) '.powershell.history')"
}
}
if (-not (Test-OMPProfileSetting -Name 'PSReadlineHistoryLoaded')) {
try {
Add-OMPProfileSetting -Name 'PSReadlineHistoryLoaded' -Value $false
}
catch {
throw 'Unable to add psreadline profile settting PSReadlineHistoryLoaded!'
}
}
if ((Test-Path "$(Get-OMPProfileSetting -Name 'PSReadlineHistoryPath').csv") -and
(-not (Get-OMPProfileSetting -Name 'PSReadlineHistoryLoaded'))) {
$null = Import-CSV "$(Get-OMPProfileSetting -Name 'PSReadlineHistoryPath').csv" | Add-History
Set-OMPProfileSetting -Name 'PSReadlineHistoryLoaded' -Value $true
}
if (-not (Test-OMPProfileSetting -Name 'PSReadlinePersistantHistoryCount')) {
try {
Add-OMPProfileSetting -Name 'PSReadlinePersistantHistoryCount' -Value 50
}
catch {
throw 'Unable to add psreadline profile settting PSReadlinePersistantHistoryCount!'
}
}
Import-OMPModule 'PSReadline'
}
$PostLoad = {}
$Config = {
<#
psreadline configuration
#>
Set-PSReadLineOption -HistoryNoDuplicates
Set-PSReadlineOption -HistorySavePath (Get-OMPProfileSetting -Name 'PSReadlineHistoryPath')
Set-PSReadLineOption -HistorySearchCursorMovesToEnd
Set-PSReadLineOption -HistorySaveStyle SaveIncrementally
Set-PSReadLineOption -MaximumHistoryCount 4000
Set-PSReadlineOption -ShowToolTips:$true
Set-PSReadlineKeyHandler -Key "Ctrl+Delete" -Function "KillWord"
Set-PSReadlineKeyHandler -Key "Ctrl+Backspace" -Function "BackwardKillWord"
Set-PSReadlineKeyHandler -Key "Shift+Backspace" -Function "BackwardKillWord"
Set-PSReadlineKeyHandler -Key "UpArrow" -Function "HistorySearchBackward"
Set-PSReadlineKeyHandler -Key "DownArrow" -Function "HistorySearchForward"
Set-PSReadlineKeyHandler -Key "Tab" -Function "MenuComplete"
Set-PSReadlineKeyHandler -Chord 'Shift+Tab' -Function "Complete"
Set-PSReadlineKeyHandler -Key "Ctrl+Q" -Function "TabCompleteNext"
Set-PSReadlineKeyHandler -Key "Ctrl+Shift+Q" -Function "TabCompletePrevious"
Set-PSReadlineKeyHandler -Key F1 -BriefDescription CommandHelp -LongDescription "Open the help window for the current command" -ScriptBlock {
# Get current line(s) of input
$ast = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$ast, [ref]$null, [ref]$null, [ref]$cursor)
# Find the current command, use Ast to find the currently processed command, even if we are currently typing parameters for it.
$commandAst = $ast.FindAll({
$node = $args[0]
$node -is [System.Management.Automation.Language.CommandAst] -and
$node.Extent.StartOffset -le $cursor -and
$node.Extent.EndOffset -ge $cursor
}, $true) | Select-Object -Last 1
# If we are in the process of typing a command ...
if ($commandAst -ne $null) {
# Get its name
$commandName = $commandAst.GetCommandName()
if ($commandName -ne $null) {
# Ensure it really is its name
$command = $ExecutionContext.InvokeCommand.GetCommand($commandName, 'All')
if ($command -is [System.Management.Automation.AliasInfo]) {
$commandName = $command.ResolvedCommandName
}
# Get Help
if ($commandName -ne $null) {
# Call help based on preference
switch ($PSReadlineHelpPreference) {
"detail" { Start-Process powershell.exe -ArgumentList "-NoExit -Command Get-Help $commandName -Detailed" }
"details" { Start-Process powershell.exe -ArgumentList "-NoExit -Command Get-Help $commandName -Detailed" }
"example" { Start-Process powershell.exe -ArgumentList "-NoExit -Command Get-Help $commandName -Examples" }
"examples" { Start-Process powershell.exe -ArgumentList "-NoExit -Command Get-Help $commandName -Examples" }
"online" { Get-Help $commandName -Online }
default { Get-Help $commandName -Online }
}
}
}
}
}
}
$ShutDown = {
$null = Get-History -Count (Get-OMPProfileSetting -Name 'PSReadlinePersistantHistoryCount') |
Export-CSV "$(Get-OMPProfileSetting -Name 'PSReadlineHistoryPath').csv" -NoTypeInformation
Set-OMPProfileSetting -Name 'PSReadlineHistoryLoaded' -Value $false
}
$Unload = {
Remove-OMPModule -Name 'psreadline'
Remove-OMPProfileSetting -Name 'PSReadlineHistoryLoaded'
Remove-OMPProfileSetting -Name 'PSReadlineHistoryPath'
Remove-OMPProfileSetting -Name 'PSReadlinePersistantHistoryCount'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/psreadline/src/psreadline.ps1
|
psreadline.ps1
|
# Nothing
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/consoleui/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$Unload = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/consoleui/src/Spin-busy.ps1
|
Spin-busy.ps1
|
function Global:Spin-Busy {
param(
[Int]$msWait = 0,
[String]$spinStr = '-\|/. ',
[Char[]]$spinChars = [Char[]] ($spinStr.ToCharArray()),
[System.Management.Automation.Host.PSHostRawUserInterface] $rawUI = (Get-Host).UI.RawUI,
[ConsoleColor]$bgColor = $rawUI.BackgroundColor,
[ConsoleColor]$fgColor = $rawUI.ForegroundColor,
[System.Management.Automation.Host.Coordinates]$curPos = $rawUI.Get_CursorPosition(),
[Int32]$startX = $curPos.X,
[Int32]$maxX = $rawUI.WindowSize.Width,
[Switch]$trails
)
begin {
$trailCell = $rawUI.NewBufferCellArray(@($spinChars[-2]), $fgColor, $bgColor);
$blankCell = $rawUI.NewBufferCellArray(@($spinChars[-1]), $fgColor, $bgColor);
$spinCells = $spinChars[0..($spinChars.Count - 3)];
for ($i=0; $i -lt ($spinCells.Count); ++$i) {
$spinCells[$i] = $rawUI.NewBufferCellArray(@($spinCells[$i]), $fgColor, $bgColor)
}
$charNdx = 0;
}
process {
if ($charNdx -lt $spinCells.Count){
$rawUI.SetBufferContents($curPos, $spinCells[$charNdx++]);
}
else {
$charNdx = 0
$rawUI.SetBufferContents($curPos, $trailCell)
if ($trails) {
if (++$curPos.X -gt $maxX) {
do {
--$curPos.X; $rawUI.SetBufferContents($curPos, $blankCell)
} until ($curPos.X -le $startX)
}
}
}
Start-Sleep -milliseconds $msWait
$_
}
end {
do {
$rawUI.SetBufferContents($curPos, $blankCell);
}
until (--$curPos.X -le $startX)
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/consoleui/src/Read-Choice.ps1
|
Read-Choice.ps1
|
function Global:Read-Choice {
Param(
[Parameter(Position=0)]
[System.String]$Message,
[Parameter(Position=1)]
[ValidateNotNullOrEmpty()]
[System.String[]]$Choices = @('&Yes','&No','Yes to &All','No &to All'),
[Parameter(Position=2)]
[System.Int32]$DefaultChoice = 0,
[Parameter(Position=3)]
[System.String]$Title = [string]::Empty
)
[System.Management.Automation.Host.ChoiceDescription[]]$Poss = $Choices | ForEach-Object {
New-Object System.Management.Automation.Host.ChoiceDescription "$($_)", "Sets $_ as an answer."
}
$Host.UI.PromptForChoice( $Title, $Message, $Poss, $DefaultChoice )
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/consoleui/src/Create-Menu.ps1
|
Create-Menu.ps1
|
function Global:CreateMenu ($Title,$MenuItems,$TitleColor,$LineColor,$MenuItemColor)
{
#CreateMenu -Title "THIS IS TITLE" -MenuItems "Exchange Server","Active Directory","Sytem Center Configuration Manager","Lync Server","Microsoft Azure" -TitleColor Red -LineColor Cyan -MenuItemColor Yellow
[string]$Title = "$Title"
$TitleCount = $Title.Length
$LongestMenuItem = ($MenuItems | Measure-Object -Maximum -Property Length).Maximum
if ($TitleCount -lt $LongestMenuItem)
{
$reference = $LongestMenuItem
}
else
{$reference = $TitleCount}
$reference = $reference + 10
$Line = "═"*$reference
$TotalLineCount = $Line.Length
$RemaniningCountForTitleLine = $reference - $TitleCount
$RemaniningCountForTitleLineForEach = $RemaniningCountForTitleLine / 2
$RemaniningCountForTitleLineForEach = [math]::Round($RemaniningCountForTitleLineForEach)
$LineForTitleLine = "`0"*$RemaniningCountForTitleLineForEach
$Tab = "`t"
Write-Host "╔" -NoNewline -f $LineColor;Write-Host $Line -NoNewline -f $LineColor;Write-Host "╗" -f $LineColor
if($RemaniningCountForTitleLine % 2 -eq 1)
{
$RemaniningCountForTitleLineForEach = $RemaniningCountForTitleLineForEach - 1
$LineForTitleLine2 = "`0"*$RemaniningCountForTitleLineForEach
Write-Host "║" -f $LineColor -nonewline;Write-Host $LineForTitleLine -nonewline -f $LineColor;Write-Host $Title -f $TitleColor -nonewline;Write-Host $LineForTitleLine2 -f $LineColor -nonewline;Write-Host "║" -f $LineColor
}
else
{
Write-Host "║" -nonewline -f $LineColor;Write-Host $LineForTitleLine -nonewline -f $LineColor;Write-Host $Title -f $TitleColor -nonewline;Write-Host $LineForTitleLine -nonewline -f $LineColor;Write-Host "║" -f $LineColor
}
Write-Host "╠" -NoNewline -f $LineColor;Write-Host $Line -NoNewline -f $LineColor;Write-Host "╣" -f $LineColor
$i = 1
foreach($menuItem in $MenuItems)
{
$number = $i++
$RemainingCountForItemLine = $TotalLineCount - $menuItem.Length -9
$LineForItems = "`0"*$RemainingCountForItemLine
Write-Host "║" -nonewline -f $LineColor ;Write-Host $Tab -nonewline;Write-Host $number"." -nonewline -f $MenuItemColor;Write-Host $menuItem -nonewline -f $MenuItemColor;Write-Host $LineForItems -nonewline -f $LineColor;Write-Host "║" -f $LineColor
}
Write-Host "╚" -NoNewline -f $LineColor;Write-Host $Line -NoNewline -f $LineColor;Write-Host "╝" -f $LineColor
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/consoleui/src/Read-HostContinue.ps1
|
Read-HostContinue.ps1
|
Function Global:Read-HostContinue {
param (
[Parameter(Position=0)]
[String]$PromptTitle = '',
[Parameter(Position=1)]
[string]$PromptQuestion = 'Continue?',
[Parameter(Position=2)]
[string]$YesDescription = 'Do this.',
[Parameter(Position=3)]
[string]$NoDescription = 'Do not do this.',
[Parameter(Position=4)]
[switch]$DefaultToNo,
[Parameter(Position=5)]
[switch]$Force
)
if ($Force) {
(-not $DefaultToNo)
return
}
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", $YesDescription
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", $NoDescription
if ($DefaultToNo) {
$ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($no,$yes)
}
else {
$ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
}
if (($host.ui.PromptForChoice($PromptTitle, $PromptQuestion , $ConsolePrompt, 0)) -eq 0) {
$true
}
else {
$false
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/vmware/Load.ps1
|
Load.ps1
|
$PreLoad = {
if (-not (Get-Module 'VMware.VimAutomation.Core' -ListAvailable)) {
throw 'vmware OhMyPsh plugin requires the vmware PowerCLI module be installed!'
} else {
Import-OMPModule 'VMware.VimAutomation.Core'
Set-OMPTheme -NoProfileUpdate
}
}
$PostLoad = {}
$Config = {}
$Shutdown = {
Remove-OMPModule -Name 'VMware*' -PluginSafe
}
$Unload = {
# Remove-Module Initialize-VMware_VimAutomation_Cis -Force
Remove-OMPModule -Name 'VMware*' -PluginSafe
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/vmware/src/Plugin.ps1
|
Plugin.ps1
|
# Put custom vmware based functions here.
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/moduleupgrade/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {
if (-not (Test-OMPProfileSetting -Name 'ModuleAutoUpgradeFrequency')) {
Write-Output "Setting initial module upgrade frequency settings to occur every 7 times the module is loaded"
Write-Output "Modify your json profile to change this frequency."
Add-OMPProfileSetting -Name 'ModuleAutoUpgradeFrequency' -Value 7
Export-OMPProfile
}
$AutoUpgradeFreq = Get-OMPProfileSetting -Name 'ModuleAutoUpgradeFrequency'
$RunCount = Get-OMPProfileSetting -Name 'OMPRunCount'
if (((Get-OMPProfileSetting -Name 'OMPRunCount') % $AutoUpgradeFreq) -eq 0) {
if (Read-HostContinue -PromptQuestion 'It is time to run module upgrades, do so now?') {
Upgrade-InstalledModule
}
else {
Write-Output "Ok, you will be asked again after $AutoUpgradeFreq more sessions..."
}
}
}
$Config = {}
$Shutdown = {}
$UnLoad = {
Remove-OMPProfileSetting -Name 'ModuleAutoUpgradeFrequency'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/moduleupgrade/src/Read-HostContinue.ps1
|
Read-HostContinue.ps1
|
Function Global:Read-HostContinue {
param (
[Parameter(Position=0)]
[String]$PromptTitle = '',
[Parameter(Position=1)]
[string]$PromptQuestion = 'Continue?',
[Parameter(Position=2)]
[string]$YesDescription = 'Do this.',
[Parameter(Position=3)]
[string]$NoDescription = 'Do not do this.',
[Parameter(Position=4)]
[switch]$DefaultToNo,
[Parameter(Position=5)]
[switch]$Force
)
if ($Force) {
(-not $DefaultToNo)
return
}
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", $YesDescription
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", $NoDescription
if ($DefaultToNo) {
$ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($no,$yes)
}
else {
$ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
}
if (($host.ui.PromptForChoice($PromptTitle, $PromptQuestion , $ConsolePrompt, 0)) -eq 0) {
$true
}
else {
$false
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/moduleupgrade/src/Upgrade-InstalledModule.ps1
|
Upgrade-InstalledModule.ps1
|
#Requires -Version 5
Function Global:Upgrade-InstalledModule {
<#
.SYNOPSIS
A small wrapper for PowerShellGet to upgrade installed modules.
.DESCRIPTION
A small wrapper for PowerShellGet to upgrade installed modules.
.PARAMETER ModuleName
Show modules which would get upgraded.
.PARAMETER Silent
Do not show progress bar.
.PARAMETER Force
Force an upgrade without any confirmation prompts.
.EXAMPLE
PS> Upgrade-InstalledModule -Force
Updates modules installed via PowerShellGet. Shows a progress bar.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Version History
1.0.0 - Initial release
#>
[CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact='Medium' )]
Param (
[Parameter(HelpMessage = 'Name of a module to check and remove old versions of.')]
[string]$ModuleName = '*',
[Parameter(HelpMessage = 'Force upgrade modules without confirmation.')]
[Switch]$Force,
[Parameter(HelpMessage = 'Do not write progress.')]
[Switch]$Silent
)
Begin {
try {
Import-Module PowerShellGet
}
catch {
Write-Warning 'Unable to load PowerShellGet. This script only works with PowerShell 5 and greater.'
return
}
$YesToAll = $false
$NoToAll = $false
}
Process {
$Count = 0
if (-not $Silent) {
Write-Progress -Activity "Retrieving installed modules" -PercentComplete 1 -Status "Processing"
}
$InstalledModules = @(Get-InstalledModule $ModuleName)
$TotalMods = $InstalledModules.Count
ForEach ($Mod in (Get-InstalledModule $ModuleName)) {
$count++
if (-not $Silent) {
$PercentComplete = [math]::Round((100*($count/$TotalMods)),0)
Write-Progress -Activity "Processing Module $($Mod.Name)" -PercentComplete $PercentComplete -Status "Checking Module For Updates"
}
$OnlineModule = Find-Module $Mod.Name
if ($OnlineModule.Version -gt $Mod.Version) {
if ($pscmdlet.ShouldProcess("Upgraded module $($Mod.Name) from $($Mod.Version.ToString()) to $($OnlineModule.Version.ToString())",
"Upgrade module $($Mod.Name) from $($Mod.Version.ToString()) to $($OnlineModule.Version.ToString())?",
"Upgrading module $($Mod.Name)")) {
if($Force -Or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to upgrade '$($Mod.Name)'?",
"Upgrading module '$($Mod.Name)'",
[ref]$YesToAll,
[ref]$NotoAll)) {
if (-not $Silent) {
Write-Progress -Activity "Upgrading Module $($Mod.Name)" -PercentComplete $PercentComplete -Status "Upgrading Module"
}
Update-Module $Mod.Name -Force -Confirm:$false
}
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/moduleclean/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {
if (-not (Test-OMPProfileSetting -Name 'ModuleAutoCleanFrequency')) {
Write-Output "Setting initial module clean frequency settings to occur every 8 times the module is loaded"
Add-OMPProfileSetting -Name 'ModuleAutoCleanFrequency' -Value 8
$AutoCleanFreq = 8
Export-OMPProfile
}
$AutoCleanFreq = Get-OMPProfileSetting -Name 'ModuleAutoCleanFrequency'
if (((Get-OMPProfileSetting -Name 'OMPRunCount') % $AutoCleanFreq) -eq 0) {
if (Read-HostContinue -PromptQuestion 'It is time to clean up (remove) old modules, do so now?') {
Remove-InstalledModule
}
else {
Write-Output "Ok, you will be asked again after $AutoCleanFreq more sessions..."
}
}
}
$Config = {}
$Shutdown = {}
$Unload = {
Remove-OMPProfileSetting -Name 'ModuleAutoCleanFrequency'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/moduleclean/src/Read-HostContinue.ps1
|
Read-HostContinue.ps1
|
Function Global:Read-HostContinue {
param (
[Parameter(Position=0)]
[String]$PromptTitle = '',
[Parameter(Position=1)]
[string]$PromptQuestion = 'Continue?',
[Parameter(Position=2)]
[string]$YesDescription = 'Do this.',
[Parameter(Position=3)]
[string]$NoDescription = 'Do not do this.',
[Parameter(Position=4)]
[switch]$DefaultToNo,
[Parameter(Position=5)]
[switch]$Force
)
if ($Force) {
(-not $DefaultToNo)
return
}
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", $YesDescription
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", $NoDescription
if ($DefaultToNo) {
$ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($no,$yes)
}
else {
$ConsolePrompt = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
}
if (($host.ui.PromptForChoice($PromptTitle, $PromptQuestion , $ConsolePrompt, 0)) -eq 0) {
$true
}
else {
$false
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/moduleclean/src/Remove-OldModule.ps1
|
Remove-OldModule.ps1
|
#Requires -Version 5
function Global:Remove-OldModule {
<#
.SYNOPSIS
A small wrapper for PowerShellGet to remove all older installed modules.
.DESCRIPTION
A small wrapper for PowerShellGet to remove all older installed modules.
.PARAMETER ModuleName
Name of a module to check and remove old versions of. Default is all modules ('*')
.PARAMETER Silent
Do not show progress bar.
.PARAMETER Force
Force removal without any confirmation prompts.
.EXAMPLE
PS> Remove-OldModules
Removes old modules installed via PowerShellGet.
.EXAMPLE
PS> Remove-OldModules -whatif
Shows what old modules might be removed via PowerShellGet.
.NOTES
Author: Zachary Loeber
Site: http://www.the-little-things.net/
Version History
1.0.0 - Initial release
#>
[CmdletBinding( SupportsShouldProcess=$True, ConfirmImpact='Medium' )]
Param (
[Parameter(HelpMessage = 'Name of a module to check and remove old versions of.')]
[string]$ModuleName = '*',
[Parameter(HelpMessage = 'Force upgrade modules without confirmation.')]
[Switch]$Force,
[Parameter(HelpMessage = 'Do not write progress.')]
[Switch]$Silent
)
Begin {
try {
Import-Module PowerShellGet
}
catch {
Write-Warning 'Unable to load PowerShellGet. This script only works with PowerShell 5 and greater.'
return
}
$YesToAll = $false
$NoToAll = $false
$ModulesToRemove = @()
}
Process {
$Count = 0
Get-InstalledModule $ModuleName | ForEach-Object {
$Count ++
if (-not $Silent) {
Write-Progress -Activity "Calculating removable modules" -PercentComplete ($Count % 100) -Status "Calculating"
}
$ThisModule = Get-InstalledModule $_.Name -AllVersions | Sort-Object Version
If ($ThisModule.count -gt 1) {
$ModulesToRemove += $ThisModule | Select-Object -First ($ThisModule.count - 1)
}
}
$Count = 0
$TotalMods = $ModulesToRemove.Count
ForEach ($Mod in $ModulesToRemove) {
$Ver = $Mod.Version.ToString()
$Count++
if ($pscmdlet.ShouldProcess("Remove module $($Mod.Name) - $($Ver)",
"Remove module $($Mod.Name) - $($Ver)?",
"Removing module $($Mod.Name) - $($Ver)")) {
if($Force -Or $PSCmdlet.ShouldContinue("Are you REALLY sure you want to remove '$($Mod.Name) - $($Ver) '?",
"Removing module '$($Mod.Name) - $($Ver)'",
[ref]$YesToAll,
[ref]$NotoAll)) {
if (-not $Silent) {
$PercentComplete = [math]::Round((100*($Count/$TotalMods)),0)
Write-Progress -Activity "Removing Old Module $($Mod.Name) (version: $($Ver))" -PercentComplete $PercentComplete -Status "Removing..."
}
Uninstall-Module $Mod.Name -RequiredVersion $Ver -Force -Confirm:$false
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/psgit/Load.ps1
|
Load.ps1
|
$PreLoad = {
Import-OMPModule 'PSGit'
}
$PostLoad = {}
$Config = {
# customize git prompt display settings
Set-GitPromptSettings -SeparatorText '' -BeforeText '' -BeforeChangesText '' -AfterChangesText '' -AfterNoChangesText '' `
-BranchText "$([PowerLine.Prompt]::Branch) " -BranchForeground White -BranchBackground Cyan `
-BehindByText '▼' -BehindByForeground White -BehindByBackground DarkCyan `
-AheadByText '▲' -AheadByForeground White -AheadByBackground DarkCyan `
-StagedChangesForeground White -StagedChangesBackground DarkBlue `
-UnStagedChangesForeground White -UnStagedChangesBackground Blue
}
$Shutdown = {
Remove-Module 'PSGit' -force
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/psgit/src/git.ps1
|
git.ps1
|
# Nothing
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/net/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$UnLoad = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/net/src/net.ps1
|
net.ps1
|
# function Reset-WiFi
# {
# $adapter = Get-WmiObject Win32_NetworkAdapter | Where { $_.Name.Contains("Wireless") }
# $wireless.Disable()
# Sleep(8)
# $wireless.Enable()
# }
# function Reset-Lan
# {
# $adapter = Get-WmiObject Win32_NetworkAdapter | Where { $_.Name.Contains("Local") }
# $wireless.Disable()
# Sleep(8)
# $wireless.Enable()
# }
function Global:Get-IPs() {
$ent = [net.dns]::GetHostEntry([net.dns]::GetHostName())
return $ent.AddressList | Where-Object { $_.ScopeId -ne 0 } | ForEach-Object {
[string]$_
}
}
#
# Author: Cookie.Monster
# Source: https://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
function Global:Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
.FUNCTIONALITY
Computers
.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
Close_Wait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
Delete_Tcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
Fin_Wait_1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
Fin_Wait_2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
Last_Ack - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
Syn_Received - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
Syn_Sent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
Time_Wait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
Cookie Monster - modified these to match netstat output per here:
http://support.microsoft.com/kb/137984
.PARAMETER ComputerName
If defined, run this command on a remote system via WMI. \\computername\c$\netstat.txt is created on that system and the results returned here
.PARAMETER ShowHostNames
If specified, will attempt to resolve local and remote addresses.
.PARAMETER tempFile
Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\netstat.txt"
.PARAMETER AddressFamily
Filter by IP Address family: IPv4, IPv6, or the default, * (both).
If specified, we display any result where both the localaddress and the remoteaddress is in the address family.
.EXAMPLE
Get-NetworkStatistics | Format-Table
.EXAMPLE
Get-NetworkStatistics iexplore -computername k-it-thin-02 -ShowHostNames | Format-Table
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Computername Computer1, Computer2
.EXAMPLE
'Computer1', 'Computer2' | Get-NetworkStatistics
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.github.io/
.LINK
http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
#>
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding()]
param(
[Parameter(Position=0)]
[System.String]$ProcessName='*',
[Parameter(Position=1)]
[System.String]$Address='*',
[Parameter(Position=2)]
$Port='*',
[Parameter(Position=3,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True)]
[System.String[]]$ComputerName=$env:COMPUTERNAME,
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[ValidateSet('*','Closed','Close_Wait','Closing','Delete_Tcb','DeleteTcb','Established','Fin_Wait_1','Fin_Wait_2','Last_Ack','Listening','Syn_Received','Syn_Sent','Time_Wait','Unknown')]
[System.String]$State='*',
[switch]$ShowHostnames,
[switch]$ShowProcessNames = $true,
[System.String]$TempFile = "C:\netstat.txt",
[validateset('*','IPv4','IPv6')]
[string]$AddressFamily = '*'
)
begin{
#Define properties
$properties = 'ComputerName','Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
#store hostnames in array for quick lookup
$dnsCache = @{}
}
process{
foreach($Computer in $ComputerName) {
#Collect processes
if($ShowProcessNames){
Try {
$processes = Get-Process -ComputerName $Computer -ErrorAction stop | select name, id
}
Catch {
Write-warning "Could not run Get-Process -computername $Computer. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
$ShowProcessNames = $false
}
}
#Handle remote systems
if($Computer -ne $env:COMPUTERNAME){
#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$Computer", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)
#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $Computer -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $Computer to delete $tempfile"
}
#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $Computer -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Throw $_
Break
}
#wait for process to complete
while (
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $Computer -ErrorAction Stop
}
catch{
$FALSE
}
)
) {
start-sleep -seconds 2
}
#gather results
if(test-path $remoteTempFile){
Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Could not get content from $remoteTempFile for results"
Break
}
Remove-Item $remoteTempFile -force
}
else{
Throw "'$tempFile' on $Computer converted to '$remoteTempFile'. This path is not accessible from your system."
Break
}
}
else{
#gather results on local PC
$results = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
}
#initialize counter for progress
$totalCount = $results.count
$count = 0
#Loop through each line of results
foreach($result in $results) {
$item = $result.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::'){
#parse the netstat line for local address and port
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else {
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
#parse the netstat line for remote address and port
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else {
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
#Filter IPv4/IPv6 if specified
if($AddressFamily -ne "*")
{
if($AddressFamily -eq 'IPv4' -and $localAddress -match ':' -and $remoteAddress -match ':|\*' )
{
#Both are IPv6, or ipv6 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
elseif($AddressFamily -eq 'IPv6' -and $localAddress -notmatch ':' -and ( $remoteAddress -notmatch ':' -or $remoteAddress -match '*' ) )
{
#Both are IPv4, or ipv4 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
}
#parse the netstat line for other properties
$procId = $item[-1]
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
#Filter the object
if($remotePort -notlike $Port -and $localPort -notlike $Port){
write-verbose "remote $Remoteport local $localport port $port"
Write-Verbose "Filtered by Port:`n$result"
continue
}
if($remoteAddress -notlike $Address -and $localAddress -notlike $Address){
Write-Verbose "Filtered by Address:`n$result"
continue
}
if($status -notlike $State){
Write-Verbose "Filtered by State:`n$result"
continue
}
if($proto -notlike $Protocol){
Write-Verbose "Filtered by Protocol:`n$result"
continue
}
#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#If we are running showprocessnames, get the matching name
if($ShowProcessNames -or $PSBoundParameters.ContainsKey -eq 'ProcessName'){
#handle case where process spun up in the time between running get-process and running netstat
if($procName = $processes | Where {$_.id -eq $procId} | select -ExpandProperty name ){ }
else {$procName = "Unknown"}
}
else{$procName = "NA"}
if($procName -notlike $ProcessName){
Write-Verbose "Filtered by ProcessName:`n$result"
continue
}
#if the showhostnames switch is specified, try to map IP to hostname
if($showHostnames){
$tmpAddress = $null
try{
if($remoteAddress -eq "127.0.0.1" -or $remoteAddress -eq "0.0.0.0"){
$remoteAddress = $Computer
}
elseif($remoteAddress -match "\w"){
#check with dns cache first
if ($dnsCache.containskey( $remoteAddress)) {
$remoteAddress = $dnsCache[$remoteAddress]
write-verbose "using cached REMOTE '$remoteAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $remoteAddress
$remoteAddress = [System.Net.DNS]::GetHostByAddress("$remoteAddress").hostname
$dnsCache.add($tmpAddress, $remoteAddress)
write-verbose "using non cached REMOTE '$remoteAddress`t$tmpAddress"
}
}
}
catch{ }
try{
if($localAddress -eq "127.0.0.1" -or $localAddress -eq "0.0.0.0"){
$localAddress = $Computer
}
elseif($localAddress -match "\w"){
#check with dns cache first
if($dnsCache.containskey($localAddress)){
$localAddress = $dnsCache[$localAddress]
write-verbose "using cached LOCAL '$localAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $localAddress
$localAddress = [System.Net.DNS]::GetHostByAddress("$localAddress").hostname
$dnsCache.add($localAddress, $tmpAddress)
write-verbose "using non cached LOCAL '$localAddress'`t'$tmpAddress'"
}
}
}
catch{ }
}
#Write the object
New-Object -TypeName PSObject -Property @{
ComputerName = $Computer
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
#Increment the progress counter
$count++
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/helpers/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {}
$Config = {}
$Shutdown = {}
$UnLoad = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/helpers/src/helpers.ps1
|
helpers.ps1
|
function Global:Reset-Module ($ModuleName) {
Remove-Module $ModuleName
Import-Module $ModuleName -force -pass | Format-Table Name, Version, Path -AutoSize
}
function Global:here {
# Little helper function. Great for quick paths to the clipboard (ie. here | clip)
(Get-Location).Path
}
function Global:Test-IsAdmin {
if ( ([System.Environment]::OSVersion.Version.Major -gt 5) -and
( new-object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
$true
}
else {
$false
}
}
function Global:Get-ChildItem-Wide {
<#
joonro/Get-ChildItem-Color
https://github.com/joonro/Get-ChildItem-Color
Add from https://github.com/JRJurman/PowerLS/blob/master/powerls.psm1
#>
$width = $host.UI.RawUI.WindowSize.Width
$pad = 2
# get the longest string and get the length
$childs = Get-ChildItem $Args
$lnStr = $childs | select-object Name | sort-object { "$_".length } -descending | select-object -first 1
$len = $lnStr.name.length
$childs |
ForEach-Object {
$output = $_.name + (" "*($len - $_.name.length+$pad))
$count += $output.length
Write-Host $output -nonewline
if ( $count -ge ($width - ($len+$pad)) ) {
Write-Host ""
$count = 0
}
}
}
Set-Alias -Name ls -Value Get-ChildItem-Wide -option AllScope -Scope Global
function Global:Split-HereString {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
[string[]]$String
)
Begin {
$TheString = ''
}
Process {
$TheString += $String
}
End {
$TheString -Split "\s*[\r\n]+\s*"
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/banner/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {
Write-SessionBannerToHost
}
$Config = {}
$Shutdown = {}
$Unload = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/banner/src/Write-SessionBannerToHost.ps1
|
Write-SessionBannerToHost.ps1
|
function Global:Write-SessionBannerToHost {
[CmdletBinding()]
param(
[int]$Spacer = 1,
[switch]$AttemptAutoFit
)
Begin {
# Retreive the current OS platform based on the existence of some known default variables in Powershell 6.
function Get-OSPlatform {
[CmdletBinding()]
param(
[Parameter()]
[Switch]$IncludeLinuxDetails
)
#$Runtime = [System.Runtime.InteropServices.RuntimeInformation]
#$OSPlatform = [System.Runtime.InteropServices.OSPlatform]
$ThisIsCoreCLR = if ($IsCoreCLR) {$True} else {$False}
$ThisIsLinux = if ($IsLinux) {$True} else {$False} #$Runtime::IsOSPlatform($OSPlatform::Linux)
$ThisIsOSX = if ($IsOSX) {$True} else {$False} #$Runtime::IsOSPlatform($OSPlatform::OSX)
$ThisIsWindows = if ($IsWindows) {$True} else {$False} #$Runtime::IsOSPlatform($OSPlatform::Windows)
if (-not ($ThisIsLinux -or $ThisIsOSX)) {
$ThisIsWindows = $true
}
if ($ThisIsLinux) {
if ($IncludeLinuxDetails) {
$LinuxInfo = Get-Content /etc/os-release | ConvertFrom-StringData
$IsUbuntu = $LinuxInfo.ID -match 'ubuntu'
if ($IsUbuntu -and $LinuxInfo.VERSION_ID -match '14.04') {
return 'Ubuntu 14.04'
}
if ($IsUbuntu -and $LinuxInfo.VERSION_ID -match '16.04') {
return 'Ubuntu 16.04'
}
if ($LinuxInfo.ID -match 'centos' -and $LinuxInfo.VERSION_ID -match '7') {
return 'CentOS'
}
}
return 'Linux'
}
elseif ($ThisIsOSX) {
return 'OSX'
}
elseif ($ThisIsWindows) {
return 'Windows'
}
else {
return 'Unknown'
}
}
function Get-PIIPAddress {
# Retreive IP address informaton from dot net core only functions (should run on both linux and windows properly)
$NetworkInterfaces = @([System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object {($_.OperationalStatus -eq 'Up')})
$NetworkInterfaces | Foreach-Object {
$_.GetIPProperties() | Where-Object {$_.GatewayAddresses} | Foreach-Object {
$Gateway = $_.GatewayAddresses.Address.IPAddressToString
$DNSAddresses = @($_.DnsAddresses | Foreach-Object {$_.IPAddressToString})
$_.UnicastAddresses | Where-Object {$_.Address -notlike '*::*'} | Foreach-Object {
New-Object PSObject -Property @{
IP = $_.Address
Prefix = $_.PrefixLength
Gateway = $Gateway
DNS = $DNSAddresses
}
}
}
}
}
function Get-PIUptime {
# Retreive platform independant uptime informaton (should run on both linux and windows properly)
param(
[switch]$FromSleep
)
switch ( Get-OSPlatform -ErrorVariable null ) {
'Linux' {
# Add me!
}
'OSX' {
# Add me!
}
Default {
try {
if (-not $FromSleep) {
$os = Get-WmiObject win32_operatingsystem
$uptime = (Get-Date) - ($os.ConvertToDateTime($os.lastbootuptime))
}
else {
$Uptime = (((Get-Date)- (Get-EventLog -LogName system -Source 'Microsoft-Windows-Power-Troubleshooter' -Newest 1).TimeGenerated))
}
$Display = "" + $Uptime.Days + " days / " + $Uptime.Hours + " hours / " + $Uptime.Minutes + " minutes"
Write-Output $Display
}
catch {}
}
}
}
function Get-PIElevatedStatus {
# Platform independant function that returns true if you are running as an elevated account, false if not.
switch ( Get-OSPlatform -ErrorVariable null ) {
'Linux' {
# Add me!
}
'OSX' {
# Add me!
}
Default {
if (([System.Environment]::OSVersion.Version.Major -gt 5) -and ((New-object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))) {
return $true
}
else {
return $false
}
}
}
}
$Spaces = (' ' * $Spacer)
$OSPlatform = Get-OSPlatform -ErrorVariable null
if ($AttemptAutoFit) {
try {
$IP = @(Get-PIIPAddress)[0]
if ([string]::isnullorempty($IP)) {
$IPAddress = 'IP: Offline'
$IPGateway = 'GW: Offline'
}
else {
$IPAddress = "IP: $(@($IP.IP)[0])/$($IP.Prefix)"
$IPGateway = "GW: $($IP.Gateway)"
}
}
catch {
$IPAddress = 'IP: NA'
$IPGateway = 'GW: NA'
}
$PSExecPolicy = "Exec Pol: $(Get-ExecutionPolicy)"
$PSVersion = "PS Ver: $($PSVersionTable.PSVersion.Major)"
$CompName = "Computer: $($env:COMPUTERNAME)"
$UserDomain = "Domain: $($env:UserDomain)"
$LogonServer = "Logon Sever: $($env:LOGONSERVER -replace '\\')"
$UserName = "User: $($env:UserName)"
$UptimeBoot = "Uptime (hardware boot): $(Get-PIUptime)"
$UptimeResume = Get-PIUptime -FromSleep
if ($UptimeResume) {
$UptimeResume = "Uptime (system resume): $($UptimeResume)"
}
} else {
# Collect all the banner data
try {
$IP = @(Get-PIIPAddress)[0]
if ([string]::isnullorempty($IP)) {
$IPAddress = 'Offline'
$IPGateway = 'Offline'
}
else {
$IPAddress = "$(@($IP.IP)[0])/$($IP.Prefix)"
$IPGateway = "$($IP.Gateway)"
}
}
catch {
$IPAddress = 'NA'
$IPGateway = 'NA'
}
$OSPlatform = Get-OSPlatform -ErrorVariable null
$PSExecPolicy = Get-ExecutionPolicy
$PSVersion = $PSVersionTable.PSVersion.Major
$CompName = $env:COMPUTERNAME
$UserDomain = $env:UserDomain
$LogonServer = $env:LOGONSERVER -replace '\\'
$UserName = $env:UserName
$UptimeBoot = Get-PIUptime
$UptimeResume = Get-PIUptime -FromSleep
}
$PSProcessElevated = 'TRUE'
if ($OSPlatform -eq 'Windows') {
if (Get-PIElevatedStatus) {
$PSProcessElevated = 'TRUE'
}
else {
$PSProcessElevated = 'FALSE'
}
}
else {
# Code to determine if you are a root user or not...
}
if ($AttemptAutoFit) {
$PSProcessElevated = "Elevated: $($PSProcessElevated)"
}
}
Process {}
End {
if ($AttemptAutoFit) {
Write-Host ("{0,-25}$($Spaces)" -f $IPAddress) -noNewline
Write-Host ("{0,-25}$($Spaces)" -f $UserDomain) -noNewline
Write-Host ("{0,-25}$($Spaces)" -f $LogonServer) -noNewline
Write-Host ("{0,-25}$($Spaces)" -f $PSExecPolicy)
Write-Host ("{0,-25}$($Spaces)" -f $IPGateway) -noNewline
Write-Host ("{0,-25}$($Spaces)" -f $CompName) -noNewline
Write-Host ("{0,-25}$($Spaces)" -f $UserName) -noNewline
Write-Host ("{0,-25}$($Spaces)" -f $PSVersion)
Write-Host
Write-Host $UptimeBoot
if ($UptimeResume) {
Write-Host $UptimeResume
}
}
else {
Write-Host "Dom:" -ForegroundColor Green -nonewline
Write-Host $UserDomain -ForegroundColor Cyan -nonewline
Write-Host "$Spaces|$Spaces" -ForegroundColor White -nonewline
Write-Host "Host:"-ForegroundColor Green -nonewline
Write-Host $CompName -ForegroundColor Cyan -nonewline
Write-Host "$Spaces|$Spaces" -ForegroundColor White -nonewline
Write-Host "Logon Svr:" -ForegroundColor Green -nonewline
Write-Host $LogonServer -ForegroundColor Cyan
#Write-Host "$Spaces|$Spaces" -ForegroundColor Yellow
Write-Host "PS:" -ForegroundColor Green -nonewline
Write-Host $PSVersion -ForegroundColor Cyan -nonewline
Write-Host "$Spaces|$Spaces" -ForegroundColor White -nonewline
Write-Host "Elevated:" -ForegroundColor Green -nonewline
if ($PSProcessElevated) {
Write-Host $PSProcessElevated -ForegroundColor Red -nonewline
}
else {
Write-Host $PSProcessElevated -ForegroundColor Cyan -nonewline
}
Write-Host "$Spaces|$Spaces" -ForegroundColor White -nonewline
Write-Host "Execution Policy:" -ForegroundColor Green -nonewline
Write-Host $PSExecPolicy -ForegroundColor Cyan
# Line 2
Write-Host "User:" -ForegroundColor Green -nonewline
Write-Host $UserName -ForegroundColor Cyan -nonewline
Write-Host "$Spaces|$Spaces" -ForegroundColor White -nonewline
Write-Host "IP:" -ForegroundColor Green -nonewline
Write-Host $IPAddress -ForegroundColor Cyan -nonewline
Write-Host "$Spaces|$Spaces" -ForegroundColor White -nonewline
Write-Host "GW:" -ForegroundColor Green -nonewline
Write-Host $IPGateway -ForegroundColor Cyan
Write-Host
# Line 3
Write-Host "Uptime (hardware boot): " -nonewline -ForegroundColor Green
Write-Host $UptimeBoot -ForegroundColor Cyan
# Line 4
if ($UptimeResume) {
Write-Host "Uptime (system resume): " -nonewline -ForegroundColor Green
Write-Host $UptimeResume -ForegroundColor Cyan
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/vagrant/Load.ps1
|
Load.ps1
|
$PreLoad = {}
$PostLoad = {
Write-Output "Vagrant status module loaded. Use Write-VagrantStatusDetailed for information about current vagrant boxes."
}
$config = {}
$Shutdown = {}
$Unload = {}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/plugins/vagrant/src/Plugin.ps1
|
Plugin.ps1
|
# Based on the great work by Posh-git!
#
# Vagrant status is slower then is resonable for a prompt to render. I am making some assumptions
# by scraping the .vagrant folder for any id files that should represent active/aborted some sort
# of Vagrant machine activity.
function Global:Get-VagrantFile {
$fileName = 'Vagrantfile'
$base = Get-Item -Force .
if ($base.PSProvider.Name -ne 'FileSystem'){
return $FALSE
}
$vagrantFile = Join-Path $base.FullName $fileName
if(Test-Path -LiteralPath $vagrantFile)
{
return $TRUE
}
return $FALSE
}
function Global:Get-VagrantDir {
$dirName = '.vagrant'
$base = Get-Item -Force .
if($base.PSProvider.Name -ne 'FileSystem'){
return $FALSE
}
$vagrantDir = Join-Path $base.FullName $dirName
if(Test-Path -LiteralPath $vagrantDir)
{
return $vagrantDir
}
return $FALSE
}
function Global:Get-VagrantEnvIndex {
$vagrantEnvVar = [environment]::GetEnvironmentVariable("VAGRANT_HOME","User")
$dirName = '.vagrant.d'
if($vagrantEnvVar)
{
if($vagrantEnvVar -contains $dirName)
{
$base = Get-Item -Force $vagrantEnvVar
$vagrantEnvDir = Join-Path $base.FullName
}
else
{
$base = Get-Item -Force $vagrantEnvVar
$vagrantEnvDir = Join-Path $base.FullName $dirName
}
if(Test-Path -LiteralPath $vagrantEnvDir)
{
$machineIndex = Get-ChildItem -Path $vagrantEnvDir -Recurse -File -Filter 'index' | % { $_.FullName }
}
return $machineIndex
}
else
{
$base = Get-Item -Force $env:USERPROFILE
$vagrantEnvDir = Join-Path $base.FullName $dirName
if(Test-Path -LiteralPath $vagrantEnvDir)
{
$machineIndex = Get-ChildItem -Path $vagrantEnvDir -Recurse -File -Filter 'index' | % { $_.FullName }
}
return $machineIndex
}
}
function Global:Write-VagrantStatusSimple {
$vagrantFolder = Get-VagrantDir
if((Test-Path $vagrantFolder) -and (Get-VagrantFile))
{
$vagrantActive = $FALSE
$items = Get-ChildItem -Path $vagrantFolder -Recurse -File -Filter 'id'
foreach($item in $items)
{
if($item.ToString().Contains("id"))
{
$vagrantActive = $TRUE
}
else
{
$vagrantActive = $FALSE
}
}
if($vagrantActive)
{
Write-Host ' [' -NoNewline
Write-Host '^' -ForegroundColor Green -NoNewline
Write-Host ']' -NoNewline
}
else
{
Write-Host ' [' -NoNewline
Write-Host '-' -ForegroundColor Gray -NoNewline
Write-Host ']' -NoNewline
}
}
elseif(Get-VagrantFile)
{
Write-Host ' [' -NoNewline
Write-Host '-' -ForegroundColor Gray -NoNewline
Write-Host ']' -NoNewline
}
}
function Global:Write-VagrantStatusDetailed {
$vagrantFolder = Get-VagrantDir
$vagrantEnvJson = Get-Content(Get-VagrantEnvIndex -Raw) | ConvertFrom-Json
$machines = @()
$d = 0
$r = 0
$a = 0
if((Test-Path $vagrantFolder) -and (Get-VagrantFile))
{
$items = Get-ChildItem -Path $vagrantFolder -Recurse -File -Filter 'index_uuid' | % { $_.FullName }
if($items)
{
foreach($item in $items)
{
if($item.ToString().Contains("index_uuid"))
{
$machines = $machines + (get-content $item)
}
}
foreach($machine in $machines)
{
foreach($envMachine in $vagrantEnvJson.machines)
{
$stateTemp = $envMachine.$machine | select -ExpandProperty state
switch($stateTemp){
'aborted' { $d += 1; break}
'running' {$r += 1; break}
'poweroff' {$d += 1; break}
default { break}
}
}
}
Write-Host ' [' -NoNewline
Write-Host "D:${d} " -ForegroundColor Gray -NoNewline
Write-Host "R:${r}" -ForegroundColor Green -NoNewline
Write-Host ']' -NoNewline
}
else
{
Write-Host ' [' -NoNewline
Write-Host "-" -ForegroundColor Gray -NoNewline
Write-Host ']' -NoNewline
}
}
elseif(Get-VagrantFile)
{
Write-Host ' [' -NoNewline
Write-Host "-" -ForegroundColor Gray -NoNewline
Write-Host ']' -NoNewline
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/golagola.ps1
|
golagola.ps1
|
function global:prompt {
$realCommandStatus = $?
$realLASTEXITCODE = $LASTEXITCODE
if ( $realCommandStatus -eq $True ) {
$EXIT="Green"
} else {
$EXIT="Red"
}
$Path = $pwd.ProviderPath
Write-Host
Write-Host "$env:USERNAME" -NoNewLine -ForegroundColor Magenta
Write-Host " @" -NoNewLine -ForegroundColor Yellow
Write-Host " $Path " -NoNewLine -ForegroundColor Green
if($gitStatus){
Get-checkgit($Path)
}
Write-Host "`n>" -NoNewLine -ForegroundColor $EXIT
$global:LASTEXITCODE = $realLASTEXITCODE
return " "
}
Set-OMPPSColor -Setting @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Green'}
Reparse = @{ Color = 'Magenta'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html|Dockerfile|gradle|pp|packergitignore|gitattributes|go|)$' }
Executable = @{ Color = 'Green'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|sh|fsx|)$' }
Text = @{ Color = 'Cyan'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown|properties|json|todo)$' }
Compressed = @{ Color = 'Yellow'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Green'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/blocky.ps1
|
blocky.ps1
|
function global:prompt {
$realCommandStatus = $?
$realLASTEXITCODE = $LASTEXITCODE
$Path = $pwd.ProviderPath
Write-Host
Write-Host " $Path " -NoNewLine -ForegroundColor Black -BackgroundColor White
if($gitStatus){
checkGit($Path)
}
if ( $realCommandStatus -eq $True ) {
$BG_EXIT="Green"
} else {
$BG_EXIT="Red"
}
$global:LASTEXITCODE = $realLASTEXITCODE
Write-Host "`n > " -NoNewLine -ForegroundColor White -BackgroundColor $BG_EXIT
return " "
}
Set-OMPPSColor -Setting @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Green'}
Reparse = @{ Color = 'Magenta'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html|Dockerfile|gradle|pp|packergitignore|gitattributes|go|)$' }
Executable = @{ Color = 'Green'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|sh|fsx|)$' }
Text = @{ Color = 'Cyan'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown|properties|json|todo)$' }
Compressed = @{ Color = 'Yellow'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Green'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/base1.ps1
|
base1.ps1
|
function global:prompt {
$realLASTEXITCODE = $LASTEXITCODE
$Host.UI.RawUI.ForegroundColor = "White"
Write-Host
Write-Host $pwd.ProviderPath -NoNewLine -ForegroundColor Green
if($gitStatus){
checkGit($pwd.ProviderPath)
}
$global:LASTEXITCODE = $realLASTEXITCODE
Write-Host "`nλ" -NoNewLine -ForegroundColor "DarkGray"
return " "
}
Set-OMPPSColor -Setting @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Green'}
Reparse = @{ Color = 'Magenta'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html|Dockerfile|gradle|pp|packergitignore|gitattributes|go|)$' }
Executable = @{ Color = 'Green'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|sh|fsx|)$' }
Text = @{ Color = 'Cyan'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown|properties|json|todo)$' }
Compressed = @{ Color = 'Yellow'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Green'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/solarizedlight.ps1
|
solarizedlight.ps1
|
# Host Foreground
$Host.PrivateData.ErrorForegroundColor = 'Red'
$Host.PrivateData.WarningForegroundColor = 'Yellow'
$Host.PrivateData.DebugForegroundColor = 'Green'
$Host.PrivateData.VerboseForegroundColor = 'Blue'
$Host.PrivateData.ProgressForegroundColor = 'Gray'
# Host Background
$Host.PrivateData.ErrorBackgroundColor = 'Gray'
$Host.PrivateData.WarningBackgroundColor = 'Gray'
$Host.PrivateData.DebugBackgroundColor = 'Gray'
$Host.PrivateData.VerboseBackgroundColor = 'Gray'
$Host.PrivateData.ProgressBackgroundColor = 'Cyan'
# Check for PSReadline
if (Get-Module -ListAvailable -Name "PSReadline") {
$options = Get-PSReadlineOption
# Foreground
$options.CommandForegroundColor = 'Yellow'
$options.ContinuationPromptForegroundColor = 'DarkYellow'
$options.DefaultTokenForegroundColor = 'DarkYellow'
$options.EmphasisForegroundColor = 'Cyan'
$options.ErrorForegroundColor = 'Red'
$options.KeywordForegroundColor = 'Green'
$options.MemberForegroundColor = 'DarkGreen'
$options.NumberForegroundColor = 'DarkGreen'
$options.OperatorForegroundColor = 'DarkCyan'
$options.ParameterForegroundColor = 'DarkCyan'
$options.StringForegroundColor = 'Blue'
$options.TypeForegroundColor = 'DarkBlue'
$options.VariableForegroundColor = 'Green'
# Background
$options.CommandBackgroundColor = 'White'
$options.ContinuationPromptBackgroundColor = 'White'
$options.DefaultTokenBackgroundColor = 'White'
$options.EmphasisBackgroundColor = 'White'
$options.ErrorBackgroundColor = 'White'
$options.KeywordBackgroundColor = 'White'
$options.MemberBackgroundColor = 'White'
$options.NumberBackgroundColor = 'White'
$options.OperatorBackgroundColor = 'White'
$options.ParameterBackgroundColor = 'White'
$options.StringBackgroundColor = 'White'
$options.TypeBackgroundColor = 'White'
$options.VariableBackgroundColor = 'White'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/jaykul.ps1
|
jaykul.ps1
|
<#
This is a theme as a token of appretiation for a fellow PowerSheller I've learned a whole
lot from. It's one of his older prompts (slightly tweaked) but still looks pretty damn cool.
#>
function global:prompt {
$realCommandStatus = $?
$realLASTEXITCODE = $LASTEXITCODE
# Output prompt string
if ( $realCommandStatus -eq $True ) {
$fg = (Get-OMPPromptColor)['PromptForeground']
} else {
$fg = (Get-OMPPromptColor)['ErrorForeground']
}
$bg = (Get-OMPPromptColor)['PromptBackground']
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
try {
Set-OMPWindowTitle -Title ("{0} - {1} ({2})" -f ("PS $($PSVersionTable.PSVersion.Major) - ${Env:UserName}@${Env:UserDomain}$(if ( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( new-object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){' (ADMIN)'})"),$pwd.Path,$pwd.Provider.Name)
}
catch {
Set-OMPWindowTitle -Title ($pwd.Path)
}
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "$([char]9556)" -NoNewLine -Foreground $fg
Write-Host " $(if($Nesting){"$Nesting "})#$($MyInvocation.HistoryID)${Stack} " -Background $bg -Foreground $fg -NoNewLine
if (Get-Module 'psgit') {
Set-GitPromptSettings -BeforeForeground $fg `
-BranchForeground $fg `
-AheadByForeground $fg `
-BehindByForeground $fg `
-BeforeChangesForeground $fg `
-StagedChangesForeground $fg `
-SeparatorForeground $fg `
-UnStagedChangesForeground $fg `
-AfterChangesForeground $fg `
-AfterNoChangesForeground $fg `
-BeforeBackground $bg `
-BranchBackground $bg `
-AheadByBackground $bg `
-BehindByBackground $bg `
-BeforeChangesBackground $bg `
-StagedChangesBackground $bg `
-SeparatorBackground $bg `
-UnStagedChangesBackground $bg `
-AfterChangesBackground $bg `
-AfterNoChangesBackground $bg `
-HideZero
Write-Host ($pwd -replace $([Regex]::Escape((Convert-Path "~"))),"~") -Background $bg -Foreground $fg -NoNewLine
Write-VcsStatus
}
Write-Host ' '
Write-Host "$([char]9562)$([char]9552)$([char]9552)$([char]9552)$([char]9557)" -Foreground $fg -NoNewLine
$global:LASTEXITCODE = $realLASTEXITCODE
# Hack PowerShell ISE CTP2 (requires 4 characters of output)
if ($Host.Name -match "ISE" -and $PSVersionTable.BuildVersion -eq "6.2.8158.0") {
return "$("$([char]8288)"*3) "
}
else {
return " "
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/solarizeddark.ps1
|
solarizeddark.ps1
|
# L
# Host Foreground
$Host.PrivateData.ErrorForegroundColor = 'Red'
$Host.PrivateData.WarningForegroundColor = 'Yellow'
$Host.PrivateData.DebugForegroundColor = 'Green'
$Host.PrivateData.VerboseForegroundColor = 'Blue'
$Host.PrivateData.ProgressForegroundColor = 'Gray'
# Host Background
$Host.PrivateData.ErrorBackgroundColor = 'Black'
$Host.PrivateData.WarningBackgroundColor = 'Black'
$Host.PrivateData.DebugBackgroundColor = 'Black'
$Host.PrivateData.VerboseBackgroundColor = 'Black'
$Host.PrivateData.ProgressBackgroundColor = 'Cyan'
# Check for PSReadline
if (Get-Module -ListAvailable -Name "PSReadline") {
$options = Get-PSReadlineOption
# Foreground
$options.CommandForegroundColor = 'Yellow'
$options.ContinuationPromptForegroundColor = 'DarkBlue'
$options.DefaultTokenForegroundColor = 'DarkBlue'
$options.EmphasisForegroundColor = 'Cyan'
$options.ErrorForegroundColor = 'Red'
$options.KeywordForegroundColor = 'Green'
$options.MemberForegroundColor = 'DarkCyan'
$options.NumberForegroundColor = 'DarkCyan'
$options.OperatorForegroundColor = 'DarkGreen'
$options.ParameterForegroundColor = 'DarkGreen'
$options.StringForegroundColor = 'Blue'
$options.TypeForegroundColor = 'DarkYellow'
$options.VariableForegroundColor = 'Green'
# Background
$options.CommandBackgroundColor = 'Black'
$options.ContinuationPromptBackgroundColor = 'Black'
$options.DefaultTokenBackgroundColor = 'Black'
$options.EmphasisBackgroundColor = 'Black'
$options.ErrorBackgroundColor = 'Black'
$options.KeywordBackgroundColor = 'Black'
$options.MemberBackgroundColor = 'Black'
$options.NumberBackgroundColor = 'Black'
$options.OperatorBackgroundColor = 'Black'
$options.ParameterBackgroundColor = 'Black'
$options.StringBackgroundColor = 'Black'
$options.TypeBackgroundColor = 'Black'
$options.VariableBackgroundColor = 'Black'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/norm.ps1
|
norm.ps1
|
<# Based on norm zsh theme. Check it (https://github.com/robbyrussell/oh-my-zsh/blob/master/themes/norm.zsh-theme) #>
function global:prompt {
$realCommandStatus = $?
$realLASTEXITCODE = $LASTEXITCODE
$lambda = [char]::ConvertFromUtf32(955)
$forwardArrow = [char]::ConvertFromUtf32(8594)
if ( $realCommandStatus -eq $True ) {
$EXIT="Yellow"
} else {
$EXIT="Red"
}
$CurrentDirectory = Split-Path -leaf -path (Get-Location)
Write-Host
Write-Host "$lambda $env:USERNAME " -ForegroundColor Yellow -NoNewline
Write-Host "$CurrentDirectory" -NoNewLine -ForegroundColor Green
if(Get-GitStatus){
Write-Host " $forwardArrow $lambda " -ForegroundColor Yellow -NoNewline
Write-Host "git" -ForegroundColor Blue -NoNewline
checkGit(Get-Location)
}
Write-Host " $forwardArrow" -NoNewLine -ForegroundColor $EXIT
$global:LASTEXITCODE = $realLASTEXITCODE
return " "
}
Set-OMPPSColor -Setting @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Green'}
Reparse = @{ Color = 'Magenta'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html|Dockerfile|gradle|pp|packergitignore|gitattributes|go|)$' }
Executable = @{ Color = 'Green'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|sh|fsx|)$' }
Text = @{ Color = 'Cyan'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown|properties|json|todo)$' }
Compressed = @{ Color = 'Yellow'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Green'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/powerline.ps1
|
powerline.ps1
|
<#
Another one of Joel Bennett's works.
This is an example of an advanced theme with some additional plugin requirements
You can either install and set the modules to autoload with OhMyPsh OR just
enable the powerline and psgit plugins which will automatically download, install,
and load the appropriate modules as well.
Add-OMPPlugin psgit
Add-OMPPlugin powerline
#>
if ((-not (get-module psgit)) -or (-not (Get-Module Powerline))) {
Write-Output "Cannot use this theme without the powerline and psgit plugins (or modules) loaded!"
Write-Output "You can add these with the following commands:"
Write-Output ' Add-OMPPlugin psgit'
Write-Output ' Add-OMPPlugin powerline'
return
}
$Global:PowerLinePrompt = 1,
(
$null, # No left-aligned content on this line
@(
@{ text = { New-PowerLineBlock (Get-Elapsed) -ErrorBackgroundColor DarkRed -ErrorForegroundColor White -ForegroundColor Black -BackgroundColor DarkGray } }
@{ bg = "Gray"; fg = "Black"; text = { Get-Date -f "T" } }
)
), @(
@{ bg = "Blue"; fg = "White"; text = { $MyInvocation.HistoryId } }
@{ bg = "Cyan"; fg = "White"; text = { [PowerLine.Prompt]::Gear * $NestedPromptLevel } }
@{ bg = "Cyan"; fg = "White"; text = { if($pushd = (Get-Location -Stack).count) { "$([char]187)" + $pushd } } }
@{ bg = "DarkBlue"; fg = "White"; text = { $pwd.Drive.Name } }
@{ bg = "DarkBlue"; fg = "White"; text = { Split-Path $pwd -leaf } }
# PSGit is still in early stages, but it has PowerLine support
@{ text = { Get-GitStatusPowerline } }
)
Set-PowerLinePrompt -CurrentDirectory -PowerlineFont:(!$SafeCharacters) -Title { "PowerShell - {0} ({1})" -f (Convert-Path $pwd), $pwd.Provider.Name }
# Setting a (slightly modified) Dark Solarized color theme as well
# Host Foreground
$Host.PrivateData.ErrorForegroundColor = 'Red'
$Host.PrivateData.WarningForegroundColor = 'Yellow'
$Host.PrivateData.DebugForegroundColor = 'Green'
$Host.PrivateData.VerboseForegroundColor = 'Blue'
$Host.PrivateData.ProgressForegroundColor = 'Gray'
# Host Background
$Host.PrivateData.ErrorBackgroundColor = 'Black'
$Host.PrivateData.WarningBackgroundColor = 'Black'
$Host.PrivateData.DebugBackgroundColor = 'Black'
$Host.PrivateData.VerboseBackgroundColor = 'Black'
$Host.PrivateData.ProgressBackgroundColor = 'Cyan'
# Check for PSReadline
if (Get-Module -ListAvailable -Name "PSReadline") {
$options = Get-PSReadlineOption
# Foreground
$options.CommandForegroundColor = 'Yellow'
$options.ContinuationPromptForegroundColor = 'DarkBlue'
$options.DefaultTokenForegroundColor = 'DarkBlue'
$options.EmphasisForegroundColor = 'Cyan'
$options.ErrorForegroundColor = 'Red'
$options.KeywordForegroundColor = 'Green'
$options.MemberForegroundColor = 'DarkCyan'
$options.NumberForegroundColor = 'DarkCyan'
$options.OperatorForegroundColor = 'DarkGreen'
$options.ParameterForegroundColor = 'DarkGreen'
$options.StringForegroundColor = 'Blue'
$options.TypeForegroundColor = 'DarkYellow'
$options.VariableForegroundColor = 'Green'
# Background
$options.CommandBackgroundColor = 'Black'
$options.ContinuationPromptBackgroundColor = 'Black'
$options.DefaultTokenBackgroundColor = 'Black'
$options.EmphasisBackgroundColor = 'Black'
$options.ErrorBackgroundColor = 'Black'
$options.KeywordBackgroundColor = 'Black'
$options.MemberBackgroundColor = 'Black'
$options.NumberBackgroundColor = 'Black'
$options.OperatorBackgroundColor = 'Black'
$options.ParameterBackgroundColor = 'Black'
$options.StringBackgroundColor = 'Black'
$options.TypeBackgroundColor = 'Black'
$options.VariableBackgroundColor = 'Black'
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/themes/base2.ps1
|
base2.ps1
|
function Global:Test-Administrator {
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
function Global:prompt {
$realLASTEXITCODE = $LASTEXITCODE
Write-Host
# Reset color, which can be messed up by Enable-GitColors
$Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor
if (Test-Administrator) { # Use different username if elevated
Write-Host "(Elevated) " -NoNewline -ForegroundColor White
}
Write-Host "$ENV:USERNAME@" -NoNewline -ForegroundColor DarkYellow
Write-Host "$ENV:COMPUTERNAME" -NoNewline -ForegroundColor Magenta
if ($s -ne $null) { # color for PSSessions
Write-Host " (`$s: " -NoNewline -ForegroundColor DarkGray
Write-Host "$($s.Name)" -NoNewline -ForegroundColor Yellow
Write-Host ") " -NoNewline -ForegroundColor DarkGray
}
Write-Host " : " -NoNewline -ForegroundColor DarkGray
Write-Host $($(Get-Location) -replace "$($env:USERPROFILE)", "~") -NoNewline -ForegroundColor Blue
Write-Host " : " -NoNewline -ForegroundColor DarkGray
Write-Host (Get-Date -Format G) -NoNewline -ForegroundColor DarkMagenta
Write-Host " : " -NoNewline -ForegroundColor DarkGray
$global:LASTEXITCODE = $realLASTEXITCODE
Write-VcsStatus
Write-Host ""
return "> "
}
Set-OMPPSColor -Setting @{
File = @{
Default = @{ Color = 'White' }
Directory = @{ Color = 'Green'}
Reparse = @{ Color = 'Magenta'}
Hidden = @{ Color = 'DarkGray'; Pattern = '^\.' }
Code = @{ Color = 'Magenta'; Pattern = '\.(java|c|cpp|cs|js|css|html|Dockerfile|gradle|pp|packergitignore|gitattributes|go|)$' }
Executable = @{ Color = 'Green'; Pattern = '\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg|sh|fsx|)$' }
Text = @{ Color = 'Cyan'; Pattern = '\.(txt|cfg|conf|ini|csv|log|config|xml|yml|md|markdown|properties|json|todo)$' }
Compressed = @{ Color = 'Yellow'; Pattern = '\.(zip|tar|gz|rar|jar|war)$' }
}
Service = @{
Default = @{ Color = 'White' }
Running = @{ Color = 'DarkGreen' }
Stopped = @{ Color = 'DarkRed' }
}
Match = @{
Default = @{ Color = 'White' }
Path = @{ Color = 'Green'}
LineNumber = @{ Color = 'Yellow' }
Line = @{ Color = 'White' }
}
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/templates/plugin/Load.ps1
|
Load.ps1
|
<#
NOTE: In either of the sections below you have the following variables at your disposal
$PluginPath = The current path of your plugin minus the name (ie. C:\temp\)
$Name = The name of your plugin folder. (ie. myplugin)
So the full path to where this file is saved would be:
Join-Path $PluginPath $Name
#>
$PreLoad = {
<#
Load any requirements here. Any modules should be loaded via Import-OMPModule
to ensure they adhere to the profile settings for module auto installation.
Example:
Import-OMPModule 'Posh-Git'
You should put any functions you want exported in a separate ps1 file (of any name) in the src
directory. If you want the function to be available in the OhMyPsh session then you will need to
create it in a global scope.
#>
}
$PostLoad = {
<#
Anything else you may want to do after the plugin loads (Write a message to the screen, create aliases, et cetera)
The only rule is that anything you want available in the user session must be scoped globally or it will
never see the outside of this module scope!
Note, anything you create here should be gracefully removed in the respective 'Unload.ps1' file in this
plugin directory. If you don't adhere to this rule your plugin will not be considered for this project.
You don't have to worry about removing any globally scoped functions, the template Unload.ps1 code will
do that and the module unload code will also remove them from memory upon being unloaded.
Example 1:
Set-Alias -Name ll -Value Get-ChildItem -option AllScope -Scope Global
Sets an alias for Get-ChildItem called 'll' in the global scope
#>
}
$Config = {
<#
This gets run after the PostLoad scriptblock. At first run it will be stored in
the profile path as the configuration to be used for this plugin moving forward.
The config scriptblock is a way to maintain plugin settings that persist through
an OhMyPsh upgrade.
#>
}
$Shutdown = {
<#
Put anything here you need to run if OhMyPsh is unloaded or the console session is killed.
If you have a profile variable that needs to be updated for the next first run of your plugin this
is the place to put it.
Example:
Set-OMPProfileSetting -Name 'PSReadlineHistoryLoaded' -Value $false
Export-OMPProfile
#>
}
$Unload = {
<#
Be nice and be modular please, unload any other profile settings or loaded modules you may
have introduced with your plugin.
*NOTE* Any 'global:<functionname> items will have already been automatically removed by
OhMyPsh at this point so you don't have to worry about those!
#>
}
|
PowerShellCorpus/PowerShellGallery/OhMyPsh/0.0.5/templates/plugin/src/Plugin.ps1
|
Plugin.ps1
|
<#
#A quick template function
function Global:Some-Function {
[CmdletBinding( )]
Param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Name
)
Begin {
$Names = @()
}
Process {
$Names += $Name
}
End {
$Names | ForEach-Object {
$_
}
}
}
#>
<# Or an alias perhaps
Set-Alias -Name mycmd -Value cmd -option AllScope -Scope Global
#>
|
PowerShellCorpus/PowerShellGallery/PSModuleTemplate/1.0.0.2/Resources/New-ProjectTemplate/PSModuleName.Tests.ps1
|
PSModuleName.Tests.ps1
|
$Script:Config = Import-PowerShellDataFile -Path "$PSScriptRoot\config.psd1"
Import-Module -Name '.\<ModuleName>' -Force
Import-Module -Name '.\Functions.psm1' -Force
Describe 'Description Name' {
Context 'Context Name #1' {
It 'UnProtect-Config works with raw strings' {
'Hello World' | UnProtect-Config | Should Be 'Hello World'
}
}
Context 'Context Name #2' {
It '...' {
$true | Should Be $true
}
It '...' {
$true | Should Not Be $false
}
}
}
|
PowerShellCorpus/PowerShellGallery/PSModuleTemplate/1.0.0.2/Resources/New-ProjectTemplate/Program.ps1
|
Program.ps1
|
<#
.SYNOPSIS
Lorem ipsum dolor sit amet.
.DESCRIPTION
Lorem ipsum dolor sit amet.
.PARAMETER Param1
Lorem ipsum dolor sit amet.
.PARAMETER Param2
Lorem ipsum dolor sit amet.
.INPUTS
Lorem ipsum dolor sit amet..
.OUTPUTS
Lorem ipsum dolor sit amet.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[object] $Param1,
[Parameter()]
[object] $Param2
)
try
{
Import-Module -Name "$PSScriptRoot\<ModuleName>" -Force
Import-Module -Name "$PSScriptRoot\Functions.psm1" -Force
$Script:Config = Import-PowerShellDataFile -Path "$PSScriptRoot\config.psd1"
Start-TranscriptLogFile
'Utilice Out-Default para transcribir al archivo log' | Out-Default
'Puede enviar texto o cualquier objeto' | Out-Default
Get-Variable | Out-Default
}
catch{
$ErrorInfo = $Error[0]
'='.PadRight(100,'=') | Out-Default
[PSCustomObject]@{
ScriptName = $ErrorInfo.InvocationInfo.ScriptName
ErrorMessage = $ErrorInfo.Exception.Message
LineNumber = $ErrorInfo.InvocationInfo.ScriptLineNumber
ColumnNumber = $ErrorInfo.InvocationInfo.OffsetInLine
Category = $ErrorInfo.CategoryInfo.Category
ErrorReason = $ErrorInfo.CategoryInfo.Reason
Target = $ErrorInfo.CategoryInfo.TargetName
StackTrace = $ErrorInfo.Exception.StackTrace
} | Out-Default
}
finally{
Stop-TranscriptLogFile
}
|
PowerShellCorpus/PowerShellGallery/cWSMan/1.0.1.31/Examples/Sample_cWSManListener_HTTP.ps1
|
Sample_cWSManListener_HTTP.ps1
|
configuration Sample_cWSManListener_HTTP
{
Import-DscResource -Module cWSMan
Node $NodeName
{
cWSManListener HTTP
{
Transport = 'HTTP'
Ensure = 'Present'
} # End of cWSManListener Resource
} # End of Node
} # End of Configuration
|
PowerShellCorpus/PowerShellGallery/cWSMan/1.0.1.31/Examples/Sample_cWSManListener_HTTPS.ps1
|
Sample_cWSManListener_HTTPS.ps1
|
configuration Sample_cWSManListener_HTTPS
{
Import-DscResource -Module cWSMan
Node $NodeName
{
cWSManListener HTTP
{
Transport = 'HTTPS'
Ensure = 'Present'
Issuer = 'CN=CONTOSO.COM Issuing CA, DC=CONTOSO, DC=COM'
} # End of cWSManListener Resource
} # End of Node
} # End of Configuration
|
PowerShellCorpus/PowerShellGallery/cWSMan/1.0.1.31/Tests/Unit/BMD_cWSManListener.Tests.ps1
|
BMD_cWSManListener.Tests.ps1
|
$DSCResourceName = 'BMD_cWSManListener'
$DSCModuleName = 'cWSMan'
$Splat = @{
Path = $PSScriptRoot
ChildPath = "..\..\DSCResources\$DSCResourceName\$DSCResourceName.psm1"
Resolve = $true
ErrorAction = 'Stop'
}
$DSCResourceModuleFile = Get-Item -Path (Join-Path @Splat)
$moduleRoot = "${env:ProgramFiles}\WindowsPowerShell\Modules\$DSCModuleName"
if(-not (Test-Path -Path $moduleRoot))
{
$null = New-Item -Path $moduleRoot -ItemType Directory
}
else
{
# Copy the existing folder out to the temp directory to hold until the end of the run
# Delete the folder to remove the old files.
$tempLocation = Join-Path -Path $env:Temp -ChildPath $DSCModuleName
Copy-Item -Path $moduleRoot -Destination $tempLocation -Recurse -Force
Remove-Item -Path $moduleRoot -Recurse -Force
$null = New-Item -Path $moduleRoot -ItemType Directory
}
Copy-Item -Path $PSScriptRoot\..\..\* -Destination $moduleRoot -Recurse -Force -Exclude '.git'
if (Get-Module -Name $DSCResourceName)
{
Remove-Module -Name $DSCResourceName
}
Import-Module -Name $DSCResourceModuleFile.FullName -Force
$breakvar = $True
InModuleScope $DSCResourceName {
######################################################################################
# Create the Mock Objects that will be used for running tests
$Global:MockFQDN = 'SERVER1.CONTOSO.COM'
$Global:MockCertificateThumbprint = '74FA31ADEA7FDD5333CED10910BFA6F665A1F2FC'
$Global:MockIssuer = 'CN=CONTOSO.COM Issuing CA, DC=CONTOSO, DC=COM'
$Global:MockCertificate = [PSObject]@{
Thumbprint = $Global:MockCertificateThumbprint
Subject = "CN=$([System.Net.Dns]::GetHostByName($ENV:computerName).Hostname)"
Issuer = $Global:MockIssuer
Extensions = @{ EnhancedKeyUsages = @{ FriendlyName = 'Server Authentication' } }
DNSNameList = @{ Unicode = "$([System.Net.Dns]::GetHostByName($ENV:computerName).Hostname)" }
}
$Global:MockListenerHTTP = [PSObject]@{
cfg = 'http://schemas.microsoft.com/wbem/wsman/1/config/listener'
xsi = 'http://www.w3.org/2001/XMLSchema-instance'
lang = 'en-US'
Address = '*'
Transport = 'HTTP'
Port = 5985
Hostname = ''
Enabled = 'true'
URLPrefix = 'wsman'
CertificateThumbprint = ''
}
$Global:MockListenerHTTPS = [PSObject]@{
cfg = 'http://schemas.microsoft.com/wbem/wsman/1/config/listener'
xsi = 'http://www.w3.org/2001/XMLSchema-instance'
lang = 'en-US'
Address = '*'
Transport = 'HTTPS'
Port = 5986
Hostname = $Global:MockFQDN
Enabled = 'true'
URLPrefix = 'wsman'
CertificateThumbprint = $Global:MockCertificateThumbprint
}
######################################################################################
Describe 'Get-TargetResource' {
Context 'No listeners exist' {
Mock Get-WSManInstance -MockWith { }
It 'should return absent listener' {
$Result = Get-TargetResource `
-Transport HTTP `
-Ensure Present
$Result.Ensure | Should Be 'Absent'
}
It 'should call Get-WSManInstance once' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'Requested listener does not exist' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP) }
It 'should return absent listener' {
$Result = Get-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure Present
$Result.Ensure | Should Be 'Absent'
}
It 'should call Get-WSManInstance once' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'Requested listener does exist' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP) }
It 'should return correct listener' {
$Result = Get-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure Present
$Result.Ensure | Should Be 'Present'
$Result.Port | Should Be $Global:MockListenerHTTP.Port
$Result.Address | Should Be $Global:MockListenerHTTP.Address
$Result.HostName | Should Be $Global:MockListenerHTTP.HostName
$Result.Enabled | Should Be $Global:MockListenerHTTP.Enabled
$Result.URLPrefix | Should Be $Global:MockListenerHTTP.URLPrefix
$Result.CertificateThumbprint | Should Be $Global:MockListenerHTTP.CertificateThumbprint
}
It 'should call Get-WSManInstance once' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
}
######################################################################################
Describe 'Set-TargetResource' {
Context 'HTTP Listener does not exist but should' {
Mock Get-WSManInstance -MockWith { }
Mock Remove-WSManInstance -MockWith { }
Mock New-WSManInstance -MockWith { }
It 'should not throw error' {
{ Set-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure 'Present' } | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
Assert-MockCalled -commandName Remove-WSManInstance -Exactly 0
Assert-MockCalled -commandName New-WSManInstance -Exactly 1
}
}
Context 'HTTPS Listener does not exist but should' {
Mock Get-WSManInstance -MockWith { }
Mock Remove-WSManInstance -MockWith { }
Mock New-WSManInstance -MockWith { }
Mock Get-ChildItem -MockWith { $Global:MockCertificate }
It 'should not throw error' {
{ Set-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Present' `
-Issuer $Global:MockIssuer } | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
Assert-MockCalled -commandName Remove-WSManInstance -Exactly 0
Assert-MockCalled -commandName New-WSManInstance -Exactly 1
Assert-MockCalled -commandName Get-ChildItem -Exactly 1
}
}
Context 'HTTP Listener exists but should not' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP) }
Mock Remove-WSManInstance -MockWith { }
Mock New-WSManInstance -MockWith { }
It 'should not throw error' {
{ Set-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure 'Absent' } | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
Assert-MockCalled -commandName Remove-WSManInstance -Exactly 1
Assert-MockCalled -commandName New-WSManInstance -Exactly 0
}
}
Context 'HTTP Listener exists and should' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP) }
Mock Remove-WSManInstance -MockWith { }
Mock New-WSManInstance -MockWith { }
Mock Get-ChildItem -MockWith { $Global:MockCertificate }
It 'should not throw error' {
{ Set-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure 'Present' `
-Issuer $Global:MockIssuer } | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
Assert-MockCalled -commandName Remove-WSManInstance -Exactly 1
Assert-MockCalled -commandName New-WSManInstance -Exactly 1
Assert-MockCalled -commandName Get-ChildItem -Exactly 0
}
}
Context 'HTTPS Listener exists and should' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTPS) }
Mock Remove-WSManInstance -MockWith { }
Mock New-WSManInstance -MockWith { }
Mock Get-ChildItem -MockWith { $Global:MockCertificate }
It 'should not throw error' {
{ Set-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Present' `
-Issuer $Global:MockIssuer } | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
Assert-MockCalled -commandName Remove-WSManInstance -Exactly 1
Assert-MockCalled -commandName New-WSManInstance -Exactly 1
Assert-MockCalled -commandName Get-ChildItem -Exactly 1
}
}
Context 'Both Listeners exists and HTTPS should' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP,$Global:MockListenerHTTPS) }
Mock Remove-WSManInstance -MockWith { }
Mock New-WSManInstance -MockWith { }
Mock Get-ChildItem -MockWith { $Global:MockCertificate }
It 'should not throw error' {
{ Set-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Present' `
-Issuer $Global:MockIssuer } | Should Not Throw
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
Assert-MockCalled -commandName Remove-WSManInstance -Exactly 1
Assert-MockCalled -commandName New-WSManInstance -Exactly 1
Assert-MockCalled -commandName Get-ChildItem -Exactly 1
}
}
}
######################################################################################
Describe 'Test-TargetResource' {
Context 'HTTP Listener does not exist but should' {
Mock Get-WSManInstance -MockWith { }
It 'should return false' {
Test-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure 'Present' | Should Be $False
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'HTTPS Listener does not exist but should' {
Mock Get-WSManInstance -MockWith { }
It 'should return false' {
Test-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Present' `
-Issuer $Global:MockIssuer | Should Be $False
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'HTTP Listener exists but should not' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP) }
It 'should return false' {
Test-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure 'Absent' | Should Be $False
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'HTTPS Listener exists but should not' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTPS) }
It 'should return false' {
Test-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Absent' | Should Be $False
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'HTTP Listener exists and should' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP) }
It 'should return true' {
Test-TargetResource `
-Transport $Global:MockListenerHTTP.Transport `
-Ensure 'Present' | Should Be $True
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'HTTPS Listener exists and should' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTPS) }
It 'should return true' {
Test-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Present' | Should Be $True
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
Context 'Both Listeners exists and HTTPS should' {
Mock Get-WSManInstance -MockWith { return @($Global:MockListenerHTTP,$Global:MockListenerHTTPS) }
It 'should return true' {
Test-TargetResource `
-Transport $Global:MockListenerHTTPS.Transport `
-Ensure 'Present' | Should Be $True
}
It 'should call expected Mocks' {
Assert-MockCalled -commandName Get-WSManInstance -Exactly 1
}
}
}
######################################################################################
}
# Clean up after the test completes.
Remove-Item -Path $moduleRoot -Recurse -Force
# Restore previous versions, if it exists.
if ($tempLocation)
{
$null = New-Item -Path $moduleRoot -ItemType Directory
$script:Destination = "${env:ProgramFiles}\WindowsPowerShell\Modules"
Copy-Item -Path $tempLocation -Destination $script:Destination -Recurse -Force
Remove-Item -Path $tempLocation -Recurse -Force
}
|
PowerShellCorpus/PowerShellGallery/cLocalGroup/1.0.1/Examples/Sample_cLocalGroup.ps1
|
Sample_cLocalGroup.ps1
|
configuration Sample_cLocalGroup
{
Import-DscResource -ModuleName cLocalGroup
cLocalGroup LocalGroup1
{
Ensure = 'Present'
GroupName = 'Group-1'
Description = 'Created by the cLocalGroup DSC resource'
Members = 'IIS APPPOOL\DefaultAppPool', 'NT AUTHORITY\IUSR'
}
cLocalGroup LocalGroup2
{
Ensure = 'Present'
GroupName = 'Group-2'
Description = 'Created by the cLocalGroup DSC resource'
MembersToExclude = "$Env:UserDomain\Domain Users", 'Guest'
MembersToInclude = "$Env:UserDomain\$Env:UserName", 'BUILTIN\Administrators'
}
}
Sample_cLocalGroup -OutputPath "$Env:SystemDrive\Sample_cLocalGroup"
Start-DscConfiguration -Path "$Env:SystemDrive\Sample_cLocalGroup" -Force -Verbose -Wait
Get-DscConfiguration
|
PowerShellCorpus/PowerShellGallery/cLocalGroup/1.0.1/ResourceDesignerScripts/GenerateCLocalGroupSchema.ps1
|
GenerateCLocalGroupSchema.ps1
|
#requires -Version 4.0 -Modules xDSCResourceDesigner
$ModuleName = 'cLocalGroup'
$ResourceName = 'cLocalGroup'
$DscResourceProperties = @(
(New-xDscResourceProperty -Type String -Attribute Write -Name Ensure -ValidateSet 'Absent', 'Present' -Description 'Indicates if the group exists. Set this property to Absent to ensure that the group does not exist. Setting it to Present (the default value) ensures that the group exists.')
(New-xDscResourceProperty -Type String -Attribute Key -Name GroupName -Description 'Indicates the name of the group.'),
(New-xDscResourceProperty -Type String -Attribute Write -Name Description -Description 'Indicates the description of the group.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name Members -Description 'Indicates that you want to ensure these members form the group.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name MembersToExclude -Description 'Indicates the users who you want ensure are not members of this group.'),
(New-xDscResourceProperty -Type String[] -Attribute Write -Name MembersToInclude -Description 'Indicates the users who you want to ensure are members of the group.')
)
New-xDscResource -Name $ResourceName -ModuleName $ModuleName -Property $DscResourceProperties -Verbose
|
PowerShellCorpus/PowerShellGallery/cLocalGroup/1.0.1/Tests/ResourceDesignerTests.ps1
|
ResourceDesignerTests.ps1
|
#requires -Version 4.0 -Modules xDSCResourceDesigner
Split-Path -Path $PSScriptRoot -Parent |
Join-Path -ChildPath 'DSCResources' |
Get-ChildItem -Directory |
Test-xDscResource -Name {$_.FullName} -Verbose
|
PowerShellCorpus/PowerShellGallery/_LibraryTest1/1.0.0.3/bin/library.ps1
|
library.ps1
|
#region Source Code
$source = @'
using System;
namespace sqlcollective.dbatools
{
namespace Configuration
{
using System.Collections;
/// <summary>
/// Configuration Manager as well as individual configuration object.
/// </summary>
[Serializable]
public class Config
{
public static Hashtable Cfg = new Hashtable();
public string Name;
public string Module;
public string Type
{
get { return Value.GetType().FullName; }
set { }
}
public Object Value;
public bool Hidden = false;
}
}
}
'@
#endregion Source Code
try { Add-Type $source -ErrorAction Stop }
catch
{
throw
}
function Get-Test
{
Write-Host "Test1"
}
|
PowerShellCorpus/PowerShellGallery/PSJsonCredential/1.1.3.0/Tests/PSJsonCredential.Tests.ps1
|
PSJsonCredential.Tests.ps1
|
#requires -version 5.0
#Pester tests for the PSJsonCredential Module
$modroot = Split-Path (Split-path $MyInvocation.MyCommand.Path)
Write-host "Importing moduling from $modroot" -ForegroundColor Cyan
Import-Module $modRoot -force
InModuleScope PSJsonCredential {
$plainText = "myPassword"
$user = "company\administrator"
$secure = ConvertTo-SecureString -String $plainText -AsPlainText -Force
$testCredential = New-object -TypeName PSCredential $user,$secure
$json = Join-Path -Path $env:TEMP -ChildPath admin.json
Describe Export {
It "Should run with out error" {
{ Export-PSCredentialToJson -credential $testCredential -Path $json -ErrorAction Stop} | Should Not Throw
}
It "Should run with pipeline input" {
{ $testCredential | Export-PSCredentialToJson -Path $json -ErrorAction Stop} | Should Not Throw
}
It "Should fail with a bad path" {
{ $testCredential | Export-PSCredentialToJson -Path Foo:\foo.json} | Should Throw
}
It "Should create a file object when using -Passthru" {
$script:out = $testCredential | Export-PSCredentialtoJson -path $json -passthru
$script:out.getType().Name | Should Be FileInfo
}
It "Should create a json file called $json" {
$script:out.fullname | Should be $json
}
It "Should not overwrite an existing file if using -NoClobber" {
$testCredential | Export-PSCredentialToJson -Path $json -NoClobber -OutVariable o
$o | Should Be $Null
}
}
Describe Get {
It "Should run without error" {
{$script:get = Get-PSCredentialFromJson -Path $json -ErrorAction Stop} | Should Not Throw
}
It "Should have a user property of $user" {
$script:get.userName | Should be $user
}
It "Should have a [string] password" {
$script:get.password.getType().name | Should be "string"
}
It "Should have an ExportDate property" {
$d = $script:get.exportDate -as [DateTime]
$d.GetType().Name | Should be "DateTime"
}
It "Should have an ExportUser property of $user" {
$script:get.exportUser | Should Be "$($env:computername)\$($env:username)"
}
It "Should have an ExportComputer property of $($env:computername)" {
$script:get.exportComputer | Should Be $Env:computername
}
It "Should have a path property of $json" {
$script:get.path | Should Be $json
}
}
Describe Import {
It "Should run without error" {
{$script:in = Import-PSCredentialFromJson -Path $json -ErrorAction Stop} | Should Not Throw
}
It "Should create a PSCredential object" {
$Script:in.GetType().Name | Should Be "PSCredential"
}
It "Should have a UserName property of $user" {
$script:in.UserName | Should be $user
}
It "Should have a secure string password that decrypts to '$plaintext'" {
$Script:in.GetNetworkCredential().Password | Should Be $plaintext
}
}
#remove json file
If (Test-Path -Path $json) {
Remove-Item -Path $json
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/TestModuleImport.ps1
|
TestModuleImport.ps1
|
BuildTask TestModuleImport -Stage Test -Properties @{
Order = 0
Implementation = {
$exceptionMessage = powershell.exe -NoProfile -Command "
try {
Import-Module $($buildInfo.ReleaseManifest.FullName) -ErrorAction Stop
exit 0
} catch {
`$_.Exception.Message
exit 1
}
"
if ($lastexitcode -ne 0) {
throw $exceptionMessage
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/TestModule.ps1
|
TestModule.ps1
|
BuildTask TestModule -Stage Test -Properties @{
Order = 2
Implementation = {
if (-not (Get-ChildItem (Join-Path $buildInfo.Source 'test') -Filter *.tests.ps1 -Recurse -File)) {
throw 'The PS project must have tests!'
}
$invokePester = {
param (
$buildInfo
)
$path = Join-Path $buildInfo.Source 'test'
if (Test-Path (Join-Path $path 'stub')) {
Get-ChildItem (Join-Path $path 'stub') -Filter *.psm1 | ForEach-Object {
Import-Module $_.FullName -Global -WarningAction SilentlyContinue
}
}
Import-Module $buildInfo.ReleaseManifest -Global -ErrorAction Stop
$params = @{
Script = $path
CodeCoverage = $buildInfo.ReleaseRootModule
OutputFile = Join-Path $buildInfo.Output ('{0}.xml' -f $buildInfo.ModuleName)
PassThru = $true
}
Invoke-Pester @params
}
if ($buildInfo.IsAdministrator -and -not (Test-CIServer)) {
$pester = Invoke-Command $invokePester -ArgumentList $buildInfo -ComputerName $env:COMPUTERNAME
} else {
$pester = & $invokePester $buildInfo
}
$path = Join-Path $buildInfo.Output 'pester-output.xml'
$pester | Export-CliXml $path
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/TestSolution.ps1
|
TestSolution.ps1
|
BuildTask TestSolution -Stage Test -Properties @{
ValidWhen = { (Test-Path (Join-Path $buildInfo.Source 'class\*.sln')) -and (Test-Path (Join-Path $buildInfo.Source 'class\packages\NUnit.ConsoleRunner.*\tools\nunit3-console.exe')) }
Order = 2
Implementation = {
Push-Location (Join-Path $buildInfo.Source 'class')
$nunitConsole = (Resolve-Path 'packages\NUnit.ConsoleRunner.*\tools\nunit3-console.exe').Path
Get-ChildItem -Filter *tests.dll -Recurse | Where-Object FullName -like '*bin*' | ForEach-Object {
& $nunitConsole $_.FullName --result ('{0}\{1}.xml' -f $buildInfo.Output.FullName, ($_.Name -replace '\.tests'))
}
Pop-Location
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/AddAppVeyorCommitMessage.ps1
|
AddAppVeyorCommitMessage.ps1
|
BuildTask AddAppveyorCommitMessage -Stage Test -Properties @{
Order = 3
ValidWhen = { Get-Command Add-AppVeyorCompilationMessage -ErrorAction SilentlyContinue }
Implementation = {
# Pester
$pester = Invoke-Pester @params
$path = Join-Path $buildInfo.Output 'pester-output.xml'
if (Test-Path $path) {
$pester = Import-CliXml $path
$params = @{
Message = 'Passed {0} of {1} tests' -f $pester.PassedCount, $pester.TotalCount
Category = 'Information'
}
if ($pester.FailedCount -gt 0) {
$params.Category = 'Warning'
}
Add-AppVeyorCompilationMessage @params
if ($pester.CodeCoverage) {
[Double]$codeCoverage = $pester.CodeCoverage.NumberOfCommandsExecuted / $pester.CodeCoverage.NumberOfCommandsAnalyzed
$params = @{
Message = '{0:P2} test coverage' -f $codeCoverage
Category = 'Information'
}
if ($codecoverage -lt $buildInfo.CodeCoverageThreshold) {
$params.Category = 'Warning'
}
Add-AppVeyorCompilationMessage @params
}
}
# Solution
Get-ChildItem $buildInfo.Output -Filter *.dll.xml | ForEach-Object {
$report = [Xml](Get-Content $_.FullName -Raw)
$params = @{
Message = 'Passed {0} of {1} solution tests in {2}' -f $report.'test-run'.passed,
$report.'test-run'.total,
$report.'test-run'.'test-suite'.name
Category = 'Information'
}
if ([Int]$report.'test-run'.failed -gt 0) {
$params.Category = 'Warning'
}
Add-AppVeyorCompilationMessage @params
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/UploadAppVeyorTestResults.ps1
|
UploadAppVeyorTestResults.ps1
|
BuildTask UploadAppVeyorTestResults -Stage Test -Properties @{
Order = 3
ValidWhen = { $null -ne $env:APPVEYOR_JOB_ID }
Implementation = {
$path = Join-Path $buildInfo.Output ('{0}.xml' -f $buildInfo.ModuleName)
if (Test-Path $path) {
$webClient = New-Object System.Net.WebClient
$webClient.UploadFile(('https://ci.appveyor.com/api/testresults/nunit/{0}' -f $env:APPVEYOR_JOB_ID), $path)
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/ValidateTestResults.ps1
|
ValidateTestResults.ps1
|
BuildTask ValidateTestResults -Stage Test -Properties @{
Order = 4
Implementation = {
$testsFailed = $false
$path = Join-Path $buildInfo.Output 'pester-output.xml'
$pester = Import-CliXml $path
# PSScriptAnalyzer
$path = Join-Path $buildInfo.Output 'psscriptanalyzer.csv'
if ((Test-Path $path) -and ($testResults = Import-Csv $path)) {
'{0} warnings were raised by PSScriptAnalyzer' -f @($testResults).Count
$testsFailed = $true
}
# Pester tests
if ($pester.FailedCount -gt 0) {
'{0} of {1} pester tests are failing' -f $pester.FailedCount, $pester.TotalCount
$testsFailed = $true
}
# Pester code coverage
[Double]$codeCoverage = $pester.CodeCoverage.NumberOfCommandsExecuted / $pester.CodeCoverage.NumberOfCommandsAnalyzed
$pester.CodeCoverage.MissedCommands | Export-Csv (Join-Path $buildInfo.Output 'CodeCoverage.csv') -NoTypeInformation
if ($codecoverage -lt $buildInfo.CodeCoverageThreshold) {
'Pester code coverage ({0:P}) is below threshold {1:P}.' -f $codeCoverage, $buildInfo.CodeCoverageThreshold
$testsFailed = $true
}
# Solution tests
Get-ChildItem $buildInfo.Output -Filter *.dll.xml | ForEach-Object {
$report = [Xml](Get-Content $_.FullName -Raw)
if ([Int]$report.'test-run'.failed -gt 0) {
'{0} of {1} solution tests in {2} are failing' -f $report.'test-run'.failed,
$report.'test-run'.total,
$report.'test-run'.'test-suite'.name
$testsFailed = $true
}
}
if ($testsFailed) {
throw 'Test result validation failed'
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Test/PSScriptAnalyzer.ps1
|
PSScriptAnalyzer.ps1
|
BuildTask PSScriptAnalyzer -Stage Test -Properties @{
Order = 1
ValidWhen = { Get-Module PSScriptAnalyzer -ListAvailable }
Implementation = {
'enumeration', 'class', 'private', 'public', 'InitializeModule.ps1' | ForEach-Object {
$path = Join-Path $buildInfo.Source $_
if (Test-Path $path) {
Invoke-ScriptAnalyzer -Path $path -Recurse | ForEach-Object {
$_
$_ | Export-Csv (Join-Path $buildInfo.Output 'psscriptanalyzer.csv') -NoTypeInformation -Append
}
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Release/UpdateCatalog.ps1
|
UpdateCatalog.ps1
|
BuildTask UpdateCatalog -Stage Release -Properties @{
Order = 1
ValidWhen = { $null -ne $env:CodeSigningCertificate }
Implementation = {
New-FileCatalog $buildInfo.Package -Path $buildInfo.Package -CatalogVersion $buildInfo.Version
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Release/SignModule.ps1
|
SignModule.ps1
|
BuildTask SignModule -Stage Release -Properties @{
Order = 1
ValidWhen = { $null -ne $env:CodeSigningCertificate }
Implementation = {
Set-AuthenticodeSignature '...'
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Publish/UpdateVersion.ps1
|
UpdateVersion.ps1
|
BuildTask UpdateVersion -Stage Publish -Properties @{
Order = 0
Implementation = {
Update-Metadata (Join-Path $buildInfo.Source $buildInfo.ReleaseManifest.Name) -PropertyName ModuleVersion -Value $buildInfo.Version
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Publish/PublishToCurrentUser.ps1
|
PublishToCurrentUser.ps1
|
BuildTask PublishToCurrentUser -Stage Publish -Properties @{
Order = 1
Implementation = {
$path = '{0}\Documents\WindowsPowerShell\Modules\{1}' -f $home, $buildInfo.ModuleName
if (-not (Test-Path $path)) {
$null = New-Item $path -ItemType Directory
}
Copy-Item $buildInfo.Package -Destination $path -Recurse -Force
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Publish/PublishToPSGallery.ps1
|
PublishToPSGallery.ps1
|
BuildTask PublishToPSGallery -Stage Publish -Properties @{
Order = 2
ValidWhen = { $null -ne $env:NuGetApiKey }
Implementation = {
Publish-Module -Path $buildInfo.Package -NuGetApiKey $env:NuGetApiKey -Repository PSGallery -ErrorAction Stop
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/Merge.ps1
|
Merge.ps1
|
BuildTask Merge -Stage Build -Properties @{
Order = 4
Implementation = {
$mergeItems = 'enumeration', 'class', 'private', 'public', 'InitializeModule.ps1' | ForEach-Object {
Join-Path $buildInfo.Source $_
}
$fileStream = [System.IO.File]::Create($buildInfo.ReleaseRootModule)
$writer = New-Object System.IO.StreamWriter($fileStream)
$usingStatements = New-Object System.Collections.Generic.List[String]
Get-ChildItem $mergeItems -Filter *.ps1 -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Extension -eq '.ps1' -and $_.Length -gt 0 } |
ForEach-Object {
$functionDefinition = Get-Content $_.FullName | ForEach-Object {
if ($_ -match '^using') {
$usingStatements.Add($_)
} else {
$_.TrimEnd()
}
} | Out-String
$writer.WriteLine($functionDefinition.Trim())
$writer.WriteLine()
}
if (Test-Path 'InitializeModule.ps1') {
$writer.WriteLine('InitializeModule')
}
$writer.Close()
$rootModule = (Get-Content $buildInfo.ReleaseRootModule -Raw).Trim()
if ($usingStatements.Count -gt 0) {
# Add "using" statements to be start of the psm1
$rootModule = $rootModule.Insert(0, "`r`n`r`n").Insert(
0,
(($usingStatements.ToArray() | Sort-Object | Get-Unique) -join "`r`n")
)
}
Set-Content -Path $buildInfo.ReleaseRootModule -Value $rootModule -NoNewline
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/TestAttributeSyntax.ps1
|
TestAttributeSyntax.ps1
|
BuildTask TestAttributeSyntax -Stage Build -Properties @{
Order = 2
Implementation = {
$hasSyntaxErrors = $false
Get-ChildItem 'public', 'private', 'InitializeModule.ps1' -Filter *.ps1 -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Extension -eq '.ps1' -and $_.Length -gt 0 } |
ForEach-Object {
$tokens = $null
[System.Management.Automation.Language.ParseError[]]$parseErrors = @()
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
(Get-Content $_.FullName -Raw),
$_.FullName,
[Ref]$tokens,
[Ref]$parseErrors
)
# Test attribute syntax
$attributes = $ast.FindAll( {
param( $ast )
$ast -is [System.Management.Automation.Language.AttributeAst]
},
$true
)
foreach ($attribute in $attributes) {
if (($type = $attribute.TypeName.FullName -as [Type]) -or ($type = ('{0}Attribute' -f $attribute.TypeName.FullName) -as [Type])) {
$propertyNames = $type.GetProperties().Name
if ($attribute.NamedArguments.Count -gt 0) {
foreach ($argument in $attribute.NamedArguments) {
if ($argument.ArgumentName -notin $propertyNames) {
'Invalid property name in attribute declaration: {0}: {1} at line {2}, character {3}' -f
$_.Name,
$argument.ArgumentName,
$argument.Extent.StartLineNumber,
$argument.Extent.StartColumnNumber
$hasSyntaxErrors = $true
}
}
}
} else {
'Invalid attribute declaration: {0}: {1} at line {2}, character {3}' -f
$_.Name,
$attribute.TypeName.FullName,
$attribute.Extent.StartLineNumber,
$attribute.Extent.StartColumnNumber
$hasSyntaxErrors = $true
}
}
}
if ($hasSyntaxErrors) {
throw 'TestAttributeSyntax failed'
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/UpdateMarkdownHelp.ps1
|
UpdateMarkdownHelp.ps1
|
BuildTask UpdateMarkdownHelp -Stage Build -Properties @{
Order = 1025
ValidWhen = { Get-Module platyPS -ListAvailable }
Implementation = {
$exceptionMessage = powershell.exe -NoProfile -Command "
try {
Import-Module $($buildInfo.ReleaseManifest.FullName) -ErrorAction Stop
New-MarkdownHelp -Module $($buildInfo.ModuleName) -OutputFolder '$($buildInfo.Source)\help' -Force
exit 0
} catch {
`$_.Exception.Message
exit 1
}
"
if ($lastexitcode -ne 0) {
throw $exceptionMessage
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/ImportDependencies.ps1
|
ImportDependencies.ps1
|
BuildTask ImportDependencies -Stage Build -Properties @{
ValidWhen = { Test-Path (Join-Path $buildInfo.Source 'modules.config') }
Implementation = {
$libPath = Join-Path $buildInfo.Package 'lib'
if (-not (Test-Path $libPath)) {
$null = New-Item $libPath -ItemType Directory
}
foreach ($module in ([Xml](Get-Content 'modules.config' -Raw)).modules.module) {
Find-Module -Name $module.Name | Save-Module -Path $libPath
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/Clean.ps1
|
Clean.ps1
|
BuildTask Clean -Stage Build -Properties @{
Order = 0
Implementation = {
if (Get-Module $buildInfo.ModuleName) {
Remove-Module $buildInfo.ModuleName
}
Get-ChildItem $buildInfo.Package.Parent.FullName -Directory -ErrorAction SilentlyContinue |
Where-Object { [Version]::TryParse($_.Name, [Ref]$null) } |
Remove-Item -Recurse -Force
if (Test-Path $buildInfo.Output) {
Remove-Item $buildInfo.Output -Recurse -Force
}
$null = New-Item $buildInfo.Output -ItemType Directory -Force
$null = New-Item $buildInfo.Package -ItemType Directory -Force
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/BuildProject.ps1
|
BuildProject.ps1
|
BuildTask BuildProject -Stage Build -Properties @{
Order = 0
ValidWhen = { (Test-Path (Join-Path $buildInfo.Source 'class\*.*proj')) -and -not (Test-Path (Join-Path $buildInfo.Source 'class\*.sln')) }
Implementation = {
Push-Location 'class'
try {
$null = Get-Command msbuild
Get-Item '*.*proj' | ForEach-Object {
$proj = [Xml](Get-Content $_.FullName)
if ($proj.Project.PropertyGroup.OutputType -eq 'winexe') {
$outputPath = Join-Path $buildInfo.ModuleBase.FullName 'bin'
} else {
$outputPath = Join-Path $buildInfo.ModuleBase.FullName 'lib'
}
if (-not (Test-Path $outputPath)) {
$null = New-Item $outputPath -ItemType Directory -Force
}
msbuild /t:Clean /t:Build /p:OutputPath=$outputPath /p:DebugSymbols=false /p:DebugType=None $_.Name
}
} catch {
throw
} finally {
Pop-Location
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/CompileClass.ps1
|
CompileClass.ps1
|
BuildTask Clean -Stage Build -Properties @{
ValidWhen = { -not (Test-Path (Join-Path $buildInfo.Source 'class\*.sln')) -and -not (Test-Path (Join-Path $this.Source 'class\*.*proj')) -and (Test-Path (Join-Path $buildInfo.Source 'class\*.cs')) }
Implementation = {
$outputPath = Join-Path $buildInfo.ModuleBase.FullName 'lib'
$typeDefinition = Get-ChildItem 'class\*.cs' -ErrorAction SilentlyContinue | Get-Content | Out-String
$params = @{
TypeDefinition = $typeDefinition
OutputType = 'Library'
OutputPath = $outputPath
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/UpdateMetadata.ps1
|
UpdateMetadata.ps1
|
BuildTask UpdateMetadata -Stage Build -Properties @{
Implementation = {
try {
# Version
Update-Metadata $buildInfo.ReleaseManifest -PropertyName ModuleVersion -Value $buildInfo.Version
# RootModule
if (Enable-Metadata $buildInfo.ReleaseManifest -PropertyName RootModule) {
Update-Metadata $buildInfo.ReleaseManifest -PropertyName RootModule -Value $buildInfo.ReleaseRootModule.Name
}
# FunctionsToExport
if (Enable-Metadata $buildInfo.ReleaseManifest -PropertyName FunctionsToExport) {
Update-Metadata $buildInfo.ReleaseManifest -PropertyName FunctionsToExport -Value (
(Get-ChildItem (Join-Path $buildInfo.Source 'public') -Filter '*.ps1' -File -Recurse).BaseName
)
}
# RequiredAssemblies
if (Test-Path (Join-Path $buildInfo.Package 'lib\*.dll')) {
if (Enable-Metadata $buildInfo.ReleaseManifest -PropertyName RequiredAssemblies) {
Update-Metadata $buildInfo.ReleaseManifest -PropertyName RequiredAssemblies -Value (
(Get-Item (Join-Path $buildInfo.Package 'lib\*.dll')).Name | ForEach-Object {
Join-Path 'lib' $_
}
)
}
}
# FormatsToProcess
if (Test-Path (Join-Path $buildInfo.Package '*.Format.ps1xml')) {
if (Enable-Metadata $buildInfo.ReleaseManifest -PropertyName FormatsToProcess) {
Update-Metadata $buildInfo.ReleaseManifest -PropertyName FormatsToProcess -Value (Get-Item (Join-Path $buildInfo.Package '*.Format.ps1xml')).Name
}
}
# LicenseUri
if (Test-Path (Join-Path $buildInfo.ProjectRoot 'LICENSE')) {
if (Enable-Metadata $buildInfo.ReleaseManifest -PropertyName LicenseUri) {
Update-Metadata $buildInfo.ReleaseManifest -PropertyName LicenseUri -Value 'https://opensource.org/licenses/MIT'
}
}
# ProjectUri
if (Enable-Metadata $buildInfo.ReleaseManifest -PropertyName ProjectUri) {
# Attempt to parse the project URI from the list of upstream repositories
[String]$pushOrigin = (git remote -v) -like 'origin*(push)'
if ($pushOrigin -match 'origin\s+(?<ProjectUri>\S+).git') {
Update-Metadata $buildInfo.ReleaseManifest -PropertyName ProjectUri -Value $matches.ProjectUri
}
}
} catch {
throw
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/CopyModuleFiles.ps1
|
CopyModuleFiles.ps1
|
BuildTask CopyModuleFiles -Stage Build -Properties @{
Order = 3
Implementation = {
$exclude = 'class', 'enumeration', 'private', 'public', 'InitializeModule.ps1', 'modules.config', 'packages.config', 'test', 'help'
Get-ChildItem $buildInfo.Source -Exclude $exclude |
Copy-Item -Destination $buildInfo.Package -Recurse -Force
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/TestSyntax.ps1
|
TestSyntax.ps1
|
BuildTask TestSyntax -Stage Build -Properties @{
Order = 1
Implementation = {
$hasSyntaxErrors = $false
Get-ChildItem 'public', 'private', 'InitializeModule.ps1' -Filter *.ps1 -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Extension -eq '.ps1' -and $_.Length -gt 0 } |
ForEach-Object {
$tokens = $null
[System.Management.Automation.Language.ParseError[]]$parseErrors = @()
$ast = [System.Management.Automation.Language.Parser]::ParseInput(
(Get-Content $_.FullName -Raw),
$_.FullName,
[Ref]$tokens,
[Ref]$parseErrors
)
if ($parseErrors.Count -gt 0) {
$parseErrors | Write-Error
$hasSyntaxErrors = $true
}
}
if ($hasSyntaxErrors) {
throw 'TestSyntax failed'
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Build/BuildSolution.ps1
|
BuildSolution.ps1
|
BuildTask BuildSolution -Stage Build -Properties @{
Order = 3
ValidWhen = { Test-Path (Join-Path $buildInfo.Source 'class\*.sln') }
Implementation = {
Push-Location (Join-Path $buildInfo.Source 'class')
try {
$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile('https://dist.nuget.org/win-x86-commandline/latest/nuget.exe', "$pwd\nuget.exe")
.\nuget.exe restore
msbuild /t:Clean /t:Build /p:DebugSymbols=false /p:DebugType=None
if ($lastexitcode -ne 0) {
throw 'msbuild failed'
}
$path = (Join-Path $buildInfo.Package 'lib')
if (-not (Test-Path $path)) {
$null = New-Item $path -ItemType Directory -Force
}
Get-Item * -Exclude *.tests, packages | Where-Object PsIsContainer | ForEach-Object {
Get-ChildItem $_.FullName -Filter *.dll -Recurse |
Where-Object FullName -like '*bin*' |
Copy-Item -Destination $path
}
} catch {
throw
} finally {
if (Test-Path .\nuget.exe) {
Remove-Item .\nuget.exe
}
Pop-Location
}
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Setup/UpdateAppVeyorYml.ps1
|
UpdateAppVeyorYml.ps1
|
BuildTask UpdateAppVeyorYml -Stage Setup -Properties @{
Order = 0
ValidWhen = {
$appVeyorYml = Join-Path $buildInfo.ProjectRoot 'appveyor.yml'
(Test-Path $appVeyorYml) -and (Get-Item $appVeyorYml).Size -gt 0
}
Implementation = {
$path = Join-Path $buildInfo.ProjectRoot 'appveyor.yml'
$content = 'os: WMF 5',
'',
'version: 1.0.{build}.0',
'',
'environment:',
' NuGetApiKey:',
' secure: kp9PPkiJ/iiPfX0b1m/NYh88GLaok3NlJc1XAr6rWH+umpCiZVwvsK9CVfMNYElL',
'',
'skip_commits:',
' message: /updated? readme.*s/',
'',
'build: false',
'',
'install:',
' - ps: |',
' $null = Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force',
' Set-PSRepository -Name PSGallery -InstallationPolicy Trusted',
' Install-Module Configuration, Pester, Indented.Build',
' Set-Location $env:APPVEYOR_BUILD_FOLDER\$env:APPVEYOR_PROJECT_NAME',
' Get-BuildInfo -BuildType Build',
'',
'build_script:',
' - ps: Start-Build -BuildType Build',
'',
'test_script:',
' - ps: Start-Build -BuildType Test'
Set-Content $path -Value $content
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/task/Setup/UpdateAppVeyorVersion.ps1
|
UpdateAppVeyorVersion.ps1
|
BuildTask UpdateAppVeyorVersion -Stage Setup -Properties @{
Order = 1
ValidWhen = { Test-Path (Join-Path $buildInfo.ProjectRoot 'appveyor.yml') }
Implementation = {
$versionString = '{0}.{1}.{{build}}' -f $buildInfo.Version.Major, $buildInfo.Version.Minor
$path = Join-Path $buildInfo.ProjectRoot 'appveyor.yml'
$content = Get-Content $path -Raw
$content = $content -replace 'version: .+', ('version: {0}' -f $versionString)
Set-Content $path -Value $content -NoNewLine
}
}
|
PowerShellCorpus/PowerShellGallery/Indented.Build/2.16.0/var/tests/CodingConventions.tests.ps1
|
CodingConventions.tests.ps1
|
function Get-ItemFromAst {
# .SYNOPSIS
# Get an item from the abstract syntax tree.
# .DESCRIPTION
# Searches for an item using the specified predicate.
# .PARAMETER Ast
# The base of the tree to search from.
# .PARAMETER Query
# Used to create the predicate.
# .INPUTS
# System.Management.Automation.Language.Ast
# System.String
# .OUTPUTS
# System.Management.Automation.PSObject
# .NOTES
# Author: Chris Dent
#
# Change log:
# 07/12/2015 - Chris Dent - Created.
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 1)]
[System.Management.Automation.Language.Ast]$Ast,
[Parameter(Mandatory = $true, Position = 2)]
[String]$Query
)
$predicate = [ScriptBlock]::Create(('param( $Ast ); {0}' -f $Query))
$matchedElements = $Ast.FindAll($Predicate, $true) | Where-Object { $_ }
if ($matchedElements) {
foreach ($element in $matchedElements) {
'{0} at line {1}, position {2}: {3}' -f
$element.Extent.Text,
$element.Extent.StartLineNumber,
$element.Extent.StartColumnNumber,
$element.Parent.Extent.Text
}
} else {
return $false
}
}
function Test-FunctionStructure {
# .SYNOPSIS
# Use the abstract syntax tree to explore the content of a command.
# .DESCRIPTION
# Test-FunctionStructure is used to analyse the content of a function to support the standards described below.
# .PARAMETER ScriptBlock
# A script block to operate against.
# .INPUTS
# System.Management.Automation.ScriptBlock
# .OUTPUTS
# System.Management.Automation.PSObject
# .EXAMPLE
# Get-Command New-GRXPathNavigator | Test-FunctionStructure
# .NOTES
# Author: Chris Dent
#
# Change log:
# 07/12/2015 - Chris Dent - Created.
[CmdletBinding()]
[OutputType([System.Management.Automation.PSObject])]
param(
[Parameter(ValueFromPipelineByPropertyName = $true)]
[ScriptBlock]$ScriptBlock
)
process {
return [PSCustomObject]@{
HasNestedFunctions = (Get-ItemFromAst $ScriptBlock.Ast.Body '$Ast -is [System.Management.Automation.Language.FunctionDefinitionAst]')
IsUsingAddType = (Get-ItemFromAst $ScriptBlock.Ast '$Ast -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $Ast.Value -eq "Add-Type"')
IsUsingAliases = (Get-ItemFromAst $ScriptBlock.Ast '$Ast -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $Ast.Parent -isnot [System.Management.Automation.Language.MemberExpressionAst] -and $Ast.StringConstantType -eq [System.Management.Automation.Language.StringConstantType]::BareWord -and (Test-Path -LiteralPath alias:$($Ast.Value))')
IsUsingNewObject = (Get-ItemFromAst $ScriptBlock.Ast '$Ast -is [System.Management.Automation.Language.PipelineAst] -and $Ast.Extent.Text -match "New-Object (-TypeName )?(Object|PSObject|PSCustomObject)"')
IsUsingThrow = (Get-ItemFromAst $ScriptBlock.Ast '$Ast -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $Ast.Value -eq "throw"')
IsUsingWriteErrorStop = (Get-ItemFromAst $ScriptBlock.Ast '$Ast -is [System.Management.Automation.Language.StringConstantExpressionAst] -and $Ast.Value -eq "Write-Error" -and $Ast.Parent.Extent.Text -match "-ErrorAction (1|Stop)"')
}
}
}
function Test-IndentationStyle {
# .SYNOPSIS
# Test a scriptblock for subjectively incorrect use of white space.
# .DESCRIPTION
# Test-IndentationStyle looks at the content of a script and attempts to determine if the indentation style is somewhat consistent or not.
#
# As a by-product this function also checks for trailing white space.
# .PARAMETER ScriptBlock
# The script block to analyse.
# .INPUTS
# System.Management.Automation.ScriptBlock
# .OUTPUTS
# System.Management.Automation.PSObject
# .EXAMPLE
# Get-Command ConvertTo-GRString | Test-IndentationStyle
# .NOTES
# Author: Chris Dent
#
# Change log:
# 08/12/2015 - Chris Dent - Created.
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)]
[ScriptBlock]$ScriptBlock
)
process {
$Indentation = [PSCustomObject]@{
Character = $null
Description = ''
HasMixed = $false
HasIncorrectIndent = $false
HasTrailingSpaces = $false
Length = 0
IncorrectIndent = (New-Object System.Collections.Generic.List[Int])
TrailingSpaces = (New-Object System.Collections.Generic.List[Int])
}
$Definition = $ScriptBlock.ToString() -split '\r?\n'
$BraceStack = New-Object System.Collections.Stack
$CommentBlock = $EscapedLineBreak = $PipelinedStack = $false
for ($i = 0; $i -lt $Definition.Length; $i++) {
if ($Definition[$i].Trim().Length -gt 0) {
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Definition[$i], [Ref]$null)
# Establish if this is a comment block or not. Tokenize would be able to tell us this more easily if it weren't line-by-line processing.
$Tokens | Where-Object { $_.Type -eq 'Comment' } | ForEach-Object {
if ($_.Content -eq '<#') {
$CommentBlock = $true
} elseif ($_.Content -eq '#>') {
$CommentBlock = $false
}
}
# Attempt to establish the indentation style
if (-not $CommentBlock) {
if ($Indentation.Character -eq $null -and $Definition[$i] -match '^([\s\t]+)') {
$Indentation.Character = [String]($matches[1][0])
$Indentation.Length = $matches[1].Length
$Indentation.Description = switch ($Indentation.Length) {
1 { 'single' }
2 { 'double' }
3 { 'triple' }
4 { 'quad' }
default { 'long' }
}
$Indentation.Description += switch ($Indentation.Character) {
' ' { '-space' }
"`t" { '-tab' }
}
}
}
# Simple tests
# Mixed indentation character
if ($Definition[$i] -match '^(\s+\t|\t+\s)') {
$Indentation.HasMixed = $true
} elseif ($Indentation.Character -eq ' ' -and $Definition[$i] -match '^\t') {
$Indentation.HasMixed = $true
} elseif ($Indentation.Character -eq "`t" -and $Defintion[$i] -match ' ') {
$Indentation.HasMixed = $true
}
# Trailing spaces
if ($Definition[$i] -match ' +$') {
$Indentation.TrailingSpaces.Add($i + 1)
}
# Account for opening and closing braces
# A little extra work is required to handle close first then open.
$Control = 0
$Tokens | Where-Object { $_.Type -in 'GroupStart', 'GroupEnd' } | ForEach-Object {
if ($_.Type -eq 'GroupStart') {
$Control++
$null = $BraceStack.Push($_.Content)
} else {
$Control--
$null = $BraceStack.Pop()
}
}
if ($Control -eq 0 -and $Tokens[0].Type -eq 'GroupEnd') {
$IndentCount = $BraceStack.Count
} elseif ($Control -lt 0 -and $Tokens.Count -gt 1 -and $Tokens[-1].Type -eq 'GroupEnd') {
# Attempting to account for " Thing)", but not "} thing (Stuff)"
# Where the last character is a closing group, but is not preceeded by the equivalent opening group
$GroupEnd = $Tokens[-1].Content
$GroupStart = switch ($GroupEnd) {
')' { '(' }
']' { '[' }
'}' { '}' }
}
if (-not ($Tokens | Where-Object { $_.Type -eq 'GroupStart' -and $_.Content -eq $GroupStart })) {
$IndentCount = $BraceStack.Count + 2
} else {
$IndentCount = $BraceStack.Count + 1
}
} elseif ($Control -gt 0) {
$IndentCount = $BraceStack.Count
} else {
$IndentCount = $BraceStack.Count + 1
}
# Handle escape characters at the end of the line, allow extra indentation to follow. PSParser cannot see these characters.
# This will apply to the next line, but will not affect the overall count.
# Extra indentation based on an occurence of this one the preceeding line.
if ($EscapedLineBreak) {
$IndentCount++
}
# Set the control variable if this has occured on this line.
if (-not $EscapedLineBreak -and $Definition[$i] -match '`$' -and $Tokens[-1].Type -ne 'Comment') {
$EscapedLineBreak = $true
}
# Handle lines ending with |.
# Indentation on the following line will be allowed but there's no way to track the end of the block with this style.
if ($PipelinedStack) {#
$IndentCount++
}
if ($Tokens[-1].Type -eq 'Operator' -and $Tokens[-1].Content -eq '|') {
$PipelinedStack = $true
}
# A final check for the PipelinedStack
if ($PipelinedStack) {
$TempIndentString = $Indentation.Character * $Indentation.Length * ($IndentCount - 1)
if ($Definition[$i] -match "^$TempIndentString\S+") {
$PipelinedStack = $false
$IndentCount--
}
}
# The amount the code is expected to be indented.
$IndentString = $Indentation.Character * $Indentation.Length * $IndentCount
# Test it
if ($Definition[$i] -notmatch "^$IndentString\S+") {
Write-Debug ("Fail: ^$IndentString\S+".PadRight(40, ' ') + "Line " + ([String]($i + 1)).PadRight(6, ' ') + $Definition[$i])
$Indentation.IncorrectIndent.Add($i + 1)
} else {
Write-Debug ("Pass: ^$IndentString\S+".PadRight(40, ' ') + "Line " + ([String]($i + 1)).PadRight(6, ' ') + $Definition[$i])
}
# If the line was previously marked as escaped, but this one is not, unset the value now testing of indentation levels have been performed.
if ($EscapedLineBreak -and $Definition[$i] -notmatch '`$' -and $Tokens[-1].Type -ne 'Comment') {
$EscapedLineBreak = $false
}
}
}
if ($Indentation.IncorrectIndent.Count -gt 0) {
$Indentation.HasIncorrectIndent = "Lines: $($Indentation.IncorrectIndent.ToArray())"
}
if ($Indentation.TrailingSpaces.Count -gt 0) {
$Indentation.HasTrailingSpaces = "Lines: $($Indentation.TrailingSpaces.ToArray())"
}
$Indentation
}
}
#
# Main
#
# This is a bit of a problem now.
$ModuleName = Split-Path (Split-Path $psscriptroot -Parent) -Leaf
$ReservedParameterNames = ([System.Management.Automation.Internal.CommonParameters]).GetProperties() | Select-Object -ExpandProperty Name
$ReservedParameterNames += ([System.Management.Automation.Internal.ShouldProcessParameters]).GetProperties() | Select-Object -ExpandProperty Name
#
# Functions tests
#
Describe 'Function help content' {
Get-Command -Module $ModuleName | ForEach-Object {
$CommandInfo = $_
$HelpContent = Get-Help $CommandInfo.Name -Full
Context $CommandInfo.Name {
It 'Must have a synopsis' {
$HelpContent.synopsis | Should Not BeNullOrEmpty
}
It 'Must have a description' {
$HelpContent.description.text | Should Not BeNullOrEmpty
}
$CommandInfo.Parameters.Values | Where-Object { $_.Name -notin $ReservedParameterNames } | ForEach-Object {
It "Must have a description for Parameters\$($_.Name)" {
(Get-Help $CommandInfo.Name -Parameter $_.Name).description.Text | Should Not BeNullOrEmpty
}
}
if ($CommandInfo.Name -match '-') {
It 'Must have at least 1 example' {
($HelpContent.examples.example | Measure-Object).Count | Should BeGreaterThan 0
}
}
It 'Must have an author in notes' {
$HelpContent.alertSet.alert.Text | Should Match 'Author: +.+'
}
It 'Must have a change log in notes' {
$HelpContent.alertSet.alert.Text | Should Match 'Change log:'
}
}
}
}
#
# Code analysis - Valid only for FunctionInfo in the context of a module
#
Describe 'Function structure' {
Get-Command -Module $ModuleName -CommandType Function | ForEach-Object {
$CommandInfo = $_
$StructuralAnalysis = $CommandInfo | Test-FunctionStructure
$IndentationStyle = $CommandInfo | Test-IndentationStyle
Context $CommandInfo.Name {
if ($CommandInfo.Name -match '-') {
It "Must use an approved verb" {
Get-Verb $CommandInfo.Verb | Should Not BeNullOrEmpty
}
}
It 'Must declare the CmdletBinding attribute to prevent parameter overloading' {
$CommandInfo.CmdletBinding | Should Be $true
}
It 'Must use PSCustomObject in place of New-Object PSObject -Property' {
$StructuralAnalysis.IsUsingNewObject | Should Be $false
}
It 'Must not use Add-Type inside the body of a function' {
$StructuralAnalysis.IsUsingAddType | Should Be $false
}
It 'Must not contain nested functions' {
$StructuralAnalysis.HasNestedFunctions | Should Be $false
}
It "Must not mix space and tab indentation" {
$IndentationStyle.HasMixed | Should Be $false
}
}
}
}
Describe 'Function structure (recommended)' {
Get-Command -Module $ModuleName -CommandType Function | ForEach-Object {
$CommandInfo = $_
$CommandMetadata = New-Object System.Management.Automation.CommandMetadata($CommandInfo)
$StructuralAnalysis = $CommandInfo | Test-FunctionStructure
$IndentationStyle = $CommandInfo | Test-IndentationStyle
Context $CommandInfo.Name {
It 'Should implement the OutputType attribute if returning output' {
$CommandInfo.OutputType.Length | Should BeGreaterThan 0
}
It 'Should not use throw if CmdLetBinding is declared' {
$CommandInfo.CmdletBinding -and $StructuralAnalysis.IsUsingThrow | Should Be $false
}
It 'Should not use Write-Error -ErrorAction Stop' {
$StructuralAnalysis.IsUsingWriteErrorStop | Should Be $false
}
It "Should be consistently indented" {
$IndentationStyle.HasIncorrectIndent | Should Be $false
}
It "Should not have unnecessary trailing white space" {
$IndentationStyle.HasTrailingSpaces | Should Be $false
}
}
}
}
|
PowerShellCorpus/PowerShellGallery/ImprovedConvertFromJson/1.0.8/functions/ConvertFrom-JsonWithArgs.Tests.ps1
|
ConvertFrom-JsonWithArgs.Tests.ps1
|
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
InModuleScope ImprovedConvertFromJson {
#region Test data
$jsonHash = @"
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
"@
$jsonArray = @"
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
}
]
"@
#endregion
Describe "ConvertFrom-JsonWithArgs" {
It "Can parse JSON dictionary" {
$output = ConvertFrom-JsonWithArgs -InputObject $jsonHash
$output | Should Not BeNullOrEmpty
$output.glossary | Should Not BeNullOrEmpty
$output.glossary.title | Should Not BeNullOrEmpty
$output.glossary.title | Should Be "example glossary"
}
It "Can parse JSON array" {
$output = ConvertFrom-JsonWithArgs -InputObject $jsonArray
$output | Should Not BeNullOrEmpty
$output.Length | Should Be 3
$output[0] | Should Not BeNullOrEmpty
$output[0].color | Should Be "red"
}
It "Sets MaxLength" {
{ConvertFrom-JsonWithArgs -InputObject $jsonArray -MaxJsonLength 1} | Should Throw
}
}
}
|
PowerShellCorpus/PowerShellGallery/ImprovedConvertFromJson/1.0.8/functions/ConvertFrom-JsonWithArgs.ps1
|
ConvertFrom-JsonWithArgs.ps1
|
<#
.SYNOPSIS
Deserializes the input object from JSON
.PARAMETER InputObject
JSON string
.PARAMETER MaxJsonLength
Maximum length to support for the input string, defaults to [int]::MaxValue
#>
function ConvertFrom-JsonWithArgs
{
[CmdletBinding()]
param
(
[parameter(ParameterSetName = 'object', ValueFromPipeline = $true, Position = 0, Mandatory = $true)]
[string]$InputObject,
[parameter(ParameterSetName = 'object', Position = 1, Mandatory = $false)]
[int]$MaxJsonLength = [int]::MaxValue
)
process
{
function PopulateJsonFrom-Dictionary
{
param
(
[System.Collections.Generic.IDictionary`2[String,Object]]$InputObject
)
process
{
$returnObject = New-Object PSObject
foreach($key in $InputObject.Keys)
{
$pairObjectValue = $InputObject[$key]
if ($pairObjectValue -is [System.Collections.Generic.IDictionary`2].MakeGenericType([String],[Object]))
{
$pairObjectValue = PopulateJsonFrom-Dictionary $pairObjectValue
}
elseif ($pairObjectValue -is [System.Collections.Generic.ICollection`1].MakeGenericType([Object]))
{
$pairObjectValue = PopulateJsonFrom-Collection $pairObjectValue
}
$returnObject | Add-Member Noteproperty $key $pairObjectValue
}
return $returnObject
}
}
function PopulateJsonFrom-Collection
{
param
(
[System.Collections.Generic.ICollection`1[Object]]$InputObject
)
process
{
$returnList = New-Object ([System.Collections.Generic.List`1].MakeGenericType([Object]))
foreach($jsonObject in $InputObject)
{
$jsonObjectValue = $jsonObject
if ($jsonObjectValue -is [System.Collections.Generic.IDictionary`2].MakeGenericType([String],[Object]))
{
$jsonObjectValue = PopulateJsonFrom-Dictionary $jsonObjectValue
}
elseif ($jsonObjectValue -is [System.Collections.Generic.ICollection`1].MakeGenericType([Object]))
{
$jsonObjectValue = PopulateJsonFrom-Collection $jsonObjectValue
}
$returnList.Add($jsonObjectValue) | Out-Null
}
return $returnList.ToArray()
}
}
$scriptAssembly = [System.Reflection.Assembly]::LoadWithPartialName("System.Web.Extensions")
$typeResolver = "public class JsonObjectTypeResolver : System.Web.Script.Serialization.JavaScriptTypeResolver
{
public override System.Type ResolveType(string id)
{
return typeof (System.Collections.Generic.Dictionary<string, object>);
}
public override string ResolveTypeId(System.Type type)
{
return string.Empty;
}
}"
Add-Type -TypeDefinition $typeResolver -ReferencedAssemblies $scriptAssembly.FullName
$jsonserial = New-Object System.Web.Script.Serialization.JavaScriptSerializer(New-Object JsonObjectTypeResolver)
$jsonserial.MaxJsonLength = $MaxJsonLength
$jsonTree = $jsonserial.DeserializeObject($InputObject)
if ($jsonTree -is [System.Collections.Generic.IDictionary`2].MakeGenericType([String],[Object]))
{
$jsonTree = PopulateJsonFrom-Dictionary $jsonTree
}
elseif ($jsonTree -is [System.Collections.Generic.ICollection`1].MakeGenericType([Object]))
{
$jsonTree = PopulateJsonFrom-Collection $jsonTree
}
return $jsonTree
}
}
|
PowerShellCorpus/PowerShellGallery/ChefAutomate/0.1.7/functions/Get-ChefAutomateUserToken.ps1
|
Get-ChefAutomateUserToken.ps1
|
<#
.SYNOPSIS
Returns the status of the nominated Chef Automate server.
.DESCRIPTION
Returns the status of the nominated Chef Automate server. Does not require an authentication token.
.EXAMPLE
C:\PS> Get-ChefAutomateStatus -automateServer 'chef-automate.company.com'
.INPUTS
Takes the DNS-resolvable name of the Chef Automate server (e.g. 'chef-automate' or 'chef-automate.company.com')
.OUTPUTS
Core server health, configuration mode and FIPS mode of the Chef Automate Server.
#>
function Get-ChefAutomateUserToken
{
[CmdletBinding()]
[Alias()]
Param
(
# Chef Automate Server (e.g. chef-automate.company.com)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateServer,
# Chef Automate Enterprise Name (e.g. MyOrg)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateOrgName
)
Begin
{
}
Process
{
$tokenURL= 'https://' + $automateServer + '/' + 'api'
}
End
{
$OutputObject = [PSCustomObject]@{
'Core Server Health' = $coreHealth
'Configuration Mode' = ($apiStatus."configuration mode").substring(0,1).toupper() + ($apiStatus."configuration mode").substring(1).tolower()
'FIPS Mode' = ($apiStatus.fips_mode).substring(0,1).toupper() + ($apiStatus.fips_mode).substring(1).tolower()
}
Write-Output -InputObject $OutputObject
}
}
|
PowerShellCorpus/PowerShellGallery/ChefAutomate/0.1.7/functions/Save-ChefAutomateComplianceProfile.ps1
|
Save-ChefAutomateComplianceProfile.ps1
|
<#
.SYNOPSIS
Downloads the nominated compliance profile as a tarball.
.DESCRIPTION
Downloads the nominated compliance profile as a tarball from the Chef Automate compliance store and saves it to a specific path or the current path.
.EXAMPLE
C:\PS> Save-ChefAutomateComplianceProfiles -automateServer 'chef-automate.company.com' -automateOrgName OrgName -automateUser admin -automateUserToken <USER-TOKEN> -complianceName 'ssh'
.EXAMPLE
C:\PS> Save-ChefAutomateComplianceProfiles -automateServer 'chef-automate.company.com' -automateOrgName OrgName -automateUser admin -automateUserToken <USER-TOKEN> -complianceName 'ssh' -profilePath 'C:\Temp'
.INPUTS
Takes the DNS-resolvable name of the Chef Automate server (e.g. 'chef-automate' or 'chef-automate.company.com'), the Chef Automate Enterprise name (e.g. OrgName), the Chef Automate user who 'owns' the compliance profiles, the user token for authentication (https://YOUR_AUTOMATE_HOST/e/YOUR_AUTOMATE_ENTERPRISE/#/dashboard?token), the Compliance profile name (e.g. 'ssh') and the local path to which to save the tarball.
.OUTPUTS
Tarball containing the specified compliance profile.
#>
function Save-ChefAutomateComplianceProfile
{
[CmdletBinding()]
[Alias()]
Param
(
# Chef Automate Server (e.g. chef-automate.company.com)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateServer,
# Chef Automate Enterprise Name (e.g. MyOrg)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateOrgName,
# Chef Automate User (e.g. 'john')
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateUser,
# Chef Automate USer Token (https://YOUR_AUTOMATE_HOST/e/YOUR_AUTOMATE_ENTERPRISE/#/dashboard?token)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateUserToken,
# Compliance Profile Name e.g. 'ssh')
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$complianceName,
# Local path for Compliance Profile e.g. 'C:\Temp')
[Parameter(Mandatory=$false,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$profilePath
)
Begin
{
}
Process
{
$profileURL = 'https://' + $automateServer + '/compliance/profiles/' + $automateUser + '/' + $complianceName + '/tar'
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("chef-delivery-enterprise", $automateOrgName)
$headers.Add("chef-delivery-user", $automateUser)
$headers.Add("chef-delivery-token", $automateUserToken)
$fileName = $complianceName +'-' + (Get-Date -Format yyyyMMddHHMMss) + '.tar.gz'
if($profilePath -eq $null){$profilePath = (Get-Item -Path ".\" -Verbose).FullName}
$localProfile = $profilePath + '\' + $fileName
Invoke-RestMethod -Method Get -Uri $profileURL -Headers $headers -OutFile $localProfile
}
End
{
$message = 'Downloaded compliance profile' + ' ' + '"' + $complianceName + '"' + ' to ' + $localProfile
Write-Output -InputObject $message
}
}
|
PowerShellCorpus/PowerShellGallery/ChefAutomate/0.1.7/functions/Get-ChefAutomateComplianceProfile.ps1
|
Get-ChefAutomateComplianceProfile.ps1
|
<#
.SYNOPSIS
Returns the details of a single compliance profile for a nominated owner.
.DESCRIPTION
Returns the details of a single compliance profile for a nominated owner from the Chef Automate compliance store.
.EXAMPLE
C:\PS> Get-ChefAutomateComplianceProfiles -automateServer 'chef-automate.company.com' -automateOrgName OrgName -automateUser admin -automateUserToken <USER-TOKEN> -complianceName 'ssh'
.INPUTS
Takes the DNS-resolvable name of the Chef Automate server (e.g. 'chef-automate' or 'chef-automate.company.com'), the Chef Automate Enterprise name (e.g. OrgName), the Chef Automate user who 'owns' the compliance profiles, the user token for authentication (https://YOUR_AUTOMATE_HOST/e/YOUR_AUTOMATE_ENTERPRISE/#/dashboard?token) and the Compliance profile name (e.g. 'ssh')
.OUTPUTS
PowerShell object containing the nominated compliance profile stored on the Chef Automate server owned by the nominated user.
#>
function Get-ChefAutomateComplianceProfile
{
[CmdletBinding()]
[Alias()]
Param
(
# Chef Automate Server (e.g. chef-automate.company.com)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateServer,
# Chef Automate Enterprise Name (e.g. MyOrg)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateOrgName,
# Chef Automate User (e.g. 'john')
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateUser,
# Chef Automate USer Token (https://YOUR_AUTOMATE_HOST/e/YOUR_AUTOMATE_ENTERPRISE/#/dashboard?token)
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$automateUserToken,
# Compliance Profile Name e.g. 'ssh')
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$complianceName
)
Begin
{
}
Process
{
$profileURL = 'https://' + $automateServer + '/compliance/profiles/' + $automateUser + '/' + $complianceName
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("chef-delivery-enterprise", $automateOrgName)
$headers.Add("chef-delivery-user", $automateUser)
$headers.Add("chef-delivery-token", $automateUserToken)
$profile = Invoke-RestMethod -Method Get -Uri $profileURL -Headers $headers
}
End
{
Write-Output -InputObject $profile
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.