SlideShare a Scribd company logo
Kaustubh Kumar
PowerShell for System
Admins
Prepared by-Kaustubh Kumar
Session 1
Prepared by-Kaustubh Kumar
Agenda
 Course Outline
 PowerShell Overview
 Basic cmdlets
Prepared by-Kaustubh Kumar
Course Outline
 Interacting with PowerShell
 Managing Windows using PowerShell
 Understanding Variables, Arrays, Hash Tables
 Understanding Pipeline and Data Management
 Managing Registry, Files and Folders
 Managing Remote Computers
 Software and Hardware inventory
 PowerShell scripting
 Using Conditions, Loops
 Using Functions
Prepared by-Kaustubh Kumar
PowerShell Overview
Prepared by-Kaustubh Kumar
Differences between DOS, VBScript and
PowerShell
Prepared by-Kaustubh Kumar
What is Windows PowerShell
 Introduced in 2006
 New scripting language
 General purpose and Administrative programming language
 An administrative interactive command shell
 A list of commands
 Script extension is PS1
 Both a cli and a ISE
 Microsoft server applications provide application specific cmdlets
 Now Open source and supports Linux and MacOS
 Commands include
 Cmdlets (pronounced as command lets)
 Filters
 Workflows
Prepared by-Kaustubh Kumar
Console of PowerShell
 Basic command line interface
 Maximum support for PowerShell features
 Minimum editing capabilities
 In case you are writing a big script then its not possible via the command line
interface.
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
ISE – Integrate Scripting Environment
 Script editor and console combination
 Some windows PowerShell features not supported
 Rich editing capabilities
Prepared by-Kaustubh Kumar
ISE features
 Powershell allows tab completion and in the ISE it will show the
help/parameters for the command being used
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
PowerShell Objects
 PowerShell takes advantage of the underlying . Net framework and takes a
different approach, using objects instead of text. Objects are just a
representation of something. They are a collection of parts and actions to use
them
 An object is a representation real-world or computer-based person place or
thing in the form of a set of data
 Computer
 Person
 User/group/application
 Printer/ Virtual machine/Datacenter
 Cluster/Storage/Network
Prepared by-Kaustubh Kumar
What is a Cmdlet
 PowerShell is more than just command statements. PowerShell uses
functions called “cmdlets.” These cmdlets do much more powerful queries
and have much better output than you'll find in the Windows command line.
With PowerShell, you can use several more input parameters that give you a
different level of output.
 Cmdlets are native Windows PowerShell commands
 Each cmdlet performs a specific, typically a small task
 Extension to Windows can include additional cmdlets ( for ex – if we have
exchange on the server then we will have cmdlets for exchange )
 Form of a cmdlet Verb-Noun (Get-Process)
 Cmdlets are organized based on the object (get-service – service is object
here)
Prepared by-Kaustubh Kumar
Basic and important Cmdlets
 Get-Command
 Get-Help
Prepared by-Kaustubh Kumar
Session 2
Prepared by-Kaustubh Kumar
How to use Cmdlets
 What are the ways of using Cmdlets
 Parameters
 Aliases
 Interact with Services, Processes, Eventlogs
Prepared by-Kaustubh Kumar
The PowerShell parameter is a fundamental component of any script. A
parameter is a way that developers enable script users to provide input at
runtime. If a PowerShell script's behavior needs to change in some way, a
parameter provides an opportunity to do so without changing the underlying
code
PowerShell Parameters
Prepared by-Kaustubh Kumar
PowerShell Alias
 PowerShell alias is another name for the cmdlet or for any command element.
 Creating Alias
 Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help
for Get-Help cmdlet.
 New-Alias -Name help -Value Get-Help
 help Get-WmiObject -Detailed
 Getting Alias
 Use get-alias cmdlet to get all the alias present in current session of powershell.
 Get-Alias
Prepared by-Kaustubh Kumar
Interact with Services, Processes, Eventlogs
 In your daily work as an administrator, you will probably often deal with applications (processes), services, and event logs so
let's take some of the knowledge you gained from the previous chapters and play with it. The examples and topics covered in
this Slide are meant to give you an idea of what you can do. By no means are they a complete list of what you can do. They will
provide you with a great starting point, though.
 Every application that is running is represented by a so-called "process". To view all running processes, use Get-Process cmdlet.
Get-Process throws a number of exceptions when you try and list the executable files of all running processes. Exceptions
occur either when there is no executable for a given process (namely System and Idle), or if you do not have permission to
see them
Prepared by-Kaustubh Kumar
 To suppress the errors we use the parameter -ErrorAction SilentlyContinue
which is available in every cmdlet - or its short form -ea 0:
 Get-Process contain a lot more information that you can see when you pipe
the result to Select-Object and have it display all object properties:
Prepared by-Kaustubh Kumar
 You can then examine the object properties available, and put together your own reports by picking the properties that you
need:
Get-Process | Select-Object Name, Description, Company, MainWindowTitle
You'll notice that there may be blank lines. They occur when a process object has no information for the particular property
you selected. For example, the property MainWindowTitle represents the text in the title bar of an application window. So, if
a process has no application window, MainWindowTitle is empty
You can use the standard pipeline to overcome this as below
Get-Process | Where-Object { $_.MainWindowTitle -ne '' } | Select-Object Description, MainWindowTitle, Name,
Company
Prepared by-Kaustubh Kumar
Using Start-Process
 Whenever you need to launch a new process and want more control, use Start-Process. This cmdlet has a number of benefits
