Vous êtes sur la page 1sur 23

WINDOWS POWERSHELL TUTORIAL

http://www.powershellpro.com/powershell-tutorial-introduction/

PowerShell Concepts

PowerShell is object-based not text-based


With PowerShell we can interact with these objects to enumerate information (object-properties)
and/or create, modify, or delete objects and/or object-properties (object-methods).
PowerShell Commands are customizable
PowerShell allows you to create your own aliases as well as creating your own cmdlets.
PowerShell is a Command line interpreter and a scripting environment
PowerShell console and Powershell ISE.

We will use Powershell ISE to both check commands or do the scripts.

By default Windows does not allow scripts or commands to be executed. We have to change the
ExecutionPolicy. Within the ISE enviroment is easy to find how both commands work, Get-
Execution Policy and Set-ExecutionPolicy.

→ Ps C:\Get-ExecutionPolicy
→ Ps C:\Set-ExecutionPolicy unrestricted

Commands
There are four categories of PowerShell commands: Cmdlet (Command-Let), PowerShell
Functions, PowerShell Scripts, and native Windows commands.

Cmdlet
→ Ps C:\ means that we run this command.
If we want to check all the cmdlets:
→ Ps C:\get-command
A cmdlet is a Verb-Noun word, if we want to check them according to its Verb or Noun:
→ Ps C:\get-command -Verb Get
→ Ps C:\get-command -Noun Service
To get help:
→ Ps C:\Get-Help
→ Ps C:\Get-Help *
→ Ps C:\Get-Help Get-Service

Stopping and Starting a Service using CmdLets


→ Ps C:\Get-Service -name Browser
→ Ps C:\Stop-Service -name Browser
→ Ps C:\Get-Service -name Browser

Aliases
Built-In PowerShell Aliases
→ Ps C:\Get-Alias
User-Defined PowerShell Aliases
Set-Alias alias command – Simple syntax, not much to it. Let’s say I want to create a User-Defined
alias for the “Get-Service” cmdlet:
→ Ps C:\Set-Alias gs Get-Service

Common Parameters (options for cmdlets)


Cmdlets follow a standard “Verb-Noun” naming convention and also use common parameters.
Note: not all cmdlets use these parameters. However, because the PowerShell engine interprets the
parameter (not the cmdlet), each common parameter is enacted in the same fashion. Below is a list
of the Common 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.

To view common and other parameters available to the “Set-ExecutionPolicy” cmdlet, type the
following at the command prompt:

→ Ps C:\Set-ExecutionPolicy -<tab>

Use the “Get-Help” cmdlet for information on parameters available to a cmdlet. Continuing to use
the “Set-ExectutionPolicy” cmdlet, let’s get-help:

→ Ps C:\Get-Help Set-ExecutionPolicy -Full

In this example, let’s use the -whatif parameter to see “what would happen” if we used the “Set-
ExecutionPolicy” cmdlet:
→ Ps C:\Set-ExecutionPolicy Unrestricted -whatif

Using the same cmdlet, choose the -confirm parameter to prompt before executing:
→ Ps C:\Set-ExecutionPolicy Unrestricted -confirm
Are you sure you want to perform this action?
[Y] Yes (Default is “Y”)
[A] Yes to All
[N] No
[L] No to All
[S] Suspend
[?] Help

Introduction to Objects
Properties and Methods of the “Get-Service” cmdlet.

Type the following to view the properties and methods of the “Get-Service” cmdlet. In this
example, the output of “Get-Service” (object) is piped into the “Get-Member” cmdlet.
→ Ps C:\Get-Service | Get-Member

Getting Properties of the “Get-Service” cmdlet.
In this example we refine our search to display
only properties by using the -MemberType parameter.
→ Ps C:\Get-Service | Get-Member -MemberType Property
Getting Methods of the “Get-Service” cmdlet.
→ Ps C:\Get-Service | Get-Member -MemberType Method
Report of all files that were created in the last day.
→ Ps C:\Get-ChildItem -Path C:\ -Recurse | Where-Object {$_.LastWriteTime -gt “01/01/2014″}

We call the “Get-ChildItem” cmdlet because we want to enumerate the file system.
-Path parameter points to the root of C:\ drive as the starting point. The -Recurse parameter means
we want all subdirectories and files enumerated.
The object returned from the “Get-ChildItem” cmdlet is piped into a script block.
Where-Object is a looping statement which finds each object that matches the criteria we are
looking for.

What is “LastWriteTime”? Type the following command:


→ Ps C:\Get-ChildItem | Get-Member

Formatting output
→ Ps C:\Get-Command Format-*

Format-Custom


Format-List
→ Ps C:\Get-ChildItem C:\Windows | Format-List
→ Ps C:\Get-ChildItem C:\Windows | Format-List -Property FullName
→ Ps C:\Get-ChildItem C:\Windows -Recurse | Format-List -Property
FullName,CreationTime,LastWriteTime


Format-Table
→ Ps C:\Get-ChildItem C:\Windows | Format-Table
→ Ps C:\Get-ChildItem C:\Windows | Format-Table -AutoSize


Format-Wide
→ Ps C:\Get-ChildItem C: | Format-Wide
→ Ps C:\Get-ChildItem C: | Format-Wide -Column 3

