Powershell-Day1

84
POWERSHELL - Rajkumar - Nikhil Sureka

Transcript of Powershell-Day1

Page 1: Powershell-Day1

POWERSHELL

- Rajkumar - Nikhil Sureka

Page 2: Powershell-Day1

Contents…• Introduction to Windows PowerShell™

Introduction to Windows PowerShell Installing Windows PowerShell in Windows Server 2008Lab1 - Implementing Windows PowerShell

• Overview of Windows PowerShell™Overview of ObjectsWorking with CmdletsTab Expansion, Aliases, and HistoryUsing Variables and TypesLab2 - Lab: Working with Windows PowerShell Cmdlets,

Aliases, Objects and Variables

Page 3: Powershell-Day1

• 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.

Page 4: Powershell-Day1

History of PowershellWindows Powershell is a Microsoftcommand-line shell and scripting language.

It was first introduced in 2003. It’s initial codename was “MONAD” which stood for

Microsoft shell (MSH)

Page 5: Powershell-Day1

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 pre-

installed)

It is available for both 32 bit and 64 bit platforms.

Page 6: Powershell-Day1

Introduction to Windows PowerShell• Download http://support.microsoft.com/kb/968929

Windows Management Framework (Windows PowerShell 2.0, Windows Remote Management (WinRM) 2.00, and Background Intelligent Transfer Service (BITS) 4.0)

Page 7: Powershell-Day1

• Download PowerShell from Microsoft's site http://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx

• Download .NET Framework PowerShell is an object based scripting language; consequently, it needs .NET Framework for the definitions of the Windows objects. PowerShell works fine with either .NET Framework v 2.0, or v 3.0. Search Microsoft’s site for:

Page 8: Powershell-Day1

• Presently, Microsoft Windows programmers have several options when it comes to scripting. They can use:

1. MS-DOS (or CMD) to create simple batch files2. VBScript for more complex programming3. PowerShell to make the most of the .NET framework

• 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 Scripting Languages

Page 9: Powershell-Day1

• A cmdlet is a lightweight command that is used in the Windows PowerShell environment.

• Cmdlets follow a verb-noun naming pattern. Examples of verbs: get, set, newExamples of nouns: service, item, date

Windows Powershell Cmdlets

Page 10: Powershell-Day1

Overview of Windows PowerShell

The .NET™ framework is leveraged and provides access to thousands of objects.The .NET™ framework is leveraged and provides access to thousands of objects.üü

Windows PowerShell 2.0 is included with Windows® 7 and supports existing scripts and command-line tools.Windows PowerShell 2.0 is included with Windows® 7 and supports existing scripts and command-line tools.üü

Cmdlets are available for performing common system and administration tasks.Cmdlets are available for performing common system and administration tasks.üü

Windows PowerShell 2.0 accepts and returns .NET objects which can be directly manipulated or sent to other tools or databases.Windows PowerShell 2.0 accepts and returns .NET objects which can be directly manipulated or sent to other tools or databases.üü

An extensible interface enables enterprise developers to build custom tools and utilities to administer their software. An extensible interface enables enterprise developers to build custom tools and utilities to administer their software. üü

Page 11: Powershell-Day1

ProductivityExchange 2003 (VBScript) E12 (Monad Script)

Mailbox Statistics

Set listExchange_Mailboxs = GetObject("winmgmts:{impersonationLevel=impersonate}!\\COMPUTERNAME\ROOT\MicrosoftExchangeV2").InstancesOf("Exchange_Mailbox")

