Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 94

PRESENTATION

T3 - GROUP 6

ANUSHA (TL)
SUBHADEEP DEB ROY
NANDINI
SAI CHARAN
VISHAL
INTRODUCTION
TO
POWERSHELL latest version : 7.1.4
August 12, 2021
What is PowerShell ?

● PowerShell is a task automation and configuration management


framework from Microsoft, consisting of a command-line shell and
associated scripting language. It is introduced in 2006.
● It is built on .Net Framework.
P/S interface
Why PowerShell ?

● Easy to use
● No Compiling
● Not case-sensitive
● PowerShell is a new environment for Windows system
administrators that allows them to use a more modern
command-line environment to manage Windows
For what powershell is used ?

● Windows PowerShell is a Microsoft framework for automating tasks


using a command-line shell and an associated scripting language.
● It is used to automate almost any task in the Windows ecosystem.
What are cmdlets?

● A cmdlet is a lightweight command that is used in the PowerShell


environment.
● The PowerShell runtime invokes these cmdlets within the context of
automation scripts that are provided at the command line.
● The PowerShell runtime also invokes them programmatically through
PowerShell APIs
Some key commands in PowerShell

● Get-Help
● Get-Command
● Get-PSDrive
● Get-Service
● Format-List
What can we do using PowerShell

● Adding and deleting groups


● Editing groups
● Creating listing to view specific types of users or groups.
● Kill a process in powershell instead of Task Manager.
● Export NTFS folder permissions.
How PowerShell is different from command prompt

● Windows PowerShell is the new Microsoft shell that


combines the old CMD functionality with a new
scripting/cmdlet instruction set with built-in system
administration functionality.
● PowerShell cmdlets allow users and administrators to
automate complicated tasks with reusable scripts.
● PowerShell is more advanced version of cmd
Powershell
Variables
Variable Examples
List Variable: Get Variable:

To list all current available variables, run the ls This is very similar to the list variable command
variable:* command.
Print Variable:

To write to a .txt file, use the Out-File command: To export data to a .csv file, use the Export-Csv
command:
Print Variable:

And to write to an HTML file, use the ConvertTo- To read a file that we exported, we use the Get-
Html command: Content cmdlet:
Powershell Array
Array creation
When creating arrays, be aware of the default PowerShell behavior. If you create an array with multiple elements, PowerShell will
create an array, as you intend. For example, put a few numbers into an array and then check the data type of the variable:
However, if you put just one value in a variable, then PowerShell will not create an array:

If a comma is used as a binary operator, then a normal array is created; if it is used as a unary operator, the array has just one element.
For example, here is how we can get an array consisting of one element:
Array List
If you will modify or search an array frequently, you can use the ArrayList class, which is designed to let you easily add, remove,
and search for items in it:
Multidimensional Arrays
Multidimensional arrays are variables that can be used to store information in a table without having to write it to a real database. It
looks like a hash table, but it can store different types of information, such as strings and integers.
Sort Array
If an array contains only one data type, you can sort the values using the Sort method:
Add and Remove Item
Array Length Array Contains

If you want to see if any of the elements in an array


To return the number of elements in array, use the
contains a particular value, use the Contains
.length parameter:
method:
Loop through an array

In order to handle each element in an array one after another, we need to make a loop using the foreach
operator.
LOOPS
&
CONDITIONAL STATEMENTS
Scripts can make decisions. How?

By using a concept called conditional logic. The PowerShell if statement and


the if/else constructs are the common ways to define conditions.

Foreach
While Loop
For Loop
Do While
If Statement
A Foreach loop reads a set of objects (iterates) and completes when it’s
finished with the last one.

The collection of objects that are read is typically represented by an array


or a hashtable.
While loop in PowerShell is an iterative loop, which runs until the condition
satisfies.

You can write multiple lines of code inside the while block and run it several
times until the criteria met.

It is like FOR loop but the structure is different.


SYNTAX:

ForEach(ITEM in COLLECTION)
{
CODE BLOCK
}

To print names and their length using foreach

To print array of numbers


Creating Folders Using FOREACH
SYNTAX:

While(text_expression)
{
Statement_1
Statement_2
..
Statement_n
}
While condition to check if number is less han 8 or not
To check for yes or no condition
SYNTAX:

for(<init>;<condition>;<repeat>)
{
<statement lists>
}

To print pattern using for loop


The PowerShell for loop can make running the same set of commands on
multiple items quickly and produce consistent results

