Tuesday, December 30, 2014

#38 : Powershell script to Map Network drive

We often need to map network drives. Especially if you are writing a package which installs something from a shared drive. It becomes important to map drives and give a drive letter for the same.

Net share is the command which can be used to accomplish the same. Below is the Powershell version of the same -

Adding a Network Drive 
(New-Object -Com WScript.Network).MapNetworkDrive("x:" , "\\divine\d$")

That's it!
But this not the all about this. There might be further requirement to remove a network drive.


Listing the Network Drives
(New-Object -Com WScript.Network).EnumNetworkDrives()


Removing a Network Drive
(New-Object -Com WScript.Network).RemoveNetworkDrive("x:")

You can use EnumNetworkDrives() to find if particular share exists or not, then remove it. Anyways, there are several methods to do something, my job was just to give your tips not thesis.

Enjoy!!


Thursday, December 25, 2014

#37 : Download Files from Internet with Powershell

Powershell can be used to download a file from internet. This might help you matching some item from internet or you can create a download manager kind of software in Powershell.
Actually, you can do nearly everything which you can do in C# or any .NET based programming language because, .NET framework is common to C#, VB.NET and Powershell as well. Both Powershell or C# compile the code into MSIL (Microsoft Intermediate Language). But the only difference is Powershell is in form of script and C# will be a program. 
Powershell scripts can be compiled using C#, but again the compiled executable will require Powershell be installed on the machine. This cannot be called as standalone executable, but again I think "Can you run a C# code when .NET framework is not installed?". Anyways, lets not waste more time in thinking, below is the piece of code- 

(new-object System.Net.WebClient).Downloadfile("http://www.freeware995.com/bin/pdfedit.exe", "d:\pdfedit.exe")

Above is smallest inner line of a possible big code which will handle download of files from Internet. 

For sake of simplicity, I always prefer to give a one-liner. The reason is, when you want to know how to do something, your intention is basically to get something too small which can be further enhanced in your program. When I search, I look for a small code and I hope everyone does. There is no point is providing a complex code which you could not understand or incorporate in your code!

Enjoy scripting!!

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!

Thursday, October 16, 2014

#29 : Creating array in Powershell

Array is programming construct of most of the high level languages. It is meant to describe a collection of elements (values or variables), each selected by one or more indices that can be computed at run time by the program.

Declaring array is very simple in Powershell and there are multiple ways to achieve it :

1. Static Array

Array : Definition  
An array type is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices that can be computed at run time by the program. Such a collection is usually called an array.
Array can be useful in your programming where you have to work on a collection of

Creating an Array in Powershell:

  1. $x=@()   
  2. $x += "Som"   
  3. $x += "Jack"   
  4. $x += "John"   
  5. $x += "Micky"   

Displaying and accessing elements of Array:
You can access each element of array with [<index_number>]. Square brackets enclosed in index number.
  1. $x[0]  
  2. $x 
Output:
Som
Som
jack
John
Mickey 


Searching an element of Array:
Array plays important role in searching in Powershell. Let's see how?

Suppose we have to search if jack exists in any of index of the array, we can search it using below statement -
    1. $x -contains "jack"    
    2. $x -contains "xx"   
    Output:
    True
    False 
     So, you may use it in your scripts like this -
    1. if ( $x -contains "jack" )   
    2. {   
    3.     Write-Host "jack exits!"   
    4. }   
    5. else   
    6. {   
    7.     Write-Host "jack does not exits!!"   
    8. }   


    Deleting an Element from Array:

    There is no direct method which can be used to delete specific index from array. But below can be tried to search and delete specific value from an Array -
    1. clear   
    2. $x=@()   
    3. $x += "Som"   
    4. $x += "Som"   
    5. $x += "Som"   
    6. $x += "Ravi"   
    7. $x += "jack"   
    8.   
    9. Write-Host "Before Deleting element named 'jack' - "    
    10. $x   
    11.   
    12. $x = $x | where {$_ -ne "jack" }   
    13.   
    14. Write-Host "After Deleting element named 'jack' - "    
    15. $x  



    Array is one of the basics of any Programming language. There are numerous other ways to create Array in Powershell.



    cls




    #--Static Array --#
     

     

    $x1 = (1,2,3)




    $x1
     
     

     
    #-OR- Write like below --#
     
     

    $x = 1 ,2 ,3


     
     
    echo "#--Just writing $x shows all elements --# "



    $x
     
     

    echo "#--Onliner to print all elements of array --# "
    $x | foreach { echo "Element - $($_)"}



     
     
    echo "#--Display all elements using foreach --# "
    foreach ( $i in $x )



    {
     
    echo "Element - $i"



    }
     
    echo "#--Display all elements using for loop --# "

    for ($c=0; $c -lt $x.Count; $c++)



    {
     
    echo "Element[$c]- $($x[$c])"



    }
     
    $y = 1 , "Som" , "Testing" , 3



    $y
     
     



     
     
    echo "#--Add two arrays --# "
    $z = $x + $y

    $z



     
     
    echo "#--Substract elements of one array --# "




    #--Below does $y -$x --#
     
     
    $n= $y | where { $x -notcontains $_ }
    $n



     
     
    echo "#--Range --#"

    $m = 1 ..6
    $m



     
     
    echo "--Adding elements to array--#"

    $Arr = @()
    $Arr += "Check-1"
    $Arr += "Check-2"
    $Arr += "Check-3"
    $Arr += "Check-4"

    $Arr



     
     
    echo "--Create Multi-dimensional Array 4x4--#"

    [string[][]]$md = @( (0,0,0,0) , (0,0,0,0), (0,0,0,0), (0,0,0,0) )

    $md[0][0]="A"
    $md[0][1]="B"
    $md[0][2]="C"
    $md[0][3]="D"

    $md[0]

    echo "------------"

    $md[1][0]="E"
    $md[1][1]="F"
    $md[1][2]="G"
    $md[1][3]="H"

    $md[1]

    echo "------------"

    $md[2][0]="I"
    $md[2][1]="J"
    $md[2][2]="K"
    $md[2][3]="L"

    $md[2]

    echo "------------"

    $md[3][0]="M"
    $md[3][1]="N"
    $md[3][2]="O"
    $md[3][3]="P"

    $md[3]




    #--Formatted display of 4x4 multi-dimensional Array--#
     
     
    echo " "
    echo "+---+---+---+---+---+"
    echo "| | 0 | 1 | 2 | 3 |"
    echo "+---+---+---+---+---+"

    for ( $a=0; $a -lt 4 ; $a++)



    {
     
    echo "| $a | $($md[$a][0]) | $($md[$a][1]) | $($md[$a][2]) | $($md[$a][3]) | $($md[$a][4]) "
    echo "+---+---+---+---+---+"


    }

     

     

     
     
    $f=@(,@(,@(,@())))

    $f[0][0][0]=1
    $f[0][0][0]=1
    $f



     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     


      

    #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...