over launching applications directly. First of all, it is a bit smarter and knows where a lot of applications are stored. It can for
example find iexplore.exe without the need for a path:
 Start-Process iexplore.exe
 Start-Process has just one limitation: it cannot return the results of console-based applications back to you. Check this out:
 $result = ipconfig
 This will store the result of ipconfig in a variable. The same done with Start-Process yields nothing:
Prepared by-Kaustubh Kumar
Stopping Processes
 If you must kill a process immediately, use Stop-Process and specify either the process ID, or use the parameter -Name to
specify the process name.
 Stop-Process -Name Notepad ( This will stop/kill all the process for Notepad)
 Stopping processes this way shouldn’t be done on a regular basis: since the application is immediately terminated, it has no
time to save unsaved results (which might result in data loss), and it cannot properly clean up (which might result in orphaned
temporary files and inaccurate open DLL counters). Use it only if a process won't respond otherwise. Use –WhatIf to simulate.
Use –Confirm when you want to have each step confirmed.
 To close a process nicely, you can close its main window (which is the automation way of closing the application window by a
mouse click). Here is a sample that closes all instances of notepad:
Prepared by-Kaustubh Kumar
Managing Services
 Services are basically processes, too. They are just executed automatically and in the background and do not
necessarily require a user logon. Services provide functionality usually not linked to any individual user.
 To find commands related to the Service use the cmdlet
 Get-command *service* -CommandType Cmdlet
Prepared by-Kaustubh Kumar
Starting, Stopping, Suspending, and Resuming Services
 To start, stop, temporarily suspend, or restart a service, use the corresponding cmdlets. You can also use Get-Service
to select the services first, and then pipe them to one of the other cmdlets. Just note that you may need local
administrator privileges to change service properties.
 If a service has dependent services, it cannot be stopped unless you also specify -Force.
Prepared by-Kaustubh Kumar
Working with Event Logs
Prepared by-Kaustubh Kumar
Reading and Writing Event Logs
 Event logs are the central place where applications as well as the operating system log all kinds of information
grouped into the categories Information, Warning, and Error. PowerShell can read and write these log files. To find
out which log files exist on your machine, use Get-EventLog with the parameter -List:
 To list the content of one of the listed event logs, use -LogName instead. This lists all events from the System event
log:
 Get-EventLog -LogName System
Prepared by-Kaustubh Kumar
Reading and Writing Event Logs
 Dumping all events is not a good idea, though, because this is just too much information. In order to filter the
information and focus on what you want to know, take a look at the column headers. If you want to filter by the
content of a specific column, look for a parameter that matches the column name.
 This line gets you the latest 10 errors from the System event log:
 Get-EventLog -LogName System -EntryType Error -Newest 10
 Writing Entries to the Event Log
 To write your own entries to one of the event logs, you first need to register an event source (which acts like your "sender" address). To register an event
source, you need local administrator privileges. Make sure you open PowerShell with full administrator rights and use this line to add a new event source
called "PowerShellScript" to the Application log:
 Once you have registered your event source, you are ready to log things to an event log. Logging (writing) event entries no longer necessarily requires
administrative privileges. Since we added the event source to the Application log, anyone can now use it to log events. You could for example use this line
inside of your logon scripts to log status information:
Prepared by-Kaustubh Kumar
Reading and Writing Event Logs
 You can now use Get-EventLog to read back your entries:
 Get-EventLog -LogName Application -Source PowerShellScript
 you can remove your event source if this was just a test and you want to get rid of it again (but you do need
administrator privileges again, just like when you created the event source):
 Remove-EventLog -Source PowerShellScript
Prepared by-Kaustubh Kumar
 Clearing Event Logs
 Increase the log limit size
 Before After
 Command: Limit-EventLog -LogName System -MaximumSize 30Mb
Prepared by-Kaustubh Kumar
 Changing the Overflow action of the logs
 Before After
 Command: Limit-EventLog -LogName System -OverflowAction DoNotOverwrite
Prepared by-Kaustubh Kumar
Working with Control Panel
 To get Control panel items
Get-ControlPanelItem
 Get control panel items by name
 This example gets control panel items that have Program or App in their names.
Prepared by-Kaustubh Kumar
Working with Control Panel
 Get control panel items by category
This command gets all control panel items in categories that have Security in their names.
 Open a control panel item
 This example opens the “Sounds” control panel item on the local computer.
 Get-ControlPanelItem -Name "*Sound" | Show-ControlPanelItem
Prepared by-Kaustubh Kumar
Session 3
 Manage Disks
 Manager Network Adapters
 Manage IP Address
Prepared by-Kaustubh Kumar
Working on Disks
Prepared by-Kaustubh Kumar
To Get a list of command/functions related to disk
To get number of disks
I am adding a virtual disk on my machine for testing purposes
Prepared by-Kaustubh Kumar
 Get-Disk will show that I have the other disk added now
 If we have more than 1 disk installed then to get the details of the required
