0% found this document useful (0 votes)
63 views

Week 14 15 PowerShell 1

PowerShell is a command-line shell and scripting language that allows system administrators to automate administrative tasks and manage Windows and other operating systems. PowerShell includes features like robust command history, tab completion, aliases, and a pipeline for chaining commands together. As a scripting language, PowerShell is commonly used to automate system management tasks and build solutions using its support for classes, functions, and modules. PowerShell Desired State Configuration allows managing infrastructure through configuration as code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views

Week 14 15 PowerShell 1

PowerShell is a command-line shell and scripting language that allows system administrators to automate administrative tasks and manage Windows and other operating systems. PowerShell includes features like robust command history, tab completion, aliases, and a pipeline for chaining commands together. As a scripting language, PowerShell is commonly used to automate system management tasks and build solutions using its support for classes, functions, and modules. PowerShell Desired State Configuration allows managing infrastructure through configuration as code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

FINAL Week 14 - 15

PowerShell
Shell
PowerShell is modern command shell that includes the best features of other popular shells. Unlike most shells that only accept and return text, PowerShell accepts and returns
.NET objects. The shell includes the following features:
• Robust command-line history
• Tab completion and command prediction (See about_PSReadLine)
• Supports command and parameter aliases
• Pipeline for chaining commands
• In-console help system, similar to Unix man pages

Scripting language
As a scripting language, PowerShell is commonly used for automating the management of systems. It is also used to build, test, and deploy solutions, often in CI/CD
environments. PowerShell is built on the .NET Common Language Runtime (CLR). All inputs and outputs are .NET objects. No need to parse text output to extract information
from output. The PowerShell scripting language includes the following features:
• Extensible through functions, classes, scripts, and modules
• Extensible formatting system for easy output
• Extensible type system for creating dynamic types
• Built-in support for common data formats like CSV, JSON, and XML

Configuration management
PowerShell Desired State Configuration (DSC) is a management framework in PowerShell that enables you to manage your enterprise infrastructure with configuration as code.
With DSC, you can:
• Create declarative configurations and custom scripts for repeatable deployments
• Enforce configuration settings and report on configuration drift
• Deploy configuration using push or pull models
WHAT IS WINDOWS POWERSHELL ?

• Windows PowerShell™ is a task-based command-line shell.


• It’s a scripting language designed for IT Professional.
• Built on the .NET Framework.
• Windows PowerShell™ helps IT professionals to automate THE ADMINISTRATION of the Windows operating system AND APPLICATIONS that run on Windows.

WHY POWERSHELL ?

• It’s not going away any time soon ( Microsoft has made it clear that PowerShell is here to stay. That’s why we have PowerShell version 2 included in Windows
Server 2008 R2 and Windows 7 by default.)
• Most Microsoft products will eventually use it
• You can’t do everything from the GUI any more
• It can make your life easier( Example: If you need to update an Active Directory attribute for a thousand users. Performing the task manually would likely take
hours to complete. Using PowerShell, you can complete the task using a single line of code.)
• Many GUIs are PowerShell front ends ( best known example of this is the Exchange Management Console )
• You can use PowerShell commands to manage your domains
• It enables interactivity between products
HOW ITS DIFFERS ?

• PowerShell is object-based not text-based


Traditional command prompt output is text-based while output in PowerShell is not. It looks like text, but it is actually an object. With traditional scripting, if you
wanted to use the output of one command in another, additional programming would be required to manipulate the data in a format the second command
could understand
• PowerShell Commands are customizable
• PowerShell commands are referred to as Cmdlets, PowerShell gives you the flexibility
to create your own CmdLets
• PowerShell is a Command line interpreter and a scripting environment
• With PowerShell not only you can enter commands, you can build your own script- blocks.

POWERSHELL APPLICATION
Windows PowerShell Console
• Similar to the Command Prompt
• Launching Windows PowerShell Console.
• Go to Start -> All Programs -> Accessories -> windows PowerShell -> Windows PowerShell
• You can also launch PowerShell from a command prompt start -> run by simply typing PowerShell
• Writing PowerShell script *.PS1 and executing through PowerShell console.
• Launching Windows PowerShell Console.
• Go to Start -> All Programs -> Accessories -> windows PowerShell -> Windows PowerShell ISE
• You can also launch PowerShell from a command prompt start -> run by simply typing PowerShell ISE

Windows PowerShell ISE


