MegaBites-AI/Windows-powershell
0372
1# Copyright (c) Microsoft Corporation.2# Licensed under the MIT License.3 4<#5 PowerShell Diagnostics Module6 This module contains a set of wrapper scripts that7 enable a user to use ETW tracing in PowerShell 7.8 #>9 10$script:windir = [System.Environment]::GetEnvironmentVariable("windir", [System.EnvironmentVariableTarget]::Machine)11 12$script:Logman = "${script:windir}\system32\logman.exe"13$script:wsmanlogfile = "${script:windir}\system32\wsmtraces.log"14$script:wsmprovfile = "${script:windir}\system32\wsmtraceproviders.txt"15$script:wsmsession = "wsmlog"16$script:pssession = "PSTrace"17$script:psprovidername = "PowerShellCore"18$script:wsmprovidername = "Microsoft-Windows-WinRM"19$script:oplog = "/Operational"20$script:analyticlog = "/Analytic"21$script:debuglog = "/Debug"22$script:wevtutil = "${script:windir}\system32\wevtutil.exe"23$script:slparam = "sl"24$script:glparam = "gl"25 26function Start-Trace27{28 Param(29 [Parameter(Mandatory=$true,30 Position=0)]31 [string]32 $SessionName,33 [Parameter(Position=1)]34 [ValidateNotNullOrEmpty()]35 [string]36 $OutputFilePath,37 [Parameter(Position=2)]38 [ValidateNotNullOrEmpty()]39 [string]40 $ProviderFilePath,41 [Parameter()]42 [Switch]43 $ETS,44 [Parameter()]45 [ValidateSet("bin", "bincirc", "csv", "tsv", "sql")]46 $Format,47 [Parameter()]48 [int]49 $MinBuffers=0,50 [Parameter()]51 [int]52 $MaxBuffers=256,53 [Parameter()]54 [int]55 $BufferSizeInKB = 0,56 [Parameter()]57 [int]58 $MaxLogFileSizeInMB=059 )60 61 Process62 {63 $executestring = " start $SessionName"64 65 if ($ETS)66 {67 $executestring += " -ets"68 }69 70 if ($null -ne $OutputFilePath)71 {72 $executestring += " -o ""$OutputFilePath"""73 }74 75 if ($null -ne $ProviderFilePath)76 {77 $executestring += " -pf ""$ProviderFilePath"""78 }79 80 if ($null -ne $Format)81 {82 $executestring += " -f $Format"83 }84 85 if ($MinBuffers -ne 0 -or $MaxBuffers -ne 256)86 {87 $executestring += " -nb $MinBuffers $MaxBuffers"88 }89 90 if ($BufferSizeInKB -ne 0)91 {92 $executestring += " -bs $BufferSizeInKB"93 }94 95 if ($MaxLogFileSizeInMB -ne 0)96 {97 $executestring += " -max $MaxLogFileSizeInMB"98 }99 100 & $script:Logman $executestring.Split(" ")101 }102}103 104function Stop-Trace105{106 param(107 [Parameter(Mandatory=$true,108 Position=0)]109 $SessionName,110 [Parameter()]111 [switch]112 $ETS113 )114 115 Process116 {117 if ($ETS)118 {119 & $script:Logman update $SessionName -ets120 & $script:Logman stop $SessionName -ets121 }122 else123 {124 & $script:Logman update $SessionName125 & $script:Logman stop $SessionName126 }127 }128}129 130function Enable-WSManTrace131{132 133 # winrm134 "{04c6e16d-b99f-4a3a-9b3e-b8325bbc781e} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii135 136 # winrsmgr137 "{c0a36be8-a515-4cfa-b2b6-2676366efff7} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append138 139 # WinrsExe140 "{f1cab2c0-8beb-4fa2-90e1-8f17e0acdd5d} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append141 142 # WinrsCmd143 "{03992646-3dfe-4477-80e3-85936ace7abb} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append144 145 # IPMIPrv146 "{651d672b-e11f-41b7-add3-c2f6a4023672} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append147 148 #IpmiDrv149 "{D5C6A3E9-FA9C-434e-9653-165B4FC869E4} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append150 151 # WSManProvHost152 "{6e1b64d7-d3be-4651-90fb-3583af89d7f1} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append153 154 # Event Forwarding155 "{6FCDF39A-EF67-483D-A661-76D715C6B008} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append156 157 Start-Trace -SessionName $script:wsmsession -ETS -OutputFilePath $script:wsmanlogfile -Format bincirc -MinBuffers 16 -MaxBuffers 256 -BufferSizeInKB 64 -MaxLogFileSizeInMB 256 -ProviderFilePath $script:wsmprovfile158}159 160function Disable-WSManTrace161{162 Stop-Trace $script:wsmsession -ETS163}164 165function Enable-PSWSManCombinedTrace166{167 param (168 [switch] $DoNotOverwriteExistingTrace169 )170 171 $provfile = [io.path]::GetTempFilename()172 173 if ($DoNotOverwriteExistingTrace) {174 $fileName = [string][guid]::newguid()175 $logfile = $PSHOME + "\\Traces\\PSTrace_$fileName.etl"176 } else {177 $logfile = $PSHOME + "\\Traces\\PSTrace.etl"178 }179 180 "$script:psprovidername 0 5" | Out-File $provfile -Encoding ascii181 "$script:wsmprovidername 0 5" | Out-File $provfile -Encoding ascii -Append182 183 if (!(Test-Path $PSHOME\Traces))184 {185 New-Item -ItemType Directory -Force $PSHOME\Traces | Out-Null186 }187 188 if (Test-Path $logfile)189 {190 Remove-Item -Force $logfile | Out-Null191 }192 193 Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ETS194 195 Remove-Item $provfile -Force -ErrorAction SilentlyContinue196}197 198function Disable-PSWSManCombinedTrace199{200 Stop-Trace -SessionName $script:pssession -ETS201}202 203function Set-LogProperties204{205 param(206 [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]207 [Microsoft.PowerShell.Diagnostics.LogDetails]208 $LogDetails,209 [switch] $Force210 )211 212 Process213 {214 if ($LogDetails.AutoBackup -and !$LogDetails.Retention)215 {216 throw (New-Object System.InvalidOperationException)217 }218 219 $enabled = $LogDetails.Enabled.ToString()220 $retention = $LogDetails.Retention.ToString()221 $autobackup = $LogDetails.AutoBackup.ToString()222 $maxLogSize = $LogDetails.MaxLogSize.ToString()223 $osVersion = [Version] (Get-CimInstance Win32_OperatingSystem).Version224 225 if (($LogDetails.Type -eq "Analytic") -or ($LogDetails.Type -eq "Debug"))226 {227 if ($LogDetails.Enabled)228 {229 if($osVersion -lt 6.3.7600)230 {231 & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled232 }233 else234 {235 & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled236 }237 }238 else239 {240 if($osVersion -lt 6.3.7600)241 {242 & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize243 }244 else245 {246 & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ms:$MaxLogSize247 }248 }249 }250 else251 {252 if($osVersion -lt 6.3.7600)253 {254 & $script:wevtutil $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize255 }256 else257 {258 & $script:wevtutil /q:$Force $script:slparam $LogDetails.Name -e:$Enabled -rt:$Retention -ab:$AutoBackup -ms:$MaxLogSize259 }260 }261 }262}263 264function ConvertTo-Bool([string]$value)265{266 if ($value -ieq "true")267 {268 return $true269 }270 else271 {272 return $false273 }274}275 276function Get-LogProperties277{278 param(279 [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] $Name280 )281 282 Process283 {284 $details = & $script:wevtutil $script:glparam $Name285 $indexes = @(1,2,8,9,10)286 $value = @()287 foreach($index in $indexes)288 {289 $value += @(($details[$index].SubString($details[$index].IndexOf(":")+1)).Trim())290 }291 292 $enabled = ConvertTo-Bool $value[0]293 $retention = ConvertTo-Bool $value[2]294 $autobackup = ConvertTo-Bool $value[3]295 296 New-Object Microsoft.PowerShell.Diagnostics.LogDetails $Name, $enabled, $value[1], $retention, $autobackup, $value[4]297 }298}299 300function Enable-PSTrace301{302 param(303 [switch] $Force,304 [switch] $AnalyticOnly305 )306 307 $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog)308 309 if (!$Properties.Enabled) {310 $Properties.Enabled = $true311 if ($Force) {312 Set-LogProperties $Properties -Force313 } else {314 Set-LogProperties $Properties315 }316 }317 318 if (!$AnalyticOnly) {319 $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog)320 if (!$Properties.Enabled) {321 $Properties.Enabled = $true322 if ($Force) {323 Set-LogProperties $Properties -Force324 } else {325 Set-LogProperties $Properties326 }327 }328 }329}330 331function Disable-PSTrace332{333 param(334 [switch] $AnalyticOnly335 )336 $Properties = Get-LogProperties ($script:psprovidername + $script:analyticlog)337 if ($Properties.Enabled) {338 $Properties.Enabled = $false339 Set-LogProperties $Properties340 }341 342 if (!$AnalyticOnly) {343 $Properties = Get-LogProperties ($script:psprovidername + $script:debuglog)344 if ($Properties.Enabled) {345 $Properties.Enabled = $false346 Set-LogProperties $Properties347 }348 }349}350Add-Type @"351using System;352 353namespace Microsoft.PowerShell.Diagnostics354{355 public class LogDetails356 {357 public string Name358 {359 get360 {361 return name;362 }363 }364 private string name;365 366 public bool Enabled367 {368 get369 {370 return enabled;371 }372 set373 {374 enabled = value;375 }376 }377 private bool enabled;378 379 public string Type380 {381 get382 {383 return type;384 }385 }386 private string type;387 388 public bool Retention389 {390 get391 {392 return retention;393 }394 set395 {396 retention = value;397 }398 }399 private bool retention;400 401 public bool AutoBackup402 {403 get404 {405 return autoBackup;406 }407 set408 {409 autoBackup = value;410 }411 }412 private bool autoBackup;413 414 public int MaxLogSize415 {416 get417 {418 return maxLogSize;419 }420 set421 {422 maxLogSize = value;423 }424 }425 private int maxLogSize;426 427 public LogDetails(string name, bool enabled, string type, bool retention, bool autoBackup, int maxLogSize)428 {429 this.name = name;430 this.enabled = enabled;431 this.type = type;432 this.retention = retention;433 this.autoBackup = autoBackup;434 this.maxLogSize = maxLogSize;435 }436 }437}438"@439 440if (Get-Command logman.exe -Type Application -ErrorAction SilentlyContinue)441{442 Export-ModuleMember Disable-PSTrace, Disable-PSWSManCombinedTrace, Disable-WSManTrace, Enable-PSTrace, Enable-PSWSManCombinedTrace, Enable-WSManTrace, Get-LogProperties, Set-LogProperties, Start-Trace, Stop-Trace443}444else445{446 # Currently we only support these cmdlets as logman.exe is not available on systems like Nano and IoT447 Export-ModuleMember Disable-PSTrace, Enable-PSTrace, Get-LogProperties, Set-LogProperties448}449 