Introduction to Windows PowerShell

Introduction to Windows PowerShell

Introduction to Windows PowerShell: Windows PowerShell is a Windows command-line shell designed especially for system administrators. Windows PowerShell includes an interactive prompt and a scripting environment that can be used independently or in combination. Windows PowerShell introduces the concept of a cmdlet (pronounced "command-let"), a simple, single-function command-line tool built into the shell. Windows PowerShell is a command-line interface for Windows computers. A command-line interface (CLI) is a program for telling your computer to do tasks using typed commands. It makes it possible to automate tasks and to do many things with one command.

Windows PowerShell is an evolution of the command line – a combination of a DOS shell and scripting environment. It can help with repetitive tasks; processes acting on many files at once, automating and scheduling tasks, and configuring Windows components and services. PowerShell is not only for running DOS commands, it is far more flexible than that. It supports complex decision making, connecting to a wide variety of data sources, and even building graphical user interfaces.

PowerShell is now an essential skill for IT and server administrators, and is often used when deploying maintenance scripts across an entire organization. It is now an essential requirement / skill for a Systems Administrator. So, let us start learning PowerShell.

Opening PowerShell

Just press Windows Key and type "powershell". It will display number of items with PowerShell.

Opening PowerShell

Like you can see number of Programs, the first option displayed here is 64-bit version. PowerShell ISE is PowerShell Integrated Scripting Environment to create PowerShell scripts.

The programs with x86 are 32-bit versions and exists for backward compatibility.

The PowerShell Console

PowerShell Console

Windows PowerShell System Requirements:

Please refer the following link for the PowerShell System requirements.

https://msdn.microsoft.com/en-us/powershell/scripting/setup/windows-powershell-system-requirements

 

Getting Ready to Use Windows PowerShell

Just open PowerShell window and start typing the commands. If you want to open as Administrator, right click and select Run as administrator.

Opening Powershell thumb

To know the version of PowerShell installed on the system, type Get-Host or $PSVersionTable . This will display the version of PowerShell installed.

get host

Getting Help: Get-Help cmdlet is used to get help. Get-Help is used in combination of other cmdlets.

Example: Get-Help Get-Process

get help

 

Update-Help # Will update the help (may take some time depending the internet connection).
Get-Help Get-Process -Online # Will open an online help in a browser.

Now, let us start with Basics of PowerShell.

Basics of PowerShell

Basics of PowerShell

What is PowerShell?