POWERSHELL ARCHITECTURE
POWERSHELL CONSOLE - SHORTCUT KEYS

• Page Up – Jumps to the first command in the history buffer.


• Page Down – Jumps to the last command in the history buffer.
• Up Arrow – goes back one command in the history buffer.
• Down Arrow – goes forward one command in the history buffer.
• Home – Jumps to the beginning of the command line.
• End – Jumps to the end of the command line.
• Ctrl+LeftArrow – goes to the left one word at a time.
• Ctrl+RightArrow – goes to the right on word at a time.
• Tab – Completes input.
• F7 – Shows history buffer (use the up and down arrow keys to navigate the buffer).

POWERSHELL CMDLETS

Cmdlets are compiled code that are available to the PowerShell environment. PowerShell commands have been standardized using a "verb-noun" naming convention.
This standard simplifies the learning curve and provides a better description of what the cmdlet does
To see a list of cmdlets available in PowerShell, type the following cmdlet:
Get-Command (Get is your verb and Command is your noun)
Get-Command –Verb Get: List all the commands which has verb “Get”.
Get-Command –Noun Service: List all the commands which has noun “Service”.

CmdLets – Getting Help and Examples

It is important to find information quickly and easily. Get-Help cmdlet has been designed for that purpose. It displays help about Windows PowerShell
cmdlets and concepts.
Get-Help: Information about cmdlets and concepts. Includes description, syntax, and remarks
Get-Help *: Information about all available help topics.
Get-Help Get-Service: Information about a specific cmdlet.
Get-Help Get-Service –Example: Information about a specific cmdlet with examples
USING CMDLETS
Get-Process: List all the process running in the machine Get-Service: List all the service running in the machine Get-Location: Gets the current path

Get-Process –name notepad

Get-Service –name browser


Alias in CmdLets
An alias is an alternative name assigned to a cmdlet.
• Built-in Aliases – Predefined alternative names for Windows, Unix, and PowerShell cmdlets.
• User-defined Aliases – Custom alternative names created by the user.

Get-Alias: List all the alias exist in the powershell commands.


Creating Alias: New-Alias Hist Get-History.

Customized Alias name


Cmdlets to create new alias Cmdlets for which you need to create alias

CMDLETS – PARAMETERS, OBJECTS, AND FORMATTING

Common Parameters: (Not all cmdlets use this parameters)


• whatif – Cmdlet is not actually executed, provides information about “what would happen” if executed.
• confirm - Prompt user before executing cmdlet.
• Verbose - Provides more detail.
• debug - Provides debugging information.
• ErrorAction - Instructs cmdlet to perform an action when errors occur. Such as: continue, stop, silently continue, and inquire.
• ErrorVariable - Use a specific variable to hold error information. This is in addition to the standard $error variable.
• OutVariable - Variable used to hold output information.
• OutBuffer - Hold a certain number of objects before calling the next cmdlet in the pipeline.

Stop-Process –name notepad –whatIf


Stop-Process –name notepad -confirm
Objects:
Cmdlets are object by default.
Get-Member helps to identify all the properties & methods exist in a cmdlets

Get-Service | Get-Member: List all the properties and methods of the Get-Service cmdlets
Get-Service | Get-Member -MemberType Method: List only the methods
Get-Service | Get-Member –MemberType Property: List only the property
FORMATTING OUTPUT:
The “Format-” cmdlets allow us to choose which format to display results in.
• Format-List à Displays the data in list
• Format-Table à Displays the data in rows and column
• Format-Wide à Compresses results of a list, to fit the screen

Get-ChildItem C:\Windows | Format-Table: Displays the folders under C:\Windows


Get-ChildItem C:\Windows | Format-Table –AutoSize : (-AutoSize to assist us with white space issues.)
Formatting Output (html, csv):

Get-Process | ConvertTo-html: Convert the output to html, Display the result in PowerShell console.
Get-Process | ConvertTo-html | out-file “C:\Processes.html”: Saves the output to a file.
Get-Process | Export-CSV Processes.csv: Convert the output to Process.csv file.
Invoke-Item Processes.csv: Open the exported Process.csv file.
POWERSHELL PROVIDERS

PowerShell Providers are .NET programs that allow us to work with data stores as if they were mounted drives.Simplifies accessing external data outside
the PowerShell environment. For example, we can access the registry as if it were a file system.

Get-PSProvider: List providers available in PowerShell

