Thursday, March 9, 2017

Troubleshooting with powershell

I like do things easy and effectively that's why I hate all the clicking back and there in windows opening log files in notepad and searching it... opening taskmgr, services.msi ...

I find lot of those informations can be obtaine using powershell quickly and searching for info is easier.
So I created for my self this list of thing I'm trying to do most during troubleshooting, I also add name of corresponding program in linux.

List of open ports (netstat)

When we need to check the network communication we need to check if server/services is listening netstat -aon give us the list of open ports, but important part is that it also provide the PID, process ID, which means that using Get-Process -id PID (see below) we can check if it's also the correct service listening on the port. It's also powerfull to combine with Select-string to get just what you search for

PS C:\Users\j.kindl> netstat -aon

Active Connections

  Proto  Local Address          Foreign Address        State           PID
  TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       888
  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       708
  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
  TCP    0.0.0.0:902            0.0.0.0:0              LISTENING       2524
  TCP    0.0.0.0:912            0.0.0.0:0              LISTENING       2524
  TCP    0.0.0.0:1801           0.0.0.0:0              LISTENING       2180
  TCP    0.0.0.0:2103           0.0.0.0:0              LISTENING       2180
...

Process (ps, kill)

Get-Process

PS C:\Users\j.kindl> Get-Process

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    727      35    25096      19708      19.86   7436   1 ApplicationFrameHost
    516      21    67336      71352              7868   0 aswidsagenta
    160      12     9068      14400       8.02   8016   0 audiodg
   3415     121   228576      40692               944   0 AvastSvc
    993      50    20092      33280     213.58  10612   1 AvastUI
    388      16     4864      11956      77.81   4888   1 BingSvc
    357      17     5256      10596       4.30   8216   1 browser_broker
    390      22    14064         36       0.63  10080   1 Calculator
    253      12     3084       1152       0.61    352   1 chrome
    252      25    68844      64728       1.27   1200   1 chrome
    284      32    54984      28428     646.75   1428   1 chrome
   2624     103   390592     156660   6,416.77   1836   1 chrome
    302      39    71356      35524   2,329.05   2592   1 chrome
    416     195   240512     241824   6,598.47   4124   1 chrome
...


Get-Process -id NUMBER
PS C:\Users\j.kindl> Get-Process -id 2180

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    323      29     3836       1396              2180   0 mqsvc

To stop/kill the process there is command Stop-Procces -id NUMBER[-Force]


Services(service)

The list and status of services can be obtained using Get-Service
PS C:\Users\j.kindl\Documents> Get-Service

Status   Name               DisplayName
------   ----               -----------
Stopped  AJRouter           AllJoyn Router Service
Stopped  ALG                Application Layer Gateway Service
Running  AppHostSvc         Application Host Helper Service
Stopped  AppIDSvc           Application Identity
Running  Appinfo            Application Information
Stopped  AppReadiness       App Readiness
...

To stop or start service there are commands Stop-Service , Start-Service


Uptime

net statistics server
PS C:\Users\j.kindl\Documents> net statistics server
Server Statistics for \\G33KSBOOK


Statistics since 2/23/2017 20:13:04


Sessions accepted                  0
Sessions timed-out                 0
Sessions errored-out               0

...

The command completed successfully.


Searching text (grep)

Searching through text is very usefull to filter just what we want (searching for) or filter out the noise we are not interested in. For that porpose Select-string is perfect. In most cases the just what you search and file(s) will be fine enough, but select-stirng is very versatile so check the help if you need something more robust.

Seraching in file:
select string "what I Seacrch" file.txt

Searching in files (all .txt in current folder):
selesc-string "what I Seacrch" *.txt

Searching in nestat output for UPD:
netstat -aon | Select-string 'UDP'

Fitlering out UPD from netstat output:
netstat -aon | Select-string 'UDP' -NotMatch

You can also use more pipes to create more complex filters
netstat -aon | Select-String '0.0.0.0' | Select-string 'UDP' -NotMatch