disk. Enter the ID of the disk as below
 To change the Operational Status of a disk (Online/Offline)
Prepared by-Kaustubh Kumar
 We will make the disk online for our training purpose.
 To initialize a disk
 Now we see that after initializing the disk it has a Partition style. Earlier it was RAW.
 To change the partition style on the disk
Prepared by-Kaustubh Kumar
To create partitions, we can do it with the Disk Unique ID, Disk number. To get the Unique ID, get the member properties
associated with the Disk by
New-Partition -DiskId 600224800163B7AB596AA348DAF975A9 -DriveLetter G -Size 50MB
New-Partition -DiskNumber 1 -DriveLetter H -Size 30MB
Prepared by-Kaustubh Kumar
To List all partitions for all disks
To remove Partitions, use the command Remove-partition. We need to specify the DiskNumber and the PartitionNumber
NOTE : THIS IS IRREVERSIBLE
Prepared by-Kaustubh Kumar
When I click on Yes and then list the disk then the partition 1 will be gone
Before
After
The G partition is removed, and it shows as unallocated in the Disk Management
Prepared by-Kaustubh Kumar
To format a volume
First get the drive letter that you want to format (see image as below) Drive contents before format
Folder contents after format
This action is IRREVERSIBLE
Think twice before formatting.
Prepared by-Kaustubh Kumar
To shrink a partition
First check what's the supported SizeMin (minimum size) and SizeMax (maximum size) in bytes to resize the partition/volume
After Shrinking the size
Prepared by-Kaustubh Kumar
Session 4
Prepared by-Kaustubh Kumar
Working on Network Adapters
Prepared by-Kaustubh Kumar
To get a list of commands associated with Adapters
Get-Command *-netadapter
To get a list of Network Adapters in the system
Get-NetAdapter
Prepared by-Kaustubh Kumar
To change the name of a network adapter
Before After
Prepared by-Kaustubh Kumar
To Disable a Network Adapter
Before
After
Prepared by-Kaustubh Kumar
To Enable the Network Adapter
Prepared by-Kaustubh Kumar
To see advanced properties of a network adapter
Let's say I want to enable the "Sleep on WoWLAN Disconnect", . I would use Set-NetAdapterAdvancedConfiguration to accomplish this.
Set-NetAdapterAdvancedProperty -DisplayName 'Sleep On WoWLAN Disconnect' -DisplayValue 'Enabled'
Prepared by-Kaustubh Kumar
Session 5
 Manage IP Addresses
 Handle Files and Folders
 Handle the Registry
