forked from jdhitsolutions/PSScriptTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrace.ps1
More file actions
210 lines (186 loc) · 9.46 KB
/
Trace.ps1
File metadata and controls
210 lines (186 loc) · 9.46 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
Function Trace-Message {
[cmdletbinding(DefaultParameterSetName = "message")]
[alias("trace")]
[outputtype("none")]
Param(
[Parameter(HelpMessage = "Specify a title for the trace window.", ParameterSetName = "init")]
[ValidateNotNullOrEmpty()]
[string]$Title = "Trace Messages",
[Parameter(HelpMessage = "Specify a background color for the trace window", ParameterSetName = "init")]
[ValidateNotNullOrEmpty()]
[string]$BackgroundColor = "#FFFFF8DC",
[Parameter(HelpMessage = "Specify the width of the trace window.", ParameterSetName = "init")]
[ValidateNotNullOrEmpty()]
[int32]$Width = 800,
[Parameter(HelpMessage = "Specify the width of the trace window.", ParameterSetName = "init")]
[ValidateNotNullOrEmpty()]
[int32]$Height = 500,
[Parameter(Position = 0, Mandatory,HelpMessage = "Specify a message to write to the trace window.", ValueFromPipeline, ParameterSetName = "message")]
[string]$Message
)
Begin {
Write-Verbose "Starting $($MyInvocation.MyCommand)"
Function _SetTraceMessage {
[cmdletbinding()]
Param(
[Parameter(Mandatory, ValueFromPipeline)]
[string]$Message
)
Begin {
$hash = $global:traceSynchHash
}
Process {
Write-Verbose "Adding message $message"
$content = "$((Get-Date).TimeOfDay) - $message"
$hash.TextBox.Dispatcher.Invoke([action] { $hash.TextBox.AppendText("$Content`n") }, "Normal")
}
End {}
}
} #begin
Process {
#must be running Windows
if ($IsLinux -OR $IsMacOS) {
Write-Warning "This command only works on Windows platforms."
#bail out
return
}
Write-Verbose "Using parameter set $($pscmdlet.ParameterSetName)"
if ($global:TraceEnabled) {
if ($PSCmdlet.ParameterSetName -eq 'init') {
Write-Verbose "Defining synchronized hashtable `$global:traceSynchHash"
$global:traceSynchHash = [hashtable]::Synchronized(@{Date=(Get-Date)})
Write-Verbose "Initializing a new runspace"
$newRunspace = [runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
Write-Verbose "Open the new runspace"
$newRunspace.Open()
Write-Verbose "Setting synchronized hashtable variable"
$newRunspace.SessionStateProxy.SetVariable("traceSynchHash", $global:traceSynchHash)
$newrunspace.SessionStateProxy.getvariable("traceSynchHash") | Out-String | Write-Verbose
$formParams = @{
Title = $title
BackgroundColor = $BackgroundColor
Width = $width
Height = $Height
}
Write-Verbose "Creating runspace script"
$psCmd = [PowerShell]::Create().AddScript( {
Param([string]$Title, [object]$BackgroundColor, [int]$width, [int]$height)
Add-Type -AssemblyName PresentationFramework -ErrorAction stop
Add-Type -AssemblyName PresentationCore -ErrorAction stop
Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop
$form = New-Object System.Windows.Window
$form.Title = $Title
$form.Height = $height
$form.Width = $width
$form.ResizeMode = "noResize"
$form.Background = $BackgroundColor
$Form.Left = 100
$form.Top = 100
#$form.WindowStartupLocation = [System.Windows.WindowStartupLocation]::CenterScreen
$grid = New-Object System.Windows.Controls.Grid
$text = New-Object System.Windows.Controls.Textbox
$text.text = ""
#$text.Text = "Starting...`n"
$text.Padding = 5
$text.Width = $form.width - 25
$text.Height = $form.Height - 100
$text.Margin = "5,5,5,5"
$text.TextWrapping = [System.Windows.TextWrapping]::Wrap
$text.VerticalAlignment = "top"
$text.IsEnabled = $True
$text.AcceptsReturn = $True
$text.VerticalScrollBarVisibility = "Auto"
$text.FontFamily = "Consolas"
$text.HorizontalAlignment = "stretch"
$text.VerticalAlignment = "top"
$grid.AddChild($text)
$Quit = New-Object System.Windows.Controls.Button
$quit.Content = "_Quit"
$quit.Width = 75
$quit.Height = 25
$quit.Margin = "10,10,0,10"
$quit.HorizontalAlignment = "Left"
$quit.VerticalAlignment = "bottom"
$quit.Add_click( {
$form.close()
$traceSynchHash.clear()
Remove-Variable -name traceSynchHash -Scope global
})
$grid.AddChild($quit)
$Save = New-Object System.Windows.Controls.Button
$save.Content = "_Save"
$save.Width = 75
$save.Height = 25
$save.Margin = "10,10,10,10"
$save.HorizontalAlignment = "right"
$save.VerticalAlignment = "bottom"
$save.Add_click( {
$SaveDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveDialog.InitialDirectory = "$ENV:Temp"
$SaveDialog.Filter = "txt Files (*.txt)|*.txt |All files (*.*)|*.*"
[void]$SaveDialog.ShowDialog()
if ($SaveDialog.Filename) {
$text.text | Out-File -FilePath $SaveDialog.filename
[System.Windows.Forms.MessageBox]::Show("Trace log exported to $($SaveDialog.Filename)", "Trace Export | Trace Message")
}
})
$grid.AddChild($Save)
$form.AddChild($grid)
#add keys to the synchronized hashtable
$traceSynchHash.TextBox = $text
$traceSynchHash.Form = $Form
#show the form
[void]$traceSynchHash.Form.ShowDialog()
$traceSynchHash.Error = $Error
})
#add parameters
[void]$psCmd.Addparameters($formParams)
$psCmd.Runspace = $newRunspace
Write-Verbose "Invoking runspace command"
$handle = $psCmd.BeginInvoke()
Write-Verbose "Using this global synchronized hashtable"
$global:traceSynchHash | Out-String | Write-Verbose
#wait for hashtable to initialize with runspace values
$i=0
do {
$i++
start-sleep -Seconds 1
#uncomment for troubleshooting
#Write-host $i -ForegroundColor yellow -NoNewline
} Until ($global:traceSynchHash.TextBox)
Write-Verbose "Creating a runspace cleanup job"
[void](New-RunspaceCleanupJob -Handle $handle -powerShell $pscmd -sleep 30 -passthru)
Write-Verbose "Getting trace metadata"
$elevated = ([security.principal.windowsprincipal]([security.principal.windowsidentity]::Getcurrent())).IsInRole([system.security.principal.securityidentifier]"S-1-5-32-544")
$os = Get-CimInstance -ClassName win32_operatingsystem -Property Caption, Version, OSArchitecture
$init = @(
"*************************************************",
"User : $($env:USERDOMAIN)\$($env:USERNAME)",
"Elevated : $Elevated",
"Computer : $env:Computername",
"PSVersion : $($PSVersionTable.PSVersion)",
"OS : $($os.caption)",
"Version : $($os.version)",
"Architecture : $($os.OSArchitecture)",
"*************************************************"
)
Write-Verbose "Init"
$init | Write-Verbose
Write-Verbose "Setting trace metadata"
$init | _SetTraceMessage
} #if init
else {
Write-Verbose "Setting message $message"
_SetTraceMessage -Message $Message
}
}
else {
Write-Verbose "TraceEnabled is set to False"
}
} #process
End {
Write-Verbose "Ending $($MyInvocation.MyCommand)"
} #end
}