Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Top 10 PowerShell Commands for Troubleshooting

Top 10 PowerShell Commands for Troubleshooting

See the top 10 PowerShell commands that Guy Leech uses in his day to day Windows troubleshooting, for many different customers, which will save you time by getting to the root of the problem much quicker than by manual methods. Lots of real world demos.

Presented at the XenApp Blog Virtual Expo - https://xenappblog.com/

Guy Leech

March 27, 2020
Tweet

More Decks by Guy Leech

Other Decks in Technology

Transcript

  1. GUY LEECH • Independent consultant, developer, trainer, adviser, troubleshooter, comedian

    • Citrix CTP • VMware vExpert • Worked in the EUC space since 1995 • Was a C++ software developer before that (on Unix) • Wrote my first program in 1980 (BASIC on a Commodore PET) • @guyrleech • guyrleech.wordpress.com • github.com/guyrleech • pastebin.com/u/guyrleech • linkedin.com/in/guyrleech/ • Available for hire
  2. WHY POWERSHELL? • Can run interactively (it’s a shell like

    in *nix – can’t do that with vbs ) • Persistent command history searching via Ctrl r • But leaves a trace with persistent profile • Lots of 3rd party scripts available • But check they aren’t malicious, either accidentally or deliberately • Tab completion of commands, arguments & parameters (and ctrl space) • Huge number of cmdlets • Many 3rd party modules available, e.g. VMware, Citrix • Repeatable – same s**t, different cmdlet – it’s (mostly) about objects • Aliases to make typing quicker (but don’t use in scripts) • Easy to export to CSV, XML, JSON for reporting/sharing/comparing (& import)
  3. TOP 10 (0XA) 1. Get-CIMInstance 2. Get-WinEvent 3. Enter-PSSession (etsn)

    4. Out-GridView (ogv) 5. Export-CSV (epcsv) 6. Test-NetConnection (tnc) 7. Get-ADUser 8. Get-ChildItem (dir, gci, ls) 9. Get-Process (ps, gps) 10. Get-Command (gcm) (In no particular order)
  4. WMI/CIM • A huge amount of available information (over 800

    non performance classes by default) • Tab completion of classes or list with Get-CimClass (v3+) • Get-WMIObject if you have to slum it with v2 (upgrade!!) • Some classes have methods which can be called, e.g. Win32_UserProfile • Filter in query, not afterwards if possible (for speed) • Can take array of machines via -ComputerName • Other name spaces, e.g. SCCM, Citrix
  5. GET-CIMINSTANCE • Get-CimInstance -ClassName Win32_Service • Get-CimInstance -ClassName Win32_Service -Filter

    "caption like 'vmware%’” • Can tab complete ClassName • Get-CimClass to see what’s available • Get-CimClass -ClassName *battery* • Different name spaces • Get-CimInstance -Namespace root/Citrix/DesktopInformation -ClassName Citrix_VirtualDesktopInfo • Can tab complete namespace • Can remote to one or more computers • Get-CimInstance –ComputerName pooter1,pooter2 –ClassName win32_volume
  6. SOME USEFUL WMI/CIM CLASSES • Win32_Process • Gives parent process

    & arguments details which Get-Process doesn’t • Need to invoke GetOwner method to get owner via Invoke-CimMethod • If on multi-user OS, filter by SessionId if relevant • Win32_OperatingSystem • LastBootUpTime • Win32_LogonSession & Win32_LoggedOnUser • Gives precise logon times for all logons since boot • Win32_ComputerSystem • Win32_Service • Executable including path which Get-Service doesn’t • But don’t use Win32_Product as it isn’t passive • Interrogate the registry • Script to grab common/useful information from multiple computers
  7. QUERYING EVENT LOGS • There are over 300 - how

    many have you been (manually) looking at? • Get-WinEvent –ListLog * | Where IsEnabled (388 on my laptop) • Get-WinEvent –ListProvider *blah* • Much easier to visualise with Out-GridView than eventvwr • Can then filter in/out & export (-PassThur) • Or save via Export-CSV • Can be remoted so don’t need to logon
  8. GET-WINEVENT • Get-WinEvent –ListLog *terminalservices* • Get-WinEvent –LogName Application •

    Get-WinEvent -ProviderName 'Application Error' | Select-Object -First 10 • Get-WinEvent -ListLog *|? RecordCount |%{ Get-WinEvent -EA Silent -FilterHashtable @{logname=$_.logname;starttime='16:29';endtime='16:31'}}|select *|sort TimeCreated|ogv • Filtering • Don’t filter afterwards (Where-Object) if possible for speed • Uses XML, XPath or Hash tables (dictionaries) • Get-WinEvent -FilterHashtable @{ LogName = 'Security' ; ID = 4688 ; StartTime = '17:00' ; EndTime = '17:20’ } • Filter/select on Properties array rather than entire message • Get-WinEvent -FilterHashtable @{ LogName = 'Security' ; ID = 4688 ; StartTime = '17:00' ; EndTime = '18:00' }|Where { $_.Properties[5].Value -match ‘\\cmd\.exe' } • Script to query all event logs in a given period
  9. REMOTING • Many cmdlets take –ComputerName and array of computers

    (comp1,comp2) • Winrm quickconfig • Enter-PSSession • Similar to telnet/ssh access in the *nix world • Interactive but no GUI programs • Less resource intensive way to get access to troubled system – ps, kill, stop-service, logoff • Great for running SysInternals procmon headless, e.g. Windows 10 logon analysis • New-PSSession, Invoke-Command –Session (& Remove-PSSession) for automation • -Credential (but store passwords securely!)
  10. TESTING NETWORKING • Ping is somewhat limited • Test-NetConnection •

    Like telnet to a (TCP) port • Test-NetConnection computername (ping) • Test-NetConnection computername –port 443 • Test-NetConnection bbc.co.uk –TraceRoute • Alias tnc
  11. ACTIVE DIRECTORY • Can use ADSI (& WMI/CIM) but ActiveDirectory

    module is easier • Add-WindowsFeature RSAT-AD-PowerShell • Users • Get-ADUser username • Get-ADUser username –Properties * • Get-ADUser -Filter "enabled -eq 'false’” • Get-ADUser –Filter * -SearchBase "ou=training,ou=demo,dc=guyrleech,dc=local“ • Set-ADUser • Get-ADGroupMember -Identity "Domain Admins"
  12. GET-PROCESS • What has used the most CPU? (not instantaneous

    but diff two readings & divide by interval) • Get-Process |Sort CPU -Descending|Select -first 10 • When did that service start? After boot? • Get-Process -Name spoolsv|select StartTime • How much memory is Chrome using? • (ps chrome|measure -Property workingset -Sum).Sum / 1MB • How much memory are McAfee processes using? Also use for sessions via SessionId • (ps |Where Path -match 'mcafee'|measure -sum -Property WorkingSet).Sum / 1MB • What’s fred running? • ps -IncludeUserName|Where UserName -eq 'CONTOSO\Fred’ (must run elevated) • What version of xxx is running? • ps acrord32| Select fileversion • What is using this dll that needs updating? • ps| Where { $_.Modules.Where( { $_.ModuleName -match 'mfaphook64.dll' } ) } • Let’s reduce the impact of this CPU hog • ps chrome | % {$_.PriorityClass = ‘BelowNormal’ }
  13. GET-CHILDITEM • Show largest files in human readable form •

    dir |sort Length -Desc| select Mode,LastWriteTime,@{n='Size (MB)';e={[int]($_.length / 1MB)}},Name -First 10 • dir -Force -Recurse -EA Silent| Sort Length -Desc| select Mode,LastWriteTime,@{n='Size (MB)';e={[int]($_.length / 1MB)}},FullName -First 10 • Get folder disk usage • (dir -Force -Recurse -EA Silent|measure -sum -Property length).Sum / 1MB • Find all files from a specific vendor • dir -Force -Recurse -EA Silent | Where { $_.VersionInfo.CompanyName -match ‘Novell' } • Find files not owned by a “trusted” account • dir |Get-Acl |Where { $_.Owner -notmatch ‘\\administrator' -and $_.Owner -notmatch ‘\\system' -and $_.Owner -notmatch ‘\\trustedinstaller' } • Not just file system – Get-PSDrive • dir Cert:\LocalMachine\My\ -recurse |Where NotAfter -le (Get-Date).AddDays( 60 ) • Delete old log files (via scheduled task) • dir *.log -recurse | Where CreationTime -lt (Get-Date).AddDays( -30 )|Remove-Item • For those with fat fingers ☺ • sal dri dir (put it in your PowerShell profile)
  14. GETTING HELP • PowerShell has lots of built-in help •

    Get-Command • gcm –verb set –noun *network* • gcm set-*network* • gcm –module ActiveDirectory • gcm ts*.exe (or type ‘ts’ and tab compete or hit ctrl space) • gcm cert*.??? (will show .msc as well as .exe) • Get-Help • -showwindow • -online • Pipe objects returned through Get-Member to see methods, properties, etc
  15. EXPORT-CSV • Export-CSV • -NoTypeInformation (unless importing & even then

    probably not necessary) • -NoClobber/-Force • -Delimiter (Dutch!) • -Append • Beware of -Encoding as Excel does not like Unicode CSV files (default works fine) • Produce reports • Scheduled or Ad-hoc • Send-MailMessage • Import-CSV • ConvertFrom-CSV • E.g. IIS logs to a grid view
  16. OUT-GRIDVIEW • Sort/Filter objects • -PassThru to get selected objects

    after “OK” clicked • Assign to variable • Pipe to Set-Clipboard (scb) • Pipe into another cmdlet/function • Can use as a GUI selector in a script
  17. OTHER CONTENDERS FOR THE TOP 10# Set-ACL – fix permissions,

    copy from a known good system Get-FileHash – are those two files the same? Is that download ok? *-Service – start/stop services or change settings Stop-Computer/Restart-Computer – errors if anyone else logged on unless –force Get-Counter – get any performance counter Measure-Object Measure-Command Get-VM (Hyper-V or VMware PowerCLI) …
  18. TIPS AND TRICKS • Prefix/Suffix commands with Get-Date to record

    when ran for cross referencing • Get-Date; Test-NetConnection dodgyserver • $PSVersionTable • See what PoSH version you are running • Ctrl r to search persistent history • Ctrl Space to show all options • Measure-Object • Measure-Command • Out-Gridview (-PassThru) • Ctrl Backspace/Delete to delete whole word back/forward • Ctrl arrow – jump words • Number conversions • ‘{0:x}’ –f 1234 • 0x4d2 • [convert]::ToString( 1234 , 2 )