Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Hidden Charms of Windows PowerShell 3.0 and 4.0 June Blender Senior Programming Writer Microsoft

Similar presentations


Presentation on theme: "The Hidden Charms of Windows PowerShell 3.0 and 4.0 June Blender Senior Programming Writer Microsoft"— Presentation transcript:

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

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 : Windows PowerShell 2.0 Included: Windows 7 and Windows Server 2008 WMF: Windows XP, Windows Server 2003 R2 Microsoft.NET 2.5, 3, CLR : 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 : 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 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

6 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

7 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

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 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() ABCABC 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 1 0 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 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 Import-Module Get-Help about_Modules

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

17 Get-ChildItem (dir) PS 3.0: New Parameters in FileSystem drives -Filedir s* -af -Directorydir s* -ad -ReadOnlydir s* -af -ar -Hiddendir s* -ar -ah -System dir s* -as -Attributesdir -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 Get-Help PS C:\> Get-Help Update-Help –ShowWindow Settings are saved.

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

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

21 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

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\\Server01\PowerShell 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 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

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

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

31 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 To: Server01 To: Server012 Localhost From: Server01 From: Server012 From: Server02 Server012

32 Get-PSSession - ComputerName PS 2.0: Gets sessions in the current session that are connected to. PS 3.0: Gets all sessions on for the current user. To get sessions in the current session, omit -ComputerName. Get-Help Get-PSSession To: Server01 To: Server012 Localhost From: Server01 From: Server012 From: Server02 Server012

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

34 How to Disconnect: 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 Get-Help about_Remote_Disconnected_Sessions DEMO !!

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:\ \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 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 PS C:\> Get-ScheduledJob Id Name JobTriggers Command Enabled UpdateHelp 1 Update-Help True Get-Help about_Scheduled_Jobs

43 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

44 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 True Microsoft.PowerShell.Host True Microsoft.PowerShell.Management True Microsoft.PowerShell.Security True PSDiagnostics False PSScheduledJob True TroubleshootingPack False

45 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: Tuesday Date: 7/9/ :00:00 AM TimeOfDay: 17:32:49:

46 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

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 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 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 Update-Help -SourcePath 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 ( in ) { } 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 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 Configuration Everything Else 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 Server02 {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 #Isolated machine 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 Get-Module = “BitsTransfer”; GUID = 8fa5064b c5c-86ea-0d311fe48875; Version = “1.0”}

71 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-Module #Gotcha Applies 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

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

74 Get-Command –ParameterName -ParameterType #Gotcha Applies to PS 3.0 and 4.0 Get-Command -ParameterName -ParameterType -ParameterName and -ParameterType work only on imported commands 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... SHA256 27A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C C:\Windows\Syst... SHA C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393 C:\Windows\Syst... SHA256 9F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D C:\Windows\Syst... SHA256 2FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A C:\Windows\Syst... SHA256 4EDE576472BC61220B5B0688D6BF6598E5DD E740E7151FC29071D6 C:\Windows\Syst... SHA256 8ED38B0A23EA5ACB67942A F4600ED70D E38135AD6C68BFF63 C:\Windows\Syst... SHA256 6D3A 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... SHA256 27A67BC6D62FB41D111123FA5FB4A8C0F934D52CEFD9AFC98221E99CCE41C39C C:\Windows\Syst... SHA C9DB8BF436AA784F7B6BF53EDE2C48E9883F37D28D99A1C402C1CCE2A6393 C:\Windows\Syst... SHA256 9F90A552D621A74D4D5B7F67FA94280F4E55E9927F715CC481C12D3B0B29379D C:\Windows\Syst... SHA256 2FB832D4E35448CA2D0B12E71401DA8FB398E0411A23B93A1DB441A C:\Windows\Syst... SHA256 4EDE576472BC61220B5B0688D6BF6598E5DD E740E7151FC29071D6 C:\Windows\Syst... SHA256 8ED38B0A23EA5ACB67942A F4600ED70D E38135AD6C68BFF63 C:\Windows\Syst... SHA256 6D3A 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 -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 PS C:\> 1,2,3,4 | foreach {$_ * 2} | foreach {$_ * 3} 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 PS C:\> Get-Help about_CommonParameters

84 PipelineVariable Common Parameter Thanks to PowerShell MVP Keith Hill of Ft. Collins, 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, keithhill.wordpress.com PS C:\> Get-Command –type cmdlet –PipelineVariable CmdName | foreach {$_.parametersets} | foreach {$_.parameters} | Select- 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

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 ] [ ] Get-ChildItem [[-Filter]] [-Exclude] [-Force] [-Include] [-Name] [- Recurse] -LiteralPath [-UseTransaction] [ ] [ ] Get-ChildItem [-Attributes ] [-Directory] [-File] [- Force] [-Hidden] [-ReadOnly] [-System] [-UseTransaction] [ ] Get-Help Get-Help, Get-Help, 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] [ ] [ ] Get-ChildItem [[-Filter]] [-Exclude] [-Force] [-Include] [-Name] [- Recurse] -LiteralPath [-UseTransaction[ ]] [ ] Get-ChildItem [-CodeSigningCert] [-DnsName ] [-EKU ] [-ExpiringInDays ] [-SSLServerAuthentication] [ ] Get-Help Get-Help, Get-Help, 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 [ ] 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: 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 June Blender Senior Programming Writer Microsoft"

Similar presentations


Ads by Google