To use any of the above listed providers , First we need to connect the providers by mounting PowerShell Drive.
Most Providers have only one PSDrive, the exceptions are the FileSystem Provider(depends on the number of drives on the system) and the Registry
Provider(HKLM and HKCU).
Get-PSDrive: List the available powershell drivers.

Using PowerShell Certificate Providers:


Set-Location cert:: Set Location to the Cert PSDrive .
Get-ChildItem: List all the Certificates on the System.
Get-ChildItem -Recurse | Export-CSV “D:\Certificates.csv”: Export the certificate to a Certificates.csv file.
Invoke-Item “D:\Certificates.csv”: Open the exported certificates.
POWERSHELL SCRIPTING BASIC

• Variables, Arrays, Xml and Hash tables.


• Arithmetic & Comparison, Logical Operators
• Using Conditional Logic.
• Processing data with Loops.
• Using Functions.
Variables:
S.No Type Description Example
1 [int] 32-bit signed integer [int]$x = 9
2 [long] 64-bit signed integer [long]$x = 98765432
3 [string] Fixed-length string of Unicode characters [string]$name = “Saravanan G”
4 [char] A Unicode 16-bit character [char]$a = ‘A’
5 [byte] An 8-bit unsigned character [byte]$a = 1
6 [bool] Boolean True/False value [bool]$a = 0
7 [decimal] An 128-bit decimal value [decimal]$i = 3.14
8 [single] Single-precision 32-bit floating point number [single]$s = 1
9 [double] Double-precision 64-bit floating point number [double]$d = 25.79
10 [xml] Xml object [xml]$x = get-content “D:\Employee.xml”

11 [array] An array of values $comp = @(“Server1″, “Server2″,


“Server3″)
12 [hashtable] Hashtable object $EmpName = @{“John” = 01; “Davis” =
02; “Smith” = 03}
SPECIAL VARIABLES: PRE-DEFINED WITHIN POWERSHELL
• $_ – Contains the current pipeline object, used in script blocks, filters, and the where statement.
• $Args – Contains an array of the parameters passed to a function.
• $Home – Specifies the user’s home directory.
• $PsHome – The directory where the Windows PowerShell is installed.

Get-Help about_automatic_variables: Cmdlet to view the complete list of special variables.

Operators:

Arithmetic Comparison Logical


+ = Addition. -eq = Equal to -not = Not

- = Subtraction -lt = Less than ! = Not

* = Multiplication -gt = Greater than -and = And

/ = Division -ge = Greater than or Equal to -or = Or

% = Modulus -le = Less than or equal to

-ne = Not equal to


Conditional Logic:

If Else Switch
$x = 2 $objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace

if ($x -eq 5) "root\CIMV2"

{Write-Host "Value is 5"} elseif "Computer "+ $objWMI.name + " is a: "


($x -eq 4)
switch ($objWMI.domainRole)
{Write-Host "Value is 4"}
{
else
1. {Write-Host "Stand alone workstation"}
{Write-Host "Value is 2"}
2. {Write-Host "Member workstation"}

3. {Write-Host "Stand alone server"} 3 {Write-Host "Member server"}

4 {Write-Host "Back-up domain controller"} 5 {Write-Host "Primary domain


controller"}

default {Write-Host "The role cannot be determined"}

}
POWERSHELL FUNCTION:
Function Time {Get-Date}

Function Add ($x, $y) #Passing Parameters in Function


{
$Ans = $x + $y
Write-Host “The Answer is $Ans”
}
Using $Args in Function:
Function Hello
{
“Hi $args, What are you doing ?”
}

Function Add
{
$args[0] + $args[1]
}

Using XML in PowerShell:


How to Query cmdlets:

Get-Process | Where-Object {$_.handles -gt 500}


Get-Process | Where-Object {$_.handles -gt 500 -and $_.handles -lt 700}
Get-Process | Where-Object {$_.handles -gt 200 -and $_.name -eq "svchost"} Get-Process | Where { $_.handles -gt 500 } | Sort handles | Format-
Table
WINDOWS POWERSHELL PIPELINE

allows us to join two or more statements with a pipe symbol, sometimes called the '|' bar key. This tells PowerShell that we want to take the output of
one command and pass it as the input to the next command. Let’s look at a simple example to better understand the power of Pipeline in Windows
PowerShell.

Get-Process | Where { $_.handles -gt 500 } | Sort handles | Format-Table

You might also like