Prepared by-Kaustubh Kumar
Manage the IP Address
Prepared by-Kaustubh Kumar
To check the IP address of all the interfaces
To Change the Address family of a Network Adapter (IPv4/IPV6)
Prepared by-Kaustubh Kumar
Added a loopback adapter for testing purposes
Prepared by-Kaustubh Kumar
To see description of the adapter
To see details of a specific network adapter
Prepared by-Kaustubh Kumar
To get the ip address of a network adapter
To see the routing table of a network adapter
Prepared by-Kaustubh Kumar
To Remove IP Address of an adapter
To assign an IP address to an Adapter
New-NetIPAddress -InterfaceIndex 49 -IPAddress "169.254.22.33" -PrefixLength 24 -
DefaultGateway 169.254.22.1
Prepared by-Kaustubh Kumar
To define a new route for the Adapter
New-NetRoute -InterfaceIndex 49 -NextHop 192.168.100.1 -DestinationPrefix 0.0.0.0/0
To Check DNS Details
Get-DnsClientServerAddress -InterfaceIndex 49
To Set DNS Addresses (Prmary/Secondary)
Set-DnsClientServerAddress -InterfaceIndex 49 -ServerAddresses @("8.8.8.8","8.8.4.4")
Prepared by-Kaustubh Kumar
Handle Files and Folders
Prepared by-Kaustubh Kumar
We will see how to
Create a new file
Create a new folder (Directory)
Copy one file to another file
Copy file to a different location
Copy folder to a different location
Move a file to a different location
Delete a file/folder
Delete a folder and its subdirectories
Get File and folders available in a drive/folder
Get the content of a file
Prepared by-Kaustubh Kumar
To Create a file
To create new objects with Windows PowerShell, you can use the New-Item cmdlet and specify the type of item you want to create, such
as a directory, file or registry key
If you are specifying a path, and the path doesn't exist then it will fail as below
Prepared by-Kaustubh Kumar
To enter/amend details in the file created
To read content of a file
To Create a directory
To create a file/ folder at a specific location , mention the relative path
Prepared by-Kaustubh Kumar
To Copy file
Prepared by-Kaustubh Kumar
To move a file to a different location
To delete a file
To delete a folder and its subfolders
We need to use the -recurse parameter
Prepared by-Kaustubh Kumar
Get Files/ Folders available on a path / drive
If you want to see the details of files/folders withing subfolders as well then use the '-
recurse' parameter
Prepared by-Kaustubh Kumar
To get content of a file
Prepared by-Kaustubh Kumar
Working with registry
Prepared by-Kaustubh Kumar
We can interact with HKCU and HKLM only using powershell
In order to interact with the registry
HKLM refers to HKey_Local_Machine
HKCU refer to HKEY_Current_User
Like we see the drives in the file system similarly in PS these keys are referred as PS
Drives
Prepared by-Kaustubh Kumar
Like we see the drives in the file system similarly in PS
these keys are referred as PS Drives
Prepared by-Kaustubh Kumar
get-ChildItem HKLM:Software
To create a folder under the software key
New-Item -Path HKLM:Software -Name Alearn
Prepared by-Kaustubh Kumar
To create a registry key and set the value
New-ItemProperty -Path HKLM:SoftwareAlearn -Name <Name of the Key> -
PropertyType DWORD -Value 23
To create a registry key and set the value
New-ItemProperty -Path HKLM:SoftwareAlearn -Name
<Name of the Key> -PropertyType String -Value 23abc
Prepared by-Kaustubh Kumar
To create a registry key and set the value
New-ItemProperty -Path HKLM:SoftwareAlearn -Name <Name of the Key> -PropertyType DWORD -Value 23
To create a registry key and set the value
New-ItemProperty -Path HKLM:SoftwareAlearn -Name
<Name of the Key> -PropertyType String -Value 23abc
Prepared by-Kaustubh Kumar
To get the item property details
get-ItemProperty -Path HKLM:SoftwareAlearn To delete a registry key
To nullify the value of the key value
Prepared by-Kaustubh Kumar
To remove the keys
Prepared by-Kaustubh Kumar
Session 6
Working with
Variables
Arrays
Hash Tables
Prepared by-Kaustubh Kumar
What is a Variable
Temporary memory location, stores the information in the Memory
Write Once read Many times
You can modify the information stored in the variable at any time
Variable has a “name” for the memory location
Variable starts with a “$” symbol
$<VariableName>
How to Store the information/ data into a variable?
1) Create a variable and store the information Manually
$Nameofvariable =“information”
$ip=192.168.1.2
$description=“This is a test variable”
2) Create a variable and store the result of a cmdlet
$svc=Get-Service
$date=Get-Date
$P=Get-Process
3) Create a variable and store the value of another variable
$service=$svc
Prepared by-Kaustubh Kumar
How to retrieve information from a Variable
1) Simply display the information from a variable
2) Use the variable name in Cmdlets
Prepared by-Kaustubh Kumar
How-to: Define PowerShell Data Types
The most common DataTypes (type accelerators) used in PowerShell are listed below.
[string] Fixed-length string of Unicode characters
[char] A Unicode 16-bit character
[byte] An 8-bit unsigned character
[int] 32-bit signed integer
[long] 64-bit signed integer
[bool] Boolean True/False value
[decimal] A 128-bit decimal value
[single] Single-precision 32-bit floating point number
[double] Double-precision 64-bit floating point number
[DateTime] Date and Time
[xml] Xml object
[array] An array of values
[hashtable] Hashtable object
Prepared by-Kaustubh Kumar
Array variables
PowerShell provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the any type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables or objects.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −
$myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
Hash Tables
Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value
that you want linked to that key. Generally we used String or numbers as keys.
This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods.
Declaring hashtable Variables
To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an
hashtable variable −
Syntax
$hash = @{ ID = 1; Shape = "Square"; Color = "Blue"}
or
$hash = @{}
Note − Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are
added whereas hashtables do not.
Example
The following code snippets are examples of this syntax −
$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"}
Print the hashtable.
$hash
Prepared by-Kaustubh Kumar
Processing Hashtable
Dot notation can be used to access hashtables keys or values.
> $hash.keys
ID
Color
Shape
> $hash.values
1
Blue
Square
Example
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
Operators
Prepared by-Kaustubh Kumar
Prepared by-Kaustubh Kumar
Using Pipe

More Related Content

Similar to Power Shell for System Admins - By Kaustubh (20)

PPTX
CCI2019 - I've got the Power! I've got the Shell!
walk2talk srl
 
PPT
PowerShell Core Skills (TechMentor Fall 2011)
Concentrated Technology
 
PDF
Windows PowerShell Step by Step 3rd Edition Wilson
phelpskwasia36
 
PPTX
PowerShell 101
Thomas Lee
 
PPTX
2016 spice world_london_breakout
Thomas Lee
 
PDF
Power on, Powershell
Roo7break
 
PPTX
PowerShell for Penetration Testers
Nikhil Mittal
 
PPTX
Introduction to powershell
Salaudeen Rajack
 
PPTX
Power shell training
David Brabant
 
PPTX
PowerShellForDBDevelopers
Bryan Cafferky
 
PPTX
Get-Help: An intro to PowerShell and how to Use it for Evil
jaredhaight
 
TXT
An a z index of windows power shell commandss
Ben Pope
 
PDF
Windows Powershell Step By Step 3rd Edition Wilson Ed
forsenqenan
 
PPTX
PowerShell 101 - What is it and Why should YOU Care!
Thomas Lee
 
PDF
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
Hitesh Mohapatra
 
PDF
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
ClapperboardCinemaPV
 
PPTX
Powershell For Developers
Ido Flatow
 
