Powershell Commands & Scripting

Process & Help related commands:

  1. get-process:  It returns all the process that are current running in windows.


PS D:\Projects\Practice> get-process

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

——-  ——    —–      —– —–   ——     — ———–

305      29    74312      92116   256     3.19   1976 AcroRd32

236      15     5180      13156    97     0.08   4276 AcroRd32

105       9     6784       8204    40     0.06   6948 audiodg

30       5      640       2644    29            1548 conhost

30       4      608       2440    27            1660 conhost

338      14     1724       3984    52             520 csrss

445      25     2232      66576   231             596 csrss

We can add a wild card search to find a particular process information as.

PS D:\Projects\Practice> get-process note*

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

——-  ——    —–      —– —–   ——     — ———–

84       8     1356       6792    91     0.17   4588 notepad

  1. stop-process: It stops a particular process depending on the process id we pass to the command.

E.g: Process id of notepad is 4588 so to stop the notepad process we can do the following.

PS D:\Projects\Practice> get-process note*

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

——-  ——    —–      —– —–   ——     — ———–

84       8     1356       6792    91     0.17   4588 notepad

PS D:\Projects\Practice> Stop-Process -id 4588

PS D:\Projects\Practice>

  1. Using –whatif to prototype a command: In the above example we stopped the process but we never came to know what the stop-process command actually did. So here we can use the –whatif parameter to know what exactly the process is doing. Below example will illustrate the same.

PS D:\Projects\Practice> Get-Process note*

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName

——-  ——    —–      —– —–   ——     — ———–

68       7     1244       5448    89     0.02    484 notepad

PS D:\Projects\Practice> stop-process -id 484 -WhatIf

What if: Performing operation “Stop-Process” on Target “notepad (484)”.

PS D:\Projects\Practice>

So the –Whatif parameter revealed the action performed “What if: Performing operation “Stop-Process” on Target “notepad (484)”.

  1. Confirming Commands: We can ask a user to confirm whether to execute the command or not
    with the –confirm parameter.

So as we can see from the screenshot the command is asking for confirmation from the user whether to continue execution.

  1. Working with the help option: If you want to get some help related to some commands use the “Get-Help” command. Lets see how it works with the commands we executed above say Stop-Process.

PS D:\Projects\Practice> Get-Help stop-process




