Skip to content

Commit b378373

Browse files
v0.3.0
Added help documentation updated README Added samples Reverted Get-PSWho to not trim when using -AsString Added code to New-CustomFileName to preserve case for non-placeholders Modified Out-VerboseTee to turn on VerboseTee
1 parent b57e954 commit b378373

23 files changed

+2624
-239
lines changed

Add-Border.ps1

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
#add a border around a string of text
22

3-
# https://gist.github.com/jdhitsolutions/0bbd6b64c107d7da23e65359c4d0e25c
3+
<#
4+
originally published at
5+
https://gist.github.com/jdhitsolutions/0bbd6b64c107d7da23e65359c4d0e25c
46
7+
#>
58
Function Add-Border {
69
<#
710
.Synopsis
@@ -92,7 +95,7 @@ Create a border around the output of a Get-Service command.
9295
Process {
9396

9497
if ($pscmdlet.ParameterSetName -eq 'single') {
95-
Write-Detail "Processing '$text'" -Prefix PROCESS | write-Verbose
98+
Write-Detail "Processing '$text'" -Prefix PROCESS | Write-Verbose
9699
#get length of text
97100
$len = $text.Length
98101
}

FileNameTools.ps1

Lines changed: 49 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,32 @@
11

2-
#TODO: aDD OPTION TO WRITE TO HOME FOLDER OR DOCUMENTS
3-
42
Function New-RandomFileName {
5-
[cmdletbinding()]
3+
[cmdletbinding(DefaultParameterSetName="none")]
64
Param(
75
[parameter(Position = 0)]
6+
[Parameter(ParameterSetName = 'none')]
7+
[Parameter(ParameterSetName = 'home')]
8+
[Parameter(ParameterSetName = 'temp')]
89
#enter an extension without the leading period e.g 'bak'
910
[string]$Extension,
11+
[Parameter(ParameterSetName = 'temp')]
1012
[alias("temp")]
11-
[Switch]$UseTempFolder
13+
[Switch]$UseTempFolder,
14+
[Parameter(ParameterSetName = 'home')]
15+
[alias("home")]
16+
[Switch]$UseHomeFolder
1217
)
1318

1419
if ($UseTempFolder) {
1520
$filename = [system.io.path]::GetTempFileName()
1621
}
22+
elseif ($UseHomeFolder) {
23+
if ($PSVersionTable.PSEdition -eq 'Core' -AND $PSVersionTable.OS -notmatch "Windows") {
24+
$filename = Join-Path -Path $env:HOME -ChildPath ([system.io.path]::GetRandomFileName())
25+
}
26+
else {
27+
$filename = Join-Path -Path $env:USERPROFILE\Documents -ChildPath ([system.io.path]::GetRandomFileName())
28+
}
29+
}
1730
else {
1831
$filename = [system.io.path]::GetRandomFileName()
1932
}
@@ -27,30 +40,31 @@ Function New-RandomFileName {
2740
$filename
2841
}
2942

30-
} #end Get-RandomFilename
43+
} #end New-RandomFilename
3144

32-
<#
33-
create a custom file name from any combination of elements
34-
computername
35-
username
36-
month
37-
day
38-
year
39-
time (hour:minute:second)
4045

41-
specify a separate like - _ or none
42-
#>
4346
Function New-CustomFileName {
4447
[cmdletbinding()]
4548
Param (
46-
[Parameter(Position = 0)]
49+
[Parameter(Position = 0,Mandatory)]
50+
[ValidateNotNullOrEmpty()]
4751
[string]$Template,
4852
[ValidateSet("Lower", "Upper", "Default")]
4953
[string]$Case = "default"
5054
)
5155

52-
[string]$filename = $Template.toLower()
56+
#convert placeholders to lower case but leave everything else as is
57+
[regex]$rx="%\w+(?=%|-|\.|\s|\(|\)|\[|\])"
58+
59+
Write-Detail "Starting $($myinvocation.MyCommand)" | Write-Verbose
60+
Write-Detail "Processing template: $template" | Write-Verbose
61+
$rx.matches($Template) | foreach-object {
62+
Write-Detail "Converting $($_.value) to lower case" | Write-Verbose
63+
$Template = $Template.replace($_.value,$_.value.tolower())
64+
}
5365

66+
[string]$filename = $Template
67+
Write-Detail "Using filename: $filename" | Write-Verbose
5468
$now = Get-Date
5569
if ($env:USERNAME) {
5670
$user = $env:USERNAME
@@ -67,23 +81,36 @@ Function New-CustomFileName {
6781
'%username' = $user
6882
'%computername' = (hostname)
6983
'%year' = $now.Year
70-
'%monthname' = ("{0:MMM}" -f $now)
84+
'%yr' = "{0:yy}" -f $now
85+
'%monthname' = ("{0:MMM}" -f $now)
7186
'%month' = $now.month
7287
'%dayofweek' = $now.DayOfWeek
7388
'%day' = $now.Day
7489
'%hour' = $now.hour
7590
'%minute' = $now.minute
7691
'%time' = "{0}{1}{2}" -f $now.hour, $now.minute, $now.Second
92+
'%string' = ([system.io.path]::GetRandomFileName()).split(".")[0]
93+
'%guid' = [System.Guid]::NewGuid().guid
7794
}
7895

7996
$hash.GetEnumerator() | foreach-object {
80-
write-verbose "Testing $filename for ($($_.key))"
97+
Write-Detail "Testing $filename for $($_.key)" | Write-Verbose
8198
if ($filename -match "($($_.key))") {
82-
write-verbose "replacing $($_.key) with $($_.value)"
99+
Write-Detail "replacing $($_.key) with $($_.value)" | Write-Verbose
83100
$filename = $filename -replace "($($_.key))",$_.value
84101
}
85102
}
86103

104+
#handle ### number replacement
105+
[regex]$rx = '%#+'
106+
if ($rx.IsMatch($filename)) {
107+
$count = $rx.Match($filename).Value.length -1
108+
$num = (0..9 | Get-Random -Count 10 | Get-Random -count $count) -join ""
109+
Write-Detail "replacing # with $num" | Write-Verbose
110+
$filename = $rx.Replace($filename,$num)
111+
}
112+
113+
Write-Detail "Converting case to $Case" | Write-Verbose
87114
Switch ($Case) {
88115
"Upper" {
89116
$filename.toUpper()
@@ -95,8 +122,7 @@ Function New-CustomFileName {
95122
$filename
96123
}
97124
} #close switch
98-
} #end New-CustomFileName
99125

100-
#New-CustomFileName '%Username-%DayofWeek.log' -Verbose
126+
Write-Detail "Ending $($myinvocation.MyCommand)" | Write-Verbose
127+
} #end New-CustomFileName
101128

102-
#New-CustomFileName '%UserName_%Computername_%Year%monthname%day-%time.txt' -case default -Verbose

Out-ConditionalColor.ps1

Lines changed: 36 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -1,115 +1,48 @@
1-
#requires -version 4.0
2-
3-
#TODO separate into parameter sets for simple or complex conditions
4-
#todo: avoid coloring the header
1+
52
Function Out-ConditionalColor {
6-
<#
7-
.Synopsis
8-
Display colorized pipelined output.
9-
.Description
10-
This command is designed to take pipeline input and display it in a colorized format, based on a set of conditions. Unlike Write-Host which doesn't write to the pipeline, this command will write to the pipeline. You can get colorized data and save the output to a variable at the same time, although you'll need to use the common OutVariable parameter (see examples).
11-
12-
The default behavior is to use a hash table with a property name and color. The color must be one of the standard console colors used with Write-Host.
13-
14-
$c = @{Stopped='Red';Running='Green'}
15-
16-
You can then pipe an expression to this command, specifying a property name and the hash table. If the property matches the key name, the output for that object will be colored using the corresponding hash table value.
17-
18-
get-service -diplayname windows* | out-conditionalcolor $c status
19-
20-
Or you can do more complex processing with an ordered hash table constructed using this format:
21-
22-
[ordered]@{ <comparison scriptblock> = <color>}
23-
24-
The comparison scriptblock can use $PSitem.
25-
26-
$h=[ordered]@{
27-
{$psitem.ws -gt 200mb}='yellow'
28-
{$psitem.vm -gt 500mb}='red'
29-
{$psitem.cpu -gt 300}='cyan'
30-
}
31-
32-
When doing a complex comparison you must use an [ordered] hashtable as each key will be processed in order using an If/ElseIf statement.
33-
34-
This command should be the last part of any pipelined expression. If you pipe to anything else, such as Sort-Object, you will lose your color formatting. Do any other sorting or filtering before piping to this command.
35-
36-
This command requires PowerShell 3.0 and later and works best in the PowerShell console. It won't do anything in the PowerShell ISE.
37-
.Parameter Conditions
38-
Use a simple hashtable for basic processing or an ordered hash table for complex.
39-
.Parameter Property
40-
When using a simple hash table, specify the property to compare using the -eq operator. If you don't specify a property you will be prompted.
41-
.Example
42-
PS C:\> get-service -displayname windows* | out-conditionalcolor -conditions @{Stopped='Red'} -property Status
43-
44-
Get all services where the displayname starts with windows and display stopped services in red.
45-
.Example
46-
PS C:\> get-service -displayname windows* | out-conditionalcolor @{Stopped='Red'} status -ov winstop
47-
48-
Repeat the previous example, but save the output to the variable winstop. When you look at $Winstop you'll see the services, but they won't be colored. This example uses the parameters positionally.
49-
.Example
50-
PS C:\> get-eventlog system -newest 50 | out-conditionalcolor @{error='red';warning='yellow'}
51-
Enter a property name: entrytype
52-
53-
Get the newest 50 entries from the System event log. Display errors in red and warnings in yellow. If you don't specify a property you will be prompted.
54-
.Example
55-
PS C:\> $c =[ordered]@{{$psitem.length -ge 1mb}='red';{$psitem.length -ge 500KB}='yellow';{$psitem.length -ge 100KB}='cyan'}
56-
57-
The first command creates an ordered hashtable based on the Length property.
58-
59-
PS C:\> dir c:\scripts\*.doc,c:\scripts\*.pdf,c:\scripts\*.xml | Select Name,LastWriteTime,Length | out-conditionalcolor $c
603

61-
The second command uses it to et certain file types in the scripts folder and display the selected properties in color depending on the file size.
62-
.Notes
63-
Last Updated: October 23, 2015
64-
Version : 2.0
65-
66-
Learn more about PowerShell:
67-
http://jdhitsolutions.com/blog/essential-powershell-resources/
68-
69-
****************************************************************
70-
* DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
71-
* THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK. IF *
72-
* YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
73-
* DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING. *
74-
****************************************************************
75-
Originally published at http://jdhitsolutions.com/blog/powershell/3462/friday-fun-out-conditionalcolor/
76-
77-
.Link
78-
About_Hash_Tables
79-
#>
80-
81-
[cmdletbinding()]
4+
[cmdletbinding(DefaultParameterSetName="property")]
825
Param(
83-
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter an ordered hashtable of conditional properties and colors.")]
84-
[ValidateScript({
85-
$_ -IS [System.Collections.Specialized.OrderedDictionary] -OR ($_ -IS [hashtable])})]
86-
[psobject]$Conditions,
87-
[Parameter(Position=1,HelpMessage="Enter a property name.")]
6+
[Parameter(Position=0,Mandatory,
7+
HelpMessage="Enter an hashtable of conditional properties and colors.",
8+
ParameterSetName="property")]
9+
[ValidateScript({
10+
#validate colors
11+
$allowed = [enum]::GetNames([system.consolecolor])
12+
$bad = $_.Values | Where-Object {$allowed -notcontains $_}
13+
if ($bad) {
14+
$valid = $allowed -join ','
15+
Throw "You are using one or more invalid colors: $($bad -join ','). Valid colors are $Valid"
16+
}
17+
else {
18+
$True
19+
}
20+
})]
21+
[hashtable]$PropertyConditions,
22+
23+
[Parameter(Mandatory,HelpMessage="Enter a property name.",
24+
ParameterSetName="property")]
8825
[string]$Property,
89-
[Parameter(Position=2,Mandatory=$True,ValueFromPipeline=$True)]
90-
[PSObject[]]$Inputobject
26+
27+
[Parameter(Position=0,Mandatory,
28+
HelpMessage="Enter an ordered hashtable of conditions and colors.",
29+
ParameterSetName="conditions")]
30+
[System.Collections.Specialized.OrderedDictionary]$Conditions,
31+
32+
[Parameter(Mandatory,ValueFromPipeline)]
33+
[PSObject[]]$InputObject
9134

9235
)
9336

9437
Begin {
9538
Write-Debug "Starting $($MyInvocation.MyCommand)"
96-
39+
write-Debug "Using parameter set $($pscmdlet.ParameterSetName)"
9740
#save original color
9841
$saved = $Host.UI.RawUI.ForegroundColor
9942

100-
Write-Debug "Original foreground color is $saved"
101-
102-
#validate colors
103-
$allowed = [enum]::GetNames([system.consolecolor])
104-
105-
$bad = $Conditions.Values | where {$allowed -notcontains $_}
106-
if ($bad) {
107-
Write-Warning "You are using one or more invalid colors: $($bad -join ',')"
108-
Break
109-
}
43+
Write-Debug "Original foreground color is $saved"
11044

111-
if ($Conditions -is [System.Collections.Specialized.OrderedDictionary]) {
112-
$Complex = $True
45+
if ($PSCmdlet.ParameterSetName -eq 'conditions') {
11346
#we'll need this later in the Process script block
11447
#if doing complex processing
11548
Write-Debug "Getting hash table enumerator and names"
@@ -139,34 +72,23 @@ Else {
13972

14073
Write-Debug "Complex comparison:"
14174
Write-Debug $If
142-
} #if complex parameter set
143-
Else {
144-
#validate a property was specified
145-
if (-NOT $Property) {
146-
[string]$property = Read-Host "Enter a property name"
147-
if (-Not $property) {
148-
Write-Debug "Blank property so quitting"
149-
Break
150-
}
151-
}
152-
Write-Debug "Conditional property is $Property"
153-
}
75+
} #if complex parameter set
15476

15577
} #Begin
15678

15779
Process {
15880

159-
If ($Complex) {
81+
If ($PSCmdlet.ParameterSetName -eq 'conditions') {
16082
#Use complex processing
16183
Invoke-Expression $if
16284
} #end complex
16385
else {
16486
#get property value as a string
16587
$value = $Inputobject.$Property.ToString()
16688
Write-Debug "Testing property value $value"
167-
if ($Conditions.containsKey($value)) {
89+
if ($PropertyConditions.containsKey($value)) {
16890
Write-Debug "Property match"
169-
$host.ui.RawUI.ForegroundColor= $Conditions.item($value)
91+
$host.ui.RawUI.ForegroundColor= $PropertyConditions.item($value)
17092
}
17193
else {
17294
#use orginal color
@@ -188,4 +110,3 @@ End {
188110

189111
} #close function
190112

191-
#create an optional alias

PSScriptTools.psd1

28 Bytes
Binary file not shown.

PSScriptTools.psm1

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,14 @@ Get-ChildItem -path $PSScriptRoot\*.ps1 | foreach-object -process {
33
. $_.FullName
44
}
55

6-
Set-Alias -Name Tee-Verbose -Value Out-TeeVerbose
6+
Set-Alias -Name Tee-Verbose -Value Out-VerboseTee
77
Set-Alias -Name occ -Value Out-ConditionalColor
8+
Set-Alias -name pswho -Value Get-PSWho
89

910
$exportParams = @{
1011
Function = 'Add-Border','Tee-Verbose','Write-Detail','Out-VerboseTee',
1112
'Get-PSWho','Out-ConditionalColor','New-RandomFileName','New-CustomFileName'
12-
Alias = 'Tee-Verbose','occ'
13+
Alias = 'Tee-Verbose','occ','pswho'
1314
}
1415

1516
Export-ModuleMember @exportParams

0 commit comments

Comments
 (0)