Escolar Documentos
Profissional Documentos
Cultura Documentos
http://www.powershellpro.com/powershell-tutorial-introduction/
PowerShell Concepts
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
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
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:
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.
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.
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 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
Powershell Scripting
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
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.
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″
$strComputer = “.”
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.
To Remove all records in the hash table, we use the clear method:
→ Ps C:\$EmpNumbers.Clear()
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"
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.
-computerName $strComputer
foreach ($objPrinter in $colPrinters) {
write-host "Name: " $objPrinter.Name
write-host "Description: " $objPrinter.Description
write-host
}
}
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.
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"}
}
Syntaxes:
do while
do
{code block}
while (condition)
while
while (condition)
{code block}
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}
· for
· foreach
· while
Example . Create a Function called “Time” which runs the Get-Date cmdlet when called.
→ Ps C:\Function Time {Get-Date}
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
{
Param ([int]$x = 0, [int]$y = 0)
$Ans = $x + $y
Write-Host $Ans
}
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}
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.
Get-WmiObject syntax:
Get-WmiObject -Class [classname] -NameSpace [namespace] -ComputerName [ComputerName]
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]
We will use an edited version of the List BIOS Information script found in the Microsoft Scripting
Repository.
Here is the code adapted:
$strComputer = “.”
$strComputer = “.”
$objADSI = [ADSI]“LDAP://DC=midominio,DC=com”
$objOU = $objADSI.create($Class, $OU)
$objOU.setInfo()
$objADSI = [ADSI]“LDAP://OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”
$objUser = $objADSI.Create($Class, $strUserName)
$objUser.Put(“sAMAccountName”, “jfuentes”)
$objUser.setInfo()
$objUser = [ADSI]“LDAP://CN=Juan
Fuentes,OU=TestOUUsers,OU=TestOU,DC=midominio,DC=com”
$objUser.put(“userAccountControl”, 544)
$objUser.SetInfo()
Write-Host “Introduce los datos del usuario que vas a crear en el Dominio”
Foreach($result in $results){
$User = $result.GetDirectoryEntry()
$user.DistinguishedName
}
Foreach($result in $results){
$User = $result.GetDirectoryEntry()
$user.DistinguishedName
}