Windows Powershell Tutorial

Written by Sathish | Dec 8, 2020 10:19:41 AM

Introduction of powershell

  • Developed by Microsoft
  • Based on Net Framework
  • It includes Scripting.
  • Capability to interact with another Windows based Software's, for instances:-

       Citrix, SQL, AD, any open APIs like Slack etc.

   Designed by   Jeffrey Snover, Bruce Payette, James Truher (et al.)
   Developer   Microsoft
   First appeared   November 14, 2006
   Stable release   5.1.14393 / August 2, 2016; 8 months ago
   Preview release   6.0.0 Alpha 17 / March 8, 2017; 35 days ago
   Typing discipline   Strong, safe, implicit and dynamic
   Platform   .NET Framework, .NET Core
   OS   Windows 7 and later, macOS, CentOS, Ubuntu
   Filename extensions
  • •.ps1 (Script)
  • •.ps1xml (XML Document)
  • •.psc1 (Console File)
  • •.psd1 (Data File)
  • •.psm1 (Script Module)
  • •.pssc (Session Configuration File)
  • •.cdxml (Cmdlet Definition XML Document)

 

Need of Powershell

Microsoft describes PowerShell as “a task-based command-line shell and scripting language… built on the NET Framework.”  What is so great about PowerShell?  Why should you use it?

  • PowerShell is both a command-line shell and scripting language
  • PowerShell can interact with a dizzying number of technologies.
  • .NET Framework, the Registry, COM, WMI, ADSI.  Exchange, Share point, Systems Center, Hyper-V, SQL.  VM ware v Center, Cisco UCS, Citrix Xen App and Xen Desktop.  REST APIs, XML, CSV, JSON, websites, Excel and other Office applications.  C# and other languages, DLL s and other binaries, including *nix tools.
  • PowerShell is object-based.This gives us incredible flexibility.  Filter, sort, measure, group, compare or take other actions on objects as they pass through the pipeline.  Work with properties and methods rather than raw text.
  • Microsoft is putting its full weight behind PowerShell. PowerShell isn’t going away.  It is a requirement in the Microsoft Common Engineering Criteria, and a Server product cannot be shipped without a PowerShell interface.
  • In many cases, Microsoft is building their GUI with the help of Powershell only. Here we can perform more than what we think on GUI.
  • PowerShell also provides a hosting API with which the PowerShell runtime can be embedded inside other applications.

BackGround of Powershell

  • In 1998, MS launched C script.  exe to allow compatible scripting languages like J script and VB Script.
  • By 2002 Microsoft had started to develop a new approach to command line management, including a shell called Monad (also known as Microsoft Shell or MSH)
  • PowerShell version 1 was released on September 26, 2006 , but officially released on Nov 14, 2006.
  • PowerShell v 2.0 was completed and released to manufacturing in August 2009, as an integral part of Windows 7 and Windows Server 2008 R2
  • On 18 August 2016, Microsoft announced that they had made PowerShell open-source and cross-platform with support for Windows, OS X, Cent OS and Ubuntu.
  • The move to open source created a second incarnation of PowerShell called “PowerShell Core”, which runs on .NET Core. It is distinct from “Windows PowerShell”, which runs on the full .NET Framework. Starting with version 5.1, PowerShell Core is bundled with Windows Server 2016 Nano Server.

Tools

Why its Better Than Alternatives ?

  • Powershell is better than its legacy alternatives like :-
  • VB Scripting, Bash
  • Consistent syntax, consistent command structure
  • Future-proof through .NET integration
  • Support through help and documentation (Get-Help)
  • Easy to find out any way, just clue is required. (Get-Command “*Service*” )

Top Most Administrative Powershell Commands


Powershell Commands Top Most Used

