Powershell Day1
Powershell Day1
Powershell Day1
Contents
Introduction to Windows PowerShell
Introduction to Windows PowerShell Installing Windows PowerShell in Windows Server 2008 Lab1 - Implementing Windows PowerShell
Windows PowerShell is a command-line shell and scripting language designed especially for system administration. Built on the Microsoft .NET Framework, Windows PowerShell helps IT professionals control and automate the administration of Windows operating systems and applications that run on Windows.
History of Powershell
Windows Powershell is a Microsoft command-line shell and scripting language. It was first introduced in 2003. Its initial codename was MONAD which stood for Microsoft shell (MSH)
History of Powershell
The first official release was in 2006 which is when the name was changed from MONAD to Powershell.
v1.0 runs on Windows XP and Vista v2.0 runs on Windows 7 (and comes preinstalled)
It is available for both 32 bit and 64 bit platforms.
Windows Management Framework (Windows PowerShell 2.0, Windows Remote Management (WinRM) 2.00, and Background Intelligent Transfer Service (BITS) 4.0)
With one of the above or a combination of all, a programmer gets complete control of all of the objects on a Windows computer.
Windows PowerShell 2.0 accepts and returns .NET objects which can be directly manipulated or sent to other tools or databases.
Database Mgmt
Dim StorGroup as New CDOEXM.StorageGroup StorGroup.DataSource.Open "LDAP://" + DCServer + "/ CN=First Storage Group,CN=InformationStore,CN=" + Server + ",CN=Servers,CN=First Administrative Group, CN=Administrative Groups,CN=First Organization, CN=Microsoft Exchange,CN=Services, CN=Configuration," + DomainName StorGroup.MoveLogFiles("C:\newlogPath", 0)
Recipient Mgmt
Command pane
Multiple tabs, each with its own command, output, and script pane
Output pane
Script pane
From the Start menu, point to All Programs, point to Windows PowerShell 2.0, and then click Windows PowerShell ISE. In the Windows PowerShell console, type Cmd.exe, or in the Run box, type powershell_ise.exe.
Moving and resizing the Command pane, Output pane, and Script pane Showing or hiding the Script pane Changing the text size in all panes of Windows PowerShell ISE
WinRM - Windows PowerShell Remoting features of Windows PowerShell are built on Windows Remote Remoting Management (WinRM)
Run an individual command, or create a persistent connection or session to run a series of commands
You can run as many commands as desired during the session. You must manually close the PSSession by using the Exit-PSSession cmdlet.
3. Command results are sent back using the WinRM protocol and appear in Windows PowerShell on the local computer
All of the local input to a remote command is collected before any of it is sent to the
remote computer.
Discovering PowerShell
PowerShell provides a discoverable environment. If you dont know something or do not remember browse around:
Get-Help (help) Get-Command (gcm) Get-PSDrive (gdr) Get-Member (gm)
PowerShell Aliases
An alias is an alternative name assigned to a Cmdlet. Aliases allow users to quickly interact with the shell. The Cmdlet get-alias is used to list all built-in aliases as shown in the diagram on the next slide:
Powershell Providers
They are .NET programs used to provide easy access to information external to the shell environment in order for the users to view it and manage it.
To obtain a listing of all the providers, the GetPSProvider cmdlet is used. To work with specific providers, use the setlocation cmdlet then specify the provider drive.
Powershell Providers
There are seven types of providers namely:
1. Alias - Provides access to the windows PowerShell aliases and their values
Get-PSProvider Sl Alias:\ GCI | where-object {$_.name like s*}
3. FileSystem - Provides access to files and directories. 4. Function - Provides access to the functions defined in Windows PowerShell.
Variables
Your Own Variables "Automatic- PowerShell Variables Environment Variables Drive Variables Scope of Variables Variable Types and "Strongly Typing" Variable Management: Behind the Scenes
Variable Name
You can use virtually any variable name you choose, names are not case sensitive. But, there are illegal characters such as; ! @ # % & , . and spaces. PowerShell will throw an error if you use an illegal character.
Variable Type
Powershell variable type is base on .NET Framework. Common variable is as below:
[adsi], [array], [bool], [byte], [char] [datetime], [decimal], [double] [int] or [int32], [long] [single], [scriptblock], [string] [WMI], [WMIclass], [xml]
PowerShell keeps a record of all variable assignments, which is accessible via a virtual drive called variable:
Dir variable:value* Name ---value2 value1 Value ----20 10
The variable "test" cannot be overwritten since it is a constant or read-only. At line:1 char:6 + $test <<<< = 200 del variable:\test -force
Constant Variable
If you need strong protection like in traditional constants, you should create a variable with the Constant option. This will change the variable to a proper constant that may neither be modified nor deleted. Only when you quit PowerShell are constants removed. Variables with the Constant option may only be created with New-Variable.
New-Variable test -value 100 -description ` "test variable with copy protection" -option Constant New-Variable : A variable named "test" already exists. At line:1 Char:13 + New-Variable <<<< test -value 100 -description "test variable with copy protection" -option Constant
Automatic Variables.
PowerShell uses variables, too, for internal purposes and calls those "automatic variables. To understand the meaning of automatic variables, you can simply view their description:
Dir variable: | Sort-Object Name | Format-Table Name, Description autosize wrap Name ---$ ? ^ _ Description ----------Execution status of last command.
Environment Variables
Reading Particular Environment Variables
$env:windir C:\Windows Searching for Environment Variables Dir env:
Scope of Variables
PSDrive
PSDrive Operation
Get-PSDrive mount -Name Seting -psProvider FileSystem Root "C:\Documents and Settings mount -Name MS -PSProvider Registry -Root HKLM\Software\Microsoft rdr -Name MS Set-Location Get-Location
Powershell Operator
Arithmetic Binary Operators
+, -, *, \, %, ++, --
Assignment Operators
=, +=, -=, *=, /=, %=
Logical Operators
!, -not, -and, -or
String Operators
+, *, -f, -replace, -match, -like
Comparison Operators
-eq, -ne, -gt, ge, -lt, le
Assignment Operators
$var=3 $var+=3 ; $var-=3 $var*=3 ;$var/=3 ; $var%=3 $var = 0x10 echo $var 16 $var = 7.56e3 echo $var 7560 $var=7MB echo $var 7340043 (bytes)
Logical Operators
(7 -eq 7) -and (2 -eq 5) (7 -eq 7) -or (2 -eq 5) (9 -eq 9) -xor (4 -eq 4) ; (9 -eq 9) -xor (4 -eq 7) (3 -eq 3) -and !(2 -eq 2) (3 -eq 3) -and -not (2 -eq 9)
String Operators
-like ; -clike ; -ilike To be like as -notlike ; -cnotlike ;-inotlike To not be like as
Match
Include
Not include
Comparison Operators
-le ; -cle ; -ile <= -eq; -ceq; -ieq = -ne; -cne; -ine != -gt; -cgt; -igt > -ge; -cge; -ige >= -lt; -clt; -ilt < -le; -cle; ile <=
Switch default
Switch [-regex|-wildcard|-exact][-casesensitive] -file <filename> (< variable >) { < Pattern 1> { code 1 } < Pattern 2> { code 2 } < Pattern 3> { code 3 } Default { code n } }
ForEachForeach-Object
ForEach ($<item or object> in $<Collection object>) { <code> } dir | ForEach -process { $_.length / 1024}
For
For (<initial>; < statement >; < count>) { <code> }
Foreach Loop
1) foreach ($number in 1,2,3,4,5,6,7,8,9,10,11,12 ) { $number * 7} 2) foreach ($number in 1... 12) {$number * 7}
3)$NumArray = (1,2,3,4,5,6,7,8,9,10,11,12)
foreach ($number in $numArray ) { $number * 7} 4) $NumArray = (1.. 12) foreach ($number in $numArray ) { $number * 7}
Do While Loop
- $i = 7; do {$i; $i +=7} while ($i -le 85)
Do Until
- $i = 7; do {$i; $i +=7} until ($i -gt 85)
Break; Continue
For ($i = 1; $i -le 10; $i++) { Write-Host $i If ($i -eq 5) { Write-Host "BREAK!! Break } } ForEach ($i in 1..10) { If ($i % 2) { Continue } $i }
Cmdlets
PSSnapin (subclass)
Default registers all Cmdlets CustomPSSnapin register specific Cmdlets
and WriteError
Cmdlets
The majority of the PowerShell functionality comes from Cmdlets Always in Verb-Noun format and never plural (Get-WmiObject or Get-Process) Cmdlets return objects not text Retrieve list of Cmdlets (Get-Command) Can tab complete
PS C:\>get-service
(Retrieve information about the services installed on your computer.)
PS C:\>set-location D:\
(It enables you to specify a new working location.)
Showing processes
Stopping a process(es)
Pipelining
One of the most powerful and possibly confusing aspects of PowerShell. The output of one program can be the input to another Pipelining is passing data and objects from one cmdlet to another in a very robust fashion.
Pipelining Example
PS C:\> Get-Process | where { $_.handlecount -gt 400 } | Format-List
2. The second, Where {..} will return the conditioned value which handlecount is greater than 400.
3. Finally the Format-list will display the results in Alphabetic order
Sorting
The sort-object cmdlet is used to produce a listing of items in ascending/descending order
Get-EventLog system -newest 5 | Sort-Object eventid
Compare 2 sets of objects Split a set of objects into groups Measure some property of a set of objects Select a set of properties from a set of objects Sort objects Make a copy of a set of objects Select a subset of objects
Utilities - Discovery
Command Function
Get-Help
Get-Command Get-Member Get-PSDrive
Help about PowerShell commands and topics Get information about anything that can be invoked Show what can be done with an object Shows what object stores are available
Understand/extend instrumentation
Extend and discover properties/methods
Update-TypeData Office.Word.Types.ps1xml $fso | Get-Member
Allows more simpler/more powerful COM scripts because of utilities and formatting
PowerShell provides native access to any .NET class Create any object
[reflection.assembly]::LoadWithPartialName("Syste m.Windows.Forms") $d = New-Object System.DateTime 2006,12,25
Access Statics
[DateTime]::Now [DateTime]::IsLeapYear(2006)