Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Hidden Charms of Windows PowerShell 3.0 and 4.0

Similar presentations


Presentation on theme: "The Hidden Charms of Windows PowerShell 3.0 and 4.0"— Presentation transcript:

1 The Hidden Charms of Windows PowerShell 3.0 and 4.0
June Blender Senior Programming Writer Microsoft Corporation @juneb_get_help

2 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

3 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

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

5 Windows PowerShell 4.0 Preview
Included in Windows 8.1 and Windows Server 2012 R2 Windows Management Framework 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

6 How to Get Windows PowerShell
Included in Windows 7 and Windows Server 2008 Windows Management Framework 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 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 for Windows 7, Windows Server 2008, Windows Server 2008 R2

7 Cool Features in PowerShell Core 3.0
The Basics Simplified syntax Get-Help -ShowWindow Getting properties and methods Show-Command Get-Command – Improved! Map Network Drive Module AutoLoading Unblock-File Get-ChildItem – Improved! 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

8 Simplified Syntax: {$_.} Avoid errors Make it work Make everyone successful

9 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

10 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

11 Get Properties … of multiple objects
. 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

12 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

13 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 Get-Help about_Properties, about_Arrays

14 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

15 Module Auto-Loading Import-Module PS 2.0: Get-Module | Import-Module
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

16 Module Auto-Loading “Gotcha”
Import-Module PS C:\> Get-Job –JobName MyScheduledJob # Nothing PS C:\> Get-ScheduledJob MyScheduledJob Id Name JobTriggers Command Enabled MyScheduledJob Update-Help True Id Name PSJobTypeName State HasMoreData MyScheduledJob PSScheduledJob Completed True Get-Help about_Modules, about_Scheduled_Jobs

17 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:

18 Get-Help -ShowWindow Settings are saved.
PS C:\> Get-Help Update-Help –ShowWindow Get-Help Get-Help

19 Get-Help –ShowWindow #Gotcha
Displays only the first paragraph of parameter descriptions Get-Help Get-Help

20 Show-Command DEMO !! Get-Help Show-Command

21 Map Network Drive New-PSDrive -Persist
New-PSDrive creates drives in the current session. PS 3.0: New-PSDrive –Persist creates mapped network drive. Get-Help New-PSDrive

22 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 FileSystem \\Server01\\PowerShell Get-Help New-PSDrive

23 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

24 Unblock-File Get-Help Unblock-File

25 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

26 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

27 Create an ISE Snippet DEMO !!

28 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 !

29 Disconnected Sessions
Start a PSSession. Run commands in the PSSession. [ Disconnect from the PSSession.] Exit Windows PowerShell. Shut down the machine. Go home… 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

30 Disconnected Sessions
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. Get-Help New-PSSession

31 PSSessions are session-independent
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. Localhost To: Server01 To: Server012 Server012 From: Server01 From: Server012 From: Server02 Get-Help New-PSSession

32 Get-PSSession -ComputerName
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. Localhost To: Server01 To: Server012 Server012 From: Server01 From: Server012 From: Server02 Get-Help Get-PSSession

33 Get-PSSession -ComputerName
# On Server01 PS C:\> New-PSSession –ComputerName Server02 PS C:\> Get-PSSession –ComputerName Server02 Id Name ComputerName State ConfigurationName Availability 1 Session Server Opened Microsoft.PowerShell Available Server02 From: Server01 # On Server02 PS C:\> Get-PSSession Id Name ComputerName State ConfigurationName Availability 1 Session Server Opened Microsoft.PowerShell Busy # On Server03 PS C:\> Get-PSSession –ComputerName Server02 Id Name ComputerName State ConfigurationName Availability 1 Session Server Disconnected Microsoft.PowerShell Busy Get-Help Get-PSSession

34 How to Disconnect: How to Connect / Reconnect: Connect-PSSession
Disconnect-PSSession Invoke-Command -InDisconnectedSession How to Connect / Reconnect: Connect-PSSession Receive-PSSession Get-Help about_Remote_Disconnected_Sessions

35 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

36 Disconnected Sessions
DEMO !! Get-Help about_Remote_Disconnected_Sessions

37 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

38 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

39 Scheduled Jobs Don’t exceed the IdleTimeout Set 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

40 Scheduled Jobs Trigger: New-JobTrigger: Sets the schedule.
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

41 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

42 Scheduled Jobs “Gotcha”
PS C:\> Get-ScheduledJob PS C:\> # function elevate; “Run as administrator” PS C:\> Start-Process PowerShell –Verb RunAs Id Name JobTriggers Command Enabled 1 UpdateHelp Update-Help True Get-Help about_Scheduled_Jobs

43 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

44 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

45 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/ :00:00 AM TimeOfDay: 17:32:49: Get-Help Update-TypeData, about_Types.ps1xml

46 Updatable Help Problem: Outdated help files
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

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

48 Update-Help Figures out which modules support Updatable 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

49 Save-Help Figures out which modules support Updatable 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

50 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

51 Update-Help for your Module
Supporting Updatable Help (MSDN) Supporting Online Help (MSDN)

52 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

53 How to Write a Script Workflow
TechNet  Library  Windows Server  Windows Server 2012  Management and Tools  Getting Started with Windows PowerShell Workflow

54 How to Write a Script Workflow
TechNet  Library  Windows Server  Windows Server 2012  Management and Tools  Getting Started with Windows PowerShell Workflow Use Windows PowerShell ISE

55 Workflow Configuration

56 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

57 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

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

59 In a workflow… A series of activities.
Each activity runs in a separate session. Cannot call methods (InlineScript). Must use explicit parameter names.

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