Group-Object
If we want to collect info in groups.
→ Ps C:\Get-Process | Group-Object Company
→ Ps C:\Get-EventLog System | Group-Object eventid

Sort-Object
If we want to sort the output.
→ Ps C:\Get-EventLog System | Group-Object eventid | Sort-Object Count -descending

Convertto-HTML
→ Ps C:\Get-Process | ConvertTo-html
→ Ps C:\Get-Process | ConvertTo-html | out-file “Processes.html”
→ Ps C:\Invoke-Item Processes.html

Export-CSV
If we want to export the output to csv format.
→ Ps C:\Get-Process | Export-CSV Processes.csv
→ Ps C:\Invoke-Item Processes.csv

Powershell providers
PowerShell Providers are .NET programs that allow us to work with data stores as if they were
mounted drives. This simplifies accessing external data outside the PowerShell environment. For
example, we can access the registry as if it were a file system. This translates to being able to use
the same cmdlets as working with files and folders, which are shown in the table below.

Cmdlet Alias Cmd Commands Descritption


Get-Location gl pwd Current Directory.
Change current
Set-Location sl cd, chdir
directory.
Copy-Item cpi copy Copy Files.
Removes a File or
Remove-Item ri del
directory.
Move-Item mi move Move a file.
Rename-Item rni rn Rename a file.
Creates a new empty
New-Item ni n/a
file or folder.
Clears the contents of
Clear-Item cli n/a
a file.
Set the contents of a
Set-Item si n/a
file.
Creates a new
Mkdir n/a md
directory.
Sends contents of a
Get-Content gc type file to the output
stream.
Set the contents of a
Set-Content sc n/a
file.

If we want to retrieve all the powershell providers:


→ Ps C:\Get-PSProvider

PowerShell Drive “PSDrive”


Using the “Get-PSProvider” cmdlet, we obtain a list of available PowerShell Providers:
→ Ps C:\Get-PSDrive

The PowerShell Alias Provider


The Alias Provider enables access to all the aliases in PowerShell
→ Ps C:\Set-Location Alias:
Now we are in PS Alias:\>
The Alias Provider enables access to all the aliases in PowerShell
View a list of aliases:
→ Ps C:\Get-ChildItem
Members and methods:
→ Ps C:\Get-ChildItem | Get-Member
Aliases starting winh R:
G→ Ps C:\et-ChildItem -Name R*
or
→ Ps C:\Get-ChildItem | Where-Object {$_.name -like “R*”}

The PowerShell Environment Provider


System Properties -> Advanced Tab -> Click the “Environment Variables” button.
Get list of available PowerShell Providers.
→ Ps C:\Get-PSDrive
Map PSDrive to Environment Provider.
→ Ps C:\Set-Location env:
Get listing of Environment Variables.
→ Ps C:\Get-ChildItem
Output the value of the “OS” variable.
→ Ps C:\Get-ChildItem OS
Output all properties for the “OS” variable.
→ Ps C:\Get-ChildItem OS | Format-List *
Create a new variable using the “New-Item” cmdlet. Let’s call the new variable “MyVariable” and
give it a value of “This is my new variable.” The Path argument will be a dot (.) meaning current
location, which would be “env:
→ Ps C:\New-Item -Path . -Name MyVariable -Value “This is my new variable”
Removing the Environment Variable
→ Ps C:\Remove-Item MyVariable

PowerShell File System Provider


The File System Provider allows you to create, retrieve, and remove files and folders. Also, the File
System Provider allow you to modify files by either appending or overwritting data.
Listing Files and Directories
Connect to the File System Provider.
→ Ps C:\Set-Location C:\
List Files and Directories under the root of C: Drive.
→ Ps C:\Get-ChildItem
List Files and Directories including sub-direcories.
→ Ps C:\Get-ChildItem -Recurse

Cmdlet Alias Cmd Commands Descritption


Get-Location gl pwd Current Directory.
Change current
Set-Location sl cd, chdir
directory.
Copy-Item cpi copy Copy Files.
Removes a File or
Remove-Item ri del
directory.
Move-Item mi move Move a file.
Rename-Item rni rn Rename a file.
Creates a new empty
New-Item ni n/a
file or folder.
Clears the contents of
Clear-Item cli n/a
a file.
Set the contents of a
Set-Item si n/a
file.
Creates a new
Mkdir n/a md
directory.
Sends contents of a
Get-Content gc type file to the output
stream.
Set the contents of a
Set-Content sc n/a
file.
PowerShell Function Provider
PowerShell has a set of Functions specified in the PowerShell engine.
Listing Functions
→ Ps C:\Set-Location Function:
→ Ps C:\Get-ChildItem

We are going to use the “Get-Content” cmdlet to view the code block of the Clear-Host Function.
→ Ps C:\Get-Content Clear-Host

The PowerShell Registry Provider


Navigate the registry.
Search the registry.
Create new registry keys.
Delete registry keys.
Add new values.
Modify existing values.
Manage ACLs (Access Control Lists).

The two PSDrives we can connect to are HKLM and HKCU. Verify this by checking which
PSDrives are available.
→ Ps C:\Get-PSDrive
→ Ps C:\Set-Location HKLM:
→ Ps C:\Set-Location HKLM:\Software
→ Ps C:\Get-ChildItem