Stop-Process [-Id] <int[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

Stop-Process -Name <string[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

Stop-Process [-InputObject] <Process[]> [-PassThru] [-Force] [-WhatIf] [Confirm]  [<CommonParameters>]





Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.

— To download and install Help files for the module that includes this cmdlet, use Update-Help.

— To view the Help topic for this cmdlet online, type: “Get-Help Stop-Process -Online” or

go to http://go.microsoft.com/fwlink/?LinkID=113412.

So we can see that a detailed help is provided with all the options we can use with Stop-Process. You can also use other options with get-help given below.

  1. Get-help Stop-Process –detailed
  2. Get-help Stop-Process –full
  3. Get-help Stop-Process –examples

Can also do a wild card search to get help as:

  1. Get-help about*
  2. Get-help get*

System info & output formatting commands:

  1. Get-Childitem Cmdlet: Used to get all the files and folders in a directory as “dir” command in DOS. Eg:

PS D:\Projects\Practice> Get-ChildItem C:\

Directory: C:\

Mode                LastWriteTime     Length Name

—-                ————-     —— —-

d—-          4/9/2013   2:07 AM            inetpub

d—-          4/9/2013   1:50 AM            Intel

d—-         7/26/2012   1:03 PM            PerfLogs

d-r–          4/9/2013   2:45 AM            Program Files

d-r–          4/8/2013   5:04 PM            Program Files (x86)

d-r–          4/8/2013   4:13 PM            Users

d—-          4/9/2013  10:23 AM            Windows

-a—          4/8/2013   2:35 PM       1024 .rnd

PS D:\Projects\Practice>

  1. Formatting output with the Format-List Cmdlet: We can pipe the Format-List Cmdlet with  Get-Childitem or any other commands to format the output in more detail as per our requirement. Given example will display all display file and folder information in C drive in more depth.

PS D:\Projects\Practice> Get-ChildItem C:\ | Format-List

Directory: C:\

Name           : inetpub

CreationTime   : 4/9/2013 2:06:56 AM

LastWriteTime  : 4/9/2013 2:07:01 AM

LastAccessTime : 4/9/2013 2:07:01 AM

Name           : Intel

CreationTime   : 4/9/2013 1:50:42 AM

LastWriteTime  : 4/9/2013 1:50:42 AM

LastAccessTime : 4/9/2013 1:50:42 AM

Name           : PerfLogs

CreationTime   : 7/26/2012 1:42:58 PM

LastWriteTime  : 7/26/2012 1:03:46 PM

LastAccessTime : 7/26/2012 1:03:46 PM

Name           : Program Files

CreationTime   : 7/26/2012 11:07:58 AM

LastWriteTime  : 4/9/2013 2:45:02 AM

LastAccessTime : 4/9/2013 2:45:02 AM

Name           : Program Files (x86)

CreationTime   : 7/26/2012 11:07:58 AM

LastWriteTime  : 4/8/2013 5:04:29 PM

LastAccessTime : 4/8/2013 5:04:29 PM

Name           : Users

CreationTime   : 7/26/2012 11:07:58 AM

LastWriteTime  : 4/8/2013 4:13:39 PM

LastAccessTime : 4/8/2013 4:13:39 PM

Name           : Windows

CreationTime   : 7/26/2012 11:07:59 AM

LastWriteTime  : 4/9/2013 10:23:30 AM

LastAccessTime : 4/9/2013 10:23:30 AM

Name           : .rnd

Length         : 1024

CreationTime   : 4/8/2013 2:35:18 PM

LastWriteTime  : 4/8/2013 2:35:18 PM

LastAccessTime : 4/8/2013 2:35:18 PM

VersionInfo    : File:             C:\.rnd







Debug:            False

Patched:          False

PreRelease:       False

PrivateBuild:     False

SpecialBuild:     False


We can also specify particular property name just to view particular properties of files and folders. Given example illustrates where we print only the name and length.

PS D:\Projects\Practice> Get-ChildItem C:\ | Format-List -Property name, length

Name : inetpub

Name : Intel

Name : PerfLogs

Name : Program Files

Name : Program Files (x86)

Name : Users

Name : Windows

Name   : .rnd

Length : 1024

Using the Format-Wide Cmdlet: We can use the Format-Wide Cmdlet in the same way we use the Format-List Cmdlet. Given Example will illustrate.

PS D:\Projects\Practice> Get-ChildItem C:\ | Format-Wide

Directory: C:\

[inetpub]                                                          [Intel]

[PerfLogs]                                                         [Program Files]

[Program Files (x86)]                                              [Users]

[Windows]                                                          .rnd

  1. New-Object Cmdlet: The use of objects in powershell helps us to do things that are not built into the Powershell. We can access comobjects using the New-Object Cmdlet. We can use following commands to access the object called as wshShell object:

$wshShell = new-object –comobject “wscript.shell”

The above line will using New-Object Cmdlet create a new instance of wscript.shell and will accolcate to variable $wshShell. Now if we want to invoke an instance of calculator by using run method we can write.


Below screenshot describes what actually happened when we executed the command:

To get the current windows installable directory path we can use the ExpandEnvironmentStrings() method.

PS D:\Projects\Practice> $wshShell.ExpandEnvironmentStrings(“%windir%”)


To get network related information we have to use the “wscript.network” object.

PS D:\Projects\Practice> $wshNetwork = new-object -comobject “wscript.network”

We can get current username logged into system we can use the username property of wscript.network object.

PS D:\Projects\Practice> $wshNetwork.UserName


To get Domain name we can use UserDomain property.

PS D:\Projects\Practice> $wshNetwork.UserDomain


To get Computer name we use ComputerName property.

PS D:\Projects\Practice> $wshNetwork.ComputerName


To display any information in popup we can use popup() method of wscript.shell object

Invoking .Net libraries and code using powershell:

PowerShell  is can invoke static methods and properties from the .Net Framework. Let’s focus on the System.DateTime class. Let’s see the different methods and properties available.

All the static member and properties will be displayed

PS D:\Projects\Practice> [System.DateTime] | gm –static

TypeName: System.DateTime

Name            MemberType Definition

—-            ———- ———-

Compare         Method     static int Compare(datetime t1, datetime t2)

DaysInMonth     Method     static int DaysInMonth(int year, int month)

Equals          Method     static bool Equals(datetime t1, datetime t2), static bool Equals(System.Object objA, System.Object objB)

FromBinary      Method     static datetime FromBinary(long dateData)

FromFileTime    Method     static datetime FromFileTime(long fileTime)

FromFileTimeUtc Method     static datetime FromFileTimeUtc(long fileTime)

FromOADate      Method     static datetime FromOADate(double d)

IsLeapYear      Method     static bool IsLeapYear(int year)

Parse           Method     static datetime Parse(string s), static datetime Parse(string s, System.IFormatProvider provider), stat…

ParseExact      Method     static datetime ParseExact(string s, string format, System.IFormatProvider provider), static datetime P…

ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object objB)

SpecifyKind     Method     static datetime SpecifyKind(datetime value, System.DateTimeKind kind)

TryParse        Method     static bool TryParse(string s, [ref] datetime result), static bool TryParse(string s, System.IFormatPro…

TryParseExact   Method     static bool TryParseExact(string s, string format, System.IFormatProvider provider, System.Globalizatio…

MaxValue        Property   static datetime MaxValue {get;}

MinValue        Property   static datetime MinValue {get;}

Now             Property   datetime Now {get;}

Today           Property   datetime Today {get;}

UtcNow          Property   datetime UtcNow {get;}

Lets try and invoke a static method:

PS D:\Projects\Practice> [System.DateTime]::IsLeapYear(2009)


We can also create .Net objects. Let’s create a date object:

PS D:\Projects\Practice> $d = new-object System.DateTime 2009,11,11

Get the current datetime using the date object.

PS D:\Projects\Practice> $d – [System.DateTime]::now

Days              : -1245

Hours             : -18

Minutes           : -26

Seconds           : -23

Milliseconds      : -650

Ticks             : -1076343836507017

TotalDays         : -1245.76832929053

TotalHours        : -29898.4399029727

TotalMinutes      : -1793906.39417836

TotalSeconds      : -107634383.650702

TotalMilliseconds : -107634383650.702

Lets add some days to the date object.

PS D:\Projects\Practice> $d.AddDays(11)

Saturday, April 20, 2009 18:29:45 PM

Lets now create a powershell script copy and save the below line of code as test.PS1 extension.

Add-Type @”

namespace t1


public class Point


public int x;

public int y;

public Point(int x, int y) {

this.x = x;

this.y = y;


public override string  ToString()


return string.Format(“POINT({0}, {1})”, x,y);


public void Double()

{ x = x*2;

y = y*2;





The command Add-Type is used to declare the type that follows in the C# code. The C# code is a simple Point class. It has a constructor, and overridden ToString method and a Double function.

Switch back to the PowerShell window and change directories to the one that holds the script and invoke the script.

PS D:\Projects\Practice> .\test.ps1

The type is now defined and be freely used. Let’s create a Point.

PS D:\Projects\Practice> $p = New-Object T1.Point 10,10

Let’s check the contents of $p.

PS D:\Projects\Practice> $p | ft –auto

x  y

–  –

10 10

Let’s invoke the Double method.

PS D:\Projects\Practice> $p.Double()

Now lets check whats the value in $p.

PS D:\Projects\Practice> $p.ToString()

POINT(20, 20)

Now lets invoke the method using the wscript.shell popup() method.

PS D:\Projects\Practice> $wshShell.Popup($p.ToString())


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s