PPTX
Introduction-to-PowerShell-azure-Syntax.pptx
MahmoudElmahdy32
 
PDF
Mastering power shell - Windows
Ariel Devulsky
 
PDF
Mastering PowerShell
Fahad Noaman
 
CCI2019 - I've got the Power! I've got the Shell!
walk2talk srl
 
PowerShell Core Skills (TechMentor Fall 2011)
Concentrated Technology
 
Windows PowerShell Step by Step 3rd Edition Wilson
phelpskwasia36
 
PowerShell 101
Thomas Lee
 
2016 spice world_london_breakout
Thomas Lee
 
Power on, Powershell
Roo7break
 
PowerShell for Penetration Testers
Nikhil Mittal
 
Introduction to powershell
Salaudeen Rajack
 
Power shell training
David Brabant
 
PowerShellForDBDevelopers
Bryan Cafferky
 
Get-Help: An intro to PowerShell and how to Use it for Evil
jaredhaight
 
An a z index of windows power shell commandss
Ben Pope
 
Windows Powershell Step By Step 3rd Edition Wilson Ed
forsenqenan
 
PowerShell 101 - What is it and Why should YOU Care!
Thomas Lee
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
Hitesh Mohapatra
 
Learn Powershell Scripting Tutorial Full Course 1dollarcart.com.pdf
ClapperboardCinemaPV
 
Powershell For Developers
Ido Flatow
 
Introduction-to-PowerShell-azure-Syntax.pptx
MahmoudElmahdy32
 
Mastering power shell - Windows
Ariel Devulsky
 
Mastering PowerShell
Fahad Noaman
 

Recently uploaded (20)

PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Ad

