forked from jdhitsolutions/PSScriptTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtilities.ps1
More file actions
437 lines (368 loc) · 13.7 KB
/
Copy pathUtilities.ps1
File metadata and controls
437 lines (368 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
Function Get-PowerShellEngine {
[CmdletBinding()]
Param([switch]$Detail)
#get the current PowerShell process and the file that launched it
$engine = Get-Process -id $pid | Get-Item
if ($Detail) {
[pscustomobject]@{
Path = $engine.Fullname
FileVersion = $engine.VersionInfo.FileVersion
PSVersion = $PSVersionTable.PSVersion.ToString()
ProductVersion = $engine.VersionInfo.ProductVersion
Edition = $PSVersionTable.PSEdition
Host = $host.name
Culture = $host.CurrentCulture
Platform = $PSVersionTable.platform
}
}
else {
$engine.FullName
}
}
Function Out-More {
[cmdletbinding()]
[alias("om")]
Param(
[Parameter(Mandatory, ValueFromPipeline)]
[object[]]$InputObject,
[ValidateRange(1, 1000)]
[Alias("i")]
[int]$Count = 50,
[Alias("cls")]
[Switch]$ClearScreen
)
Begin {
if ($ClearScreen) {
Clear-Host
}
Write-Verbose "Starting: $($MyInvocation.Mycommand)"
Write-Verbose "Using a count of $count"
#initialize an array to hold objects
Write-Verbose "Initializing data array"
$data = @()
#initialize some variables to control flow
$ShowAll = $False
$ShowNext = $False
$Ready = $False
$Quit = $False
} #begin
Process {
if ($Quit) {
Write-Verbose "Quitting"
Break
}
elseif ($ShowAll) {
$InputObject
}
elseif ($ShowNext) {
Write-Verbose "Show Next"
$ShowNext = $False
$Ready = $True
$data = , $InputObject
}
elseif ($data.count -lt $count) {
Write-Verbose "Adding data"
$data += $Inputobject
}
else {
#write the data to the pipeline
$data
#reset data
$data = , $InputObject
$Ready = $True
}
If ($Ready) {
#pause
Do {
Write-Host "[M]ore [A]ll [N]ext [Q]uit " -ForegroundColor Green -NoNewline
$r = Read-Host
if ($r.Length -eq 0 -OR $r -match "^m") {
#don't really do anything
$Asked = $True
}
else {
Switch -Regex ($r) {
"^n" {
$ShowNext = $True
$InputObject
$Asked = $True
}
"^a" {
$InputObject
$Asked = $True
$ShowAll = $True
}
"^q" {
#bail out
$Asked = $True
$Quit = $True
}
Default {
$Asked = $False
}
} #Switch
} #else
} Until ($Asked)
$Ready = $False
$Asked = $False
} #else
} #process
End {
#test if data is from a get-help command in
#which case it will be a single string that needs
#to be broken apart
if ([regex]::Matches($data, "`n").count -gt 1) {
[void]$PSBoundParameters.remove("Inputobject")
Write-Verbose "Splitting input and re-running through Out-More"
$data.split("`n") | Out-More @PSBoundParameters
}
elseif ($data[0].psobject.typenames -contains "MamlCommandHelpInfo") {
Write-Verbose "Help output detected"
[void]$PSBoundParameters.remove("Inputobject")
($data | Out-String).split("`n") | Out-More @PSBoundParameters
}
#display whatever is left in $data
if ($data -AND -Not $ShowAll) {
Write-Verbose "Displaying remaining data"
$data
}
Write-Verbose "Ending: $($MyInvocation.Mycommand)"
} #end
} #end Out-More
Function Invoke-InputBox {
[cmdletbinding(DefaultParameterSetName = "plain")]
[alias("ibx")]
[OutputType([system.string], ParameterSetName = 'plain')]
[OutputType([system.security.securestring], ParameterSetName = 'secure')]
Param(
[Parameter(ParameterSetName = "secure")]
[Parameter(HelpMessage = "Enter the title for the input box. No more than 25 characters.",
ParameterSetName = "plain")]
[ValidateNotNullorEmpty()]
[ValidateScript( {$_.length -le 25})]
[string]$Title = "User Input",
[Parameter(ParameterSetName = "secure")]
[Parameter(HelpMessage = "Enter a prompt. No more than 50 characters.", ParameterSetName = "plain")]
[ValidateNotNullorEmpty()]
[ValidateScript( {$_.length -le 50})]
[string]$Prompt = "Please enter a value:",
[Parameter(HelpMessage = "Use to mask the entry and return a secure string.",
ParameterSetName = "secure")]
[switch]$AsSecureString,
[string]$BackgroundColor = "White"
)
if ((Test-IsPSWindows)) {
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
#remove the variable because it might get cached in the ISE or VS Code
Remove-Variable -Name myInput -Scope script -ErrorAction SilentlyContinue
$form = New-Object System.Windows.Window
$stack = New-Object System.Windows.Controls.StackPanel
#define what it looks like
$form.Title = $title
$form.Height = 150
$form.Width = 350
$form.Background = $BackgroundColor
$label = New-Object System.Windows.Controls.Label
$label.Content = " $Prompt"
$label.HorizontalAlignment = "left"
$stack.AddChild($label)
if ($AsSecureString) {
$inputbox = New-Object System.Windows.Controls.PasswordBox
}
else {
$inputbox = New-Object System.Windows.Controls.TextBox
}
$inputbox.Width = 300
$inputbox.HorizontalAlignment = "center"
$stack.AddChild($inputbox)
$space = New-Object System.Windows.Controls.Label
$space.Height = 10
$stack.AddChild($space)
$btn = New-Object System.Windows.Controls.Button
$btn.Content = "_OK"
$btn.Width = 65
$btn.HorizontalAlignment = "center"
$btn.VerticalAlignment = "bottom"
#add an event handler
$btn.Add_click( {
if ($AsSecureString) {
$script:myInput = $inputbox.SecurePassword
}
else {
$script:myInput = $inputbox.text
}
$form.Close()
})
$stack.AddChild($btn)
$space2 = New-Object System.Windows.Controls.Label
$space2.Height = 10
$stack.AddChild($space2)
$btn2 = New-Object System.Windows.Controls.Button
$btn2.Content = "_Cancel"
$btn2.Width = 65
$btn2.HorizontalAlignment = "center"
$btn2.VerticalAlignment = "bottom"
#add an event handler
$btn2.Add_click( {
$form.Close()
})
$stack.AddChild($btn2)
#add the stack to the form
$form.AddChild($stack)
#show the form
[void]$inputbox.Focus()
$form.WindowStartupLocation = [System.Windows.WindowStartupLocation]::CenterScreen
[void]$form.ShowDialog()
#write the result from the input box back to the pipeline
$script:myInput
}
else {
Write-Warning "Sorry. This command requires a Windows platform."
#bail out
Return
}
}
Function Set-ConsoleTitle {
[cmdletbinding(SupportsShouldProcess)]
[OutputType("None")]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "Enter the title for the console window.")]
[ValidateNotNullorEmpty()]
[string]$Title
)
Begin {
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)"
$width = ($host.UI.RawUI.MaxWindowSize.Width * 2)
} #begin
Process {
if ($host.Name -ne "ConsoleHost") {
Write-Warning "This command must be run from a PowerShell console session. Not the PowerShell ISE or Visual Studio Code or similar environments."
}
elseif (($title.length -ge $width)) {
Write-Warning "Your title is too long. It needs to be less than $width to fit your current console."
}
else {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Setting console title to $Title"
if ($pscmdlet.ShouldProcess($Title)) {
$host.ui.RawUI.WindowTitle = $Title
}
}
} #process
End {
Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)"
} #end
} #close Set-ConsoleTitle
Function Set-ConsoleColor {
[cmdletbinding(SupportsShouldProcess)]
[OutputType("None")]
Param(
[Parameter(HelpMessage = "Specify a foreground console color")]
[ValidateNotNullorEmpty()]
[alias("fg")]
[System.ConsoleColor]$Foreground,
[Parameter( HelpMessage = "Specify a background console color")]
[ValidateNotNullorEmpty()]
[alias("bg")]
[System.ConsoleColor]$Background,
[Alias("cls")]
[switch]$ClearScreen,
[switch]$Passthru
)
Begin {
Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($myinvocation.mycommand)"
} #begin
Process {
if ($host.Name -ne "ConsoleHost") {
Write-Warning "This command must be run from a PowerShell console session. Not the PowerShell ISE or Visual Studio Code or similar environments."
#bail out
}
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Bound Parameters"
$PSBoundParameters | Out-String | Write-Verbose
# ! There are issues with this if PSReadline is running
if (Get-Module -name PSReadline) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Detected PSReadline Module is loaded"
Write-Warning "You appear to be running the PSReadline module. Please use Set-PSReadlineOption or related command to modify the console."
#make sure we don't clear the screen
$ClearScreen = $False
}
else {
if ($Foreground) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Configuring console foreground color to $Foreground"
if ($pscmdlet.ShouldProcess($Foreground)) {
$host.ui.RawUI.ForegroundColor = $Foreground
$modified = $True
}
}
if ($Background) {
Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Configuring console background color to $Background"
if ($pscmdlet.ShouldProcess($Background)) {
$host.ui.RawUI.BackgroundColor = $Background
$modified = $True
}
}
}
} #process
End {
if ($ClearScreen) {
Clear-Host
}
#only passthru if asked for and if a change was made.
if ($Passthru -AND $modified) {
$host.ui.RawUI | Select-Object -Property ForegroundColor, BackgroundColor
}
Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($myinvocation.mycommand)"
} #end
} #close Set-ConsoleTitle
#This command is not exported
<#
You use this function like this:
$newrunspace = <code>
$pscmd = [powershell]::create()
add commands to $pscmd
$pscmd.runspace = $newrunspace
$handle = $pscmd.beginInvoke()
Start a thread job to test if runspace is being used and close it if it is finished
New-RunspaceCleanUpJob -handle $handle -powershell $pscmd -sleepinterval 30
#>
Function New-RunspaceCleanupJob {
[cmdletbinding()]
[OutputType("None", "ThreadJob")]
Param(
[Parameter(Mandatory, HelpMessage = "This should be the System.Management.Automation.Runspaces.AsyncResult object from the BeginInvoke() method.")]
[ValidateNotNullorEmpty()]
[object]$Handle,
[Parameter(Mandatory)]
[ValidateNotNullorEmpty()]
[System.Management.Automation.PowerShell]$PowerShell,
[Parameter(HelpMessage = "Specify a sleep interval in seconds")]
[ValidateRange(5, 600)]
[int32]$SleepInterval = 10,
[Parameter(HelpMessage = "Pass the thread job object to the pipeline")]
[switch]$Passthru
)
$job = Start-ThreadJob -ScriptBlock {
param($handle, $ps, $sleep)
#the Write-Host lines are so that if you look at the results of the thread job
#you'll see something you can use for debugging or troubleshooting.
Write-Host "[$(Get-Date)] Sleeping in $sleep second loops"
Write-Host "Watching this runspace"
Write-Host ($ps.runspace | Select-Object -property * | Out-String)
#loop until the handle shows as completed, sleeping the the specified
#number of seconds
do {
Start-Sleep -Seconds $sleep
} Until ($handle.IsCompleted)
Write-Host "[$(Get-Date)] Closing runspace"
$ps.runspace.close()
Write-Host "[$(Get-Date)] Disposing runspace"
$ps.runspace.Dispose()
Write-Host "[$(Get-Date)] Disposing PowerShell"
$ps.dispose()
Write-Host "[$(Get-Date)] Ending job"
} -ArgumentList $Handle, $PowerShell, $SleepInterval
if ($passthru) {
#Write the ThreadJob object to the pipeline
$job
}
}