Cmdlet Alias Cmd Commands Descritption


Get-Location gl pwd Current Directory.
Change current
Set-Location sl cd, chdir
directory.
Copy-Item cpi copy Copy Files.
Removes a File or
Remove-Item ri del
directory.
Move-Item mi move Move a file.
Rename-Item rni rn Rename a file.
Creates a new empty
New-Item ni n/a
file or folder.
Clears the contents of
Clear-Item cli n/a
a file.
Set the contents of a
Set-Item si n/a
file.
Creates a new
Mkdir n/a md
directory.
Sends contents of a
Get-Content gc type file to the output
stream.
Set the contents of a
Set-Content sc n/a
file.
Example of using the “Get-ChildItem” cmdlet to list DNS server Zone properties:
→ Ps C:\Get-ChildItem -Path “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\DNS
Server\Zones”

The PowerShell Variable Provider


Connect to the PSDrive Variable: and Show a List of Available Variables
Connect to the PSDrive.
→ Ps C:\Set-Location Variable:
→ Ps C:\Get-ChildItem

List the Information in the PSHome Variable


→ Ps C:\$PSHome

Create a User Defined Variable


→ Ps C:\New-Item MyVar -Value “This is my new variable.”
You can also use the “Set-Variable” cmdlet to accomplish the same:
→ Ps C:\Set-Variable MyVar2 -Value “This is my second variable.”
This last example is most commonly used when scripting. You will find yourself using this example
more than the others:
→ Ps C:\$MyVar3 = “This is my third variable.”
Let’s sort the listing of variables by name and verify our newly created variables exist.
→ Ps C:\Get-ChildItem | Sort {$_.Name}

Use the “Remove-Item” cmdlet to remove the variables we created:


→ Ps C:\Remove-Item MyVar,MyVar2,MyVar3

The PowerShell Certificate Provider


Set Location to the Cert PSDrive and List all the Certificates on the System
→ Ps C:\Set-Location cert:
→ Ps C:\Get-ChildItem

If you want a report of all certificates on a system:


→ Ps C:\Get-ChildItem -Recurse | Export-CSV “C:\Certificates.csv”
View results:
→ Ps C:\Invoke-Item “C:\Certificates.csv”

Powershell Scripting

Variables, Arrays, and Hash Tables


Variables – allows us to store single bits of information.
Arrays – allows us to store information in an index.
Hash Table – allows us to store in key-value pairs.

PowerShell Variables
In PowerShell, variables can contain text strings, integers, and even objects
Special Variable Examples
$_ – 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.
$Error – Contains objects for which an error occurred while being processed in a cmdlet.
$Home – Specifies the user’s home directory.
$PsHome – The directory where the Windows PowerShell is installed.
To view the complete list of Special Variables in PowerShell, type the following:
→ Ps C:\Get-Help about_automatic_variables

In PowerShell, ALL variable names must start with the “$” character. Once data is assigned to a
PowerShell variable, it’s automatically declared. The “=” operator is used to assign data to a
variable.
→ Ps C:\$strComputer = “Computer1″
There is a “Set-Variable” cmdlet that can also be used:
→ Ps C:\Set-Variable -Name strUser -Value “Usuario”

Verify that the $strUser variable is holding the data we assigned to it.
→ Ps C:\Write-Output $strUser
-or just type-
→ Ps C:\$strUser

Type Description
[int] 32-bit signed integer
[long] 64-bit signed integer
[string] Fixed-length string of Unicode characters
[char] A Unicode 16-bit character
[byte] An 8-bit unsigned character
[bool] Boolean True/False value
[decimal] An 128-bit decimal value
Single-precision 32-bit floating point
[single]
number
Double-precision 64-bit floating point
[double]
number
[xml] Xml object
[array] An array of values
[hashtable] Hashtable object

String Concatenation
Concatenation is the process of joining together two strings. Here is an example:
→ Ps C:\$strA = “Hello “
→ Ps C:\$strB = “World!”
→ Ps C:\$strC = $strA += $strB
→ Ps C:\$strC

Aside from joining strings we can also replace words using the -replace parameter.
→ Ps C:\$strA = “Cadena nueva”
→ Ps C:\$strB = $strA -replace “nueva”, “vieja”
→ Ps C:\$strB

Working with Numbers


Assigning integer and decimal values are simple:
→ Ps C:\$x = 1
→ Ps C:\$y = 1.2
→ Ps C:\$x
→ Ps C:\$y
Though it is not required, it is considered good form to assign the data type of a variable.
→ Ps C:\[string]$strComputer = “MyFileServer01″
→ Ps C:\[int]$x = 9
→ Ps C:\[decimal]$y = 9.9

PowerShell Operators
= Assigns a value to a variable.
+ or += Addition.
- or -= Subtraction.
* or *= Multiplication.
/ or /= Division.
% or %= Modulus (retrieves the remainder of a division operation).

→ Ps C:\$x = 10 * 2 / 5 * 2 + 5 * 5
→ Ps C:\$x

→ Ps C:\$x = 1
→ Ps C:\$x
→ Ps C:\1
→ Ps C:\$x++
→ Ps C:\$x
→ Ps C:\2
→ Ps C:\$x++
→ Ps C:\$x
→ Ps C:\3
→ Ps C:\$x--
→ Ps C:\$x
→ Ps C:\2