Using a for loop gives more control over limits and conditions on when
the code should exit. This is compared with the foreach or the ForEach-
Object cmdlet, where iteration stops after the last item in the collection
was processed.
Update progress using for loop
First is the Do keyword, then the script block that I want to “do.”

Then comes the While keyword, and the condition that is evaluated to
determine if another loop will occur.

SYNTAX:

Do{
..
Block of statements
..}
while(condition);
To check if the tool is present or not using do while

To check for the connection using do while loop


IThe If Statement in PowerShell allows the programmer to control the flow
of execution of the program, the” IF” statement defines if a program has to
execute a section of code or not, based on whether a given condition
expression is correct or not.

Here correct in programming terms true or false.

SYNTAX:
if(condition) {
// Executes when the condition
is true
}else {
// Executes when the condition
is false
}
To check if the banks are open or not using loop
Switch function in PowerShell is used to handle multiple If statements or in
other terms it is replacement of multiple conditions If/Else If/Else.

To check a single condition in Script or Function, you can use If/else


statement but if you want to evaluate more IF statements then use Switch.

SYNTAX:
Switch (<Value>)
{
<Condition1> {Action1}
<Condition2> {Action2}
}
Break Statement

A break statement is used to terminate the execution of the loop(while or do

while or for) and the control is transferred to next statement or break.

Continue Statement

Unlike break statement, the continue statement does not terminate a loop

(while or do-while or for).


Benefits of loops

● Increase code reusability, which makes code smaller

● The faster calculation for big data, saving a lot of manual labor

● The redundancy of code is less.


Windows
Management
Instrumentation
About WMI

•Windows Management Instrumentation is a subsystem of PowerShell


that gives admins access to powerful system monitoring tools.
•Allows to retrieve and manage information of the Windows Server
•Built – in since Windows 2000
•Used in GPO
•Each new version of Windows introduces improvements to WMI,
including new WMI classes, as well as new capabilities for existing WMI
classes
Basics of WMI
● Architecture of WMI
❏ Providers
❏ A provider is a Component Object Model (COM) object
that acts as an intermediary between WMI and a managed
object
❏ Name Spaces
❏ Namespaces are not physical locations, but are more like
logical databases
❏ Classes
❏ The WMI system classes are a collection of predefined
classes based on the Common Information Model (CIM)
Uses of Windows Management
Instrumentation:

● Report on drive configuration for locally attached drives,


and for mapped drives.
● Report on available memory, both physical and virtual.
● Back up the event log.
● Modify the registry.
Exploring WMI Module
Get-Wmiobject:

Syntax:

Get-WmiObject [-Class] <String>] [-ComputerName <String[]>][-Namespace <String>][-Filter


<String>]
Examples:

Get-WmiObject -Class Win32_Bios

Get-WmiObject -Class Win32_Processor

Get-WmiObject -Class __Namespace -Namespace root

Get-WmiObject -Class Win32_Service -ComputerName 10.0.0.7


Win32_BIOS Win32_Processor
WMI Command

To get the users of


the computer.
WMI Command

To get Different
disk partitions.
Accessing Remote Computer Services Namespaces
Remove-Wmiobject:
Remove-WmiObject
[-Class] <String>
[-Impersonation <ImpersonationLevel>]
[-Authentication <AuthenticationLevel>]
[-Locale <String>]
[-EnableAllPrivileges]
[-Authority <String>]
[-Credential <PSCredential>]
[-ThrottleLimit <Int32>]
[-ComputerName <String[]>]
[-Namespace <String>]
[-WhatIf]
[-Confirm]
[<CommonParameters>]
Examples:
To Terminate a running process

Get-WmiObject -Class Win32_Process |


where {$_.Name -like "Notepad*"}

Get-WmiObject -Class Win32_Process |


where {$_.Name -like "Notepad*"} | Remove-WmiObject
Checking Process running in the System
WMI Events

● Get-Event
● Get-EventSubscriber
● New-Event
● Register-WmiEvent
● Remove-Event
● Unregister-Event
Exploring WMI Events

Register-WmiEvent

Get-Event

$query = "SELECT * from


Win32_VolumeChangeEvent
WITHIN 5"
Register-WmiEvent -Query $query
-SourceIdentifier 'USBEvent'
Exploring WMI Events