Searching through Eventlog (note that you need to use -InputObject as Get-EventLog return objects not string):
Get-EventLog -logname System | select-string -InputObject {$_.message} reboot

Print out the file (cat)

To print out the file content to screen you can use old classic type or Get-Content.

type file(s)
type file.txt
type *.txt

Get-content file(s)
Get-Content file.txt
Get-Content *.txt

Specific lines (head, tail)

Sometimes you just need few lines from file/output, to just check the structure of log or format of the date to create proper filter with for select-string.
Or you just need the last events from the log file.
For this you can use Get-Content or Select-Object. I hope the examples are self explanatory.

Get-Content -TotalCount 10
type file | Select-object -first 10

Get-Content -Tail 10
type file | Select-object -last 10

Sorting (sort,uniq)

Sorting and getting unique records are two very handy abilities. In powershel for both there is one command Sort-Object [-unique].
If you are sorting objcets, like output of ls, Get-ChildItem, GetWmiObject .... you can also use -property NAME to sort based on object property you want.

Sorting based on the file size:
PS C:\Users\j.kindl\Documents> ls | Sort-Object -property Length


    Directory: C:\Users\j.kindl\Documents


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         3/9/2017     10:49             22 20170000
-a----        11/1/2016     12:06           1977 ShareSize.vbs
-a----       10/19/2016     20:34          11475 Test-Port.ps1
-a----        8/22/2016     12:23         182711 HorskaVyzva2016Sumava.gpx
-a----        8/23/2016     20:31         233030 HorskaVyzva2016Sumava.pdf
-a----         6/5/2016     18:54         276947 DVB-T_AfterStart.txt
-a----        4/15/2016      0:39         302900 DVB-T_TVRunning.txt
-a----        10/5/2015     14:19         731520 UPnP_Cast_to_Xbox360.pcapng
-a----        8/16/2016     22:55        9283351 WhichPokemon.xcf
d-----        1/25/2017     19:58                GitHub
....
d-----         1/8/2016     14:02                Rodokmen

Sorting text file:
PS C:\Users\j.kindl\Documents> type .\software.txt |Sort-Object -Descending
Vendor                  InstallDate
Skype Technologies S.A. 20170224
Microsoft Corporation   20170305
Microsoft Corporation   20170305
Microsoft Corporation   20170305
Microsoft Corporation   20170305
------                  -----------

PS C:\Users\j.kindl\Documents> type .\software.txt |Sort-Object -Descending -Unique
Vendor                  InstallDate
Skype Technologies S.A. 20170224
Microsoft Corporation   20170305
------                  -----------

Counting lines, words, chars (wc)

Another tiny commandlet/utility which is increadibly useful is Measure-Object. It will be able to count the words (chars separated by white spaces), chars and most important lines.
This comes very handy to find the number of log records in given time period and compare it with abilites of software to process it.(or not and crash/freeze)

example below actaully counts how many open UDP ports is there:
PS C:\Users\j.kindl\Documents> netstat -aon | Select-string 'UDP' -NotMatch | Measure-Object -Line

Lines Words Characters Property
----- ----- ---------- --------
  118

Searching in EventLog

Very important source of information what and when happend is event log it self.
To access eventlog powershell have command Get-Eventlog


PS C:\Users\j.kindl> Get-EventLog -logname System -newest 1

   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
   17673 Mar 04 09:25  Information Microsoft-Windows...            1 The system has returned from a low power state....


If want to be effective in searching in event log we want to know the properties on which we can query we can use command Format-list to obtain the properties.

PS C:\Users\j.kindl> Get-EventLog -logname System -newest 1 | Format-List -property *


EventID            : 1
MachineName        : g33ksbook
Data               : {}
Index              : 17673
Category           : (0)
CategoryNumber     : 0
EntryType          : Information
Message            : The system has returned from a low power state.

                     Sleep Time: 2017-03-03T23:01:26.365204100Z
                     Wake Time: 2017-03-04T08:25:28.112939900Z

                     Wake Source: 0