PowerShell Arrays
To create an array, we create a variable and assign the array. Arrays are noted by the “@” symbol.

→ Ps C:\$strComputers = @(“Server1″, “Server2″, “Server3″)

List the values in the array:


→ Ps C:\$strComputers

List the number of items within the array using the count property.
→ Ps C:\$strComputers.Count
List values by their index number:
→ Ps C:\$strComputers[0]
→ Ps C:\$strComputers[1]
→ Ps C:\$strComputers[2]

→ Ps C:\$strComputers[2] = “Server4″

Verify the element was modified:


→ Ps C:\$strComputers

Using the + operator, we can combine arrays:


→ Ps C:\$x = @(1, 2, 3, 4, 5)
→ Ps C:\$y = @(6, 7, 8, 9, 10)
→ Ps C:\$z = $x + $y
→ Ps C:\$z

Example: Copy this code in a file and try to run it.


To run a script: .\script.ps1

$strComputer = “.”

$colItems = get-wmiobject -class Win32_BIOS -namespace root\CIMV2 -comp $strComputer


foreach ($objItem in $colItems) {

write-host “BIOS Characteristics: ” $objItem.BiosCharacteristics

write-host “BIOS Version: ” $objItem.BIOSVersion

write-host “Build Number: ” $objItem.BuildNumber

write-host “Caption: ” $objItem.Caption

write-host “Code Set: ” $objItem.CodeSet

write-host “Current Language: ” $objItem.CurrentLanguage

write-host “Description: ” $objItem.Description

write-host “Identification Code: ” $objItem.IdentificationCode

write-host “Installable Languages: ” $objItem.InstallableLanguages

write-host “Installation Date: ” $objItem.InstallDate

write-host “Language Edition: ” $objItem.LanguageEdition

write-host “List Of Languages: ” $objItem.ListOfLanguages

write-host “Manufacturer: ” $objItem.Manufacturer

write-host “Name: ” $objItem.Name

write-host “Other Target Operating System: ” $objItem.OtherTargetOS

write-host “Primary BIOS: ” $objItem.PrimaryBIOS

write-host “Release Date: ” $objItem.ReleaseDate

write-host “Serial Number: ” $objItem.SerialNumber

write-host “SMBIOS BIOS Version: ” $objItem.SMBIOSBIOSVersion

write-host “SMBIOS Major Version: ” $objItem.SMBIOSMajorVersion

write-host “SMBIOS Minor Version: ” $objItem.SMBIOSMinorVersion

write-host “SMBIOS Present: ” $objItem.SMBIOSPresent

write-host “Software Element ID: ” $objItem.SoftwareElementID

write-host “Software Element State: ” $objItem.SoftwareElementState

write-host “Status: ” $objItem.Status

write-host “Target Operating System: ” $objItem.TargetOperatingSystem

write-host “Version: ” $objItem.Version
write-host
}

Hash Tables
A Hash table is also known as a dictionary. It is an array that allows you to store data in a “key-
value” pair association. The “key” and “value” entries can be any data type and length. The
elements must be quoted if they contain a space.

Creating a hash of users associated with their employee number:


→ Ps C:\$EmpNumbers = @{“John” = 112233; “Dave” = 223344; “Justine” = 334455}

Add a new employee record:


→ Ps C:\$EmpNumbers["Rose Jones"] = 445566

Delete an employee record:


→ Ps C:\$EmpNumbers.Remove(“Rose Jones”)
To find a employee number:
→ Ps C:\$EmpNumbers["John"]

To Remove all records in the hash table, we use the clear method:
→ Ps C:\$EmpNumbers.Clear()

Conditional Logic (if, elseif, else, and switch)

PowerShell Comparison Operators:

Operator Description
-eq Equal to
-lt Less than
-gt Greater than
-ge Greater than or Eqaul to
-le Less than or equal to
-ne Not equal to

Examples:

Tom -eq TOM The result is "True"

Tom -ieq TOM The result is "True"

Tom -ceq TOM. The result is "False"

PowerShell Logical Operators:

Operator Description
-not Not
! Not
-and And
-or Or

Conditional Logic
if (condition) {code block}

elseif (condition) {code block}
else (condition) {code block}

example:
Copy this code into a file and execute it:
x = 2 #creates a variable x and assigns 2 as the value

if ($x -eq 5) {Write-Host "Hello my name is Juan"}

elseif ($x -eq 4) {Write-Host "Hello, my name is María"}

elseif ($x -eq 2) {Write-Host "Hello, my name is Lucas"}

elseif ($x -gt 1) {Write-Host "Hello, my name is Teresa"}

else {"I have no idea what my name is?"}
The name will be Lucas

Copy the following code into a .ps1 script file. Name it PrintReport.ps1 and execute the script.

$strComputer = Read-Host "Printer Report – Enter Computer Name"



$OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" `

-ComputerName $strComputer
# if statement to run code for Windows 7 and Windows 2012 Server.

if (($OS.Version -eq "6.2.9200") -or ($OS.Version -eq "6.1.7600"))