For Each objExchange_Mailbox in listExchange_MailboxsWScript.echo "AssocContentCount =” + objExchange_Mailbox.AssocContentCountWScript.echo " DateDiscoveredAbsentInDS =” + objExchange_Mailbox.DateDiscoveredAbsentInDSWScript.echo " DeletedMessageSizeExtended =” + objExchange_Mailbox. DeletedMessageSizeExtendedWScript.echo " LastLoggedOnUserAccount =” + objExchange_Mailbox. LastLoggedOnUserAccountWScript.echo " LastLogoffTime =” + objExchange_Mailbox. LastLogoffTimeWScript.echo " LastLogonTime =” + objExchange_Mailbox. LastLogonTime WScript.echo " LegacyDN =” + objExchange_Mailbox. LegacyDNWScript.echo " MailboxDisplayName =” + objExchange_Mailbox. MailboxDisplayNameWScript.echo " MailboxGUID =” + objExchange_Mailbox. MailboxGUID WScript.echo " ServerName =” + objExchange_Mailbox. ServerName WScript.echo " Size =” + objExchange_Mailbox. SizeWScript.echo " StorageGroupName =” + objExchange_Mailbox. StorageGroupName WScript.echo " StorageLimitInfo =” + objExchange_Mailbox. StorageLimitInfo WScript.echo " StoreName =” + objExchange_Mailbox. StoreName WScript.echo " TotalItems =” + objExchange_Mailbox. TotalItems Next

get-mailboxstatistics –server $servername

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)

move-storagegrouppath -identity “First Storage Group“ –log "C:\newlogPath”

Recipient Mgmt

Dim objMailbox As CDOEXM.IMailboxStore

Set objMailbox = GetObject("LDAP://" + DCServer + "CN=FOO,CN=users," + DomainName)

objMailbox.CreateMailbox "LDAP://" + DCServer + "/CN=Private MDB,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

enable-mailbox -identity domain\FOO –database “First Storage Group\Private MDB”

Page 12: Powershell-Day1

Overview of the Windows PowerShell 2.0 Integrated Scripting Environment (ISE)

The ISE enables you to run commands and design, write, test, and debug scripts in a Windows GUI

Command pane

Output pane

Script pane

Multiple tabs, each with its own command, output, and script pane

Page 13: Powershell-Day1

Using the Windows PowerShell ISE Editor

Windows PowerShell ISE Profile– ISE has its own Windows PowerShell profile, Microsoft.PowerShell_ISE_profile.ps1– You can store functions, aliases, variables, and commands

that you use in Windows PowerShell ISE in this profile

Start the Windows PowerShell ISE:• 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”.

Start the Windows PowerShell ISE:• 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”.

üü

Customize the Windows PowerShell ISE by:

• 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

Customize the Windows PowerShell ISE by:

• 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

üü

You can run any Windows PowerShell expression or command in Windows PowerShell ISE

Page 14: Powershell-Day1

WinRM - Windows PowerShell Remoting

Two types of remoting:– Fan-out remoting: provides one-to-many remoting to run scripts across multiple computers from

a single console– One-to-one interactive remoting: provides the ability to remotely troubleshoot a specific

computer

Remoting features of Windows PowerShell are built on Windows Remote Management (WinRM)Remoting features of Windows PowerShell are built on Windows Remote Management (WinRM)üü

Run an individual command, or create a persistent connection or session to run a series of commandsRun an individual command, or create a persistent connection or session to run a series of commandsüü

Remote administration is also known as remotingRemote administration is also known as remotingüü

Page 15: Powershell-Day1

Connecting to a Remote ComputerTwo ways to create a connection to a remote computer:

Create a temporary connection• You can start an interactive session by using the Invoke-Command cmdlet with the

ComputerName parameter.• A temporary connection is created for the command and closes the connection when the

command completes.

Create a persistent connection• Open a new Windows PowerShell session (PSSession) on the remote computer, then connect

to the computer and enter the session.– The New-PSSession cmdlet creates the PSSession.– The Enter-PSSession cmdlet connects you to the PSSession.

• You can run as many commands as desired during the session.• You must manually close the PSSession by using the Exit-PSSession cmdlet.

Page 16: Powershell-Day1

How Remote Commands Are Processed1. Local computer sends the Windows PowerShell

command to the remote computer using the WinRM protocol

2. Command runs in Windows PowerShell on the remote computer

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.

The output is returned to the local computer as it is generated.

üü

üü

Page 17: Powershell-Day1

Running Remote Commands

To run commands in a PSSession:– Use the Session parameter of the Invoke-Command cmdlet to specify the session– Use the ComputerName parameter to retrieve objects from remote computers

