Wednesday, December 17, 2014

#36 : How to find CPU Usage Percent with Powershell?

Hi All,

CPU-Utilization can be achieved with the command below -

Get-WmiObject win32_processor | select LoadPercentage | fl

Let's dissect the line and try to understand -


Posh (0016) > Get-WmiObject win32_processor


__GENUS                     : 2
__CLASS                     : Win32_Processor
__SUPERCLASS                : CIM_Processor
__DYNASTY                   : CIM_ManagedSystemElement
__RELPATH                   : Win32_Processor.DeviceID="CPU0"
__PROPERTY_COUNT            : 48
__DERIVATION                : {CIM_Processor, CIM_LogicalDevice, CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER                    : DIVINE
__NAMESPACE                 : root\cimv2
__PATH                      : \\DIVINE\root\cimv2:Win32_Processor.DeviceID="CPU0"
AddressWidth                : 32
Architecture                : 9
Availability                : 3
Caption                     : x64 Family 6 Model 23 Stepping 10
ConfigManagerErrorCode      :
ConfigManagerUserConfig     :
CpuStatus                   : 1
CreationClassName           : Win32_Processor
CurrentClockSpeed           : 1196
CurrentVoltage              : 16
DataWidth                   : 64
Description                 : x64 Family 6 Model 23 Stepping 10
DeviceID                    : CPU0
ErrorCleared                :
ErrorDescription            :
ExtClock                    : 200
Family                      : 185
InstallDate                 :
L2CacheSize                 : 1024
L2CacheSpeed                :
L3CacheSize                 : 0
L3CacheSpeed                : 0
LastErrorCode               :
Level                       : 6
LoadPercentage              : 1
Manufacturer                : GenuineIntel
MaxClockSpeed               : 2300
Name                        : Pentium(R) Dual-Core CPU       T4500  @ 2.30GHz
NumberOfCores               : 2
NumberOfLogicalProcessors   : 2
OtherFamilyDescription      :
PNPDeviceID                 :
PowerManagementCapabilities :
PowerManagementSupported    : False
ProcessorId                 : BFEBFBFF0001067A
ProcessorType               : 3
Revision                    : 5898
Role                        : CPU
SocketDesignation           : uPGA-478
Status                      : OK
StatusInfo                  : 3
Stepping                    :
SystemCreationClassName     : Win32_ComputerSystem
SystemName                  : DIVINE
UniqueId                    :
UpgradeMethod               : 185
Version                     :
VoltageCaps                 :




The result shows overall CPU-Utilization which can be matched with the CPU Usage in Task-Manager. WMI plays very important role in getting these valuable information. But this is also required that WMI service should be running on the machine where you are running these commands.



Happy scripting!!

Tuesday, December 9, 2014

#35 : How to know Windows Startup commands with Powershell?

Hi Guys,

Being Powershell developer, we always look for some good solution and simple solution. When I find something useful and simple, I share them with all of you.




While looking into WMI Explorer, I found a good stuff which could tell us the list of programs which run a windows start-up. Below is the command for the same -

Get-WmiObject -Class Win32_StartupCommand

Enjoy Scripting!

Wednesday, December 3, 2014

#34 : Find uptime of the host using Powershell

Sometimes we need to know the uptime of a host while troubleshooting. It plays lot more important role while troubleshooting.

We can use net stats srv command to get this information. If you check the output of this command, you will see a line which shows uptime is "Statistics since .. ". You can use this line and get desired result by doing some pipelining. The result should compare from current time and give result in number of days,hours, minutes and seconds.

You can see the article about "Difference between two dates" here for better understanding.

Let's try the command "net stats srv"

net stats srv 

Server Statistics for \\WIN-4SV8KNP9VNV


Statistics since 7/16/2017 1:11:09 AM


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

Kilobytes sent                     0
Kilobytes received                 0

Mean response time (msec)          0

System errors                      0
Permission violations              0
Password violations                0

Files accessed                     0
Communication devices accessed     0
Print jobs spooled                 0

Times buffers exhausted

  Big buffers                      0
  Request buffers                  0

The command completed successfully.



You may  notice that we can remove "Statistics since" and then uptime is there to be processed. We will use the same logic.


clear 
$uptime=net stats srv | where {$_ -match "since"} | foreach {$_.replace("Statistics since","") } | 
foreach { $($((Get-Date) - (Get-Date $_)).Days).tostring().padleft(3,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Hours).tostring().padleft(2,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Minutes).tostring().padleft(2,"0").tostring() + ":" + 
 $($((Get-Date) - (Get-Date $_)).Seconds).tostring().padleft(2,"0").tostring() 
 } | foreach { $_.replace(" ", "") } 

echo "Uptime of Host [$(hostname)]`t: $uptime (DD:HH:MM:SS)"


Output:
Uptime of Host [Divine] : 000:00:45:24 (DD:HH:MM:SS)

The above script can be modified to generate a report based on all hosts in your environment. But, I would like you to at least comment once. How long I would write without any comment?

Tuesday, November 25, 2014

#33 : Complete script to download file with Powershell

Powershell can be used to download some files from internet or intranet. We can simply do it with Invoke-WebRequest.

Below is the code which can be used for this purpose :

#--------------------------------------------------------------------------------------------------------------
#-- Script to Download file 
#--------------------------------------------------------------------------------------------------------------

function Download-File ([string]$url , [string]$target)
{
 trap {
  echo "Error occured" 
  continue 
 }
 
 if ( !(Test-path $target ))
 {
  invoke-webrequest $url -OutFile $target
 }
 else 
 {
  echo "Error : Directory does not exit!"
 }

}

#--------------------------------------------------------------------------------------------------------------

Download-File "http://site.foo.com/file.exe" "C:\temp"

#--------------------------------------------------------------------------------------------------------------

Enjoy!

Tuesday, November 11, 2014

#32 : How to check if TCP/IP Port is open?

Without talking much, please find the code below.
#------------------------------------------------------------------------------------------
#     Script : Check_Port.ps1 
#     Author : Som DT.
#    Purpose : Checking if Port is open on target TCP/IP server from current host 
#------------------------------------------------------------------------------------------

function Check-Port([string]$HostName, [string] $PortNumber) 
{
    #--Set the client --# 
    $tcp = New-Object System.Net.Sockets.TcpClient
    
    #--Connecting to the Port --# 
    $tcp.connect($HostName , $PortNumber ) 
    

}

Enjoy!

Monday, November 3, 2014

#31 : Loading file content into Array of Hash Table

While programming, sometimes we need to read some configuration entries from a flat file. There are several approaches to do it, I have followed the below approach to read file-entries into a hash table which is also an array.
I have assumed that there is a flat file which contains multiple lines of information about employee. This can be configuration settings or it can be anything. I have used this simple example for simplicity -







There might be many other approach to do it, I do not advocate it as a best approach, but if you want to have full control and understandability of the code, you may use the above approach.

Thursday, October 30, 2014

#30 : Using Progressbar with a purpose

Progressbar is simply achieved in Powershell with Write-progress cmdlet. This cmdlet can be used with below example -

Write-Progress -Activity "File-Copy" -PercentComplete 55 -Status "Something" -Id 1

Running the above command in Powershell prompt is not meaningful, it will not display anything. I saw so many articles about Write-Progess, but all of them are using a dummy example to use Progressbar, so I am presenting an example which will show you a real utilization of Write-progress.
Example of using Write-Progress

The example demonstrates the utilization of Write-Progress. In this example, we will copy files from a source location to a destination and we will display progessbar for this. The status of progressbar will show the status of task. It does not show the file-copy status of individual file, but it shows the percent status of file-copy task as a whole.
I will use SOURCE_PATH and TARGET_PATH variables and if you are testing it on your computer, you must change the path. For god sake, do not use a disk where operating system is installed and do not use a disk which has low disk space. Anyways, a professional will not do such mistake.





Isn't this easy to use Write-Progress in your other scripts!
Enjoy Scripting!

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...