{
write-host "Computer Name: " $strComputer

#nested if statement

if ($OS.Version -eq "6.2.9200") {write-host "OS Version: Windows 2012 SERVER"}

elseif ($OS.Version -eq "6.1.7600") {write-host "OS Version: Windows 7"}

$colPrinters = Get-WmiObject -Class win32_Printer -namespace
"root\CIMV2" `


-computerName $strComputer

foreach ($objPrinter in $colPrinters) {

write-host "Name: " $objPrinter.Name

write-host "Description: " $objPrinter.Description

write-host
}
}

# if statement to run code for Windows 2008 Server



elseif ($OS.Version -eq "6.0.6001")
{

write-host "Computer Name: " $strComputer

write-host "OS Version: Windows 2003 SERVER"

$colPrinters = Get-WmiObject -Class win32_PrintJob -namespace "root\CIMV2" `

-computername $strComputer

foreach ($objPrinter in $colPrinters) {

write-host "Name: " $objPrinter.Name

write-host "Description: " $objPrinter.Description

write-host}

}

# if OS not identified

else {write-host "The OS for: $strComputer is not supported."}

write-host "–END OF REPORT–"

When the script is executed, you are prompted to enter the computer name you wish to enumerate.
By adding the "Read-Host" cmdlet, you're now able to enumerate other computers on your network.

Using the Switch Statement for Multiple Comparisons


The Switch statement syntax:
switch (expression)
{

(test) {code block}

value {code block}

default {code block}

}

Example:
$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2"

"Computer "+ $objWMI.name + " is a: "
switch ($objWMI.domainRole)