To run a remote command on multiple computers:– Use the Invoke-Command for temporary connections and multiple computer names– Use the Session parameter for persistent connections and multiple PSSessions– Type the name of each computer in the ComputerName parameter of the Invoke-

Command

To run a local script on remote computers– Use the FilePath parameter of the Invoke-Command cmdlet

Page 18: Powershell-Day1

Discovering PowerShell

• PowerShell provides a discoverable environment. If you don’t know something or do not remember – browse around:

• Most of the commands support wildcards

Get-Help (help)Get-Command (gcm)Get-PSDrive (gdr)Get-Member (gm)

PS C:\> get-command *snapin*

Page 19: Powershell-Day1

• 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 Aliases

Page 20: Powershell-Day1
Page 21: Powershell-Day1

• 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 Get-PSProvider cmdlet is used.

• To work with specific providers, use the set-location cmdlet then specify the provider drive.

Powershell Providers

Page 22: Powershell-Day1

• There are seven types of providers namely:

1. Alias - Provides access to the windows PowerShell aliases and their valuesGet-PSProviderSl Alias:\GCI | where-object {$_.name –like “s*”}

2. Environment - Provides access to the Windows environment variables.

3. FileSystem - Provides access to files and directories.

4. Function - Provides access to the functions defined in Windows PowerShell.

Powershell Providers

Page 23: Powershell-Day1

5. RegistryProvides access to the system registry keys and values.

6. Variable Provides access to Windows PowerShell variables and their values.

7. CertificateProvides read-only access to certificate stores and certificates.

Powershell Providers cont….

Page 24: Powershell-Day1

Variables

• Your Own Variables• "Automatic“- PowerShell Variables• Environment Variables• Drive Variables• Scope of Variables• Variable Types and "Strongly Typing"• Variable Management: Behind the Scenes

Page 25: Powershell-Day1

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.

Page 26: Powershell-Day1

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]

Page 27: Powershell-Day1

Your Own Variables• PowerShell creates new variables automatically so there is no need to

specifically "declare" variables. Simply assign data to a variable. The only thing you need to know is that variable names are always prefixed with a "$“

• # Create variables and assign to values$amount = 120$VAT = 0.19

# Calculate:$result = $amount * $VAT

# Output result$result

22.8• # Replace variables in text with values:

$text = "Net amount $amount matches gross amount $result"$text

Net amount 120 matches gross amount 142.8

Page 28: Powershell-Day1

Exchanging the Contents of Variables

• $Value1 = 10$Value2 = 20$Temp = $Value1$Value1 = $Value2$Value2 = $Temp

• $Value1 = 10; $Value2 = 20$Value1, $Value2 = $Value2, $Value1

Page 29: Powershell-Day1

• PowerShell keeps a record of all variable assignments, which is accessible via a virtual drive called variable:

• Dir variable:value* Name Value

---- -----value2 20value1 10

• Verify Whether a Variable Exists Test-Path variable:\value2

True

Page 30: Powershell-Day1

• $listing = Get-ChildItem c:\ $listing

• Directory: Microsoft.PowerShell.Core\FileSystem::C:\

Mode LastWriteTime Length Name---- ------------- ------ ----d---- 06.26.2007 15:36 2420d---- 05.04.2007 21:06 ATId---- 08.28.2006 18:22 Documents and settingsd---- 08.08.2007 21:46 EFSTMPWPd---- 04.28.2007 02:18 perflogs(...)

# Populate several variables with the same value in one step:$a = $b = $c = 1

Page 31: Powershell-Day1

Cmdlets for Variable…

Page 32: Powershell-Day1

Write-Protecting Variables: Creating Constants