PowerShell is Microsoft new Command Line Interface for Windows systems, it provides access to:

  • Existing Windows Command Line tools.
  • PowerShell Cmdlets (PowerShell own Commands)
  • PowerShell Functions
  • Access to the .Net Framework API
  • Access to WMI (Windows Management Instrumentation
  • Access to Windows COM (Component Object Model)
  • Access to function in Windows DLL (Dynamic Linked Libraries)
  • Access to different third party APIs like VMWare, Citrix, Microsoft Exchange, Office 365 and many more.

 Checking the PowerShell Version:

Just open the Powershell console and type Get-Host or $PSVersionTable This will display the PowerShell version installed on the system.

Basics of PowerShell 1

Getting Help in PowerShell: We have built in help in PowerShell. We also can update help using PowerShell commands.

Just type Get-Help in the console.

get help 1

Press Y to update.

GET-HELP

The Get-Help cmdlet displays help at the command line from content in help files on your computer. Without help files, Get-Help displays basic help about cmdlets and functions. You can also use Get-Help to display online help for cmdlets and functions.

To get help for a cmdlet, type: Get-Help

UPDATE-HELP

To download and install help files on your computer:
* Start Windows PowerShell with the "Run as administrator" option.
* Type: Update-Help

After the help files are installed, you can use the Get-Help cmdlet to display the help topics. You can also use the Update-Help cmdlet to download updated help files so that your local help files are always up-to-date.

ONLINE HELP

You can find help for Windows PowerShell online in the TechNet Library beginning at http://go.microsoft.com/fwlink/?LinkID=108518.

To open online help for any cmdlet or function, type: Get-Help -Online

Running PowerShell Commands:

To get the list of commands, type Get-Command

get command

Get-Alias

Get-Alias command will display all the cmdlet aliases. Get-Alias will display the cmdlet Name.

PS C:\> Get-Alias gwmi

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           gwmi -> Get-WmiObject


PS C:\> Get-Alias dir

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Alias           dir -> Get-ChildItem

Configuring PowerShell Console:

We can configure PowerShell console as we may want. Changing the colors, changing back ground color, font and other settings. There are many ways of doing this.

One is a graphical way: Just right click on title bar and a settings window will be opened.

Windows PowerShell Properties

Just navigate to different tabs and change the settings as required.

Other way is through PowerShell commands.

Here are some examples:

$console = $host.UI.RawUI
$console.ForegroundColor = "black"
$console.BackgroundColor = "white"
Clear-Host

Working with Data types, PowerShell Variables

Working with PowerShell Data types, PowerShell Variables

Windows PowerShell uses the Microsoft .NET Framework data types. Whenever you use PowerShell, whether it is querying data or making a change to some configuration or existing object, you are working with different types of objects. Everything that you query or work with is an object such as a string or a larger object with multiple properties that may have other nested objects within it.

PowerShell Data types:

  • System.String
  • System.Int32
  • System.Int64
  • System.Double
  • System.Decimal
  • System.Object[]
  • System.Collections.Hashtable

We need not to define the type of variable. PowerShell automatically decides the type of variable. Variables are always specified with the initial character $, and can include any alphanumeric characters or the underscore in their names.

$variable1, $variable2 … Variables are not case sensitive.

Working with Strings:

See the following examples. We are assigning a string to variable $a.

PS C:\> $a = "I am a string"
PS C:\> $a.GetType().FullName
System.String
PowerShell automatically assigned the variable to System.String . Now let us play with strings.
PS C:> $a = "One" 
PS C:> $b = "Two" 
PS C:> $a + $b 
OneTwo 
PS C:> "$a$b" 
OneTwo 
PS C:> $a$b 
At line:1 char:3
 + $a$b
 + ~~
 Unexpected token '$b' in expression or statement.
 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
 + FullyQualifiedErrorId : UnexpectedToken
$a$b has thrown some error. We cannot use like this. If you want to print both the variables, use them in “”.

Now, what will happen if you use single quotes? (‘).  Let us see..

PS C:\> '$a$b'
$a$b

Single quote marks result in literal values being echoed back; double quote marks result in the actual value of a variable being echoed back.

Working with Numbers:

PS C:\> $a = 1234; $a
1234
PS C:\> $a.GetType().FullName
System.Int32
PS C:\> $a = 12345678910; $a
12345678910
PS C:\> $a.GetType().FullName
System.Int64
PS C:\> $a = 1234.5678; $a
1234.5678
PS C:\> $a.GetType().FullName
System.Double
PS C:\> $a=1234.5678d; $a
1234.5678
PS C:\> $a.GetType().FullName
System.Decimal
PS C:\>

Converting Data types:

PS C:\> $a = [double] "1234"
PS C:\> $a.GetType().FullName
System.Double
PS C:\> $a = [decimal] "1234"
PS C:\> $a.GetType().FullName
System.Decimal

Working with Arrays:

A PowerShell array holds a list of data items.

Creating Arrays
To create an Array just separate the elements with commas or using explicit syntax:

PS C:\> $myArray = "Hello","World", "One", 1, 1.5, "Hello World"
PS C:\> $myArray
Hello
World
One
1
1.5
Hello World
PS C:\> $myArray = @("Hello","World", "One", 1, 1.5, "Hello World")
PS C:\> $myArray
Hello
World
One
1
1.5
Hello World

range operator (..):

PS C:\> $myArray = (10..15)
PS C:\> $myArray
10
11
12
13
14
15
PS C:\>

Create an empty array:

$myArray$  = @()

Add values to an Array. This is done using the += operator

$countries += 'India'

Retrieve items from an Array:

PS C:\> $myArray = "Hello","World", "One", 1, 1.5, "Hello World" 
PS C:\> $myArray[0] 
Hello 

PS C:\> $myArray[4] 
1.5 

PS C:\> $myArray[5] 
Hello World

Length of Array:

PS C:\> $myArray.Count
6

Searching array:

PS C:\> $arrColors = "blue", "red", "green", "yellow", "white", "pink", "orange", "turquoise"
PS C:\> $arrColors -contains "black"
False
PS C:\> $arrColors -contains "orange"
True

Working with Hash Tables:

Hash tables are collections that take the System.Collections.Hashtable data type. The primary difference between hash tables and arrays is that hash tables use named keys rather than index numbers to identify values.
Hash Tables are one of the most flexible datatypes supported in PowerShell.
We create a hash table by using the @ symbol followed by a set of braces that enclose the collection of key/value pairs.

PS C:\> $a = @{a="Birds"; b="Animals"; c="Mountains"; d="Oceans"}
PS C:\> $a
 
Name                           Value
----                           -----
c                              Mountains
d                              Oceans
b                              Animals
a                              Birds
 
PS C:\> $a.a
Birds
PS C:\> $a.d
Oceans
PS C:\> $name = @{FirstName = "My FirstName"; LastName = "My LastName";}
PS C:\> $name
 
Name                           Value
----                           -----
LastName                       My LastName
FirstName                      My FirstName
 
PS C:\> $name.FirstName
My FirstName
PS C:\> $name.LastName
My LastName

Operators and expressions – Arithmetic, assignment, comparison, pattern matching logical and bit wise operators

Operators and expressions – Arithmetic, assignment, comparison, pattern matching logical and bit wise operators

PowerShell includes the following comparison operators:

Operator TypeOperatorsDescription
Equality -eq
-ne
-gt
-ge
-lt
-le
equals
not equals
greater than
greater than or equal
less than
less than or equal
Matching -like
-notlike
-match
-notmatch
Returns true when string matches wildcard pattern
Returns true when string does not match wildcard pattern
Returns true when string matches regex pattern – $matches contains matching strings
Returns true when string does not match regex pattern – $matches contains matching strings
Containment -contains
-notcontains
-in
-notin
Returns true when reference value contained in a collection
Returns true when reference value not contained in a collection
Returns true when test value contained in a collection
Returns true when test value not contained in a collection
Replacement -replace replace a string pattern
Type comparison -is
-isnot
Returns true if both object are the same type
Returns true if the objects are not the same type

Examples:

Equality Operators:

PS C:\> 2 -eq 2
True
PS C:\> 2 -eq 3
False
PS C:\> 2 -ne 3
True
PS C:\> 2 -ne 2
False

PowerShell operators are by default not case sensitive.

PS C:> "PowerShell" -eq "PowerShell"
True
PS C:> "PowerShell" -eq "POWERSHELL"
True

If you want to make case sensitive, then we have to use -ceq.

PS C:> "PowerShell" -ceq "POWERSHELL"
False
PS C:> 10 -gt 10
False
PS C:> 10 -gt 11
False
PS C:> 100 -gt 10
True
PS C:> 10 -gt 100
False
PS C:> 10 -ge 10
True
PS C:> 100 -ge 10
True
PS C:> 10 -lt 100
True
PS C:> 100 -lt 10
False
PS C:> 10 -le 100
True
PS C:> 100 -le 10
False
PS C:>

Matching Operators:

PS C:\> "WindowsServer2012" -like "Windows"
False
PS C:\> "WindowsServer2012" -like "Windows*"
True
PS C:\> "WindowsServer2012" -like "*Server2012"
True
PS C:\> "WindowsServer2012" -like "*Server*"
True
PS C:\> "WindowsServer2012" -match "Server"
True
PS C:\> "WindowsServer2012" -match "2012"
True
PS C:\> "WindowsServer2012" -match "Windows"
True
PS C:\> "WindowsServer2012" -cmatch "Windows"
True
PS C:\> "WindowsServer2012" -cmatch "WINDOWS"
False
PS C:\> "WindowsServer2012" -notmatch "WINDOWS"
False
PS C:\> "WindowsServer2012" -cnotmatch "WINDOWS"
True

Containment Operators:

PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False
PS C:\> "Windows", "PowerShell" -Contains "*Shell"
False

Replacement:

PS C:\> $a = "Windows Server 2012"
 
PS C:\> $a -replace "2012","2016"
Windows Server 2016

Type Comparison:

PS C:\> 123 -is [int]
True
 
PS C:\> "Red" -is [string]
True
 
PS C:\> $a = 1,2,3,4,5
PS C:\> $a -is [array]
True

PowerShell Pipeline

PowerShell Pipeline ( | ) :

PowerShell pipeline tells PowerShell that you want to take the output of one command and pass it as the input (or pipe it) to the next command. Here we are passing complete objects. Using the pipe character (|), you can quickly and easily select objects and then perform an action on them.

When you “pipe” objects, PowerShell tries to associate the piped objects with one of the parameters of the receiving cmdlet. In a simple language, piping is sending the objects in the output of one command to another command.

Command-1 | Command-2 | Command-3

Let’s look at an example:

PS C:\> Get-Process
 
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     44       5      708       3164    44     0.03    888 conhost
     57       7     1808       7408    53     4.31   3156 conhost
    179      11     1620       3800    43     1.09    328 csrss
    163      15     1680      10096    46     1.52    396 csrss
    347      32    14420      20024   621     1.47   1336 dfsrs
    102       8     1412       3920    22     0.02   1700 dfssvc
    193      13     3160      10256    48     0.09   2132 dllhost
  10284    7411    89816      88140   141     0.34   1368 dns
    206      19    23368      35332   121     0.42    784 dwm
    927      52    18184      47460   398     1.58   2776 explorer
      0       0        0         24     0               0 Idle
     89      11     1440       4280    26     0.00   1396 ismserv
   1641     156    54608      63672  1177     7.14    492 lsass
    122      14     4092       9532    95     0.45   1616 ManagementAgentHost
   1601      38    35884      43488   576     0.61   1292 Microsoft.ActiveDirectory.WebServices
    151      12     1992       6648    40     0.03   2236 msdtc
    363      24    60784      69856   608     7.17   3148 powershell
    258      10     3312       7504    29     1.78    484 services
     53       2      296       1160     4     0.13    216 smss
    440      28     7196      15560    89     6.52   1260 spoolsv
    542      33     6700      15168   616     0.38     76 svchost
    344      15     3464      10052    46     0.20    644 svchost
    327      16     2684       6612    24     0.55    676 svchost
    363      33    10408      12276    56     0.45    712 svchost
    462      20    10872      14112    59     3.05    856 svchost
   1113      43    15752      29468   124     5.88    892 svchost
    735      24     5760      11568    81     0.27    936 svchost
    227      17     8180      10376   615     0.13   1112 svchost
    711       0      112        344     3     4.30      4 System
    156      11     1500       6032    79     0.03   2864 taskhostex
    148      11     2376       9768   105     0.80   3064 TPAutoConnect
    164      12     2864       8328    70     2.31   1572 TPAutoConnSvc
    162      15     1900       7872    44     0.11    732 vds
    127      11     4356      10640    66     0.06   1508 VGAuthService
     67       6      988       4044    45     0.02    804 vmacthlp
    323      23     8004      17888    87     0.69   1580 vmtoolsd
    196      18     5084      14604   104     2.13   2364 vmtoolsd
     79       8      712       3628    40     0.48    388 wininit
    153       8     1224       9156    54     0.58    440 winlogon
    310      16     8560      15384    69     5.34   2244 WmiPrvSE

The above Get-Process with a pipeline:

PS C:\> Get-Process | Sort-Object ProcessName
 
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
     57       7     1840       7436    53     4.34   3156 conhost
     44       5      708       3164    44     0.03    888 conhost
    163      15     1680      10096    46     1.59    396 csrss
    179      11     1620       3800    43     1.09    328 csrss
    344      32    14412      20028   620     1.47   1336 dfsrs
    102       8     1412       3920    22     0.02   1700 dfssvc
    193      13     3160      10256    48     0.09   2132 dllhost
  10287    7411    89816      88148   141     0.36   1368 dns
    206      19    23368      35332   121     0.42    784 dwm
    927      52    18184      47464   398     1.66   2776 explorer
      0       0        0         24     0               0 Idle
     89      11     1440       4280    26     0.00   1396 ismserv
   1636     156    54564      63636  1177     7.17    492 lsass
    122      14     4092       9532    95     0.45   1616 ManagementAgentHost
   1611      38    35844      43472   575     0.61   1292 Microsoft.ActiveDirectory.WebServices
    151      12     1992       6648    40     0.03   2236 msdtc
    399      24    66824      76924   609     7.36   3148 powershell
    254      10     3260       7480    29     1.78    484 services
     53       2      296       1160     4     0.13    216 smss
    440      28     7196      15560    89     6.61   1260 spoolsv
   1108      43    15700      29440   124     5.91    892 svchost
    457      20    10788      14092    59     3.06    856 svchost
    228      17     8228      10392   615     0.13   1112 svchost
    735      24     5760      11568    81     0.27    936 svchost
    344      14     3412      10036    45     0.20    644 svchost
    542      33     6700      15168   616     0.38     76 svchost
    355      32    10304      12212    55     0.45    712 svchost
    325      16     2676       6600    24     0.55    676 svchost
    711       0      112        344     3     4.30      4 System
    156      11     1500       6032    79     0.03   2864 taskhostex
    148      11     2376       9768   105     0.80   3064 TPAutoConnect
    164      12     2868       8332    70     2.36   1572 TPAutoConnSvc
    162      15     1900       7872    44     0.11    732 vds
    127      11     4356      10640    66     0.06   1508 VGAuthService
     67       6      988       4044    45     0.02    804 vmacthlp
    196      18     5104      14624   104     2.19   2364 vmtoolsd
    323      23     7996      17880    87     0.69   1580 vmtoolsd
     79       8      712       3628    40     0.48    388 wininit
    153       8     1224       9156    54     0.58    440 winlogon
    307      16     7972      14852    69     5.39   2244 WmiPrvSE
PS C:\> Get-Process | Sort-Object CPU -Descending
 
Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    433      24    65412      75544   609     7.41   3148 powershell
   1634     156    54564      63632  1177     7.22    492 lsass
    438      28     7144      15544    89     6.69   1260 spoolsv
   1107      43    15140      29032   124     6.02    892 svchost
    307      16     8176      15080    69     5.41   2244 WmiPrvSE
     57       7     1840       7444    53     4.38   3156 conhost
    711       0      112        344     3     4.31      4 System
    457      20    10788      14092    59     3.09    856 svchost
    164      12     2860       8324    70     2.36   1572 TPAutoConnSvc
    196      18     5140      14632   104     2.33   2364 vmtoolsd
    252      10     3260       7480    29     1.78    484 services
    163      15     1680      10096    46     1.66    396 csrss
    927      52    18184      47464   398     1.66   2776 explorer
    340      32    14412      20020   620     1.47   1336 dfsrs
    179      11     1620       3800    43     1.09    328 csrss
    148      11     2376       9764   105     0.81   3064 TPAutoConnect
    323      23     8000      17884    87     0.73   1580 vmtoolsd
   1631      38    35884      43556   576     0.61   1292 Microsoft.ActiveDirectory.WebServices
    153       8     1224       9156    54     0.58    440 winlogon
    323      16     2668       6588    24     0.55    676 svchost
    206      19    23368      35328   121     0.52    784 dwm
     79       8      712       3628    40     0.48    388 wininit
    353      32    10252      12192    54     0.45    712 svchost
    122      14     4092       9532    95     0.45   1616 ManagementAgentHost
    546      33     6796      15204   617     0.38     76 svchost
  10287    7411    89816      88152   141     0.36   1368 dns
    738      24     5776      11584    81     0.27    936 svchost
    344      14     3412      10036    45     0.20    644 svchost
     53       2      296       1160     4     0.13    216 smss
    228      17     8176      10376   615     0.13   1112 svchost
    162      15     1900       7872    44     0.11    732 vds
    193      13     3160      10256    48     0.09   2132 dllhost
    127      11     4356      10640    66     0.06   1508 VGAuthService
     44       5      708       3164    44     0.03    888 conhost
    151      12     1992       6648    40     0.03   2236 msdtc
    156      11     1500       6032    79     0.03   2864 taskhostex
    102       8     1412       3920    22     0.02   1700 dfssvc
     67       6      988       4044    45     0.02    804 vmacthlp
     89      11     1440       4280    26     0.00   1396 ismserv
      0       0        0         24     0               0 Idle

Multiple pipelines:

PS C:\> Get-Process | Select-Object ProcessName, CPU | Sort-Object CPU -Descending
 
ProcessName                                                                                                         CPU
-----------                                                                                                         ---
powershell                                                                                                     7.609375
lsass                                                                                                           7.40625
spoolsv                                                                                                        6.859375
svchost                                                                                                        6.109375
WmiPrvSE                                                                                                       5.453125
conhost                                                                                                             4.5
System                                                                                                         4.359375
svchost                                                                                                           3.125
TPAutoConnSvc                                                                                                  2.453125
vmtoolsd                                                                                                       2.421875
services                                                                                                        1.78125
csrss                                                                                                          1.734375
explorer                                                                                                         1.6875
dfsrs                                                                                                          1.515625
csrss                                                                                                           1.09375
TPAutoConnect                                                                                                  0.859375
vmtoolsd                                                                                                       0.796875
Microsoft.ActiveDirectory.WebServices                                                                          0.609375
winlogon                                                                                                       0.578125
svchost                                                                                                          0.5625
dwm                                                                                                            0.515625
wininit                                                                                                        0.484375
svchost                                                                                                        0.453125
ManagementAgentHost                                                                                            0.453125
dns                                                                                                               0.375
svchost                                                                                                           0.375
svchost                                                                                                        0.265625
svchost                                                                                                        0.203125
smss                                                                                                              0.125
svchost                                                                                                           0.125
vds                                                                                                            0.109375
dllhost                                                                                                         0.09375
VGAuthService                                                                                                    0.0625
conhost                                                                                                         0.03125
msdtc                                                                                                           0.03125
taskhostex                                                                                                      0.03125
dfssvc                                                                                                         0.015625
vmacthlp                                                                                                       0.015625
ismserv                                                                                                               0

Some more examples:

PS C:\> Get-Service spooler
 
Status   Name               DisplayName
------   ----               -----------
Running  spooler            Print Spooler
 
PS C:\> Get-Service spooler | Restart-Service

The above command will get the service name “spooler” and restart spooler service.

 

Scripting, flow control (if-elseif-else, while loop, do-while loop, for loop, break and continue, switch)

Scripting, flow control (if-elseif-else, while loop, do-while loop, for loop, break and continue, switch)

If ( ) … elseif ( ) … else { }

Syntax:

if ( condition ) { commands_to_execute }

[ elseif ( condition2 ) { commands_to_execute } ]

[ else { commands_to_execute } ]

if(2 -eq 2)
{
    Write-Host "True"
}
else
{
    Write-Host "False"
}

The output of above script will be "True".

if(2 -eq 5)
{
    Write-Host "True"
}
else
{
    Write-Host "False"
}

The above script will print "False".

Example of if-elseif-else :

$os = Get-WmiObject win32_operatingsystem
if ($os.Caption -match "2003")
{
	Write-Host "Windows Server 2003"
}

elseif ($os.Caption -match "2008")
{
	Write-Host "Windows Server 2008"
}

else
{
	Write-Host "Neither Windows 2003 nor Windows 2008"
}

while loop:

Syntax
while (condition) {command_block}

$a = 1

while ($a -lt 6)
{
	Write-Host $a
	$a++
}

1
2
3
4
5

do-while loop:

Syntax:

Do { command_block while (condition)

do
{
    Write-Host $a
    $a++
}
while ($a -le 10)

1
2
3
4
5
6
7
8
9
10

for Loop:

Syntax
for (init; condition; repeat)
{command_block}

for($a=1; $a -le 10; $a++)
{
     Write-Host $a
}

1
2
3
4
5
6
7
8
9
10

break

Break is used to exit a loop immediately.

Break can also be used to stop script execution when it is placed outside a loop or switch statement.

In a For, ForEach, While, Do loop or in a Switch statement you can add a break statement to exit each code block.

Example:

for($i = 1; $i -le 10; $i++)
{
    if($i -eq 5) {break}
    $i;
}

The output of the above code will be as follows:

1
2
3
4

continue

Return to top of a program loop, skip just this iteration of the loop.

for ($i = 1; $i -le 10; $i++)
{
    if ($i -eq 5) { continue }
    $i;
}

The output of the above code will be as follows:

1
2
3
4
6
7
8
9
10

Let us see how we can use continue statement for printing odd numbers from 1 to 10.

for($i = 1; $i -le 10; $i++)
{
    if($i%2 -eq 0) {continue}
    $i;
}

And here is the output:

1
3
5
7
9

switch

switch ($fruit)
{
    "Apple" {echo "Apple is my favorite fruit!"; break}
    "Orange" {echo "Orange is my favorite fruit!"; break}
    "Mango" {echo "Mango is my favorite fruit!"; break}
    default {echo "This is default statement"; break}
}

The put will be as per the value of $fruit. If no value is assigned to $fruit, or not equal to any of the cases, it will print the default.

PowerShell Functions

PowerShell Functions:

PowerShell Functions are extremely useful when working with PowerShell scripts that perform the same tasks repeatedly. You can make your functions as simple or as complex as necessary.

Syntax

The following is the syntax for a function:

function [] [([type]$parameter1[,[type]$parameter2])]
{
param([type]$parameter1 [,[type]$parameter2])
dynamicparam {<statement list>}
begin {<statement list>}
process {<statement list>}
end {<statement list>}
}

Simple Function

function hello { "Hello world!" }

hello

In the above PowerShell code, we are are defining a simple function named hello in first line and calling the function in next line. This function simply prints "Hello world!" to the console.

function testfunction {Get-Process}

testfunction

Syntax is as simple as function <function-name> {statements}

To use the function, type function-name.

function square($a)
{
    return $a*$a;
}

square(20);
square(19);

The above function will display square of any variable passed to the function.

Function Names

Functions names should consist of a verb-noun pair in which the verb identifies the action that the function performs and the noun identifies the item on which the cmdlet performs its action.

Functions with Parameters

You can use parameters with functions, including named parameters, positional parameters, switch parameters, and dynamic parameters.

Named parameters

Microsoft's cmdlets mainly use named parameters.

Example:

function Restart-GivenService($service)
{
    Restart-Service $service
}

$s = "spooler"
Restart-GivenService($s)

Error Handling, exceptions and debugging

One of the key parts of any good PowerShell script is error handling.

PowerShell errors are of two types. Terminating and Non-Terminating Errors.

Terminating Error: A terminating error is an error that will halt a function or operation. A serious error during execution that halts the command (or script execution) completely. If you make a syntax error or run out of memory, that is a terminating error. Terminating errors can be caught and handled.
Examples: non-existent cmdlets, syntax errors that would prevent a cmdlet from running, or other fatal errors.

PS C:\> do-something
do-something : The term 'do-something' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ do-something
+ ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (do-something:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Non-Terminating Error: Non-terminating errors allow Powershell to continue and usually come from cmdlets or other managed situations. A non-serious error that allows execution to continue despite the failure. Under normal circumstances they cannot be caught by Try-Catch-Finally.
Examples: operational errors such file not found, permissions problems, etc.

PS C:\> Get-ChildItem C:\temp\ -Recurse
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/6/2018 11:49 PM folder1
d----- 1/6/2018 11:49 PM folder2
d----- 1/6/2018 11:50 PM folder3
-a---- 1/6/2018 11:49 PM 0 file1.txt
-a---- 1/6/2018 11:50 PM 0 file2.txt
Get-ChildItem : Access to the path 'C:\temp\folder3' is denied.
At line:1 char:1
  + Get-ChildItem C:\temp\ -Recurse
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo : PermissionDenied: (C:\temp\folder3:String) [Get-ChildItem], UnauthorizedAccessException
  + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

We can catch the non-terminating erros by specifying -ErrorAction Stop on the end of a cmdlet. The available options with -ErrorAction are SilentlyContinue, Stop, Continue, Inquire, Ignore, Suspend.

Error Action Preference:

$ErrorActionPreference is a global variable saying how PowerShell will treat non-terminating errors.

The default value of $ErrorActionPreference is "Continue". It is not recommended to use $ErrorActionPreference = "SilentlyContinue" as this will suppress all the errors.

SilentlyContinue – error messages are suppressed and execution continues.
Stop – forces execution to stop, behaving like a terminating error.
Continue – the default option. Errors will display and execution will continue.
Inquire – prompt the user for input to see if we should proceed.
Ignore – (new in v3) – the error is ignored and not logged to the error stream. Has very restricted usage scenarios.

Try-catch-finally:

Catching a Terminating Error:
We use PowerShell try – catch to catch to catch terminating error.

Try {
#Do some stuff
}
Catch {
#Got an error do something else
}

try{
  do-something
}
catch{
  $_.Exception.Message
}

The term 'do-something' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

In the above example, only the error is caught. We can store this value to a variable if required. It failed to execute the given command in try block. So exception is caught.

Working with Files and Folders

PowerShell  – Working with Files and Folders

Creating Folders and Files:

We use the cmdlet New-Item to create a folder or a file. We need to specify the Item type (the FileSystem Windows PowerShell provider distinguishes between directories and files).

The following command creates a new folder in the present working directory.

PS C:\temp> New-Item folder1 -ItemType Directory

Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/7/2018 12:24 AM folder1

We can also create a folder or file directly by giving a path.

PS C:\temp> New-Item c:\temp\folder2 -ItemType Directory

Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/7/2018 12:28 AM folder2

PS C:\Users\Venu> New-Item c:\temp\folder2\textfile.txt -ItemType File

Directory: C:\temp\folder2

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/7/2018 6:48 PM 0 textfile.txt

The above command will create a file textfile.txt in the given path C:\temp\folder2\

Listing all files and folders in a folder:

You can get all items directly within a folder by using Get-ChildItem. By default, Get-ChildItem does not display system files and hidden files. If you want to include those files, add an optional parameter Force. If you want to list files and folders of sub folders as well, add Recurse option.

Get-ChildItem

Get-ChildItem C:\temp\

Get-ChildItem C:\Windows\System32\ -Force -Recurse

Copying Files and Folders:

Copying is done with Copy-Item.

Copy-Item C:\temp\folder2\textfile.txt c:\temp\folder1\

If file is there already in the destination folder, you can use -Force option. This will replace the existing file.

Copy-Item C:\temp\folder2\textfile.txt c:\temp\folder1\ -Force

The following command will copy all content in the folder to new path.

Copy-Item C:\temp C:\temp2 -Recurse -Force

Removing All Files and Folders Within a Folder

You can remove contained items using Remove-Item. It will prompt if there is any content in the folder.

Remove-Item C:\temp2

Remove-Item C:\temp2 -Recurse -Force

Reading Text Files:

Get-Content is used to read the content of a file into an array.

Let is create a text file for testing.

PS C:\temp> New-Item test.txt -ItemType File

Directory: C:\temp

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/7/2018 7:19 PM 0 test.txt

Add some content to the file

PS C:\temp> Add-Content .\test.txt "This is first line"

PS C:\temp> Add-Content .\test.txt "This is second line"

PS C:\temp> Add-Content .\test.txt "third line"

PS C:\temp> Add-Content .\test.txt "fourth line"

PS C:\temp> Add-Content .\test.txt "fifth line"

Now read content of the file using Get-Content

PS C:\temp> Get-Content .\test.txt

This is first line
This is second line
third line
fourth line
fifth line
PS C:\temp>

We can also assign the output to a variable. Result will be stored as an array. If you want to display first line only, try the following:

PS C:\temp> $content = Get-Content .\test.txt
PS C:\temp> $content[0]
This is first line

Regular Expressions

PowerShell – Writing Regular Expressions

A regular expression is a string, written using a special regular expression language, that helps a computer identify strings that are of a particular format—such as an IP address, a UNC, or an e-mail address. A well-written regular expression has the ability to allow a Windows PowerShell script to accept as valid or reject as invalid data that does not conform to the format you've specified.

The Windows PowerShell –match operator compares a string to a regular expression and then returns either True or False depending on whether the string matches the regex.

Here is an example of a simple match

PS C:\> "WinAdmin.org" -match "WIn"
True
PS C:\> "WinAdmin.org" -match "windows"
False

By default, a regex is case-insensitive in PowerShell. But if you want to match case sensitive, you can use -cmatch

PS C:\> "WinAdmin.org" -cmatch "admin"
False
PS C:\> "WinAdmin.org" -cmatch "Admin"
True

Regular Expressions – Wildcards and Repeaters

A regex can contain a few wildcard characters.

. (period) – matches one instance of any character

? (question mark) – matches zero or one instance of any character

* matches zero or more of the specified characters

+ matches one or more of the specified characters.

PS C:\> "hello" -match "h.llo"
True
PS C:\> "hello" -match "h?ello"
True
PS C:\> "hello" -match "h?llo"
True
PS C:\> "hello" -match "h*o"
True
PS C:\> "hello" -match "hel+o"
True

Regular Expressions – Character Classes

  • \w matches any word character, meaning letters and numbers.
  • \s matches any white space character, such as tabs, spaces, and so forth.
  • \d matches any digit character.
PS C:\> "Windows Server" -match "\w"
True
PS C:\> "Windows Server" -match "\w\s\w"
True
PS C:\> "Windows Server" -match "\d"
False
PS C:\> "Windows Server 2016" -match "\d"
True

Regular Expressions – Character Groups, Ranges, and Sizes

A regex can also contain groups or ranges of characters, enclosed in square brackets. For example, [aeiou] means that any one of the included characters—a, e, i, o, or u—is an acceptable match. [a-zA-Z] indicates that any letter in the range a-z or A-Z is acceptable

PS C:\> "Windows" -match "Win[def]ows"
True

Creating a regular expression to check IP.

PS C:\> "192.168.0.1" -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
True
PS C:\> "192.168.0.A" -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
False

 

Parse and scrape a web page

Parse and scrape a web page

Invoke-WebRequest:

The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML elements.

This cmdlet was introduced in Windows PowerShell 3.0.

Invoke-WebRequest show you formatted output of various properties of the corresponding web request. Like most cmdlets, Invoke-WebRequest returns an object.

Example:

PS C:\> $WebResponse = Invoke-WebRequest "http://winadmin.org"
PS C:\> $WebResponse

Parseandscr1

As the result is an object, we can see various object properties from the output.

If you want to see only the content of web page, use $webResponse.Content

Get links from a web page: $webResponse.Links.href

080920 1557 Parseandscr2

GetImages from a web page: $webResponse.Images.src

PS C:\> $webResponse.Images.src
http://winadmin.org/wp-content/uploads/2014/10/logo.png
http://0.gravatar.com/avatar/9c8fef70f5b6853e3152a593e8243d2d?s=20&amp;d=mm&amp;r=g
http://winadmin.org/wp-content/uploads/2017/05/050117_1757_BasicsofPow1.png
http://winadmin.org/wp-content/uploads/2017/05/050117_1757_BasicsofPow2.png
http://winadmin.org/wp-content/uploads/2017/05/050117_1757_BasicsofPow3.png
http://0.gravatar.com/avatar/9c8fef70f5b6853e3152a593e8243d2d?s=20&amp;d=mm&amp;r=g
http://winadmin.org/wp-content/uploads/2017/03/031617_1825_Installinga1.png
http://winadmin.org/wp-content/uploads/2017/03/031617_1825_Installinga2.png
http://winadmin.org/wp-content/uploads/2017/03/031617_1825_Installinga3.png
http://winadmin.org/wp-content/uploads/2017/03/031617_1825_Installinga4.png
http://0.gravatar.com/avatar/9c8fef70f5b6853e3152a593e8243d2d?s=20&amp;d=mm&amp;r=g
http://winadmin.org/wp-content/uploads/image/2017-03/Opening%20Powershell.png
http://winadmin.org/wp-content/uploads/2017/03/031617_1737_ThePowerShe1.png
http://winadmin.org/wp-content/uploads/image/2017-03/adding%20windows%20powershell%20ISE%20feature.GIF
https://winadmin.org/wp-content/uploads/2017/05/Opening-Powershell_thumb.png
https://winadmin.org/wp-content/uploads/2017/05/image_thumb.png
https://winadmin.org/wp-content/uploads/2017/05/image_thumb-1.png
http://0.gravatar.com/avatar/9c8fef70f5b6853e3152a593e8243d2d?s=20&amp;d=mm&amp;r=g
http://winadmin.org/wp-content/uploads/2017/01/011117_0945_VPShellResd1.png
http://0.gravatar.com/avatar/9c8fef70f5b6853e3152a593e8243d2d?s=20&amp;d=mm&amp;r=g
http://winadmin.org/wp-content/uploads/image/2016-01/disk%20cleanup.png
http://winadmin.org/wp-content/uploads/image/2016-01/disk%20cleanup1.png
http://winadmin.org/wp-content/uploads/image/2016-01/disk%20cleanup2.png
http://winadmin.org/wp-content/uploads/image/2016-01/disk%20cleanup3.png
http://winadmin.org/wp-content/uploads/image/2016-01/disk%20cleanup4.png
http://winadmin.org/wp-content/uploads/2016/01/013116_0637_DeleteWindo7.png
PS C:\>

Getting Forms from a webpage:

PS C:\> $webResponse.Forms


Id Method Action Fields
-- ------ ------ ------
searchform get http://winadmin.org/ {[s, ]}

We can even submit the web forms using PowerShell and can use to login.

 

Reading XML with PowerShell

Reading XML with PowerShell

We can read XML files using PowerShell. For example, we have the following content in foods.xml file

<foods>
   <food>
       <name>Belgian Waffles</name>
       <price>$5.95</price>
       <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
       <calories>650</calories>
   </food>


   <food>
     <name>Strawberry Belgian Waffles</name>
     <price>$7.95</price>
     <description>Light Belgian waffles covered with strawberries and whipped cream</description>
     <calories>900</calories>
   </food>


  <food>
     <name>Berry-Berry Belgian Waffles</name>
     <price>$8.95</price>
     <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
     <calories>900</calories>
   </food>


  <food>
     <name>French Toast</name>
     <price>$4.50</price>
     <description>Thick slices made from our homemade sourdough bread</description>
     <calories>600</calories>
   </food>


  <food>
     <name>Homestyle Breakfast</name>
     <price>$6.95</price>
     <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
     <calories>950</calories>
   </food>
</foods>

Read the xml document

PS C:\> [xml]$XmlDocument = Get-Content .\foods.xml
PS C:\> $XmlDocument

foods
-----
foods


PS C:\> $XmlDocument.foods

food
----
{Belgian Waffles, Strawberry Belgian Waffles, Berry-Berry Belgian Waffles, French Toast...}

PS C:\> $XmlDocument.foods.food

name                        price description                                                                         calories
----                        ----- -----------                                                                         --------
Belgian Waffles             $5.95 Two of our famous Belgian Waffles with plenty of real maple syrup                   650
Strawberry Belgian Waffles  $7.95 Light Belgian waffles covered with strawberries and whipped cream                   900
Berry-Berry Belgian Waffles $8.95 Light Belgian waffles covered with an assortment of fresh berries and whipped cream 900
French Toast                $4.50 Thick slices made from our homemade sourdough bread                                 600
Homestyle Breakfast         $6.95 Two eggs, bacon or sausage, toast, and our ever-popular hash browns                 950

PS C:\> $XmlDocument.foods.food.name
Belgian Waffles
Strawberry Belgian Waffles
Berry-Berry Belgian Waffles
French Toast
Homestyle Breakfast

We can also use to directly read the values using Select-Xml cmdlet.

PS C:\> $path = "foods.xml"
PS C:\> $xpath = "/foods/food"
PS C:\> Select-Xml -Path $path -XPath $xpath | Select-Object -ExpandProperty Node

name                        price description                                                                         calories
----                        ----- -----------                                                                         --------
Belgian Waffles             $5.95 Two of our famous Belgian Waffles with plenty of real maple syrup                   650
Strawberry Belgian Waffles  $7.95 Light Belgian waffles covered with strawberries and whipped cream                   900
Berry-Berry Belgian Waffles $8.95 Light Belgian waffles covered with an assortment of fresh berries and whipped cream 900
French Toast                $4.50 Thick slices made from our homemade sourdough bread                                 600
Homestyle Breakfast         $6.95 Two eggs, bacon or sausage, toast, and our ever-popular hash browns                 950

 

Working with WMI (Windows Management Instrumentation)

Working with WMI (Windows Management Instrumentation)

One of the most useful jobs for PowerShell is to create a bank of WMI based scripts. Furthermore, scripting WMI with PowerShell is much easier and more efficient than WMI with VBScript.

What is WMI?

WMI is the Microsoft implementation of Web-Based Enterprise Management (WBEM), with some enhancements in the initial version of it, WBEM is a industry initiative to develop a standard technology for accessing management information in an enterprise environment that covers not only Windows but also many other types of devices like routers, switches, storage arrays …etc. WMI uses the Common Information Model (CIM) industry standard to represent systems, applications, networks, devices, and other managed components. CIM is developed and maintained by the Distributed Management Task Force (DMTF).

To list out all the available WMI Objects available, execute the following command.

Get-WmiObject -List

Wow, there are many WMI Objects available.

Let us see some examples on what we can do with PowerShell and WMI.

Get-WmiObject win32_computersystem — gives the details of the local computer system

PS C:\> Get-WmiObject win32_computersystem


Domain : winadmin.org
Manufacturer : VMware, Inc.
Model : VMware Virtual Platform
Name : DC01
PrimaryOwnerName : Windows User
TotalPhysicalMemory : 2146877440

If you want to query a remote system, then use Get-WmiObject win32_computersystem -ComputerName vc01

PS C:\> Get-WmiObject win32_computersystem -ComputerName vc01


Domain : winadmin.org
Manufacturer : VMware, Inc.
Model : VMware Virtual Platform
Name : VC01
PrimaryOwnerName : Windows User
TotalPhysicalMemory : 8589328384

If we are not providing any credentials, then PowerShell will use the logged in user's credentials. If the logged in user does not have access to target computersystem, you will receive an error that access is denied.

we need to use the command as follows:
Get-WmiObject win32_computersystem -ComputerName vc01 -Credential winadmin\wintel

This will prompt for a password.

Let us see some more examples.

PS C:\> Get-WmiObject win32_operatingsystem


SystemDirectory : C:\Windows\system32
Organization    :
BuildNumber     : 9600
RegisteredUser  : Windows User
SerialNumber    : 00330-52470-32472-AAOEM
Version         : 10.0.19041
PS C:\> Get-WmiObject win32_operatingsystem | select Caption, CSDVersion

Caption                                   CSDVersion
-------                                   ----------
Microsoft Windows Server 2012 R2 Standard

Here, CSDVersion is Service Pack

PS C:\> Get-WmiObject win32_bios

SMBIOSBIOSVersion : 6.00
Manufacturer      : Phoenix Technologies LTD
Name              : PhoenixBIOS 4.0 Release 6.0
SerialNumber      : VMware-56 4d 65 8a 54 68 57 32-85 4e 79 44 7c 0c f8 ca
Version           : INTEL - 6040000
PS C:\> Get-WmiObject win32_logicaldisk


DeviceID     : C:
DriveType    : 3
ProviderName :
FreeSpace    : 52686172160
Size         : 64055406592
VolumeName   :

DeviceID     : D:
DriveType    : 5
ProviderName :
FreeSpace    : 0
Size         : 4477562880
VolumeName   : IR2_SSS_X64FREV_EN-US_DV5

Get-WmiObject win32_process : Displays all the processes running on local machine.

PS C:\> Get-WmiObject win32_process | select Name

Name
----
System Idle Process
System
smss.exe
csrss.exe
wininit.exe
csrss.exe
winlogon.exe
services.exe
lsass.exe
svchost.exe
svchost.exe
dwm.exe
vmacthlp.exe
svchost.exe
svchost.exe
svchost.exe
svchost.exe
svchost.exe
spoolsv.exe
Microsoft.ActiveDirectory.WebServices.exe
dfsrs.exe
dns.exe
ismserv.exe
VGAuthService.exe
vmtoolsd.exe
dfssvc.exe
WmiPrvSE.exe
svchost.exe
vds.exe
dllhost.exe
msdtc.exe
taskhostex.exe
explorer.exe
vmtoolsd.exe
powershell.exe
conhost.exe
powershell.exe
conhost.exe
WmiPrvSE.exe
WmiApSrv.exe

Get-WmiObject win32_service : Displays all the services available on local machine. (You can also use Get-Service also).

So it is up to you what to use and how to use. Try to remember as many keywords as possible. There are many accounts I worked where there was no internet access.  ..

Managing Registry with PowerShell

Managing Registry with PowerShell

Managing registry with PowerShell: Registry keys are items on Windows PowerShell drives, working with them is very similar to working with files and folders. Registry entries are properties of keys and, as such, cannot be directly browsed, we need to take a slightly different approach when working with them.

Playing with Windows Registry is dangerous and sometimes may cause system damage. Only proceed if you know what you are doing. First try on test servers with proper registry backup.

Get list of available providers: Get-PSDrive

PS C:\> Get-PSDrive

Name           Used (GB)     Free (GB) Provider      Root                                               CurrentLocation
----           ---------     --------- --------      ----                                               ---------------
Alias                                  Alias
C                 239.38        713.88 FileSystem    C:\
Cert                                   Certificate   \
Env                                    Environment
Function                               Function
HKCU                                   Registry      HKEY_CURRENT_USER
HKLM                                   Registry      HKEY_LOCAL_MACHINE
Variable                               Variable
WSMan                                  WSMan

Listing All Subkeys of a Registry Key:

PS C:\> Get-ChildItem -Path hkcu:\ | Select-Object Name

Name
----
HKEY_CURRENT_USER\AppEvents
HKEY_CURRENT_USER\Console
HKEY_CURRENT_USER\Control Panel
HKEY_CURRENT_USER\Environment
HKEY_CURRENT_USER\EUDC
HKEY_CURRENT_USER\Keyboard Layout
HKEY_CURRENT_USER\Network
HKEY_CURRENT_USER\Printers
HKEY_CURRENT_USER\SOFTWARE
HKEY_CURRENT_USER\System
HKEY_CURRENT_USER\Uninstall
HKEY_CURRENT_USER\Volatile Environment

If you use Get-ChildItem -Path hkcu:\ , this will display Name and Property.

The following command will copy all Keys and properties in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion1

PS C:\> Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion1'

PS C:\>

Managing Registry with PowerShell 1

Creating Keys

Creating new keys in the registry is simpler than creating a new item in a file system. Because all registry keys are containers, you do not need to specify the item type; you simply supply an explicit path, such as:

PS C:\> New-Item -Path hkcu:\NewItem_DeleteMe

Hive: HKEY_CURRENT_USER

Name             Property
----             --------
NewItem_DeleteMe

Managing Registry with PowerShell 2

Deleting Keys

Deleting items is essentially the same for all providers. The following commands will silently remove items:
Delete-Item -Path hkcu:\NewItem_DeleteMe

PS C:\> Remove-Item -Path hkcu:\NewItem_DeleteMe
PS C:\>

PowerShell Remote Sessions and Invoke-Command

PowerShell Remote Sessions:

PowerShell Remote Sessions and Invoke-Command: PowerShell Remoting lets you run PowerShell commands or access full PowerShell sessions on remote Windows systems. It's similar to SSH for accessing remote terminals on other operating systems.

Enable PowerShell Remoting

Enable PowerShell Remoting on the PC You Want to Access Remotely
Your first step is to enable PowerShell Remoting on the PC to which you want to make remote connections. There are several methods to do this.

On that PC, you'll need to open PowerShell with administrative privileges.
Enable-PSRemoting -Force

PS C:\> Enable-PSRemoting -Force

WinRM has been updated to receive requests.
WinRM service started.

WinRM has been updated for remote management.
Enabled remote access.​

winrm quickconfig

PS C:\> winrm quickconfig
WinRM is not set up to receive requests on this machine.
The following changes must be made:

Start the WinRM service.
Make these changes [y/n]? y
WinRM has been updated to receive requests.
WinRM service started.
WinRM is already set up for remote management on this computer.

PS C:\>​

Using server manager – GUI

Enabling Remote Management

Configure TrustedHosts:

Next, you need to configure the TrustedHosts setting on both the PC to which you want to connect and the PC (or PCs) you want to connect from, so the computers will trust each other. You can do this in one of two ways.

PS C:\Windows\system32> get-Item wsman:\localhost\client\trustedhosts


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts

There are no Trustedhosts defined here. If the target server is in the same domain, there is no need to cinfigure trustedhosts. It will be trusted automatically.

To add trusted hosts, use the command Set-Item wsman:\localhost\client\trustedhosts *

PS C:\Windows\system32> Set-Item wsman:\localhost\client\trustedhosts *

WinRM Security Configuration.
This command modifies the TrustedHosts list for the WinRM client. The computers in the TrustedHosts list might not be authenticated. The client might send credential information to these computers. Are you sure that you want to modify this list?
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): Y
PS C:\Windows\system32> get-Item wsman:\localhost\client\trustedhosts


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts                                   *


PS C:\Windows\system32>

Now, once the configuration is completed successfully, restart WinRM service.

Restart-Service WinRM

Now you should be able to connect to the remote server.

PS C:\> Enter-PSSession -ComputerName vc01

[vc01]: PS C:\Users\wintel\Documents> hostname
vc01
[vc01]: PS C:\Users\wintel\Documents>

If you anticipate making multiple connections to a remote system, use the New-PSSession cmdlet to create a remote Windows PowerShell session. New-PSSession permits you to store the remote session in a variable, and it provides you with the ability to enter and leave the remote session as often as required, without the additional overhead of creating and destroying remote sessions.

 
PS C:\> $s = New-PSSession -ComputerName vc01
PS C:\> Invoke-Command -Session $s -ScriptBlock {hostname}
vc01
PS C:\> Invoke-Command -Session $s -ScriptBlock {hostname; Get-WmiObject win32_computersystem;}
vc01

Domain              : winadmin.org
Manufacturer        : VMware, Inc.
Model               : VMware Virtual Platform
Name                : VC01
PrimaryOwnerName    : Windows User
TotalPhysicalMemory : 8589328384
PSComputerName      : vc01

If the server is a non-domain server or other domain server, you should specify the Credentials.

PS C:\> $cred = Get-Credential
PS C:\> $s = New-PSSession -ComputerName vc01 -Credential $cred
PS C:\> Invoke-Command -Session $s -ScriptBlock {hostname; Get-WmiObject win32_computersystem;}
vc01

Domain              : winadmin.org
Manufacturer        : VMware, Inc.
Model               : VMware Virtual Platform
Name                : VC01
PrimaryOwnerName    : Windows User
TotalPhysicalMemory : 8589328384
PSComputerName      : vc01

GUI Forms PowerShell

GUI Forms PowerShell

Windows PowerShell also supports building of Graphical User Interface (Forms). Many of the GUI administration tools available are scripted in PowerShell. There are many commercial and free tools available in the market, but let us see how to build a GUI form with PowerShell scripting.

Let us build a simple form now.

There are only three things required to launch a form from PowerShell:

  1. Load the System.Windows.Forms assembly;
  2. Create a new object of type system.windows.forms.form
  3. Call the ShowDialog() method on your new object.
Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.ShowDialog()

Save the above code and run the code. You can see a GUI Form like the following:

PowerShell GUI Forms

Let us add some more features to our form.

$Form.Height = 500
$Form.Width = 500

the above code will change the size of our form to 500 x 500.

$Form.BackColor = "Red" ## this will change the background color of the form to Red.

Now, let us add some more controls to our form.

PowerShell GUI Forms

Let is add some more functionality to our form.

Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.Height = 200
$Form.Width = 400
$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = "Click the button to get OS details"
$Label1.AutoSize = $true
$Label1.width = 25
$Label1.height = 10
$Label1.location = New-Object System.Drawing.Point(20,40)
$Label1.Font = 'Microsoft Sans Serif,10'
$TextBox1 = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline = $false
$TextBox1.width = 300
$TextBox1.height = 20
$TextBox1.location = New-Object System.Drawing.Point(20,80)
$TextBox1.Font = 'Microsoft Sans Serif,10'
$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "Click me!"
$Button1.width = 80
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(257,34)
$Button1.Font = 'Microsoft Sans Serif,10'
$Form.controls.AddRange(@($Label1,$TextBox1,$Button1))
$Button1.Add_Click({ $TextBox1.Text = (Get-WmiObject win32_operatingsystem).Caption; })
$Form.ShowDialog()

Save and run the code with PowerShell. On clicking the button, the textbox field will be updated with the Operating System Name of the current machine

080920 1604 GUIFormsPow3

Let is break down the code:

Create the form:

Add-Type -AssemblyName System.Windows.Forms  ## adding the assembly
$Form = New-Object system.Windows.Forms.Form  ## we are defining the form here
$Form.Height = 200  ## Form heoght
$Form.Width = 400  ## Form width

Create Label control:

$Label1 = New-Object system.Windows.Forms.Label  ## Create Label
$Label1.text = "Click the button to get OS details"  ## Label text that will be displayed
$Label1.width = 25  ## Label width
$Label1.height = 10  ## Label height
$Label1.location = New-Object System.Drawing.Point(20,40)  ## Label Position

Create TextBox Control:

$TextBox1 = New-Object system.Windows.Forms.TextBox  ## Create TextBox
$TextBox1.multiline = $false  ## restricting the text to a single line. make this $true if you want to maek a multiline textbox and define number of lines.
$TextBox1.width = 300   ## width
$TextBox1.height = 20  ## height
$TextBox1.location = New-Object System.Drawing.Point(20,80)  ## position

Create Button Control:

$Button1 = New-Object system.Windows.Forms.Button  ## create Button control
$Button1.text = "Click me!"  ## Button Text that will be displayed
$Button1.width = 80  ## Button width
$Button1.height = 30  ## Button height
$Button1.location = New-Object System.Drawing.Point(257,34)   ## Button Position

Add Controls to the Form:

$Form.controls.AddRange(@($Label1,$TextBox1,$Button1))  ## this line will add the controls created in previous steps.

Add Button Click action:

$Button1.Add_Click({ $TextBox1.Text = (Get-WmiObject win32_operatingsystem).Caption; })

Show the Form:

$Form.ShowDialog()

Here are some of the GUI designer tools that you can try. I will add more in the future. You can try the following tools for building GUI utilities.

POSHGUI

Sapian PowerShell Studio

Configure WinRM for HTTPS

Configure WinRM for HTTPS manually

Configuring for HTTPS involves following steps.

    • Check whether WinRM service is running
    • Create HTTPS listener
    • Add firewall exception
    • Validate HTTPS listener

Check whether WinRM service is running

Get-Service WiRM

PS C:\Users\wintel> Get-Service WinRM

Status  Name  DisplayName
------  ----  -----------
Running WinRM Windows Remote Management (WS-Manag...​

If the WinRM service is not running, you might need to configure WinRM using winrm quickconfig. When you configure winrm first time, it is configured to use 5985 by default.

check already registered listeners by running following command

PS C:\Users\Administrator> WinRM e winrm/config/listener
Listener
Address = *
Transport = HTTP
Port = 5985
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
ListeningOn = 127.0.0.1, 172.20.20.1, ::1, fe80::5efe:172.20.20.1%15, fe80::d071:b058:c541:a212%12

Create HTTPS listener

To create a HTTPS listener, you need to have a certificate.

Generate SSL Certificate with one of these options

winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="<YOUR_DNS_NAME>"; CertificateThumbprint="<COPIED_CERTIFICATE_THUMBPRINT>"}

C:\>winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="vc01.winadmin.org";CertificateThumbprint="9a20b7dab60933e3ce2ba6fddc02025dcdb83558"}

ResourceCreated
Address = http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous
ReferenceParameters
ResourceURI = http://schemas.microsoft.com/wbem/wsman/1/config/listener
SelectorSet
Selector: Address = *, Transport = HTTPS​

Add firewall exception

You can use command and GUI tool to configure firewall exception.

Via command

# Add a new firewall rule

netsh advfirewall firewall add rule name="Windows Remote Management (HTTPS-In)" dir=in action=allow protocol=TCP localport=5986

Using Windows Firewall with Advanced Security GUI tool.

Open Windows Firewall with Advanced Security and click New Rule.
Configuring WinRM 1

Select Port
Configuring WinRM 2

Specific local ports – Enter 5986
Configuring WinRM 3

Select Allow the connection
Configuring WinRM 4

Select the options whatever is required
Configuring WinRM 5

And give a name and click Finish
Configuring WinRM 6

Now check the WinRM Listener. The output should be as follows.

C:\>WinRM e winrm/config/listener

Listener
  Address = *
  Transport = HTTP
  Port = 5985
  Hostname
  Enabled = true
  URLPrefix = wsman
  CertificateThumbprint
  ListeningOn = 127.0.0.1, 172.20.20.2, 192.168.20.2, ::1, fe80::5efe:172.20.20.2%17, fe80::5efe:192.168.20.2%16, fe80::1c21:cbdc:66d9:967%12, fe80::4d34:b19b:402c:ae3a%13
Listener
  Address = *
  Transport = HTTPS
  Port = 5986
  Hostname = vc01.winadmin.org
  Enabled = true
  URLPrefix = wsman
  CertificateThumbprint = 9a20b7dab60933e3ce2ba6fddc02025dcdb83558
  ListeningOn = 127.0.0.1, 172.20.20.2, 192.168.20.2, ::1, fe80::5efe:172.20.20.2%17, fe80::5efe:192.168.20.2%16, fe80::1c21:cbdc:66d9:967%12, fe80::4d34:b19b:402c:ae3a%13

Verify you can connect to the machine via HTTPS

PS C:\Users\Administrator> Enter-PSSession -Cn vc01.winadmin.org -UseSSL
[vc01.winadmin.org]: PS C:\Users\wintel\Documents>

If you give only host name, it will give errors and will not connect.

PS C:\Users\Administrator> Enter-PSSession -Cn vc01 -UseSSL

Enter-PSSession : Connecting to remote server vc01 failed with the following error message : The server certificate onthe destination computer (vc01:5986) has the following errors:
The SSL certificate contains a common name (CN) that does not match the hostname. For more information, see theabout_Remote_Troubleshooting Help topic.
At line:1 char:1
  + Enter-PSSession -Cn vc01 -UseSSL
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo : InvalidArgument: (vc01:String) [Enter-PSSession], PSRemotingTransportException
  + FullyQualifiedErrorId : CreateRemoteRunspaceFailed​