{

0 {Write-Host "Stand alone workstation"}

1 {Write-Host "Member workstation"}

2 {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 can not be determined"}

}

Conditional Logic Using Loops


do while - Script block executes as long as condition value = True.
while - Same as “do while.”
do until – Script block executes until the condition value = True.
for – Script block executes a specified number of times.
foreach - Executes script block for each item in a collection or array.

do while and while

Syntaxes:

do while

do
{code block}

while (condition)
while

while (condition)
{code block}

Example: do while – Count to 5


$i = 1
do {Write-Host $i; $i++}
while ($i -le 5)
or
$i = 1
do {

Write-Host $i

$i++
}


while ($i -le 5)

Example: Monitor Notepad and report any failure and log the time the failure occurred.
#launches Notepad
Notepad
#Setup a do while loop that does nothing while property value is True.

do {}

While (get-process notepad | select -Property Responding)
#Code to run when loop stops (when notepad is closed)

$strTime = get-date

Write-Host “The Application Notepad failed to respond on: $strTime”

do until
Syntax:

do
{code block}

until (condition)

Example:
$i = 1
do {Write-Host $i; $i++}

until ($i -gt 5)
The do until loop to control the collection of user input

$strResponse = “Quit”
do {$strResponse = Read-Host “Are you sure you want to quit application? (Y/N)”}

until ($strResponse -eq “Y”)

for
Syntax:

for (initialization; condition; repeat)

{code block}
Example:
for ($i=1; $i -le 5; $i++)
{Write-Host $i}

The for loop can also be used to process elements within an array.
$ints = @( 1, 2, 3, 4, 5)
for ($i=0; $i -le $ints.Length – 1; $i++)

{Write-Host $ints[$i]}

foreach
Syntax:

foreach ($<item> in $<collection>)

{code block}
Example:

$ints = @(1, 2, 3, 4, 5)
foreach ($i in $ints)
{Write-Host $i}

How about listing processor information.


$strComputer = “.”
$colItems = get-wmiobject -class “Win32_Processor” -namespace “root\CIMV2″ `

-computername $strComputer
foreach ($objItem in $colItems) {

write-host “Caption: ” $objItem.Caption

write-host “CPU Status: ” $objItem.CpuStatus

write-host “Current Clock Speed: ” $objItem.CurrentClockSpeed

write-host “Device ID: ” $objItem.DeviceID

write-host “L2 Cache Size: ” $objItem.L2CacheSize

write-host “L2 Cache Speed: ” $objItem.L2CacheSpeed

write-host “Name: ” $objItem.Name
write-host
}

We want to determine which processes are running on our computer.

foreach ($item in Get-Process)


{if ($item.Responding -eq “True”){Write-Host $Item.Name}}

The Break Statement


for($i=1; $i -le 10; $i++)

{

Write-Host $i

break

}
$i=0

$varB = (10,20,30,40)

foreach ($var in $varB)
{
$i++
if ($var -eq 30)
{

break

}
}


Write-Host “30 was found in array position $i”

The Continue Statement


In a script, the continue statement causes program flow to move immediately to the top of the
innermost loop controlled by any of these statements:

· for
· foreach
· while

while ($ctr -lt 10)



{

$ctr += 1

if ($ctr -eq 5)
{continue}

Write-Host $ctr
}


Functions and Filters


Function Syntax:
Function(keyword) FunctionName (parameters) {script block}
The syntax uses the keyword Function, a FunctionName you provide, optional parameters, and the
script block.

Example . Create a Function called “Time” which runs the Get-Date cmdlet when called.
→ Ps C:\Function Time {Get-Date}

Passing Arguments to Functions


Method 1: Passing Arguments in a comma separated list. Notice that the parameters enclosed in
parenthesis and separated by a comma, much like an array.

Function Add ($x, $y)


{
$Ans = $x + $y
Write-Host “The Answer is $Ans”
}

Method 2: Using the Param keyword. When using the Param keyword, notice that we are defining
the arguments within the scriptblock {}. The Param keyword must be the first word inside the
script block.
Function Add
{
param ($x, $y)

$Ans = $x + $y

Write-Host “The Answer is $Ans”

}

Method 3: There is a special variable $Args which contains an array of the parameters passed to a
function. Let’s use this variable to show how we can pass an argument using string expantion.
Function HAL {“What are you doing $args ?”}

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

Assigning a Default Value


We can also assign a default value should an argument not get passed to the function.

Function Add
{
Param ([int]$x = 0, [int]$y = 0)
$Ans = $x + $y

Write-Host $Ans
}


Using the PowerShell Special Variable “$input”

The $input variable allows a function to access data coming from the pipeline. For example let’s
say were looking for the folder “Windows” and we don’t know where it is located.
First build the function to find the Windows Folder:

Function FindFolder
{
$input | Where-Object {$_.Name -eq “Windows”}
}

Next Type the following command which pipes the cmdlet output to the function we defined:
→ Ps C:\Get-ChildItem -Path C:\ | FindFolder

In this example we will use a filter to find the Hosts file on a system.
Create the Function:

Function FindHosts
{
$input | Where-Object {$_.Name -eq “hosts”}
}
→ Ps C:\Get-ChildItem -Path C:\ -Recurse | FindHosts

PowerShell Filters

A Filter and a Function are essentially the same. The difference is how they process data.
Filter Syntax:
Filter(Keyword) FilterName (parameters) {Script Block}
Executing scripts:
Dot Source (Calling Scripts and Functions)
Essentially, “dot-source” means using dot-notation to call script blocks, functions, and/or aliases
from within your script. We’re going to use the same script examples above, but instead of calling
the function written within the script, we will use dot-notation to call scripts that exists outside the
main script. The syntax used for dot-notation and script-blocks is:
.{}

To call my script:
.{.\my_script.ps1}

PowerShell Scripting with WMI


Scripting with Windows Management Instrumentation (WMI) – Properties

WMI is basically a database of information maintained on each Windows system. We connect to the
WMI Service to query information maintained in the database. To visually see WMI on your system
do the following:
Open “Computer Management” from Administrative Tools.
Expand “Services and Applications.”
Right-click “WMI Control” and choose Properties.
Click on the Advanced Tab.
Notice: Default namespace for scripting by default set to root/cimv2.

Using PowerShell to Find Classes, Properties, and Methods.


List the available Classes on the local machine
→ Ps C:\Get-WmiObject -List -Namespace “root\CIMV2″

List the available Classes on a remote machine


→ Ps C:\Get-WmiObject -List -Namespace “root\CIMV2″ -ComputerName
TypeComputerNameHere

List the Properties and Methods of a WMI Class.


Let’s get the properties and methods using the “Get-Member” cmdlet.
→ Ps C:\Get-WmiObject -Class “Win32_Processor” -Namespace “root\CIMV2″ | Get-Member

Scripting with WMI


We want to get all the hardware data of all the servers on our network, with all these data:
Machine manufacturer, model number, and serial number.
BIOS information to determine if updates are required,
OS type
CPU information: Manufacturer, type, speed, and version.
Amount of memory in each server.
Disk information: Size, interface type, and media type.
Network Information: IP settings and MAC address.

Get-WmiObject syntax:
Get-WmiObject -Class [classname] -NameSpace [namespace] -ComputerName [ComputerName]

Here is the script structured in functions:


#* FileName: ServerInventory.ps1

Function SysInfo {
$colItems = Get-WmiObject Win32_ComputerSystem -Namespace “root\CIMV2″ `

-ComputerName $strComputer
foreach($objItem in $colItems) {

Write-Host “Computer Manufacturer: ” $objItem.Manufacturer

Write-Host “Computer Model: ” $objItem.Model

Write-Host “Total Memory: ” $objItem.TotalPhysicalMemory “bytes”
}
}