Source             : Microsoft-Windows-Power-Troubleshooter
ReplacementStrings : {2017-03-03T23:01:26.365204100Z, 2017-03-04T08:25:28.112939900Z, 33998, 11531...}
InstanceId         : 1
TimeGenerated      : 3/4/2017 9:25:29
TimeWritten        : 3/4/2017 9:25:29
UserName           : NT AUTHORITY\LOCAL SERVICE
Site               :
Container          :

To search when my PC was rebooted (Respectively when Event Log service started, similarly you can search when it stopped with eventID 6006) I use "command" where to specify query in $_ links to the event(s) return by Get-EventLog.

PS C:\Users\j.kindl> Get-EventLog -logname System | where {$_.eventID -eq 6005}

   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
   16931 Feb 23 20:13  Information EventLog               2147489653 The Event log service was started.
   13372 Jan 11 23:57  Information EventLog               2147489653 The Event log service was started.
   11730 Dec 17 12:50  Information EventLog               2147489653 The Event log service was started.
   11213 Dec 11 10:24  Information EventLog               2147489653 The Event log service was started.
   10160 Nov 28 17:13  Information EventLog               2147489653 The Event log service was started.
    9198 Nov 14 14:53  Information EventLog               2147489653 The Event log service was started.
    9007 Nov 13 17:55  Information EventLog               2147489653 The Event log service was started.
    8104 Nov 01 18:16  Information EventLog               2147489653 The Event log service was started.
    7991 Nov 01 18:10  Information EventLog               2147489653 The Event log service was started.
    7683 Oct 31 19:55  Information EventLog               2147489653 The Event log service was started.
    6593 Oct 18 09:35  Information EventLog               2147489653 The Event log service was started.
    5451 Oct 04 19:24  Information EventLog               2147489653 The Event log service was started.
    5365 Oct 04 19:18  Information EventLog               2147489653 The Event log service was started.
    3623 Sep 16 15:47  Information EventLog               2147489653 The Event log service was started.
    2417 Sep 02 23:18  Information EventLog               2147489653 The Event log service was started.
    1416 Aug 24 02:08  Information EventLog               2147489653 The Event log service was started.
     535 Aug 11 15:50  Information EventLog               2147489653 The Event log service was started.
     220 Aug 10 22:57  Information EventLog               2147489653 The Event log service was started.
       3 Aug 10 22:44  Information EventLog               2147489653 The Event log service was started.


WMI

WMi is great source of information about you system, OS version, software installed, processes running, services, disks, network interfaces, name it... and probably it's there.

Using Get-WmiObject you can access the WMI information, either by addressing the Class and work with return object or use WQL (WMI Query language), which is actaully subset of SQL (so when you know SQL you know WQL).

To get all from class (Win32_OperatingSystem), it gives more info then query "select * from  Win32_OperatingSystem"
Get-WmiObject Win32_OperatingSystem | select-object -property *

To get just some info you can use select-object -property NAME(S)
PS C:\Users\j.kindl\Documents> Get-WmiObject Win32_OperatingSystem | select-object -property Name, OSArchitecture | format-list

Name           : Microsoft Windows 10 Home|C:\WINDOWS|\Device\Harddisk0\Partition2
OSArchitecture : 64-bit

Same but using WQL query:
PS C:\Users\j.kindl\Documents> Get-WmiObject -Query "select Name, OSArchitecture from Win32_OperatingSystem"


__GENUS          : 2
__CLASS          : Win32_OperatingSystem
__SUPERCLASS     :
__DYNASTY        :
__RELPATH        : Win32_OperatingSystem=@
__PROPERTY_COUNT : 2
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
Name             : Microsoft Windows 10 Home|C:\WINDOWS|\Device\Harddisk0\Partition2
OSArchitecture   : 64-bit
PSComputerName   :