$process = "calc.exe"
$WMIQuery = "SELECT *
FROM
__InstanceCreationEvent
WITHIN 5 WHERE
TargetInstance ISA
'Win32_Process' AND
TargetInstance.Name =
'$Process'"
Register-WmiEvent -Query
$WMIQuery `
-SourceIdentifier "Process
$Process"
Summary:
•WMI is one of the most powerful tools available to Windows
administrators.
•WMI and PowerShell provide access to the event engine so that you can
be alerted when things happen. You can also configure an action to be
performed when an event is triggered.
•WMI is a standards-based management toolset that’s installed by default
in modern Windows systems. It supplies a large number of classes that
correspond to physical entities in your systems, such as CPU, operating
system, or installed application.
•Due to the complexity, the lack of documentation, and the difficulty in using
it in the past it's not popular.
Exploring the Active
Directory Module
What is an
Active Directory?

Active Directory (AD) is


a database and set of
services that connect
users with the network resources they need to get their work done.

Active Directory is a
Centralized Hierarchical
Directory Database.
Active Directory Services:

1. Lightweight Directory Services (AD LDS)


2. Lightweight Directory Access Protocol (LDAP)
3. Certificate Services or AD CS
4. Federation Services (AD FS)
5. Rights Management Services (AD RMS)
The Hierarchical Structure of Active Directory Domain Services

Domain
Domain
How to Install Active Directory using Powershell

1. Type Start PowerShell and press Enter within the Command Prompt window to open a new Windows
PowerShell console window.
2.Type Add-WindowsFeature AD-Domain-Services and press Enter to install
Active Directory Domain Services.
After Installing
To add domain name:
2. Type Install-ADDSForest -DomainName training.com -InstallDNS and press Enter to create a new forest and domain named training.com. After this,
the server needs a restart and will now be a Domain Controller
3. The domain controller promotion will complete and the server will be rebooted finalizing the process.
DNS will be also installed
How to create an Organization Unit (OU)

1. Identify the domain in which the OU is to be created.


(In our example, we are using training.com)

2. Create and compile the script for creating the desired OU. Execute the script
in PowerShell.
For demo, we are using :

New-ADOrganizationalUnit -Name "DemoOU" -Path "DC=training,DC=com"


After applying the command, the OU will be created.
● To check the OU:
Get-ADObject -Filter { ObjectClass -eq 'organizationalunit' }
We can create OU inside OUs and can show them in the same manner.

New-ADOrganizationalUnit -Name "NestedOU" -Path "ou=DemoOU,DC=training,


DC=com" - here NestedOU is created inside DemoOU and afterwards the details is shown.
To create a user inside an OU

You can create an AD user in a specific OU by using the -path parameter in New-ADuser.

In our example, we are creating a user Binod under DemoOU


To check whether the user is present or not:

Get-ADUser -Filter * -SearchBase “ou=Target_OU,dc=training,dc=com”

We used Get-ADUser -Filter * -SearchBase “ou=DemoOU, dc=training, dc=com” to check the users inside DemoOU
To set properties of a user:
There are several properties to change, for example we are using few of them.

Set-ADUser -Identity Binod -Surname Khanna -HomePage 'http://training.com/


employees/Binod' -LogonWorkstations 'BK-DSKTOP, BK-LPTOP'
To move a user from one OU to another OU:
Here, Subha is in Kolkata OU initially
Now, to move ‘Subha’ from Kolkata Ou to India OU, we have used get-aduser Subha | Move-ADObject -TargetPath
‘ou=India,dc=training,dc=com’ and afterwards Subha shifted to India OU from Kolkata one
How to create a group inside an OU:
We have to define the OU in which the group will be there also along with the scope

new-adgroup -name Demo -description "Demo Group" -groupscope Global -path "OU=DemoOU ,dc=training, dc=com"
The Scope of the group along with the name and path is required
To check the availability of a group:
We use ‘Get-AdGroup’ followed by group name
To Add members in a group:
We use Add-AdGroupMember followed by the names of users
To check members inside a group:
We use the cmdlet Get-ADGroupMember followed by groupname
Get-ADGroupMember -identity Demo
To add members in bulk:
Use ADD-AdGroupMember followed by the usernames.
To Remove members from a group:
We use Remove-ADGroupMember cmdlet followed by username/usernames
To Change GroupScope of a Group:
We use Set-ADGroup followed by groupname and new groupscope
To Remove a group:
We use Remove-ADGroup followed by group name
To Delete an OU:
We use Remove-ADOrganizationUnit followed by the path of the OU
To Delete an OU (Where accidental prevention is marked):
We have to run the script followed by path of the Organization Unit
Get-ADOrganizationalUnit -Identity 'OU=DemoOU2,DC=training,DC=com' |
Set-ADObject -ProtectedFromAccidentalDeletion:$false -PassThru |
Remove-ADOrganizationalUnit -Confirm:$false

You might also like