• New-Variable test -value 100 -description `"test variable with write-protection" -option ReadOnly

• $test 100• $test = 200

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

Page 33: Powershell-Day1

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

Page 34: Powershell-Day1

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. ^

_

Page 35: Powershell-Day1
Page 36: Powershell-Day1

Environment Variables

• Reading Particular Environment Variables $env:windir C:\Windows• Searching for Environment Variables

Dir env:

Page 37: Powershell-Day1

Deleting and Modifying Environment Variables

• del env:\windir• $env:OS = "Apple MacIntosh OS X"

Dir env:

# The folder is now added to the path environment:$env:path += ";C:\myTools"

Page 38: Powershell-Day1

Scope of Variables

Page 39: Powershell-Day1

All Variables are Object

• [int]$Age=22• $Age.GetType()• $Age GetType().Name• $Age | Get-Member• $Title=“manager”• $Title.length• $Title.CompareTo()

Page 40: Powershell-Day1

PSDrive

Page 41: Powershell-Day1

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

Page 42: Powershell-Day1

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

Page 43: Powershell-Day1

Arithmetic Binary Operators

• 123+789 ; 222-876• 34.5*44.2 ; 13/7• 123%5• $var++ ; ++$var $var = $var + 1• $var-- ; --$var $var = $var – 1

Page 44: Powershell-Day1

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)

Page 45: Powershell-Day1

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)

Page 46: Powershell-Day1

String Operators-like ; -clike ; -ilike To be like as

-notlike ; -cnotlike ;-inotlike To not be like as

-match ; -cmatch ;-imatch Match

-notmatch ; -cnotmatch ; -inotmatch Not match

-contains ; -ccontains ; -icontains Include

-notcontains; -cnotcontains ;

-inotcontains

Not include

Page 47: Powershell-Day1

Comparison Operators

• -le ; -cle ; -ile <=• -eq; -ceq; -ieq =• -ne; -cne; -ine !=• -gt; -cgt; -igt >• -ge; -cge; -ige >=• -lt; -clt; -ilt <• -le; -cle; ile <=

Page 48: Powershell-Day1
Page 49: Powershell-Day1

Loop and Flow Control

• If…. elseif… else…• Switch…… default• ForEach( Foreach-Object)• For • While• Do….. While• Do…..Until• Break & Continue

Page 50: Powershell-Day1

If…. elseif… else…

If (< statement 1>) { < code 1> } Elseif (< statement 2>) { < code 2> … } Else { <code n> }

Page 51: Powershell-Day1

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 } }

Page 52: Powershell-Day1

ForEach( Foreach-Object)ForEach ($<item or object> in $<Collection object>) { <code> }

dir | ForEach -process { $_.length / 1024}

Page 53: Powershell-Day1

For

For (<initial>; < statement >; < count>) {<code>

}

Page 54: Powershell-Day1

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}

Page 55: Powershell-Day1

While, do while, do until

• While (< statement >) {<code> }

• Do { < code >} While (< statement >)

• Do {<code>} Until (<statement>)

ps. “Until” can wait something happen!!

Page 56: Powershell-Day1

While, Do While, Do Until

• While Loops- $i =7; while ($i -le 85) { $i; $i +=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)

Page 57: Powershell-Day1

Break; Continue

• For ($i = 1; $i -le 10; $i++) {Write-Host $iIf ($i -eq 5) { Write-Host "BREAK!!“Break } }

• ForEach ($i in 1..10) {If ($i % 2) {

Continue }$i }

Page 58: Powershell-Day1

Cmdlets

• PSSnapin (subclass)– Default – registers all Cmdlets– CustomPSSnapin – register specific Cmdlets

• Parameters and Parameter Sets• Begin/End/StopProcessing• ProcessRecord

• WriteObject and WriteError

Page 59: Powershell-Day1

Cmdlets

• The majority of the PowerShell functionality comes from Cmdlet’s

• Always in Verb-Noun format and never plural (Get-WmiObject or Get-Process)

• Cmdlet’s return objects not text• Retrieve list of Cmdlet’s (Get-Command)• Can tab complete

Page 60: Powershell-Day1

• Below are sample Cmdlets following the verb-noun naming pattern:

PS C:\>get-childitem C:\(Gets the items and child items in one or more specified locations.)

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.)

PS C:\> set-location “c:\my documents”

Sample Powershell Cmdlets

Page 61: Powershell-Day1

• Get-Help(get-help set-* gives all cmdlets that start with Set-.)

• Get-Command (you’ll get back a list of all the Windows PowerShell cmdlets)

• Get-Member(will enumerate the properties and methods of that object.)

• Get-Psdrive (Gets the Windows PowerShell drives in the current session)

• Format-List(each property is displayed on a separate line)

5 key powershell commands

Page 62: Powershell-Day1

Showing processes

Page 63: Powershell-Day1

Getting help on commands

Page 64: Powershell-Day1

Stopping a process(es)

Page 65: Powershell-Day1

Script Security Settings - Execution Policy

• Restricted – No scripts can be run. Windows PowerShell can be used only in interactive mode.

• AllSigned – Only scripts signed by a trusted publisher can be run.

• RemoteSigned – Downloaded scripts must be signed by a trusted publisher before they can be run.

• Unrestricted – No restrictions; all Windows PowerShell scripts can be run.

Page 66: Powershell-Day1

• Use the Get-ExecutionPolicy cmdlet to retrieve the current effective script execution policy.

• Use the Set-ExecutionPolicy cmdlet to change the script execution policy to unrestricted as shown below:Set-ExecutionPolicy unrestricted

Setting script execution policy

Page 67: Powershell-Day1

• 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.

• A | B | C meaning the output of A goes to B, and the output of B goes to C.

Pipelining

Page 68: Powershell-Day1

PS C:\> Get-Process | where { $_.handlecount -gt 400 } | Format-List

This example is actually executing three cmdlets

1. The first, Get-Process, returns a list of all running processes

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

Pipelining Example

Page 69: Powershell-Day1

PS C:\> Get-Process | where { $_.handlecount -gt 400 } | Format-List

ProcessName : csrssId : 1080ProcessName : explorerId : 1952ProcessName : GrooveId : 2656ProcessName : inetinfoId : 1524

Pipelining Example Output

Page 70: Powershell-Day1

• The sort-object cmdlet is used to produce a listing of items in ascending/descending order

Get-EventLog system -newest 5 | Sort-Object eventid

Produces the output below:

Sorting

Page 71: Powershell-Day1

• Running a script can be done either within or outside PowerShell.

• Running the script within PowerShell requires the following steps:

1. Type the full path to the script2. Include the name of the script3. Ensure you include the PS1 extension

C:\mytest\RetrieveAndSortServiceState.PS1

Running windows powershell scripts

Page 72: Powershell-Day1

• Running scripts outside PowerShell requires the following steps:

1. Type the full path to the script2. Include the name of the script3. Ensure you include the PS1 extension4. Feed this to the PowerShell.exe program5. Use the –noexit argument to keep the PowerShell console

after script execution

Powershell –noexit C:\mytest\RetrieveAndSortServiceState.PS1

Running windows powershell scripts

Page 73: Powershell-Day1

Utilities – Object ManipulationCommand ActionCompare Compare 2 sets of objectsGroup Split a set of objects into groupsMeasure Measure some property of a set of objectsSelect Select a set of properties from a set of objectsSort Sort objectsTee Make a copy of a set of objectsWhere Select a subset of objects

Page 74: Powershell-Day1

Utilities - DiscoveryCommand FunctionGet-Help Help about PowerShell commands and

topicsGet-Command Get information about anything that can be

invokedGet-Member Show what can be done with an objectGet-PSDrive Shows what object stores are available

Page 75: Powershell-Day1

Transformation and OutputCommands Functions

Format -Custom -List -Table -Wide

Convert objects into formatting records

Out -File -Host -Printer -String

Convert formatting records into output-specific directives.

Export/Import -CliXML -CSV

Converts objects into and out of file formats

ConvertTo -HTML

Converts object into other objects

Page 76: Powershell-Day1

• Files and FoldersNew-Item is a quick and easy way to create a new file or folder on your computer.

Creating a file:New-Item c:\scripts\new_file.txt -type file

Creating a folder:New-Item c:\scripts\Windows PowerShell -type directory

Creating new items using Scripts

Page 77: Powershell-Day1

$intFolders = 10$intPad$i = 1New-Variable -Name strPrefix -Value "testFolder" -Option constant

do { if ($i -lt 10) {$intPad=0 new-item -path c:\mytest -name $strPrefix$intPad$i -type

directory} else {new-item -path c:\mytest -name $strPrefix$i -type

directory} $i++ }until ($i -eq $intFolders+1)

Creating multiple folders

Page 78: Powershell-Day1

$intFolders = 10$intPad$i = 1New-Variable -Name strPrefix -Value "testFolder" -

Option constant

do { if ($i -lt 10) {$intPad=0 Remove-item -path c:\mytest\$strPrefix$intPad$i} else {Remove-item -path c:\mytest\$strPrefix$i} $i++ }until ($i -eq $intFolders+1)

Deleting multiple folders

Page 79: Powershell-Day1

Scripting with COMAccess existing instrumentation

Bind to COM objects$fso = New-Object -ComObject Scripting.FileSystemObject$m = [System.Runtime.InteropServices.Marshal]$word = $m::GetActiveObject("Word.Application")

Invoke methods/access properties$fso.GetDrive(“C:”)$fso.VolumeName = “System Drive”

Understand/extend instrumentationExtend and discover properties/methods

Update-TypeData Office.Word.Types.ps1xml$fso | Get-Member

Manipulate and format resultsDefine and import custom formating

Update-FormatData Office.Word.Format.ps1xml$word.RecentFiles | Sort name | Format-Table

Allows more simpler/more powerful COM scripts because of utilities and formatting

Page 80: Powershell-Day1

• It is a hierarchical namespace, in which the layers build on one another like a Lightweight Directory Access Protocol (LDAP) directory used in Active Directory, or the file system structure on a hard disk drive.

• WMI can be used to: report on drive configuration, report on available memory both physical and virtual, back up the event log, modify registry, schedule tasks, share folders, switch from a static to a dynamic IP address.

• The WMI model has three sections namely:1. Resources2. Infrastructure 3. Consumers

Windows Management Instrumentation(WMI) Model

Page 81: Powershell-Day1

Scripting with WMIPowerShell provides native WMI supportGet-WmiObject

Allows for inspection of WMI namespaceGet-WmiObject –list [-Namespace xx]Get-WmiObject –Class xx –Namespace xx –Property xxx – Filter xxx –ComputerName xxx –Credential xxx

Native language support[WMI] “\\JPSDESK10\root\cimv2:Win32_Process.Handle="0“[WMICLASS] "ROOT\cimv2:WIN32_PROCESS"[WMISEARCHER]"select * from Win32_process WHERE Name = 'calc.exe'"

Page 82: Powershell-Day1

Scripting with .NETPowerShell provides native access to any .NET classCreate any object

[reflection.assembly]::LoadWithPartialName("System.Windows.Forms")$d = New-Object System.DateTime 2006,12,25

Access Properties/Invoke Methods$d.DayOfWeek$d.AddDays(-30)

Access Statics[DateTime]::Now[DateTime]::IsLeapYear(2006)

Allows admins to easily access and leverage a huge API set because of scriptability, utilities and formatting

Page 83: Powershell-Day1

Scripting with XMLPowerShell provides native XML supportNative datatype

$x=[xml]"<a><b><c>TEST</c></b></a>“$b =[xml](type c:\i386\mssecure.xml)

Native syntax to access “data” view of properties

$b.BulletinDataStore.Bulletins.Bulletin[0]

Access to XML methods $b.BulletinDataStore.SelectNodes(“//Patch”)

XML properties available through PSBase property

$b.BulletinDataStore.PSBase.innerXml

Page 84: Powershell-Day1

Calling into .NET framework

• Use .NET types in your scripts

• Call into .NET directly

PS C:\> [System.Reflection.Assembly]:: LoadWithPartialName("System.Windows.Forms")PS C:\> [System.Windows.Forms.MessageBox]::Show("Hello“)

PS C:\> echo $([DateTime]::Now)