You can also run the Get-WmiObject remotly:
Get-WmiObject -computername IP Win32_Computersystem

or
Get-WmiObject -computername HOST -Credential Domain\User -Query "Select * from Win32_Bios"


Usefull WMI queries

If your software is crashing and hard to find why it's good to what was installed with this query you can get the list of installed software including dates, when it was installed:
PS C:\Users\j.kindl\Documents> Get-WmiObject Win32_Product | select-object -property Name,Version,Vendor,InstallDate

Name                                                                                                       Version        Vendor                  InstallDate
----                                                                                                       -------        ------                  -----------
digiCamControl                                                                                             2.0.0.0        Duka Istvan             20160619

Microsoft Application Error Reporting                                                                      12.0.6015.5000 Microsoft Corporation   20150702
Office 16 Click-to-Run Extensibility Component                                                             16.0.7766.2047 Microsoft Corporation   20170305
Office 16 Click-to-Run Localization Component                                                              16.0.7668.2066 Microsoft Corporation   20170305
Office 16 Click-to-Run Extensibility Component 64-bit Registration                                         16.0.7766.2047 Microsoft Corporation   20170305
Office 16 Click-to-Run Licensing Component                                                                 16.0.7766.2047 Microsoft Corporation   20170305

Now as the date is in format YYYYMMDD it's easily sortable and comparable. The higher number the newer installation. So to get software installed since beginig of Feb 2017 you would use where InstallDate > 20170200 the Select-Object command in example below is doing output more readable:
PS C:\Users\j.kindl\Documents> Get-WmiObject -query "Select * from Win32_Product where InstallDate > 20170200" | Select-Object -property Name,Version,Vendor,InstallDate

Name                                                               Version        Vendor                  InstallDate
----                                                               -------        ------                  -----------
Office 16 Click-to-Run Extensibility Component                     16.0.7766.2047 Microsoft Corporation   20170305
Office 16 Click-to-Run Localization Component                      16.0.7668.2066 Microsoft Corporation   20170305
Office 16 Click-to-Run Extensibility Component 64-bit Registration 16.0.7766.2047 Microsoft Corporation   20170305
Office 16 Click-to-Run Licensing Component                         16.0.7766.2047 Microsoft Corporation   20170305
Skype™ 7.32                                                        7.32.104       Skype Technologies S.A. 20170224

Enviromental variable(env)

Enviromental variables among others include also shortcats to certain folders, so to get there without remebering the path you can use $env:VARIABLE (in explorer you can use %VARIABLE%)
For example:
cd $env:HOMEPATH

the list of variables can be obtained using Get-ChildItem Env:
PS C:\Users\j.kindl\Documents> Get-ChildItem Env:

Name                           Value
----                           -----
ALLUSERSPROFILE                C:\ProgramData
APPDATA                        C:\Users\j.kindl\AppData\Roaming
CommonProgramFiles             C:\Program Files\Common Files
CommonProgramFiles(x86)        C:\Program Files (x86)\Common Files
CommonProgramW6432             C:\Program Files\Common Files
COMPUTERNAME                   G33KSBOOK
ComSpec                        C:\WINDOWS\system32\cmd.exe
FP_NO_HOST_CHECK               NO
HOMEDRIVE                      C:
HOMEPATH                       \Users\j.kindl
...
SystemDrive                    C:
SystemRoot                     C:\WINDOWS
TEMP                           C:\Users\JC340~1.KIN\AppData\Local\Temp
TMP                            C:\Users\JC340~1.KIN\AppData\Local\Temp
USERDOMAIN                     G33KSBOOK
USERDOMAIN_ROAMINGPROFILE      G33KSBOOK
USERNAME                       j.kindl
USERPROFILE                    C:\Users\j.kindl
windir                         C:\WINDOWS
windows_tracing_flags          3
windows_tracing_logfile        C:\BVTBin\Tests\installpackage\csilogfile.log

No comments: