the hidden charms of windows powershell 3.0 and 4.0 june blender senior programming writer microsoft...
TRANSCRIPT
The Hidden Charmsof
Windows PowerShell 3.0 and 4.0
June Blender Senior Programming WriterMicrosoft Corporation@[email protected]
Today’s Topics
• A Bit O’ History: How did we get to Windows PowerShell 4.0?
• Cool Features of Windows PowerShell 3.0
• What’s in Windows PowerShell 4.0 Preview (beside DSC)
• Windows PowerShell Help
• Q & A
A bit o’ history….• 2005: Windows PowerShell 1.0
• Out-of-band download• Included in Windows Server 2003
• 2009: Windows PowerShell 2.0• Included: Windows 7 and Windows Server 2008• WMF: Windows XP, Windows Server 2003 R2• Microsoft .NET 2.5, 3, CLR 3
• 2012: Windows PowerShell 3.0 (Includes 2.0)• Included: Windows 8 and Windows Server 2012• WMF: Windows 7, Windows Server 2008• Microsoft .NET 4, 4.5, CLR 4• Includes: Windows PowerShell 2.0
• 2013: Windows PowerShell 4.0 Preview• Included: Windows 8.1 and Windows Server 2012 R2• WMF: Windows 7 SP1, Windows Server 2008 SP1, Windows Server 2012• Microsoft .NET 4.5, CLR 4
A bit o’ history….
• 2005: Windows PowerShell 1.0 • Introduction to a .NET-based shell
• 2009: Windows PowerShell 2.0• Remote management
• 2012: Windows PowerShell 3.0• Coverage, Workflows
• 2013: Windows PowerShell 4.0• Control, DSC
Windows PowerShell 4.0 Preview• Windows PowerShell 4.0
• Included in Windows 8.1 and Windows Server 2012 R2• Windows Management Framework 4.0
for Windows 7, Windows Server 2008, Windows Server 2008 R2
• Requires .NET 4.5 (Get-ItemProperty -Name Release -Path 'HKLM:\
Software\Microsoft\NET Framework Setup\NDP\v4\Full'
• Windows 8, Windows Server 2012• Upgrade to Windows 8.1, Windows Server 2012 R2
• Windows PowerShell 2.0• Not included in Windows PowerShell 4.0 Preview• To install, use Server Manager or Programs in Control Panel
How to Get Windows PowerShell• Windows PowerShell 2.0
• Included in Windows 7 and Windows Server 2008• Windows Management Framework 2.0
for Windows XP, Windows Vista, Windows Server 2003• Windows 8.1: Programs in Control Panel• Windows Server 2012 R2: Server Manager
• Windows PowerShell 3.0 (Includes 2.0)• Included in Windows 8 and Windows Server 2012• Windows Management Framework 3.0
for Windows 7, Windows Server 2008, Windows Server 2008 R2
• Windows PowerShell 4.0• Included in Windows 8.1 and Windows Server 2012 R2• Windows Management Framework 4.0
for Windows 7, Windows Server 2008, Windows Server 2008 R2
Cool Features in PowerShell Core 3.0
The Basics• Simplified syntax• Getting properties and methods• Get-Command – Improved!• Module AutoLoading• Get-ChildItem – Improved!
• Get-Help -ShowWindow• Show-Command• Map Network Drive• Unblock-File • ISE snippets
The Advanced Parts• Disconnected Sessions• Windows PowerShell Workflow• Scheduled Jobs• Dynamic Type Data• Updatable Help
Windows PowerShell 3.0 includes Windows PowerShell 2.0 running side-by-side
Get-Help
Simplified Syntax:
{$_.}
Avoid errorsMake it workMake everyone successful
Simplified Syntax: ForEach-Object
PS 2.0: Get-Module | ForEach-Object {$_.NestedModules}
PS 3.0: Get-Module | ForEach-Object NestedModules
Get-Module | ForEach-Object {$_.NestedModules.Name}
{$_.}
Get-Help ForEach-Object
Simplified Syntax: Where-Object
PS 2.0: Get-Process | Where {$_.ProcessorAffinity} Get-Process | Where {$_.BasePriority –gt 8}
PS 3.0: Get-Process | Where ProcessorAffinity Get-Process | Where BasePriority –gt 8
{$_.}
Get-Help Where-Object
Get Properties… of multiple objects
PS 2.0: # One object (Get-Module PSScheduledJob).Name (Get-Module -ListAvailable).Name #Null PS 3.0: # One or more objects (Get-Module -ListAvailable).Name
.
Get-Help about_Properties
Invoke Methods… of multiple objects
PS 2.0: # One object # Multiple objects $a = ‘abc’ $b = ‘abc’, ‘def’ $a.ToUpper() $b.ToUpper() #FAIL PS 3.0: # One or more objects $a.ToUpper() $b.ToUpper() ABC ABC
DEF
Get-Help about_Methods
Count / Length… of a single object if ($p.Count –gt 0)…
PS 2.0: # One object # Multiple objects 'abc'.Count ('abc', 'def').Count #Nothing 2 PS 3.0: # One object # Zero objects 'abc'.Count $null.Count 1 0
Get-Help about_Properties, about_Arrays
Get-Command
PS 2.0: Gets commands in the current session.
PS 3.0: Gets commands in all installed modules.• In PSModulePath environment variable• + current session
Get-Help Get-Command
Module Auto-LoadingPS 2.0: Get-Module | Import-Module
PS 3.0: Modules are imported automatically:
• Use a command in the module• Get-Command (any command in the module)• Get-Help (any command in the module)
Modules are *not* imported automatically:• Get-Command *• Get-Help *• Not in PSModulePath environment variable
Import-Module
Get-Help about_Modules
Module Auto-Loading “Gotcha”PS C:\> Get-Job –JobName MyScheduledJob# Nothing
PS C:\> Get-ScheduledJob MyScheduledJob
Id Name JobTriggers Command Enabled-- ---- ----------- ------- -------1 MyScheduledJob 1 Update-Help True
PS C:\> Get-Job –JobName MyScheduledJob
Id Name PSJobTypeName State HasMoreData-- ---- ------------ ----- -----------2 MyScheduledJob PSScheduledJob Completed True
Import-Module
Get-Help about_Modules, about_Scheduled_Jobs
Get-ChildItem (dir)PS 3.0: New Parameters in FileSystem drives -File dir s* -af -Directory dir s* -ad -ReadOnly dir s* -af -ar -Hidden dir s* -ar -ah -System dir s* -as -Attributes dir -att !d,!d+h #No spaces D, R, H, S; !, +, “,”
PS C:\> Dir *.ps1 –Attributes !r | attrib +r
Get-Help Get-ChildItem -Path C:
Get-Help -ShowWindow
Get-Help Get-Help
PS C:\> Get-Help Update-Help –ShowWindow
Settings are saved.
Get-Help –ShowWindow #Gotcha
Get-Help Get-Help
Displays only the first paragraph of parameter descriptions
Show-Command
Get-Help Show-Command
DEMO !!
Map Network Drive New-PSDrive -Persist
PS 2.0: New-PSDrive creates drives in the current session.
PS 3.0: New-PSDrive –Persist creates mapped network drive.
Get-Help New-PSDrive
Map Network Drive New-PSDrive –Persist
• Root must be on a remote computer
• Name must comply with Windows drive name standards (one letter)
• User-specific, including “Run as administrator”
PS C:\> New-PSDrive -Root \\Server01\PowerShell -Name P -PSProvider FileSystem -Persist
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
P 1148.67 248.54 FileSystem \\Server01\\PowerShell
Get-Help New-PSDrive
Unblock-File
• The Unblock-File cmdlet lets you open files that were downloaded from the Internet.
• It unblocks Windows PowerShell script files that were downloaded from the Internet so you can run them, even when the Windows PowerShell execution policy is RemoteSigned.
• Much better than changing the execution policy to Unrestricted.
Get-Help Unblock-File
Unblock-File
Get-Help Unblock-File
ISE Snippets
Get-Help New-ISESnippet
• Creates a reusable text "snippet" in Windows PowerShell ISE.
• Comes with built-in snippets
• You can create your own snippets!
Snippet Cmdlets:• New-IseSnippet• Get-IseSnippet• Import-IseSnippet
ISE Snippet "Gotchas"• Description parameter is required.
• To view snippets, Ctrl-J or Edit/Start-Snippets or Right-click/Start Snippets
• If you run New-IseSnippet in the console (not ISE), it works, but returns a InvokeMethodOnNull error that you can ignore.
• To delete a user-created snippet, use Remove-Item PS C:\> Get-IseSnippet <title> | Remove-Item
Get-Help New-ISESnippet
Create an ISE Snippet
DEMO !!
What’s New in Core 3.0?The Advanced Parts
• Disconnected Sessions• Session Configuration Files• Windows PowerShell Workflow• Updatable Help• Scheduled Jobs• Dynamic Type Data
Windows PowerShell 3.0 includes Windows PowerShell 2.0 !
Disconnected Sessions1. Start a PSSession.
2. Run commands in the PSSession.
3. [ Disconnect from the PSSession.]
4. Exit Windows PowerShell.
5. Shut down the machine.
6. Go home…
7. Boot up your laptop.
8. Start Windows PowerShell.
9. Reconnect to the PSSession.
10. Get the results of commands run in the session.
At work…
At home…
Get-Help about_Remote_Disconnected_Sessions
Disconnected Sessions
Get-Help New-PSSession
DISCONNECTED SESSION CMDLETS • New-PSSession: Creates a PSSession.• Disconnect-PSSession: Disconnects a PSSession. • Connect-PSSession: Connects to a disconnected PSSession. • Receive-PSSession: Gets the results of commands that ran in disconnected
sessions.
• Get-PSSession: Gets PSSessions on the local computer or on remote computers.
• Invoke-Command: InDisconnectedSession parameter creates a PSSession and immediately disconnects.
PSSessions are session-independent
PS 2.0:New-PSSession: Creates a connection from the current session to another computer.
PS 3.0:New-PSSession: Creates a connection that issaved at the remote end, even if the currentSession is disconnected.
Get-Help New-PSSession
To: Server01To: Server012
Localhost
From: Server01From: Server012From: Server02
Server012
Get-PSSession -ComputerName
PS 2.0:Gets sessions in the current session that are connected to <ComputerName>.
PS 3.0:Gets all sessions on <ComputerName> for the current user.
To get sessions in the current session, omit -ComputerName.
Get-Help Get-PSSession
To: Server01
To: Server012
Localhost
From: Server01From: Server012From: Server02
Server012
Get-PSSession -ComputerName
Get-Help Get-PSSession
# On Server01PS C:\> New-PSSession –ComputerName Server02
PS C:\> Get-PSSession –ComputerName Server02
Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Session1 Server02 Opened Microsoft.PowerShell Available
From: Server01
Server02
# On Server03PS C:\> Get-PSSession –ComputerName Server02
Id Name ComputerName State ConfigurationName Availability-- ---- ------------ ----- ----------------- ------------ 1 Session1 Server02 Disconnected Microsoft.PowerShell Busy
# On Server02PS C:\> Get-PSSession
Id Name ComputerName State ConfigurationName Availability-- ---- ------------ ----- ----------------- ------------ 1 Session1 Server02 Opened Microsoft.PowerShell Busy
How to Disconnect:• Disconnect-PSSession• Invoke-Command -InDisconnectedSession
How to Connect / Reconnect:
• Connect-PSSession• Receive-PSSession
Get-Help about_Remote_Disconnected_Sessions
Disconnected Sessions#Gotchas
Don’t exceed the IdleTimeoutSet the BufferMode carefully
• IdleTimeoutMs: How long a disconnected session can be idle before being deleted. Default value.
• OutputBufferingMode: What happens to session output when the output buffer is full. • Values: • Block: Stop the command• Drop: Delete old output (FIFO)
• MaxIdleTimeoutMs: The maximum idle timeout that is permitted by the session configuration.
Get-Help about_Remote_Disconnected_Sessions
Disconnected Sessions
Get-Help about_Remote_Disconnected_Sessions
DEMO !!
Disconnected Sessions: How it WorksSession Configurations• PSSessions are saved in the session configuration ("endpoint") on the remote
computer (aka "server-side")
• A session configuration is a collection of settings that create the environment of sessions for remote users.
• Under the covers, they are WSMan plug-ins. (dir WSMan:\<computer>\Plugin) • Every session uses a session configuration. If you don't specify one, you get the
default, Microsoft.PowerShell
• The ACL on the session configuration determines who can connect to the computer remotely.
• You can use session configurations to create custom sessions for remote users.
Get-Help about_Session_Configurations
Session ConfigurationsSession Configuration Files• To create a session configuration in Windows PowerShell 2.0, you need
to write a C# program.
• To create a session configuration in Windows PowerShell 3.0 (and later!), you use a session configuration file that contains a hash table.
• Yes, you can create your own custom session configurations. It's easy!
• New-PSSessionConfigurationFile -Path MySession.pssc
• Register-PSSessionConfiguration -Name WithProfile -StartupScript C:\users\juneb\Documents\WindowsPowerShell\profile.ps1
Get-Help about_Session_Configuration_Files, New-PSSessionConfigurationFile
Scheduled JobsDon’t exceed the IdleTimeoutSet the BufferMode carefully• Scheduled jobs are a unique hybrid of Windows PowerShell
background jobs and scheduled tasks.
• Run asynchronously and in the background on the schedule that you specify.
• Results of each job instance that runs are automatically saved and easily retrieved.
• Use Job cmdlets to manage the running instances.
• You can see scheduled jobs in Task Scheduler and manage them in Windows PowerShell.
Get-Help about_Scheduled_Jobs
Scheduled Jobs Don’t exceed the IdleTimeoutSet the BufferMode carefully
• Trigger: New-JobTrigger: Sets the schedule.
• Options: New-ScheduledJobOption: Set conditions for running the job.
• Command that runs (script block / script)
• Create the scheduled job: Register-ScheduledJob ("Run as administrator")
Get-Help about_Scheduled_Jobs
Scheduled Jobs "Gotchas"• Run as administrator
• Be mindful of the options.
• Options use Task Scheduler default values.
• Might prevent the task from running -- ever.
• Read: Get-Help New-ScheduledJobOption –Parameter *
Get-Help about_Scheduled_Jobs
Scheduled Jobs “Gotcha”PS C:\> Get-ScheduledJobPS C:\>
# function elevate; “Run as administrator”PS C:\> Start-Process PowerShell –Verb RunAs
PS C:\> Get-ScheduledJob
Id Name JobTriggers Command Enabled-- ---- ----------- ------- -------1 UpdateHelp 1 Update-Help True
Get-Help about_Scheduled_Jobs
Dynamic Type Data
Get-Help Update-TypeData, about_Types.ps1xml
• Adds extended type data only to the current session
• Much simpler than creating a Types.ps1xml file
• TypeData Cmdlets• Update-TypeData -TypeName adds the type to the session
• Update-TypeData -DefaultDisplayPropertySet changes the properties that are displayed by default
• Get-TypeData gets the type data in the current session (static and dynamic)
• Remove-TypeData deletes extended type data from the current session
Dynamic Type Data
Get-Help Update-TypeData, about_Types.ps1xml
PS C:\>Update-TypeData –TypeName System.Management.Automation.PSModuleInfo -MemberName SupportsUpdatableHelp -MemberType ScriptProperty -Value {if ($this.HelpInfoUri) {$True} else {$False}}
PS C:\>Get-Module -ListAvailable | Format-Table Name, SupportsUpdatableHelp
Name SupportsUpdatableHelp---- -------------------------------Microsoft.PowerShell.Diagnostics TrueMicrosoft.PowerShell.Host TrueMicrosoft.PowerShell.Management TrueMicrosoft.PowerShell.Security TruePSDiagnostics FalsePSScheduledJob TrueTroubleshootingPack False
Dynamic Type Data
Get-Help Update-TypeData, about_Types.ps1xml
PS C:\>Update-TypeData -TypeName System.DateTime-DefaultDisplayPropertySet DayOfWeek, Date, TimeOfDay
PS C:\>Get-Date | Format-List
DayOfWeek: TuesdayDate: 7/9/2013 12:00:00 AMTimeOfDay: 17:32:49:5829247
Updatable Help Don’t exceed the IdleTimeoutSet the BufferMode carefully
• Problem: Outdated help files• Help is continuously updated. Help XML files are part of
Windows, so they're hard to update (trusted installer).• Online help is great, but users want updated help at the
command line.
• Solution: Updatable Help• Update-Help cmdlet downloads help files from the Internet
and installs them (correctly!).• Compares versions and installs when a new one is available.
Get-Help about_Updatable_Help
Updatable Help
• Offline: Save-Help• Save-Help cmdlet downloads help files from the Internet
and saves them in a file system directory.• Update-Help gets help from a file system directory and
installs it (correctly!)• Multilingual Support• HelpInfo information files support a version for each locale.
• Enhanced Online Help• Get-Help -Online works even when there are no help files
on the box.• Autogenerated Help• Get-Help creates basic help when there are no help files
online or on the box.
Update-Help Don’t exceed the IdleTimeoutSet the BufferMode carefully
• Figures out which modules support Updatable Help• Finds Updatable Help at an Internet site.• Compares versions• Downloads help package• Unpacks it • Verifies it• Installs it in the locale-specific subdirectory of the module
directory.
To use the help, type Get-Help.• You don't need to restart Windows PowerShell.
Get-Help Update-Help, about_Updatable_Help
Save-Help Don’t exceed the IdleTimeoutSet the BufferMode carefully
• Figures out which modules support Updatable Help• Finds Updatable Help at an Internet site.• Compares versions• Downloads help package to a specified <directory>
Update-Help -SourcePath <directory>• Checks version• Unpacks files• Verifies them• Installs them
Get-Help Save-Help, about_Updatable_Help
Update-Help "Gotchas"Don’t exceed the IdleTimeoutSet the BufferMode carefully
• Must be Administrator to update help in $pshome (System32).
• You might be interrupted by network
• Some module don't support Updatable Help.• Look for HelpInfoUri property value
• Updatable help hasn't been released or updated.
• Online Help (-Online) isn’t supported.• Look for HelpUri property value
Get-Help about_Updatable_Help
Update-Help for your Module
• Supporting Updatable Help (MSDN)• http://go.microsoft.com/fwlink/?LinkID=242129
• Supporting Online Help (MSDN)• http://go.microsoft.com/fwlink/?LinkID=242132
Windows PowerShell Workflow• Long-running series of commands and scripts run
on hundreds of machines.• Runs activities in sequence and in parallel.• Checkpoints: Save state and data• Supports disconnected sessions
Get-Help about_Workflow
How to Write a Script Workflow http://go.microsoft.com/fwlink/?LinkID=262872
TechNet Library Windows Server Windows Server 2012 Management and Tools Getting Started with Windows PowerShell Workflow
How to Write a Script Workflow http://go.microsoft.com/fwlink/?LinkID=262872
TechNet Library Windows Server Windows Server 2012 Management and Tools Getting Started with Windows PowerShell Workflow
Use Windows PowerShell ISE
Workflow Configuration
How to Run a Workflow• Run at the command line or in a PSSession on a workflow server computer.
• If using a PSSession, use the Microsoft.PowerShell.Workflow session configuration. • The New-PSWorkflowSession cmdlet creates a session that uses the
workflow session configuration.• Performance (timeouts, quotas)• SharedHost mode (same process for a user on different computers)• Managed node support
• Automatically creates workflow jobs on every managed node• Quotas and throttling on managed nodes• Recycles sessions other resources
• Run the workflow as a job. • Suspend and resume jobs• All workflows have the AsJob common parameter
Checkpoints• Save state (values of variables) and data (output
generated thus far) at a certain place in the code.
• If the workflow suspends and restarts, it restarts from the last checkpoint, not from the beginning.
• Workflow author can add checkpoints.• Checkpoint-Workflow activity• PSPersist activity common parameter
• Workflow user can add checkpoints.• PSPersist workflow common parameter
Suspend-Job and Resume-Job• Works only on workflow jobs.
• Suspend-Job: Runs to the next checkpoint, takes the checkpoint, and pauses.
• Resume-Job: Resumes from the last checkpoint.
In a workflow…• A series of activities.• Each activity runs in a separate session.• Cannot call methods (InlineScript).• Must use explicit parameter names.
In a workflow…• Run in parallel.• Suspend the workflow (from within the workflow).• Restart-Computer (even the workflow server).• Suspend and Resume-Job: Resumes from the last
checkpoint.
Running in "Parallel"• Can run concurrently.• Can run in any order (indeterminate).
Workflow Test-Workflow{ Parallel {
$p = Get-Process$s = Get-Service
}}
Running in Parallel• Managed nodes are processed in parallel.• Parallel keyword
parallel { activity1; activity2 … }
• ForEach -Parallel (<item> in <collection>) { <activities>}
• Sequence keyword• In Parallel script block
Running in Sequence in Parallel
Workflow Test-Workflow{ Parallel {
$p = Get-Process$s = Get-Service
sequence{ $a = Get-ADUser … if ($a) {… }}
}}
Run a Workflow# Create a workflow session on the workflow server computerPS C:\> $s = New-PSWorkflowSession -ComputerName Server01 -Name WF
# Run the Get-Inventory workflow in the session as a job# PSComputerName = Managed nodes# Resources must be on server computerPS C:\> Invoke-Command -Session $s {Get-Inventory -PSComputerName (Get-Content Servers.txt) -AsJob -JobName WFTest}
Run a Workflow (cont.)# Suspend the job PS C:\> Invoke-Command -Session $s {Suspend-Job -JobName WFTest}
# And disconnect the sessionPS C:\> Disconnect-PSSession $s
# Reconnect the sessionPS C:\> $s1 = Connect-PSSession -ComputerName Server01 -Name WF
# And resume the jobPS C:\> Invoke-Command -Session $s1 {Resume-Job -Name WFTest}
Windows PowerShell Core 4.0 Preview
• Save-Help for non-installed modules• Update-Help on isolated computers• Get-Module enhancements• PipelineVariable common parameter
• Get-FileHash
• ScheduledJob improvements• Workflow enhancements• ISE Debugger features
Desired State ConfigurationEverything Else
Windows PowerShell 4.0 includes all of the features of Windows PowerShell 3.0.
Windows PowerShell 2.0 runs side-by-sidefor backward compatibility, but is NOT included.
Get-Help about_Windows_PowerShell 4.0
Save-Help for Non-Installed Modules- Computer that has modules is not connected to the
Internet or is not permitted to download filesfrom the Internet
- Computer with download privileges doesn’t have themodule
# Run on Server01
PS C:\> $m = Invoke-Command –ComputerName Server02 {Get-Module –Name HardwareCertification –ListAvailable}
PS C:\> Save-Help –Module $m –DestinationPath \\Server\HelpFiles
Get-Help Save-Help
Update-Help on Isolated Computers- Computer that has unique module is not connected
to any networks
- Computer with download privileges doesn’t have themodule
#Isolated machinePS C:\> Get-Module –Name HardwareCertification |
Export-Clixml –Path \\ThumbDrive\HardCert.xml
#Networked machinePS C:\> $m = Import-Clixml \\ThumbDrive\HardCert.xmlPS C:\> Save-Help –Module $m–DestinationPath \\ThumbDrive\HardwareCertifcation.dll-help.xml
#Isolated machinePS C:\> Update-Help -Module HardwareCertification -SourcePath \\ThumbDrive\HardwareCertifcation.dll-help.xml
Get-Help about_Updatable_Help
Get-Module –FullyQualifiedNameTakes a hash table or a string
# HashtableGet-Module –FullyQualifiedName @{ModuleName = “BitsTransfer”; ModuleVersion = “1.0.0.0”; GUID = 8fa5064b-8479-4c5c-86ea-0d311fe48875}
# StringGet-Module –FullyQualifiedName BitsTransfer
Get-Help Get-Module
Get-Module –FullyQualifiedNameTakes a hash table or a string
# In a hash table, ModuleName and ModuleVersion are required. GUID is optional. -------------------------------------------------------Get-Module –FullyQualifiedName @{ModuleName = “BitsTransfer”; Version = “1.0”}
# Key names (e.g. ModuleVersion) cannot be abbreviated.
# Both –Name and –FullyQualifiedName accept a name string. Nothing else is permitted in the string.-------------------------------------------------------Get-Module –FullyQualifiedName BitsTransferGet-Module –Name BitsTransfer
# Version matches 1.0 or 1.0.0 for 1.0.0.0, but not 1.0.0.2 or 1.1.0.0Get-Module –FullyQualifiedName @{ModuleName = “BitsTransfer”; GUID = 8fa5064b-8479-4c5c-86ea-0d311fe48875; Version = “1.0”}
Get-Module - Shows version by default Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands---------- ------- ---- ----------------Manifest 1.0.0.0 BitsTransfer {Add-BitsFile, Re...Manifest 1.0.0.0 CimCmdlets {Get-CimAssociate...Script 1.0.0.0 ISE {New-IseSnippet, ...Manifest 3.0.0.0 Microsoft.PowerShell.Diagnostics {Get-WinEvent, Ge...Manifest 3.0.0.0 Microsoft.PowerShell.Host {Start-Transcript...Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Content, Cle...
Get-Help Get-Module
Get-Module #GotchaApplies to PS 3.0 and 4.0
Get-Command
Get-Command
-ListImported
Get-Command is a super-set of Get-Command -ListImported
Get-Help Get-Command
Get-Module #GotchaApplies to PS 3.0 and 4.0
Get-Module -List
Get-Module
Get-Module –ListAvailableis *not* a super-set of Get-Module
Get-Module can include modules thatare not in $env:PSModulePath
Get-Help Get-Module
Get-Command –ParameterName -ParameterType #Gotcha Applies to PS 3.0 and 4.0
Get-Command
-ParameterName-ParameterType
-ParameterName and-ParameterType work onlyon imported commands
Get-Help Get-Command
Get-FileHash *New in Windows PowerShell 4.0
PS C:\> Get-FileHash –Path $pshome\Modules\*\en-US\*
Algorithm Hash Path--------- ---- ----SHA256 6106D0DCAD89F50DCBD255B910E959924A72EABC0C63679B0AC789BB5400EC23 C:\Windows\Syst...SHA256 27A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C C:\Windows\Syst... SHA256 897C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393 C:\Windows\Syst...SHA256 9F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D C:\Windows\Syst... SHA256 2FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A915459154 C:\Windows\Syst...SHA256 4EDE576472BC61220B5B0688D6BF6598E5DD4527766744E740E7151FC29071D6 C:\Windows\Syst...SHA256 8ED38B0A23EA5ACB67942A4194007F4600ED70D54596523E38135AD6C68BFF63 C:\Windows\Syst...SHA256 6D3A7198863AA081C1043CE66F7C46EFAFB1F4268A86550F3D40EBE36871AAC9 C:\Windows\Syst...
Supports:
SHA1, SHA256, SHA384, SHA512MACTripleDESMD5, RIPEMD160
Get-Help Get-FileHash
Get-FileHash *New in Windows PowerShell 4.0
• Has –Path and –Algorithm parameters• But no file search or filtering• Use Get-ChildItem and pipe to Get-FileHash
PS C:\> dir $pshome\* -Recurse –File | Get-FileHash
Algorithm Hash Path--------- ---- ----SHA256 6106D0DCAD89F50DCBD255B910E959924A72EABC0C63679B0AC789BB5400EC23 C:\Windows\Syst...SHA256 27A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C C:\Windows\Syst... SHA256 897C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393 C:\Windows\Syst...SHA256 9F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D C:\Windows\Syst... SHA256 2FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A915459154 C:\Windows\Syst...SHA256 4EDE576472BC61220B5B0688D6BF6598E5DD4527766744E740E7151FC29071D6 C:\Windows\Syst...SHA256 8ED38B0A23EA5ACB67942A4194007F4600ED70D54596523E38135AD6C68BFF63 C:\Windows\Syst...SHA256 6D3A7198863AA081C1043CE66F7C46EFAFB1F4268A86550F3D40EBE36871AAC9 C:\Windows\Syst...
Get-Help Get-FileHash
Get-FileHash *New in Windows PowerShell 4.0
• Is a function in Microsoft.PowerShell.Utility
• To see how it works:(Get-Command Get-FileHash).Definition
Get-Help Get-FileHash
-RunIndefinitely Parameter inNew-JobTriggerSet-JobTrigger
• Runs the job repeatedly (no end time).
• Interval (time between runs) is determined by the value of RepetitionInterval parameter. (Default is 0; do not repeat)
• Equivalent to setting the RepetitionDuration parameter to TimeSpan.MaxValue
Get-Help New-JobTriggerGet-Help Set-JobTrigger
-RunIndefinitely Parameter inNew-JobTriggerSet-JobTrigger
#Job trigger runs the job every two hoursPS C:\> $t = New-JobTrigger –Once –RepetitionInterval (New-Timespan –hours 2) –RepeatIndefinitely
PS C:\> Register-ScheduledJob –Name Scan -Trigger $t-FilePath Scan.ps1
#To stop an indefinite job, set RepetitionDuration to 0.PS C:\> Set-ScheduledJob –Name Scan –Trigger (New-JobTrigger –Once –RepetitionDuration 0)
Get-Help New-JobTriggerGet-Help Set-JobTrigger
-RunNow Parameter inRegister-ScheduledJobSet-ScheduledJob
# Don’t need to change the scheduled job.PS C:\> Set-ScheduledJob –Name UpdateHelp -RunNow
• Runs the new scheduled job as a scheduled job.
• The job results are saved in the AppData directory ($home\AppData\Local\Microsoft\Windows\PowerShell\ScheduledJobs)
• Start-Job runs a scheduled job as a regular Windows PowerShell job. The job results are not saved in the AppData directory.
Get-Help Register-ScheduledJob Set-ScheduledJob
PipelineVariable Common Parameter
• Captures and saves intermediate results
• Great for one-liners
• Common parameter: Available on all cmdlets, workflows, and advanced functions
• “Gotcha”: Variable disappears when the pipeline ends
Get-Help about_CommonParameters
PipelineVariable Common Parameter
#Enter a variable name without $PS C:\> ... | ...-PipelineVariable <name>
PS C:\> 1,2,3,4 | foreach {$_ * 2} | foreach {$_ * 3}6121824
PS C:\> 1,2,3,4 | foreach –PipelineVariable x2 {$_ * 2} | foreach –PipelineVariable x3 {$_ * 3} | {"2x = $x2, 3x = $x3"}2x = 2, 3x = 62x = 4, 3x = 122x = 6, 3x = 182x = 8, 3x = 24
Get-Help about_CommonParameters
PipelineVariable Common Parameter "Gotcha"PS C:\> 1,2,3,4 | foreach –PipelineVariable x2 {$_ * 2} | foreach –PipelineVariable x3 {$_ * 3} | {"x2 = $x2, x3 = $x3"}X2 = 2, x3 = 6X2 = 4, x3 = 12X2 = 6, x3 = 18X2 = 8, x3 = 24
# Variables exists only within the pipeline. # They are gone when the pipeline ends
PS C:\> $x2PS C:\>
PS C:\> $x3PS C:\>
Get-Help about_CommonParameters
PipelineVariable Common Parameter Thanks to PowerShell MVP Keith Hill of Ft. Collins, CO@r_keith_hillkeithhill.wordpress.com PS C:\> Get-Command –type cmdlet | foreach {$_.parametersets} | foreach {$_.parameters} | Select-Object Name
Name----ComputerNameLocalCredentialUnjoinDomainCredentialCredentialDomainNameOUPathServer...
Name : ComputerNameParameterType : System.String[]IsMandatory : FalseIsDynamic : FalsePosition : -2147483648ValueFromPipeline : TrueValueFromPipelineByPropertyName : TrueValueFromRemainingArguments : FalseHelpMessage :Aliases : {}
PipelineVariable Common Parameter Thanks to PowerShell MVP Keith Hill of Ft. Collins, CO@r_keith_hillkeithhill.wordpress.com PS C:\> Get-Command –type cmdlet –PipelineVariable CmdName | foreach {$_.parametersets} | foreach {$_.parameters} | Select-Object @{Label=Cmdlet; Expression=$CmdName}, Name
Cmdlet Name------ ----Add-Computer ComputerNameAdd-Computer LocalCredential...Add-Content ValueAdd-Content PassThru...
Workflow Enhancments
• Foreach –Parallel –ThrottleLimit caps the number of concurrent connections. Resource management.
• If the client computer running a workflow restarts, Windows PowerShell Workflow automatically reconnects to managed nodes.
• ISE debugger debugs script workflows!
• -ErrorAction Suspend suspends the workflow if an error occurs. “Suspend” runs to the next checkpoint and stops until you resume it.
Get-Help about_Workflow about_Foreach_Parallel
ISE Debugger *New in Windows PowerShell 4.0
• Debugs Windows PowerShell script workflows
• Debugs scripts on remote computers
Get-Help about_Windows_PowerShell_ISE
Get-Help• -Detailed: Adds parameter descriptions and
examples• -Full: Adds Inputs, Outputs, Notes• -Parameter: Only parameter descriptions; for one
or all (*) parameters• -Examples: Only the examples• -Path: Help for cmdlets in a provider path• -ShowWindow: Full help displayed in a window.
Works for About help, too.
Get-Help Get-Help
Get-Help in Provider Path(Get-Help Get-ChildItem).Syntax
PS C:\ps-test> (get-help get-childitem).syntax
Get-ChildItem [[-Path]] [[-Filter]] [-Exclude] [-Force] [-Include] [-Name] [-Recurse] [-UseTransaction <SwitchParameter>] [<CommonParameters>]
Get-ChildItem [[-Filter]] [-Exclude] [-Force] [-Include] [-Name] [-Recurse] -LiteralPath [-UseTransaction] [<SwitchParameter>] [<CommonParameters>]
Get-ChildItem [-Attributes <FileAttributes]>] [-Directory] [-File] [-Force] [-Hidden] [-ReadOnly] [-System] [-UseTransaction] [<CommonParameters>]
Get-Help Get-Help, Get-Help <ProviderName>, Get-Help about_Providers
Get-Help in Provider Path(Get-Help Get-ChildItem).Syntax
PS Cert:> (get-help get-childitem).syntax
Get-ChildItem [[-Path]] [[-Filter]] [-Exclude] [-Force] [-Include] [-Name] [-Recurse] [-UseTransaction] [<SwitchParameter>] [<CommonParameters>]
Get-ChildItem [[-Filter]] [-Exclude] [-Force] [-Include] [-Name] [-Recurse] -LiteralPath [-UseTransaction[<SwitchParameter>]] [<CommonParameters>]
Get-ChildItem [-CodeSigningCert] [-DnsName <string>] [-EKU <string>] [-ExpiringInDays <int>] [-SSLServerAuthentication] [<CommonParameters>]Get-Help Get-Help, Get-Help <ProviderName>, Get-Help about_Providers
TechNet Help: Windows PowerShell Corehttp://technet.microsoft.com/en-us/library/bb978526.aspx
TechNet Library Scripting Windows PowerShell
Windows PowerShell on Windows Server
http://technet.microsoft.com/en-us/library/hh801900.aspxTechNet Library Windows Server Windows Server 2012 Management and Tools
Windows PowerShell on MSDNhttp://msdn.microsoft.com/en-us/library/windows/desktop/dd835506(v=vs.85).aspxMSDN Windows Desktop Develop Server and System -> System Administration Windows PowerShell
Writing HelpEvery shared Windows PowerShell command must have help!
Functions: Use comment-based help – it's really easy
<#
.Synopsis
Gets all parameters
.Description
Get-Parameters gets all parameters of all commands in the session and commands in modules in $env:PSModulePath.
.Parameter Command
Gets only the parameters of the specified commands.
.Examples
Get-Parameters
Get-Parameters –Command Get-Module
#> Get-Help about_Comment_Based_Help
Writing Helpful HelpEvery shared Windows PowerShell command must have help!
• Don't repeat. Tell the user what they need to use the command.• DON'T: Get-Name gets the name. • DO: The Get-Name function gets the name of remote computer.
• Each parameter description should have two parts:• The effect of using the parameter (and omitting it, if appropriate)• Valid parameter values
-ComputerName <string>[ ]Runs the command on the specified remote computers. By default, the command runs on all computers in the network. Enter the DNS name or IP address of a remote computer, or to specify the local computer, enter "localhost".
Writing Helpful Examples
• Start with the simplest command (no parameters)
• Add examples in order of increasing complexity
• Use real-world examples
• Use full cmdlet and parameter names, not aliases or abbreviations.
• Teach one skill at a time.
• Don't be clever!
Community Resources
• Team blog: http://blogs.msdn.com/PowerShell • Script Center: http://technet.Microsoft.com/ScriptCenter • Hey, Scripting Guy blog• PowerShell.org• PowerShell Magazine• Channel 9: http://channel9.msdn.com/tags/PowerShell
• Books: Get latest version. Search for 3.0 or 4.0.• Learn Windows PowerShell in a Month of Lunches by Don Jones• Window PowerShell in Action by Bruce Payette• Windows PowerShell Cookbook by Lee Holmes• Windows PowerShell for Developers by Doug Finke• PowerShell Deep Dives by Windows PowerShell MVPs
• Blogs, Twitter• Jeffrey Snover, Oisin Grehan, Jeffery Hicks, Mike F. Robbins, Rohn Edwards• Richard Siddaway, Boe Prox, Jan Egil Ring, Steven Muraski, Scripting Guys,
ScriptingWife