Power Shell for System Admins - By Kaustubh

  • 1. Kaustubh Kumar PowerShell for System Admins Prepared by-Kaustubh Kumar
  • 3. Agenda  Course Outline  PowerShell Overview  Basic cmdlets Prepared by-Kaustubh Kumar
  • 4. Course Outline  Interacting with PowerShell  Managing Windows using PowerShell  Understanding Variables, Arrays, Hash Tables  Understanding Pipeline and Data Management  Managing Registry, Files and Folders  Managing Remote Computers  Software and Hardware inventory  PowerShell scripting  Using Conditions, Loops  Using Functions Prepared by-Kaustubh Kumar
  • 6. Differences between DOS, VBScript and PowerShell Prepared by-Kaustubh Kumar
  • 7. What is Windows PowerShell  Introduced in 2006  New scripting language  General purpose and Administrative programming language  An administrative interactive command shell  A list of commands  Script extension is PS1  Both a cli and a ISE  Microsoft server applications provide application specific cmdlets  Now Open source and supports Linux and MacOS  Commands include  Cmdlets (pronounced as command lets)  Filters  Workflows Prepared by-Kaustubh Kumar
  • 8. Console of PowerShell  Basic command line interface  Maximum support for PowerShell features  Minimum editing capabilities  In case you are writing a big script then its not possible via the command line interface. Prepared by-Kaustubh Kumar
  • 10. ISE – Integrate Scripting Environment  Script editor and console combination  Some windows PowerShell features not supported  Rich editing capabilities Prepared by-Kaustubh Kumar
  • 11. ISE features  Powershell allows tab completion and in the ISE it will show the help/parameters for the command being used Prepared by-Kaustubh Kumar
  • 13. PowerShell Objects  PowerShell takes advantage of the underlying . Net framework and takes a different approach, using objects instead of text. Objects are just a representation of something. They are a collection of parts and actions to use them  An object is a representation real-world or computer-based person place or thing in the form of a set of data  Computer  Person  User/group/application  Printer/ Virtual machine/Datacenter  Cluster/Storage/Network Prepared by-Kaustubh Kumar
  • 14. What is a Cmdlet  PowerShell is more than just command statements. PowerShell uses functions called “cmdlets.” These cmdlets do much more powerful queries and have much better output than you'll find in the Windows command line. With PowerShell, you can use several more input parameters that give you a different level of output.  Cmdlets are native Windows PowerShell commands  Each cmdlet performs a specific, typically a small task  Extension to Windows can include additional cmdlets ( for ex – if we have exchange on the server then we will have cmdlets for exchange )  Form of a cmdlet Verb-Noun (Get-Process)  Cmdlets are organized based on the object (get-service – service is object here) Prepared by-Kaustubh Kumar
  • 15. Basic and important Cmdlets  Get-Command  Get-Help Prepared by-Kaustubh Kumar
  • 17. How to use Cmdlets  What are the ways of using Cmdlets  Parameters  Aliases  Interact with Services, Processes, Eventlogs Prepared by-Kaustubh Kumar
  • 18. The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code PowerShell Parameters Prepared by-Kaustubh Kumar
  • 19. PowerShell Alias  PowerShell alias is another name for the cmdlet or for any command element.  Creating Alias  Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help for Get-Help cmdlet.  New-Alias -Name help -Value Get-Help  help Get-WmiObject -Detailed  Getting Alias  Use get-alias cmdlet to get all the alias present in current session of powershell.  Get-Alias Prepared by-Kaustubh Kumar
  • 20. Interact with Services, Processes, Eventlogs  In your daily work as an administrator, you will probably often deal with applications (processes), services, and event logs so let's take some of the knowledge you gained from the previous chapters and play with it. The examples and topics covered in this Slide are meant to give you an idea of what you can do. By no means are they a complete list of what you can do. They will provide you with a great starting point, though.  Every application that is running is represented by a so-called "process". To view all running processes, use Get-Process cmdlet. Get-Process throws a number of exceptions when you try and list the executable files of all running processes. Exceptions occur either when there is no executable for a given process (namely System and Idle), or if you do not have permission to see them Prepared by-Kaustubh Kumar
  • 21.  To suppress the errors we use the parameter -ErrorAction SilentlyContinue which is available in every cmdlet - or its short form -ea 0:  Get-Process contain a lot more information that you can see when you pipe the result to Select-Object and have it display all object properties: Prepared by-Kaustubh Kumar
  • 22.  You can then examine the object properties available, and put together your own reports by picking the properties that you need: Get-Process | Select-Object Name, Description, Company, MainWindowTitle You'll notice that there may be blank lines. They occur when a process object has no information for the particular property you selected. For example, the property MainWindowTitle represents the text in the title bar of an application window. So, if a process has no application window, MainWindowTitle is empty You can use the standard pipeline to overcome this as below Get-Process | Where-Object { $_.MainWindowTitle -ne '' } | Select-Object Description, MainWindowTitle, Name, Company Prepared by-Kaustubh Kumar
  • 23. Using Start-Process  Whenever you need to launch a new process and want more control, use Start-Process. This cmdlet has a number of benefits over launching applications directly. First of all, it is a bit smarter and knows where a lot of applications are stored. It can for example find iexplore.exe without the need for a path:  Start-Process iexplore.exe  Start-Process has just one limitation: it cannot return the results of console-based applications back to you. Check this out:  $result = ipconfig  This will store the result of ipconfig in a variable. The same done with Start-Process yields nothing: Prepared by-Kaustubh Kumar
  • 24. Stopping Processes  If you must kill a process immediately, use Stop-Process and specify either the process ID, or use the parameter -Name to specify the process name.  Stop-Process -Name Notepad ( This will stop/kill all the process for Notepad)  Stopping processes this way shouldn’t be done on a regular basis: since the application is immediately terminated, it has no time to save unsaved results (which might result in data loss), and it cannot properly clean up (which might result in orphaned temporary files and inaccurate open DLL counters). Use it only if a process won't respond otherwise. Use –WhatIf to simulate. Use –Confirm when you want to have each step confirmed.  To close a process nicely, you can close its main window (which is the automation way of closing the application window by a mouse click). Here is a sample that closes all instances of notepad: Prepared by-Kaustubh Kumar
  • 25. Managing Services  Services are basically processes, too. They are just executed automatically and in the background and do not necessarily require a user logon. Services provide functionality usually not linked to any individual user.  To find commands related to the Service use the cmdlet  Get-command *service* -CommandType Cmdlet Prepared by-Kaustubh Kumar
  • 26. Starting, Stopping, Suspending, and Resuming Services  To start, stop, temporarily suspend, or restart a service, use the corresponding cmdlets. You can also use Get-Service to select the services first, and then pipe them to one of the other cmdlets. Just note that you may need local administrator privileges to change service properties.  If a service has dependent services, it cannot be stopped unless you also specify -Force. Prepared by-Kaustubh Kumar
  • 27. Working with Event Logs Prepared by-Kaustubh Kumar
  • 28. Reading and Writing Event Logs  Event logs are the central place where applications as well as the operating system log all kinds of information grouped into the categories Information, Warning, and Error. PowerShell can read and write these log files. To find out which log files exist on your machine, use Get-EventLog with the parameter -List:  To list the content of one of the listed event logs, use -LogName instead. This lists all events from the System event log:  Get-EventLog -LogName System Prepared by-Kaustubh Kumar
  • 29. Reading and Writing Event Logs  Dumping all events is not a good idea, though, because this is just too much information. In order to filter the information and focus on what you want to know, take a look at the column headers. If you want to filter by the content of a specific column, look for a parameter that matches the column name.  This line gets you the latest 10 errors from the System event log:  Get-EventLog -LogName System -EntryType Error -Newest 10  Writing Entries to the Event Log  To write your own entries to one of the event logs, you first need to register an event source (which acts like your "sender" address). To register an event source, you need local administrator privileges. Make sure you open PowerShell with full administrator rights and use this line to add a new event source called "PowerShellScript" to the Application log:  Once you have registered your event source, you are ready to log things to an event log. Logging (writing) event entries no longer necessarily requires administrative privileges. Since we added the event source to the Application log, anyone can now use it to log events. You could for example use this line inside of your logon scripts to log status information: Prepared by-Kaustubh Kumar
  • 30. Reading and Writing Event Logs  You can now use Get-EventLog to read back your entries:  Get-EventLog -LogName Application -Source PowerShellScript  you can remove your event source if this was just a test and you want to get rid of it again (but you do need administrator privileges again, just like when you created the event source):  Remove-EventLog -Source PowerShellScript Prepared by-Kaustubh Kumar
  • 31.  Clearing Event Logs  Increase the log limit size  Before After  Command: Limit-EventLog -LogName System -MaximumSize 30Mb Prepared by-Kaustubh Kumar
  • 32.  Changing the Overflow action of the logs  Before After  Command: Limit-EventLog -LogName System -OverflowAction DoNotOverwrite Prepared by-Kaustubh Kumar
  • 33. Working with Control Panel  To get Control panel items Get-ControlPanelItem  Get control panel items by name  This example gets control panel items that have Program or App in their names. Prepared by-Kaustubh Kumar
  • 34. Working with Control Panel  Get control panel items by category This command gets all control panel items in categories that have Security in their names.  Open a control panel item  This example opens the “Sounds” control panel item on the local computer.  Get-ControlPanelItem -Name "*Sound" | Show-ControlPanelItem Prepared by-Kaustubh Kumar
  • 35. Session 3  Manage Disks  Manager Network Adapters  Manage IP Address Prepared by-Kaustubh Kumar
  • 36. Working on Disks Prepared by-Kaustubh Kumar
  • 37. To Get a list of command/functions related to disk To get number of disks I am adding a virtual disk on my machine for testing purposes Prepared by-Kaustubh Kumar
  • 38.  Get-Disk will show that I have the other disk added now  If we have more than 1 disk installed then to get the details of the required disk. Enter the ID of the disk as below  To change the Operational Status of a disk (Online/Offline) Prepared by-Kaustubh Kumar
  • 39.  We will make the disk online for our training purpose.  To initialize a disk  Now we see that after initializing the disk it has a Partition style. Earlier it was RAW.  To change the partition style on the disk Prepared by-Kaustubh Kumar
  • 40. To create partitions, we can do it with the Disk Unique ID, Disk number. To get the Unique ID, get the member properties associated with the Disk by New-Partition -DiskId 600224800163B7AB596AA348DAF975A9 -DriveLetter G -Size 50MB New-Partition -DiskNumber 1 -DriveLetter H -Size 30MB Prepared by-Kaustubh Kumar
  • 41. To List all partitions for all disks To remove Partitions, use the command Remove-partition. We need to specify the DiskNumber and the PartitionNumber NOTE : THIS IS IRREVERSIBLE Prepared by-Kaustubh Kumar
  • 42. When I click on Yes and then list the disk then the partition 1 will be gone Before After The G partition is removed, and it shows as unallocated in the Disk Management Prepared by-Kaustubh Kumar
  • 43. To format a volume First get the drive letter that you want to format (see image as below) Drive contents before format Folder contents after format This action is IRREVERSIBLE Think twice before formatting. Prepared by-Kaustubh Kumar
  • 44. To shrink a partition First check what's the supported SizeMin (minimum size) and SizeMax (maximum size) in bytes to resize the partition/volume After Shrinking the size Prepared by-Kaustubh Kumar
  • 46. Working on Network Adapters Prepared by-Kaustubh Kumar
  • 47. To get a list of commands associated with Adapters Get-Command *-netadapter To get a list of Network Adapters in the system Get-NetAdapter Prepared by-Kaustubh Kumar
  • 48. To change the name of a network adapter Before After Prepared by-Kaustubh Kumar
  • 49. To Disable a Network Adapter Before After Prepared by-Kaustubh Kumar
  • 50. To Enable the Network Adapter Prepared by-Kaustubh Kumar
  • 51. To see advanced properties of a network adapter Let's say I want to enable the "Sleep on WoWLAN Disconnect", . I would use Set-NetAdapterAdvancedConfiguration to accomplish this. Set-NetAdapterAdvancedProperty -DisplayName 'Sleep On WoWLAN Disconnect' -DisplayValue 'Enabled' Prepared by-Kaustubh Kumar
  • 52. Session 5  Manage IP Addresses  Handle Files and Folders  Handle the Registry Prepared by-Kaustubh Kumar
  • 53. Manage the IP Address Prepared by-Kaustubh Kumar To check the IP address of all the interfaces To Change the Address family of a Network Adapter (IPv4/IPV6)
  • 54. Prepared by-Kaustubh Kumar Added a loopback adapter for testing purposes
  • 55. Prepared by-Kaustubh Kumar To see description of the adapter To see details of a specific network adapter
  • 56. Prepared by-Kaustubh Kumar To get the ip address of a network adapter To see the routing table of a network adapter
  • 57. Prepared by-Kaustubh Kumar To Remove IP Address of an adapter To assign an IP address to an Adapter New-NetIPAddress -InterfaceIndex 49 -IPAddress "169.254.22.33" -PrefixLength 24 - DefaultGateway 169.254.22.1
  • 58. Prepared by-Kaustubh Kumar To define a new route for the Adapter New-NetRoute -InterfaceIndex 49 -NextHop 192.168.100.1 -DestinationPrefix 0.0.0.0/0 To Check DNS Details Get-DnsClientServerAddress -InterfaceIndex 49 To Set DNS Addresses (Prmary/Secondary) Set-DnsClientServerAddress -InterfaceIndex 49 -ServerAddresses @("8.8.8.8","8.8.4.4")
  • 60. Prepared by-Kaustubh Kumar We will see how to Create a new file Create a new folder (Directory) Copy one file to another file Copy file to a different location Copy folder to a different location Move a file to a different location Delete a file/folder Delete a folder and its subdirectories Get File and folders available in a drive/folder Get the content of a file
  • 61. Prepared by-Kaustubh Kumar To Create a file To create new objects with Windows PowerShell, you can use the New-Item cmdlet and specify the type of item you want to create, such as a directory, file or registry key If you are specifying a path, and the path doesn't exist then it will fail as below
  • 62. Prepared by-Kaustubh Kumar To enter/amend details in the file created To read content of a file To Create a directory To create a file/ folder at a specific location , mention the relative path
  • 64. Prepared by-Kaustubh Kumar To move a file to a different location To delete a file To delete a folder and its subfolders We need to use the -recurse parameter
  • 65. Prepared by-Kaustubh Kumar Get Files/ Folders available on a path / drive If you want to see the details of files/folders withing subfolders as well then use the '- recurse' parameter
  • 66. Prepared by-Kaustubh Kumar To get content of a file
  • 68. Prepared by-Kaustubh Kumar We can interact with HKCU and HKLM only using powershell In order to interact with the registry HKLM refers to HKey_Local_Machine HKCU refer to HKEY_Current_User Like we see the drives in the file system similarly in PS these keys are referred as PS Drives
  • 69. Prepared by-Kaustubh Kumar Like we see the drives in the file system similarly in PS these keys are referred as PS Drives
  • 70. Prepared by-Kaustubh Kumar get-ChildItem HKLM:Software To create a folder under the software key New-Item -Path HKLM:Software -Name Alearn
  • 71. Prepared by-Kaustubh Kumar To create a registry key and set the value New-ItemProperty -Path HKLM:SoftwareAlearn -Name <Name of the Key> - PropertyType DWORD -Value 23 To create a registry key and set the value New-ItemProperty -Path HKLM:SoftwareAlearn -Name <Name of the Key> -PropertyType String -Value 23abc
  • 72. Prepared by-Kaustubh Kumar To create a registry key and set the value New-ItemProperty -Path HKLM:SoftwareAlearn -Name <Name of the Key> -PropertyType DWORD -Value 23 To create a registry key and set the value New-ItemProperty -Path HKLM:SoftwareAlearn -Name <Name of the Key> -PropertyType String -Value 23abc
  • 73. Prepared by-Kaustubh Kumar To get the item property details get-ItemProperty -Path HKLM:SoftwareAlearn To delete a registry key To nullify the value of the key value
  • 74. Prepared by-Kaustubh Kumar To remove the keys
  • 75. Prepared by-Kaustubh Kumar Session 6 Working with Variables Arrays Hash Tables
  • 76. Prepared by-Kaustubh Kumar What is a Variable Temporary memory location, stores the information in the Memory Write Once read Many times You can modify the information stored in the variable at any time Variable has a “name” for the memory location Variable starts with a “$” symbol $<VariableName> How to Store the information/ data into a variable? 1) Create a variable and store the information Manually $Nameofvariable =“information” $ip=192.168.1.2 $description=“This is a test variable” 2) Create a variable and store the result of a cmdlet $svc=Get-Service $date=Get-Date $P=Get-Process 3) Create a variable and store the value of another variable $service=$svc
  • 77. Prepared by-Kaustubh Kumar How to retrieve information from a Variable 1) Simply display the information from a variable 2) Use the variable name in Cmdlets
  • 78. Prepared by-Kaustubh Kumar How-to: Define PowerShell Data Types The most common DataTypes (type accelerators) used in PowerShell are listed below. [string] Fixed-length string of Unicode characters [char] A Unicode 16-bit character [byte] An 8-bit unsigned character [int] 32-bit signed integer [long] 64-bit signed integer [bool] Boolean True/False value [decimal] A 128-bit decimal value [single] Single-precision 32-bit floating point number [double] Double-precision 64-bit floating point number [DateTime] Date and Time [xml] Xml object [array] An array of values [hashtable] Hashtable object
  • 79. Prepared by-Kaustubh Kumar Array variables PowerShell provides a data structure, the array, which stores a fixed-size sequential collection of elements of the any type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables or objects. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList − $myList = 5.6, 4.5, 3.3, 13.2, 4.0, 34.33, 34.0, 45.45, 99.993, 11123
  • 82. Prepared by-Kaustubh Kumar Hash Tables Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. Generally we used String or numbers as keys. This tutorial introduces how to declare hashtable variables, create hashtables, and process hashtable using its methods. Declaring hashtable Variables To use an hashtable in a program, you must declare a variable to reference the hashtable. Here is the syntax for declaring an hashtable variable − Syntax $hash = @{ ID = 1; Shape = "Square"; Color = "Blue"} or $hash = @{} Note − Ordered dictionaries can be created using similar syntax. Ordered dictionaries maintain the order in which entries are added whereas hashtables do not. Example The following code snippets are examples of this syntax − $hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"} Print the hashtable. $hash
  • 83. Prepared by-Kaustubh Kumar Processing Hashtable Dot notation can be used to access hashtables keys or values. > $hash.keys ID Color Shape > $hash.values 1 Blue Square Example