1. Navigate the Windows Registry like the file system: cd hkcu:
2. Search recursively for a certain string within files: dir –r | select string “search for this”
3. Find the five processes using the most memory: ps | sort –p ws | select –last 5
4. Cycle a service (stop, and then restart it) like DHCP: Restart-Service DHCP
5. List all items within a folder: Get-Child Item – Force
6. Re curse over a series of directories or folders: Get-Child Item –Force c:\directory –Recurse
7. Remove all files within a directory without being prompted for each: Remove-Item C:\to be deleted –Recurse
8. Restart the current computer: (Get-Wmi Object -Class Win 32_Operating System -Computer Name .).Win32 Shutdown(2)
9. Get information about the make and model of a computer: Get Wmi Object -Class Win 32_Computer System
10. Get information about the BIOS of the current computer: Get-Wmi Object -Class Win 32_BIOS -Computer Name .
11. List installed hot fixes — QFEs, or Windows Update files: Get-Wmi Object -Class Win 32_Quick Fix Engineering -      Computer  Name .
12. Get the username of the person currently logged on to a computer: Get-Wmi Object -Class Win  32_ Computer System -Property User Name -Computer Name .
13. Find just the names of installed applications on the current computer: Get-Wmi Object -Class Win 32_ Product -Computer Name . | Format-Wide -Column 1
14. Get IP addresses assigned to the current computer: Get-Wmi Object -Class Win32_Network Adapter Configuration -Filter IP Enabled=TRUE -Computer Name . | Format-Table -Property IP Address
15. Get a more detailed IP configuration report for the current machine: Get-Wmi Object -Class Win 32_ Network Adapter Configuration -Filter IP Enabled=TRUE -Computer Name . | Select-Object -Property [a-z]* -Exclude Property IPX*,WINS*
16. Find network cards with DHCP enabled on the current computer: Get-Wmi Object -Class Win32_Network Adapter Configuration -Filter “DHCP Enabled=true” -Computer Name .
17. Enable DHCP on all network adapters on the current computer: Get-Wmi Object -Class Win32_Network Adapter Configuration -Filter IP Enabled=true -Computer Name . | For Each-Object -Process {$_.Enable DHCP()}
18. Install an MSI package on a remote computer:
(Get-WMI Object -Computer Name TARGET MACHINE -List | Where-Object -Filter Script {$_.Name -eq “Win 32_ Product”}).Install(\\MACHINEWHEREMSIRESIDES\path\package. msi)
19. Upgrade an installed application with an MSI-based application upgrade package:
(Get-Wmi Object -Class Win 32_Product -Computer Name . -Filter “Name=’name_of_app_to_be_upgraded'”).Upgrade(\\MACHINEWHEREMSIRESIDES\path\upgrade_package.msi)
20. Remove an MSI package from the current computer:
(Get-WMI Object -Class Win 32_Product -Filter “Name=’product_to_remove'” -Computer Name . ).Uninstall()
21. Remotely shut down another machine after one minute:
Start-Sleep 60; Restart-Computer –Force –Computer Name TARGET MACHINE
22. Add a printer:
(New-Object -Com Object W Script. Network).Add Windows Printer Connection(“\\printer server\hplaser3”)
23. Remove a printer:
(New-Object -Com Object W Script. Network).Remove Printer Connection(“\\printer server\hplaser3 “)
24. Enter into a remote Power Shell session— you must have remote management enabled:
enter-possession TARGET MACHINE
25. Use the PowerShell invoke command to run a script on a remote servers: invoke-command -computer name machine 1, machine 2 -file path c:\Script\script.ps1

Powershell Commands : Multiple Ways to perform One Task

Shutdown a computer

Stop-Computer “Computer Name 1, Name 2”

Stop-Computer –computer DC1 –Credential new traders\administrator
Shutdown –i (to restart/shutdown bulk of computer in one shot with message)
Restart-Computer “Computer Name 1”
Get-wmi object –class WIN 32_Operating System –Computer Name .).Invoke method(“Win 32 Shutdown”,0)
Or
(gwmi Win 32_Operating System).Win 32 Shutdown(0).

1.Log Off   “0”

2.Forced Log Off   “4”

3.Shutdown “1”

4.Forced Shutdown “5”

5.Reboot  “2”

6.ForcedReboot  “6”

7.Power Off  “8”

8.Forced Power Off  “12”

Concept of pipeline

Pipe-lining could almost be described as PowerShell’s signature tune.

Piping work almost everywhere in Powershell
PowerShell does not pipe text between commands. Instead, it pipes objects.
Piping is used for several purposes like:- got a focused result, use output of previous command to further within same line, filtering.
PowerShell encourages you to join two statements so that the output of the first clause, becomes the input of the second clause.
Example :- Get-Process

SELECTING

Select or Select-Object

Get-process | Select ID,Process Name


SORTING

Sort-Object
 
 

 

MEASURING

Measure-Object / Count

 
 

EXPORTING/ CONVERTING

Export-csv/

Get-child item > c:\test1. txt

Get-child item | Out-File c:\test2. txt

Convert To-Html

Convert To-Secure String :- Convert any string into Encrypted form

-As Secure String :- Take input from user in secure way

$var = Read-Host -As Secure String

$var1 = Convert To-Secure String -Secure String $var

FILTERING

Where-Object

IMPORTING

Get-Content :- To Read content from a file (.txt/ .csv /.xlsx)

  • $var = Get-Content -Path .\Desktop\names.txt
  • for each ($i in $var)
  • {
  • Write-Host $i
  • Start-Sleep -Seconds 1
  • }
 
  • Import-csv :- To Read Data from csv file
  • $var = Import-Csv -Path .\Desktop\names. csv

Formatting Output

Condition

VARIABLE ($)

  • Variables are always specified with the initial character $, and can include any alphanumeric characters or the underscore in their names.

IF / IF-ELSE

  • $var = (get-process).count

if($var -gt 110)

  • {
  • Write-Host “We have $var process in running state “
  • }
  • Else {
  • Write-Host “Number of Processes are less than 100 in count.”

 

Looping (For/ Eor-each/While)

FOR / FOR-EACH LOOP

For Each is specially used to fetch elements from an array

WHILE/ DO-WHILE LOOP

While :-  As long as the condition remains true, PowerShell reruns the {commandblock} section.

while($val -ne 10) { $val++ Write-Host $val }

 
 

Do-While:- First the Command Block will run and then it will check condition

Do {

$val++ Write-Host $val

} while($val -ne 10)

 

 Take User Input

  
 
Display output:-  Write-Host / Echo / Write-Output

 WRITE-HOST
 

Write-Host is having more attributes

Write-Host –No New Line “Counting from 1 to 9 (in seconds):  “

for each($element in 1..9){

Write-Host –No New Line  “${element} “

Start-Sleep –Seconds 1

}

Write-Host “”

Output :-  Counting from 1 to 9 (in seconds):  1 2 3 4 5 6 7 8 9

WRITE-OUTPUT

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen.

PS C:\> Write-Output “test output” | Get-Member

This command pipes the “test output” string to the Get-Member cmd let, which displays the members of the System. String class, demonstrating that the string was passed along the pipeline.