PhillyPosh_2013-07-11_June_Blender

Report
The Hidden Charms
of
Windows PowerShell
3.0 and 4.0
June Blender
Senior Programming Writer
Microsoft Corporation
@juneb_get_help
[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!
The Advanced Parts
•
•
•
•
•
Disconnected Sessions
Windows PowerShell Workflow
Scheduled Jobs
Dynamic Type Data
Updatable Help
Get-Help
•
•
•
•
•
Get-Help -ShowWindow
Show-Command
Map Network Drive
Unblock-File
ISE snippets
Windows PowerShell 3.0 includes
Windows PowerShell 2.0 running
side-by-side
Simplified Syntax:
{$_.}
Avoid errors
Make it work
Make 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
$a = ‘abc’
$a.ToUpper()
PS 3.0:
# One or more objects
$a.ToUpper()
ABC
Get-Help about_Methods
# Multiple objects
$b = ‘abc’, ‘def’
$b.ToUpper() #FAIL
$b.ToUpper()
ABC
DEF
Count / Length
… of a single object if ($p.Count –gt 0)…
PS 2.0:
# One object
'abc'.Count
#Nothing
# Multiple objects
('abc', 'def').Count
2
PS 3.0:
# One object
'abc'.Count
1
# Zero objects
$null.Count
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-Loading
PS 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
Get-Help about_Modules
Import-Module
Module Auto-Loading “Gotcha”
Import-Module
PS C:\> Get-Job –JobName MyScheduledJob
# Nothing
PS C:\> Get-ScheduledJob MyScheduledJob
Id
-1
Name
---MyScheduledJob
JobTriggers
----------1
Command
Enabled
------------Update-Help True
PS C:\> Get-Job –JobName MyScheduledJob
Id
-2
Name
---MyScheduledJob
PSJobTypeName
-----------PSScheduledJob
State
----Completed
Get-Help about_Modules, about_Scheduled_Jobs
HasMoreData
----------True
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
Settings are saved.
PS C:\> Get-Help Update-Help –ShowWindow
Get-Help Get-Help
Get-Help –ShowWindow #Gotcha
Displays only the first paragraph of parameter descriptions
Get-Help Get-Help
Show-Command
DEMO !!
Get-Help Show-Command
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
Get-Help New-PSDrive
\\Server01\\PowerShell
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
• 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
Get-Help New-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 Sessions
1.
2.
3.
4.
5.
6.
Start a PSSession.
Run commands in the PSSession.
[ Disconnect from the PSSession.]
Exit Windows PowerShell.
Shut down the machine.
Go home…
7.
8.
9.
10.
Boot up your laptop.
Start Windows PowerShell.
Reconnect to the PSSession.
Get the results of commands run in the
session.
At work…
At home…
Get-Help about_Remote_Disconnected_Sessions
Disconnected Sessions
DISCONNECTED SESSION CMDLETS
•
•
•
•
New-PSSession:
Disconnect-PSSession:
Connect-PSSession:
Receive-PSSession:
• Get-PSSession:
• Invoke-Command:
Get-Help New-PSSession
Creates a PSSession.
Disconnects a PSSession.
Connects to a disconnected PSSession.
Gets the results of commands that ran in disconnected
sessions.
Gets PSSessions on the local computer or on remote
computers.
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 is
saved at the remote end, even if the current
Session is disconnected.
Get-Help New-PSSession
Localhost
To: Server01
To: Server012
Server012
From: Server01
From: Server012
From: Server02
Get-PSSession -ComputerName
PS 2.0:
Gets sessions in the current session that are
connected to <ComputerName>.
Localhost
To: Server01
To: Server012
PS 3.0:
Gets all sessions on <ComputerName> for the current
user.
Server012
To get sessions in the current
session, omit -ComputerName.
Get-Help Get-PSSession
From: Server01
From: Server012
From: Server02
Get-PSSession -ComputerName
# On Server01
PS C:\> New-PSSession –ComputerName Server02
Server02
PS C:\> Get-PSSession –ComputerName Server02
From: Server01
Id Name
-- ---1 Session1
ComputerName
-----------Server02
State
----Opened
ConfigurationName
----------------Microsoft.PowerShell
Availability
-----------Available
# On Server02
PS C:\> Get-PSSession
Id Name
-- ---1 Session1
ComputerName
-----------Server02
State
----Opened
ConfigurationName
----------------Microsoft.PowerShell
Availability
-----------Busy
ConfigurationName
----------------Microsoft.PowerShell
Availability
-----------Busy
# On Server03
PS C:\> Get-PSSession –ComputerName Server02
Id Name
-- ---1 Session1
ComputerName
-----------Server02
Get-Help Get-PSSession
State
----Disconnected
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 IdleTimeout
Set 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
DEMO !!
Get-Help about_Remote_Disconnected_Sessions
Disconnected Sessions: How it Works
Session 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 Configurations
Session 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 Jobs
Don’t exceed the IdleTimeout
Set the BufferMode
carefully
of Windows
PowerShell
• Scheduled jobs are a unique hybrid
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 IdleTimeout
Set 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-ScheduledJob
PS C:\>
# function elevate; “Run as administrator”
PS C:\> Start-Process PowerShell –Verb RunAs
PS C:\> Get-ScheduledJob
Id
-1
Name
JobTriggers Command
Enabled
-------------- ------------UpdateHelp 1
Update-Help True
Get-Help about_Scheduled_Jobs
Dynamic Type Data
• 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
Get-Help Update-TypeData, about_Types.ps1xml
Dynamic Type Data
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
True
Microsoft.PowerShell.Host
True
Microsoft.PowerShell.Management
True
Microsoft.PowerShell.Security
True
PSDiagnostics
False
PSScheduledJob
True
TroubleshootingPack
False
Get-Help Update-TypeData, about_Types.ps1xml
Dynamic Type Data
PS C:\>Update-TypeData -TypeName System.DateTime
-DefaultDisplayPropertySet DayOfWeek, Date, TimeOfDay
PS C:\>Get-Date | Format-List
DayOfWeek: Tuesday
Date: 7/9/2013 12:00:00 AM
TimeOfDay: 17:32:49:5829247
Get-Help Update-TypeData, about_Types.ps1xml
Updatable Help
Don’t exceed the IdleTimeout
Set 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 IdleTimeout
Set 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 IdleTimeout
Set 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 IdleTimeout
Set 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 computer
PS 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 computer
PS C:\> Invoke-Command -Session $s {GetInventory -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 session
PS C:\> Disconnect-PSSession $s
# Reconnect the session
PS C:\> $s1 = Connect-PSSession ComputerName Server01 -Name WF
# And resume the job
PS C:\> Invoke-Command -Session $s1
{Resume-Job -Name WFTest}
Windows PowerShell Core 4.0 Preview
Desired State Configuration
Everything Else
•
•
•
•
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
Windows PowerShell 4.0 includes all of the
features of Windows PowerShell 3.0.
Windows PowerShell 2.0 runs side-by-side
for 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 files
from the Internet
- Computer with download privileges doesn’t have the
module
# 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 the
module
#Isolated machine
PS C:\> Get-Module –Name HardwareCertification |
Export-Clixml –Path \\ThumbDrive\HardCert.xml
#Networked machine
PS C:\> $m = Import-Clixml \\ThumbDrive\HardCert.xml
PS C:\> Save-Help –Module $m
–DestinationPath \\ThumbDrive\HardwareCertifcation.dll-help.xml
#Isolated machine
PS C:\> Update-Help -Module HardwareCertification
-SourcePath \\ThumbDrive\HardwareCertifcation.dll-help.xml
Get-Help about_Updatable_Help
Get-Module –FullyQualifiedName
Takes a hash table or a string
# Hashtable
Get-Module –FullyQualifiedName @{ModuleName = “BitsTransfer”;
ModuleVersion = “1.0.0.0”;
GUID = 8fa5064b-8479-4c5c-86ea-0d311fe48875}
# String
Get-Module –FullyQualifiedName BitsTransfer
Get-Help Get-Module
Get-Module –FullyQualifiedName
Takes 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 BitsTransfer
Get-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.0
Get-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
---------Manifest
Manifest
Script
Manifest
Manifest
Manifest
Version
------1.0.0.0
1.0.0.0
1.0.0.0
3.0.0.0
3.0.0.0
3.1.0.0
Name
---BitsTransfer
CimCmdlets
ISE
Microsoft.PowerShell.Diagnostics
Microsoft.PowerShell.Host
Microsoft.PowerShell.Management
Get-Help Get-Module
ExportedCommands
---------------{Add-BitsFile, Re...
{Get-CimAssociate...
{New-IseSnippet, ...
{Get-WinEvent, Ge...
{Start-Transcript...
{Add-Content, Cle...
Get-Module #Gotcha
Applies to PS 3.0 and 4.0
Get-Command
Get-Command
-ListImported
Get-Help Get-Command
Get-Command is a
super-set of
Get-Command -ListImported
Get-Module #Gotcha
Applies to PS 3.0 and 4.0
Get-Module -List
Get-Module –ListAvailable
is *not* a super-set of
Get-Module
Get-Module can include modules that
are not in $env:PSModulePath
Get-Module
Get-Help Get-Module
Get-Command –ParameterName -ParameterType
#Gotcha Applies to PS 3.0 and 4.0
Get-Command
-ParameterName and
-ParameterType work only
on imported commands
-ParameterName
-ParameterType
Get-Help Get-Command
Get-FileHash
*New in Windows PowerShell 4.0
PS C:\> Get-FileHash –Path $pshome\Modules\*\en-US\*
Algorithm
--------SHA256
SHA256
SHA256
SHA256
SHA256
SHA256
SHA256
SHA256
Hash
---6106D0DCAD89F50DCBD255B910E959924A72EABC0C63679B0AC789BB5400EC23
27A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C
897C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393
9F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D
2FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A915459154
4EDE576472BC61220B5B0688D6BF6598E5DD4527766744E740E7151FC29071D6
8ED38B0A23EA5ACB67942A4194007F4600ED70D54596523E38135AD6C68BFF63
6D3A7198863AA081C1043CE66F7C46EFAFB1F4268A86550F3D40EBE36871AAC9
Supports:
SHA1, SHA256, SHA384, SHA512
MACTripleDES
MD5, RIPEMD160
Get-Help Get-FileHash
Path
---C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
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
--------SHA256
SHA256
SHA256
SHA256
SHA256
SHA256
SHA256
SHA256
Hash
---6106D0DCAD89F50DCBD255B910E959924A72EABC0C63679B0AC789BB5400EC23
27A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C
897C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393
9F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D
2FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A915459154
4EDE576472BC61220B5B0688D6BF6598E5DD4527766744E740E7151FC29071D6
8ED38B0A23EA5ACB67942A4194007F4600ED70D54596523E38135AD6C68BFF63
6D3A7198863AA081C1043CE66F7C46EFAFB1F4268A86550F3D40EBE36871AAC9
Get-Help Get-FileHash
Path
---C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
C:\Windows\Syst...
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 in
New-JobTrigger
Set-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-JobTrigger
Get-Help Set-JobTrigger
-RunIndefinitely Parameter in
New-JobTrigger
Set-JobTrigger
#Job trigger runs the job every two hours
PS 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 (NewJobTrigger –Once –RepetitionDuration 0)
Get-Help New-JobTrigger
Get-Help Set-JobTrigger
-RunNow Parameter in
Register-ScheduledJob
Set-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}
6
12
18
24
PS C:\>
foreach
2x = 2,
2x = 4,
2x = 6,
2x = 8,
1,2,3,4 | foreach –PipelineVariable x2 {$_ * 2} |
–PipelineVariable x3 {$_ * 3} | {"2x = $x2, 3x = $x3"}
3x = 6
3x = 12
3x = 18
3x = 24
Get-Help about_CommonParameters
PipelineVariable Common Parameter "Gotcha"
PS C:\>
foreach
X2 = 2,
X2 = 4,
X2 = 6,
X2 = 8,
1,2,3,4 | foreach –PipelineVariable x2 {$_ * 2} |
–PipelineVariable x3 {$_ * 3} | {"x2 = $x2, x3 = $x3"}
x3 = 6
x3 = 12
x3 = 18
x3 = 24
# Variables exists only within the pipeline.
# They are gone when the pipeline ends
PS C:\> $x2
PS C:\>
PS C:\> $x3
PS C:\>
Get-Help about_CommonParameters
PipelineVariable Common Parameter
Thanks to PowerShell MVP Keith Hill of Ft. Collins, CO
@r_keith_hill
keithhill.wordpress.com
PS C:\> Get-Command –type cmdlet | foreach {$_.parametersets} |
foreach {$_.parameters} | Select-Object Name
Name
---ComputerName
LocalCredential
UnjoinDomainCredential
Credential
DomainName
OUPath
Server
...
Name
: ComputerName
ParameterType
: System.String[]
IsMandatory
: False
IsDynamic
: False
Position
: -2147483648
ValueFromPipeline
: True
ValueFromPipelineByPropertyName : True
ValueFromRemainingArguments : False
HelpMessage
:
Aliases
: {}
PipelineVariable Common Parameter
Thanks to PowerShell MVP Keith Hill of Ft. Collins, CO
@r_keith_hill
keithhill.wordpress.com
PS C:\> Get-Command –type cmdlet –PipelineVariable CmdName |
foreach {$_.parametersets} | foreach {$_.parameters} | SelectObject @{Label=Cmdlet; Expression=$CmdName}, Name
Cmdlet
-----Add-Computer
Add-Computer
...
Add-Content
Add-Content
...
Name
---ComputerName
LocalCredential
Value
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 Core
http://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.aspx
TechNet  Library  Windows Server  Windows Server 2012 
Management and Tools
Windows PowerShell on MSDN
http://msdn.microsoft.com/en-us/library/windows/desktop/dd835506(v=vs.85).aspx
MSDN  Windows  Desktop  Develop  Server and System -> System Administration
 Windows PowerShell
Writing Help
Every 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 Help
Every 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

similar documents