61 Running in "Parallel" Can run concurrently.
Can run in any order (indeterminate). Workflow Test-Workflow { Parallel { $p = Get-Process $s = Get-Service }

62 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

63 Running in Sequence in Parallel
Workflow Test-Workflow { Parallel { $p = Get-Process $s = Get-Service sequence $a = Get-ADUser … if ($a) {… } }

64 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 {Get-Inventory -PSComputerName (Get-Content Servers.txt) -AsJob -JobName WFTest}

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

66 Windows PowerShell Core 4.0 Preview
Desired State Configuration Everything Else Save-Help for non-installed modules Get-FileHash Update-Help on isolated computers ScheduledJob improvements Get-Module enhancements Workflow enhancements PipelineVariable common parameter 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

67 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 Server {Get-Module –Name HardwareCertification –ListAvailable} PS C:\> Save-Help –Module $m –DestinationPath \\Server\HelpFiles Get-Help Save-Help

68 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 PS C:\> Update-Help -Module HardwareCertification -SourcePath \\ThumbDrive\HardwareCertifcation.dll-help.xml Get-Help about_Updatable_Help

69 Get-Module –FullyQualifiedName
Takes a hash table or a string # Hashtable Get-Module = “BitsTransfer”; ModuleVersion = “ ”; GUID = 8fa5064b c5c-86ea-0d311fe48875} # String Get-Module –FullyQualifiedName BitsTransfer Get-Help Get-Module

70 Get-Module –FullyQualifiedName
Takes a hash table or a string # In a hash table, ModuleName and ModuleVersion are required. GUID is optional. Get-Module = “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 for , but not or GUID = 8fa5064b c5c-86ea-0d311fe48875;

71 - Shows version by default
Get-Module - Shows version by default Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules ModuleType Version Name ExportedCommands Manifest BitsTransfer {Add-BitsFile, Re... Manifest CimCmdlets {Get-CimAssociate... Script ISE {New-IseSnippet, ... Manifest Microsoft.PowerShell.Diagnostics {Get-WinEvent, Ge... Manifest Microsoft.PowerShell.Host {Start-Transcript... Manifest Microsoft.PowerShell.Management {Add-Content, Cle... Get-Help Get-Module

72 Get-Command -ListImported
Get-Module #Gotcha Applies to PS 3.0 and 4.0 Get-Command is a super-set of Get-Command -ListImported Get-Command Get-Command -ListImported Get-Help Get-Command

73 Get-Module -List Get-Module #Gotcha Get-Module –ListAvailable
Applies to PS 3.0 and 4.0 Get-Module –ListAvailable is *not* a super-set of Get-Module Get-Module -List Get-Module Get-Module can include modules that are not in $env:PSModulePath Get-Help Get-Module

74 -ParameterName -ParameterType
Get-Command –ParameterName -ParameterType #Gotcha Applies to PS 3.0 and 4.0 -ParameterName and -ParameterType work only on imported commands Get-Command -ParameterName -ParameterType Get-Help Get-Command

75 Get-FileHash *New in Windows PowerShell 4.0
PS C:\> Get-FileHash –Path $pshome\Modules\*\en-US\* Algorithm Hash Path SHA D0DCAD89F50DCBD255B910E959924A72EABC0C63679B0AC789BB5400EC23 C:\Windows\Syst... SHA A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C C:\Windows\Syst... SHA C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393 C:\Windows\Syst... SHA F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D C:\Windows\Syst... SHA FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A C:\Windows\Syst... SHA EDE576472BC61220B5B0688D6BF6598E5DD E740E7151FC29071D6 C:\Windows\Syst... SHA ED38B0A23EA5ACB67942A F4600ED70D E38135AD6C68BFF63 C:\Windows\Syst... SHA D3A AA081C1043CE66F7C46EFAFB1F4268A86550F3D40EBE36871AAC9 C:\Windows\Syst... Supports: SHA1, SHA256, SHA384, SHA512 MACTripleDES MD5, RIPEMD160 Get-Help Get-FileHash

76 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 SHA D0DCAD89F50DCBD255B910E959924A72EABC0C63679B0AC789BB5400EC23 C:\Windows\Syst... SHA A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C C:\Windows\Syst... SHA C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393 C:\Windows\Syst... SHA F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D C:\Windows\Syst... SHA FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A C:\Windows\Syst... SHA EDE576472BC61220B5B0688D6BF6598E5DD E740E7151FC29071D6 C:\Windows\Syst... SHA ED38B0A23EA5ACB67942A F4600ED70D E38135AD6C68BFF63 C:\Windows\Syst... SHA D3A AA081C1043CE66F7C46EFAFB1F4268A86550F3D40EBE36871AAC9 C:\Windows\Syst... Get-Help Get-FileHash

77 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

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

79 -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 (New-JobTrigger –Once –RepetitionDuration 0) Get-Help New-JobTrigger Get-Help Set-JobTrigger

80 Register-ScheduledJob Set-ScheduledJob
-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

81 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

82 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:\> 1,2,3,4 | foreach –PipelineVariable x2 {$_ * 2} | foreach –PipelineVariable x3 {$_ * 3} | {"2x = $x2, 3x = $x3"} 2x = 2, 3x = 6 2x = 4, 3x = 12 2x = 6, 3x = 18 2x = 8, 3x = 24 Get-Help about_CommonParameters

83 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 = 6 X2 = 4, x3 = 12 X2 = 6, x3 = 18 X2 = 8, x3 = 24 # Variables exists only within the pipeline. # They are gone when the pipeline ends PS C:\> $x2 PS C:\> PS C:\> $x3 Get-Help about_CommonParameters

84 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 : ValueFromPipeline : True ValueFromPipelineByPropertyName : True ValueFromRemainingArguments : False HelpMessage : Aliases : {}

85 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} | Expression=$CmdName}, Name Cmdlet Name Add-Computer ComputerName Add-Computer LocalCredential ... Add-Content Value Add-Content PassThru

86 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

87 ISE Debugger *New in Windows PowerShell 4.0
Debugs Windows PowerShell script workflows Debugs scripts on remote computers Get-Help about_Windows_PowerShell_ISE

88 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

89 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

90 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

91 TechNet Help: Windows PowerShell Core
TechNet  Library  Scripting  Windows PowerShell

92 Windows PowerShell on Windows Server
TechNet  Library  Windows Server  Windows Server 2012  Management and Tools

93 Windows PowerShell on MSDN
MSDN  Windows  Desktop  Develop  Server and System -> System Administration  Windows PowerShell

94 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

95 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".

96 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!

97 Community Resources Team blog: http://blogs.msdn.com/PowerShell
Script Center: Hey, Scripting Guy blog PowerShell.org PowerShell Magazine Channel 9: 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


Download ppt "The Hidden Charms of Windows PowerShell 3.0 and 4.0"

Similar presentations


Ads by Google