Function BIOSInfo {
$colItems = Get-WmiObject Win32_BIOS -Namespace “root\CIMV2″ -computername
$strComputer

foreach($objItem in $colItems) {

Write-Host “BIOS:”$objItem.Description

Write-Host “Version:”$objItem.SMBIOSBIOSVersion”.”`

$objItem.SMBIOSMajorVersion”.”$objItem.SMBIOSMinorVersion

Write-Host “Serial Number:” $objItem.SerialNumber
}
}

Function OSInfo {
$colItems = Get-WmiObject Win32_OperatingSystem -Namespace “root\CIMV2″`

-Computername $strComputer
foreach($objItem in $colItems) {

Write-Host “Operating System:” $objItem.Name
}
}

Function CPUInfo {
$colItems = Get-WmiObject Win32_Processor -Namespace “root\CIMV2″`

-Computername $strComputer
foreach($objItem in $colItems) {

Write-Host “Processor:” $objItem.DeviceID $objItem.Name
}
}


Function DiskInfo {
$colItems = Get-WmiObject Win32_DiskDrive -Namespace “root\CIMV2″`

-ComputerName $strComputer
foreach($objItem in $colItems) {

Write-Host “Disk:” $objItem.DeviceID

Write-Host “Size:” $objItem.Size “bytes”

Write-Host “Drive Type:” $objItem.InterfaceType

Write-Host “Media Type: ” $objItem.MediaType
}
}

Function NetworkInfo {
$colItems = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace “root\CIMV2″`

-ComputerName $strComputer | where{$_.IPEnabled -eq “True”}
foreach($objItem in $colItems) {

Write-Host “DHCP Enabled:” $objItem.DHCPEnabled

Write-Host “IP Address:” $objItem.IPAddress

Write-Host “Subnet Mask:” $objItem.IPSubnet

Write-Host “Gateway:” $objItem.DefaultIPGateway

Write-Host “MAC Address:” $ojbItem.MACAddress
}
}

#* SCRIPT BODY

#* Connect to computer

$strComputer = “.”
#* Call SysInfo Function

Write-Host “Sytem Information”
SysInfo
Write-Host
#* Call BIOSinfo Function

Write-Host “System BIOS Information”
BIOSInfo
Write-Host
#* Call OSInfo Function

Write-Host “Operating System Information”
OSInfo
Write-Host
#* Call CPUInfo Function

Write-Host “Processor Information”
CPUInfo
Write-Host
#* Call DiskInfo Function

Write-Host “Disk Information”
DiskInfo
Write-Host
#* Call NetworkInfo Function

Write-Host “Network Information”
NetworkInfo
Write-Host
#* END OF SCRIPT: [ServerInventory]


Modifications that we can apply on this script:


If we want to connect to a remote computer:
#* Connect to computer

$strComputer = “ComputerName”

If we want the computer to be prompted to the user:


$strComputer = Read-Host “Enter Computer Name”

Write-Host “Computer:” $strComputer

Use an array to gather information from multiple computers


The servers name are in a file
$arrComputers = get-Content -Path “C:\MyScripts\Computers.txt”
foreach ($strComputer in $arrComputers)
…...

Scripting with Windows Management Instrumentation (WMI) – Creating Reports

We will use an edited version of the List BIOS Information script found in the Microsoft Scripting
Repository.
Here is the code adapted:

$strComputer = “.”

$colItems = get-wmiobject -class “Win32_BIOS” -namespace “rootCIMV2″ `



-computername $strComputer
foreach ($objItem in $colItems) {

“BIOS Version: ” + $objItem.BIOSVersion

“Description: ” + $objItem.Description

“Status: ” + $objItem.Status
“Version: ” + $objItem.Version
” ”
}
Then run it redirecting its output to a text file:

.BIOS.ps1 >> “C:MyScriptsBios.txt”


or
.BIOS.ps1 | Out-File -Filepath “C:MyScriptsBios.txt” -append

Output results to an Excel spreadsheet

$strComputer = “.”

$Excel = New-Object -Com Excel.Application



$Excel.visible = $True
$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.WorkSheets.Item(1)

$Sheet.Cells.Item(1,1) = “Computer”

$Sheet.Cells.Item(1,2) = “Drive Letter”

$Sheet.Cells.Item(1,3) = “Description”

$Sheet.Cells.Item(1,4) = “FileSystem”

$Sheet.Cells.Item(1,5) = “Size in GB”

$Sheet.Cells.Item(1,6) = “Free Space in GB”
$WorkBook = $Sheet.UsedRange

$WorkBook.Interior.ColorIndex = 8

$WorkBook.Font.ColorIndex = 11
$WorkBook.Font.Bold = $True
$intRow = 2

$colItems = Get-wmiObject -class “Win32_LogicalDisk” -namespace “root\CIMV2″ `

-computername $strComputer
foreach ($objItem in $colItems) {

$Sheet.Cells.Item($intRow,1) = $objItem.SystemName

$Sheet.Cells.Item($intRow,2) = $objItem.DeviceID

$Sheet.Cells.Item($intRow,3) = $objItem.Description

$Sheet.Cells.Item($intRow,4) = $objItem.FileSystem

$Sheet.Cells.Item($intRow,5) = $objItem.Size / 1GB

$Sheet.Cells.Item($intRow,6) = $objItem.FreeSpace / 1GB
$intRow = $intRow + 1
}

$WorkBook.EntireColumn.AutoFit()

Clear

Managing Active Directory with Windows PowerShell

The Active Directory Name Space


As a systems administrator you need to be familiar with the following terms:

Active Directory Hierarchical structure


LDAP Distinguished Name (DN) – CN=John Martin,OU=Sales,DC=DomainName,DC=com
LDAP Relative Distinguished Name (RDN) – John Martin
Common Name (CN) – John Martin
Canonical Name version one – DC=com/DC=DomainName/OU=Sales/CN=John Martin
Canonical Name version two – DomainName.com/Sales/John Martin
User Principal Name (UPN) – John.Martin@DomainName.com
Down level Name (SAM Account) – DomainName\jmartin -or- jmartin
Creating an Organizational Unit
$Class = “organizationalUnit”
$OU = “OU=TestOU”

$objADSI = [ADSI]“LDAP://DC=midominio,DC=com”

$objOU = $objADSI.create($Class, $OU)

$objOU.setInfo()

Creating a User Account


$Class = “User”
$strUserName = “CN=Juan Fuentes”

$objADSI = [ADSI]“LDAP://OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”

$objUser = $objADSI.Create($Class, $strUserName)

$objUser.Put(“sAMAccountName”, “jfuentes”)

$objUser.setInfo()

Modifying the User Account


$objUser = [ADSI]“LDAP://CN=Juan
Fuentes,OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”
$objUser.put(“givenName”, “Juan”)
$objUser.put(“initials”, “D.”)
$objUser.put(“sn”, “Fuentes”)
$objUser.put(“DisplayName”, “Fuentes, Juan”)
$objUser.put(“description”, “IT Manager”)
$objUser.put(“PhysicalDeliveryOfficeName”, “Building 44 suite 195″)
$objUser.put(“telephoneNumber”, “555-555-5555″)
$objUser.put(“mail”, “juanfuentes@midominio.com“)
$objUser.setInfo()

User Access Control Flags

Ads Constant Hex Value Decimal Value


ADS_UF_SCRIPT 0x0001 1
ADS_UF_ACCOUNTDISAB
0x0002 2
LE
ADS_UF_HOMEDIR_REQU
0x0008 8
IRED
ADS_UF_LOCKOUT 0x0010 16
ADS_UF_PASSWD_NOTRE
0x0020 32
QD
ADS_UF_PASSWD_CANT_
0x0040 64
CHANGE
ADS_UF_ENCRYPTED_TE 0x0080 128
XT_PASSWORD_ALLOWE
D
ADS_UF_TEMP_DUPLICAT
0x0100 256
E_ACCOUNT
ADS_UF_NORMAL_ACCO
0x0200 512
UNT
ADS_UF_INTERDOMAIN_
0x0800 2048
TRUST_ACCOUNT
ADS_UF_WORKSTATION_
0x1000 4096
TRUST_ACCOUNT
ADS_UF_SERVER_TRUST_
0x2000 8192
ACCOUNT
ADS_UF_DONT_EXPIRE_P
0x10000 65536
ASSWD
ADS_UF_MNS_LOGON_A
0x20000 131072
CCOUNT
ADS_UF_SMARTCARD_RE
0x40000 262144
QUIRED
ADS_UF_TRUSTED_FOR_
0x80000 524288
DELEGATION
ADS_UF_NOT_DELEGATE
0x100000 1048576
D
ADS_UF_USE_DES_KEY_
0x200000 2097152
ONLY
ADS_UF_DONT_REQUIRE
0x400000 4194304
_PREAUTH
ADS_UF_PASSWORD_EXP
0x800000 8388608
IRED
ADS_UF_TRUSTED_TO_A 0x1000000 16777216
UTHENTICATE_FOR_DEL
EGATION

Modify User Account Control (Enable the Account)

$objUser = [ADSI]“LDAP://CN=Juan
Fuentes,OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”
$objUser.put(“userAccountControl”, 544)
$objUser.SetInfo()

Deleting a User Account


$Class = “User”
$strUserName = “CN=Juan Fuentes”
$objADSI = [ADSI]“LDAP://OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”

$objUser = $objADSI.Delete($Class, $strUserName)

$objUser.setInfo()

Interaction with users.


Create users from interactive script:

Write-Host “Introduce los datos del usuario que vas a crear en el Dominio”

# Set Variables from User Input



$FirstName = Read-Host “Nombre Usuario”

$LastName = Read-Host “Apellido Usuario”

$DisplayName = ($LastName + “, ” + $FirstName)

$Office = Read-Host “Localidad”

$Phone = Read-Host “Teléfono”

$CN = (“CN=” + $FirstName + ” ” + $LastName)

$Class = “User”

$strUserName = $CN
#connect to AD and create user

$objADSI = [ADSI]“LDAP://OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”

$objUser = $objADSI.Create($Class, $strUserName)

$objUser.Put(“SAMAccountName”, $FirstName)
# Commit the object in AD
$objUser.setInfo()
#Set General Tab Properties

#Bind to the user Object

$objADSI = [ADSI]“LDAP://$CN,OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”

$objUser.Put(“givenName”, “$firstName”)

$objUser.Put(“SN”, “$LastName”)

$objUser.Put(“DisplayName”, “$DisplayName”)

$objUser.Put(“PhysicalDeliveryOfficeName”, “$office”)

$objUser.Put(“telephoneNumber”, “$phone”)
#set UserAccessControl

$objUser.put(“userAccountControl”, 544)
#Commit changes

$objUser.setInfo()

Searching Active Directory


Report of all AD accounts with the password set “Not to Expire.”

$Search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”)


$Search.filter = “(&(objectClass=user)(userAccountControl:1.2.840.113556.1.4.803:=65536))”
$results = $Search.Findall()

Foreach($result in $results){

$User = $result.GetDirectoryEntry()
$user.DistinguishedName
}

To get a list of all users in a specific OU.


$ADsPath = [ADSI]“LDAP://OU=Disabled Accounts,DC=midominio,DC=com”
$Search = New-Object DirectoryServices.DirectorySearcher($ADsPath)
$Search.filter = “(objectClass=user)”
$Search.PageSize = 1000
$Search.SearchScope = “OneLevel” $results = $Search.Findall()

Foreach($result in $results){

$User = $result.GetDirectoryEntry()
$user.DistinguishedName
}

Vous aimerez peut-être aussi