Monthly Archive

Categories

.psd1 files

.psd1 files are usually used as module manifests

You can test the manifest

PS>  Test-ModuleManifest -Path 'C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psd1' | fl

Name              : Pester
Path              : C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psd1
Description       : Pester provides a framework for running BDD style Tests to execute and validate PowerShell commands inside of PowerShell and offers a powerful set of Mocking Functions that allow tests to mimic and mock the  functionality of any command inside of a piece of powershell code being tested. Pester tests can execute any command or script that is accesible to a pester test file. This can include functions, Cmdlets,  Modules and scripts. Pester can be run in ad hoc style in a console or it can be integrated into the Build scripts of a Continuous Integration system.
ModuleType        : Script
Version           : 3.4.0
NestedModules     : {}
ExportedFunctions : {Describe, Context, It, Should...}
ExportedCmdlets   :
ExportedVariables : {Path, TagFilter, ExcludeTagFilter, TestNameFilter...}
ExportedAliases   :

 

or you can view the whole output

 

PS>  Test-ModuleManifest -Path 'C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psd1' | fl *

LogPipelineExecutionDetails : False
Name                        : Pester
Path                        : C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psd1
ImplementingAssembly        :
Definition                  :
Description       : Pester provides a framework for running BDD style Tests to execute and validate PowerShell commands inside of PowerShell and offers a powerful set of Mocking Functions that allow tests to mimic and mock the  functionality of any command inside of a piece of powershell code being tested. Pester tests can execute any command or script that is accesible to a pester test file. This can include functions, Cmdlets,  Modules and scripts. Pester can be run in ad hoc style in a console or it can be integrated into the Build scripts of a Continuous Integration system.
Guid                        : a699dea5-2c73-4616-a270-1f7abb777e71
HelpInfoUri                 :
ModuleBase                  : C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0
PrivateData                 : {PSData}
Tags                        : {powershell, unit testing, bdd, tdd...}
ProjectUri                  : https://github.com/Pester/Pester
IconUri                     : http://pesterbdd.com/images/Pester.png
LicenseUri                  : http://www.apache.org/licenses/LICENSE-2.0.html
ReleaseNotes                :
RepositorySourceLocation    :
Version                     : 3.4.0
ModuleType                  : Script
Author                      : Pester Team
AccessMode                  : ReadWrite
ClrVersion                  :
CompanyName                 : Pester
Copyright                   : Copyright (c) 2016 by Pester Team, licensed under Apache 2.0 License.
DotNetFrameworkVersion      :
ExportedFunctions           : {[Describe, Describe], [Context, Context], [It, It], [Should, Should]...}
Prefix                      :
ExportedCmdlets             : {}
ExportedCommands            : {[Describe, Describe], [Context, Context], [It, It], [Should, Should]...}
FileList                    : {}
CompatiblePSEditions        : {}
ModuleList                  : {}
NestedModules               : {}
PowerShellHostName          :
PowerShellHostVersion       :
PowerShellVersion           : 2.0
ProcessorArchitecture       : None
Scripts                     : {}
RequiredAssemblies          : {}
RequiredModules             : {}
RootModule                  : Pester.psm1
ExportedVariables           : {[Path, ], [TagFilter, ], [ExcludeTagFilter, ], [TestNameFilter, ]...}
ExportedAliases             : {}
ExportedWorkflows           : {}
ExportedDscResources        : {}
SessionState                :
OnRemove                    :
ExportedFormatFiles         : {}
ExportedTypeFiles           : {}

 

You can also import the contents of the .psd1 file

PS>  Import-PowerShellDataFile -Path 'C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Pester.psd1'

Name                           Value                                                                                          
----                           -----                                                                                          
Copyright                      Copyright (c) 2016 by Pester Team, licensed under Apache 2.0 License.                          
ModuleToProcess                Pester.psm1                                                                                    
PrivateData                    {PSData}                                                                                       
PowerShellVersion              2.0                                                                                            
CompanyName                    Pester                                                                                         
GUID                           a699dea5-2c73-4616-a270-1f7abb777e71                                                           
Author                         Pester Team                                                                                    
FunctionsToExport              {Describe, Context, It, Should...}                                                             
VariablesToExport              {Path, TagFilter, ExcludeTagFilter, TestNameFilter...}                                         
Description                    Pester provides a framework for running BDD style Tests to execute and validate PowerShell co...
ModuleVersion                  3.4.0 

 

which in some ways is more useful as you can easily see what is actually in the manifets rather than dealing with a lot of empty properties.

 

You can create .psd1 files to hold other data and read them with Import-PowerShellDataFile. Default parameters for your favourite cmdlets is one thing that comes to mind

Get-ComputerInfo

One of the new items in PowerShell 5.1 is the Get-ComputerInfo cmdlet

PS>  Get-Command Get-ComputerInfo -Syntax

Get-ComputerInfo [[-Property] <string[]>] [<CommonParameters>]

 

PS>  Get-ComputerInfo

WindowsBuildLabEx                                       : 14393.0.amd64fre.rs1_release.160715-1616
WindowsCurrentVersion                                   : 6.3
WindowsEditionId                                        : Professional
WindowsInstallationType                                 : Client
WindowsInstallDateFromRegistry                          : 19/07/2016 12:27:55
WindowsProductId                                        : XXXXXXXXXXXXXXXXXXXX
WindowsProductName                                      : Windows 10 Pro
WindowsRegisteredOrganization                           :
WindowsRegisteredOwner                                  : XXXXXXXXXXXXXXXXXXXX

WindowsSystemRoot                                       : C:\WINDOWS
BiosCharacteristics                                     : {7, 11, 12, 15...}
BiosBIOSVersion                                         : {OEMA - 1072009, 2.05.0250, American
                                                          Megatrends - 4028E}
BiosBuildNumber                                         :
BiosCaption                                             : 2.05.0250
BiosCodeSet                                             :
BiosCurrentLanguage                                     : en|US|iso8859-1
BiosDescription                                         : 2.05.0250
BiosEmbeddedControllerMajorVersion                      : 255
BiosEmbeddedControllerMinorVersion                      : 255
BiosFirmwareType                                        : Uefi
BiosIdentificationCode                                  :
BiosInstallableLanguages                                : 1
BiosInstallDate                                         :
BiosLanguageEdition                                     :
BiosListOfLanguages                                     : {en|US|iso8859-1}
BiosManufacturer                                        : American Megatrends Inc.
BiosName                                                : 2.05.0250
BiosOtherTargetOS                                       :
BiosPrimaryBIOS                                         : True
BiosReleaseDate                                         : 10/04/2015 01:00:00
BiosSeralNumber                                         : 036685734653
BiosSMBIOSBIOSVersion                                   : 2.05.0250
BiosSMBIOSMajorVersion                                  : 2
BiosSMBIOSMinorVersion                                  : 7
BiosSMBIOSPresent                                       : True
BiosSoftwareElementState                                : Running
BiosStatus                                              : OK
BiosSystemBiosMajorVersion                              : 2
BiosSystemBiosMinorVersion                              : 5
BiosTargetOperatingSystem                               : 0
BiosVersion                                             : OEMA - 1072009
CsAdminPasswordStatus                                   : Unknown
CsAutomaticManagedPagefile                              : True
CsAutomaticResetBootOption                              : True
CsAutomaticResetCapability                              : True
CsBootOptionOnLimit                                     :
CsBootOptionOnWatchDog                                  :
CsBootROMSupported                                      : True
CsBootStatus                                            : {0, 0, 0, 0...}
CsBootupState                                           : Normal boot
CsCaption                                               : RSSURFACEPRO2
CsChassisBootupState                                    : Safe
CsChassisSKUNumber                                      : Surface_Pro_2
CsCurrentTimeZone                                       : 60
CsDaylightInEffect                                      : True
CsDescription                                           : AT/AT COMPATIBLE
CsDNSHostName                                           : RSsurfacePro2
CsDomain                                                : WORKGROUP
CsDomainRole                                            : StandaloneWorkstation
CsEnableDaylightSavingsTime                             : True
CsFrontPanelResetStatus                                 : Unknown
CsHypervisorPresent                                     : False
CsInfraredSupported                                     : False
CsInitialLoadInfo                                       :
CsInstallDate                                           :
CsKeyboardPasswordStatus                                : Unknown
CsLastLoadInfo                                          :
CsManufacturer                                          : Microsoft Corporation
CsModel                                                 : Surface Pro 2
CsName                                                  : RSSURFACEPRO2
CsNetworkAdapters                                       : {USB Ethernet, WiFi, Bluetooth Network
                                                          Connection}
CsNetworkServerModeEnabled                              : True
CsNumberOfLogicalProcessors                             : 4
CsNumberOfProcessors                                    : 1
CsProcessors                                            : {Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz}
CsOEMStringArray                                        : {EU}
CsPartOfDomain                                          : False
CsPauseAfterReset                                       : -1
CsPCSystemType                                          : Mobile
CsPCSystemTypeEx                                        : Slate
CsPowerManagementCapabilities                           :
CsPowerManagementSupported                              :
CsPowerOnPasswordStatus                                 : Unknown
CsPowerState                                            : Unknown
CsPowerSupplyState                                      : Safe
CsPrimaryOwnerContact                                   :
CsPrimaryOwnerName                                      : XXXXXXXXXXXXXXXXXXXX
CsResetCapability                                       : Other
CsResetCount                                            : -1
CsResetLimit                                            : -1
CsRoles                                                 : {LM_Workstation, LM_Server, NT,
                                                          Potential_Browser...}
CsStatus                                                : OK
CsSupportContactDescription                             :
CsSystemFamily                                          : Surface
CsSystemSKUNumber                                       : Surface_Pro_2
CsSystemType                                            : x64-based PC
CsThermalState                                          : Safe
CsTotalPhysicalMemory                                   : 8506093568
CsPhyicallyInstalledMemory                              : 8388608
CsUserName                                              : RSsurfacePro2\Richard
CsWakeUpType                                            : PowerSwitch
CsWorkgroup                                             : WORKGROUP
OsName                                                  : Microsoft Windows 10 Pro
OsType                                                  : WINNT
OsOperatingSystemSKU                                    : 48
OsVersion                                               : 10.0.14393
OsCSDVersion                                            :
OsBuildNumber                                           : 14393
OsHotFixes                                              : {KB3176927}
OsBootDevice                                            : \Device\HarddiskVolume2
OsSystemDevice                                          : \Device\HarddiskVolume4
OsSystemDirectory                                       : C:\WINDOWS\system32
OsSystemDrive                                           : C:
OsWindowsDirectory                                      : C:\WINDOWS
OsCountryCode                                           : 44
OsCurrentTimeZone                                       : 60
OsLocaleID                                              : 0809
OsLocale                                                : en-GB
OsLocalDateTime                                         : 28/07/2016 14:30:32
OsLastBootUpTime                                        : 27/07/2016 09:02:45
OsUptime                                                : 1.05:27:47.0631253
OsBuildType                                             : Multiprocessor Free
OsCodeSet                                               : 1252
OsDataExecutionPreventionAvailable                      : True
OsDataExecutionPrevention32BitApplications              : True
OsDataExecutionPreventionDrivers                        : True
OsDataExecutionPreventionSupportPolicy                  : OptIn
OsDebug                                                 : False
OsDistributed                                           : False
OsEncryptionLevel                                       : 256
OsForegroundApplicationBoost                            : Maximum
OsTotalVisibleMemorySize                                : 8306732
OsFreePhysicalMemory                                    : 5530384
OsTotalVirtualMemorySize                                : 9617452
OsFreeVirtualMemory                                     : 6525292
OsInUseVirtualMemory                                    : 3092160
OsTotalSwapSpaceSize                                    :
OsSizeStoredInPagingFiles                               : 1310720
OsFreeSpaceInPagingFiles                                : 1274160
OsPagingFiles                                           : {C:\pagefile.sys}
OsHardwareAbstractionLayer                              : 10.0.14393.0
OsInstallDate                                           : 19/07/2016 13:27:55
OsManufacturer                                          : Microsoft Corporation
OsMaxNumberOfProcesses                                  : 4294967295
OsMaxProcessMemorySize                                  : 137438953344
OsMuiLanguages                                          : {en-GB}
OsNumberOfLicensedUsers                                 :
OsNumberOfProcesses                                     : 77
OsNumberOfUsers                                         : 2
OsOrganization                                          :
OsArchitecture                                          : 64-bit
OsLanguage                                              : en-GB
OsProductSuites                                         : {TerminalServicesSingleSession}
OsOtherTypeDescription                                  :
OsPAEEnabled                                            :
OsPortableOperatingSystem                               : False
OsPrimary                                               : True
OsProductType                                           : WorkStation
OsRegisteredUser                                        : XXXXXXXXXXXXXXXXXXXX
OsSerialNumber                                          : 00330-80000-00000-AA844
OsServicePackMajorVersion                               : 0
OsServicePackMinorVersion                               : 0
OsStatus                                                : OK
OsSuites                                                : {TerminalServices,
                                                          TerminalServicesSingleSession}
OsServerLevel                                           :
KeyboardLayout                                          : en-GB
TimeZone                                                : (UTC+00:00) Dublin, Edinburgh, Lisbon,
                                                          London
LogonServer                                             : \\RSSURFACEPRO2
PowerPlatformRole                                       : Slate
HyperVisorPresent                                       : False
HyperVRequirementDataExecutionPreventionAvailable       : True
HyperVRequirementSecondLevelAddressTranslation          : True
HyperVRequirementVirtualizationFirmwareEnabled          : True
HyperVRequirementVMMonitorModeExtensions                : True
DeviceGuardSmartStatus                                  : Off
DeviceGuardRequiredSecurityProperties                   :
DeviceGuardAvailableSecurityProperties                  :
DeviceGuardSecurityServicesConfigured                   :
DeviceGuardSecurityServicesRunning                      :
DeviceGuardCodeIntegrityPolicyEnforcementStatus         :
DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus :

 

You can use the –Property parameter to restrict output

PS>  Get-ComputerInfo -Property OsArchitecture, OsUptime

OsArchitecture OsUptime
-------------- --------
64-bit         1.05:34:53.9424271

 

Wild cards are allowed so this works and lists all properties starting with OS

Get-ComputerInfo -Property Os*

 

Looking at the output it seems to be a collection of properties from a number of CIM classes. Might be fun to track down what comes from where one rainy day

PowerShell 5.1 preview

Windows 10 shipped with PowerShell 5.0 installed. The latest preview builds, and presumably, next months anniversary update have had PowerShell 5.1. Windows 2016 TP5 also ships with PowerShell 5.1

A PowerShell 5.1 preview is now available for Windows 7, 8.1, 2008 R2, 2012 and 2012 R2

Details from

https://blogs.msdn.microsoft.com/powershell/2016/07/16/announcing-windows-management-framework-wmf-5-1-preview/

PowerShell in Action–Deal of the Day-23 July 2016

Deal of the Day July 23: Half off my book Windows PowerShell in Action, Third Edition. Use code dotd072316au at http://bit.ly/2afnOPj

 

Deal of the Day details at https://www.manning.com/dotd

Parallel copy files over remoting session

In response to this post - https://richardspowershellblog.wordpress.com/2015/05/28/copy-files-over-ps-remoting-sessions/

 

I was asked how you could copy files in parallel to multiple machines.

 

As soon as anyone mentions parallelism I think of workflows so I ended up with this

$computers = 'W16TP5TGT01', 'W16TP5TGT02'

workflow parallelcopy {
  param ([string[]]$computername)
  foreach -parallel ($computer in $computername) {
     InlineScript {
       $s = New-PSSession -ComputerName $using:computer
       Copy-Item -Path C:\Scripts\New-NanoMachine.ps1 -Destination C:\Source -ToSession $s
       Remove-PSSession -Session $s
     }
  }
}

parallelcopy -computername $computers

 

A couple of issues I found. First off –Tosession and –FromSession haven’t been added to the Copy-Item workflow activity. This means you have to use an Inline script block to access those parameters

 

Secondly accessing a emoting session created outside of the workflow generates a session busy error when trying to perform the copy so have to move the session creation into the Inline script.

 

If you had a lot of files, or a lot of data, to copy to multiple machines this approach may be worthwhile. For small amounts of data then the approach in the original article is probably best.

Manning Deal of the Day 19 July 2016

Deal of the Day July 19: Half off my book Learn Active Directory Management in a Month of Lunches. Use code dotd071916au at http://bit.ly/2a8jroO

 

For more information on Manning’s Deal of the Day see -  https://www.manning.com/dotd.

Biggest innovation in PowerShell is…

The imminent arrival of PowerShell 5.1 in the Windows 10 Anniversary update (assumption as the Windows 10 Insider previews have been showing PowerShell 5.1 for some time) and Windows Server 2016 (TP5 shows PowerShell 5.1) and the fact that PowerShell was officially released to the world 10 years ago come November started me thinking about what has been the biggest innovation in PowerShell over those 10 years.

 

Contenders that come to mind include:

- Remoting
- PowerShell modules
- CIM & CIM sessions
- Workflows
- Job engine
- Desired State Configuration
- PowerShell Gallery and package management
- PowerShell classes
- JSON support in PowerShell
- Internationalisation
- Error handling - try/catch
- Debugging enhancements
- REST API and Odata support
- PowerShell support for Microsoft products
- PowerShell support from third part vendors
- PowerShell community

 

Which do you think?

 

Or is it something else?

 

Leave a comment as I’m intrigued as to what people think has been the biggest PowerShell innovation

Summer goodies

Looks like we’re set for some summer goodies over the next few months.

 

First up is Windows 10 anniversary update that’s due 2 August

https://blogs.windows.com/buildingapps/2016/07/12/windows-10-anniversary-sdk-preview-build-14388-released/

 

Followed by the Windows Server 2016 launch at the end of September

https://blogs.technet.microsoft.com/windowsserver/2016/07/12/windows-server-2016-new-current-branch-for-business-servicing-option/

 

TP5 is stated to be feature complete – my testing so far shows some rough edges. Hope launch means general availability and not another 2-3 month wait like we had with Windows 2012 R2

 

The article is also interesting for showing how Windows server and Nano server will be treated differently. Windows server wil get patches in the traditional cycle we’ve come to know and love(?). Nano server will be more like Windows 10 with updates 2-3 times per year – including new features. Hopefully that would include Nano server being able to support more roles

Copying across multiple remoting sessions

I needed to copy the same file to multiple machines so I tried this:

$computers = 'W16CN01', 'W16CN02'

$s = New-PSSession -ComputerName $computers

Copy-Item -Path 'C:\Source\Windows 2016 TP5\Cumulative Update for Windows Server 2016 Technical Preview 5 (KB3163016)\AMD64-all-windows10.0-kb3163016-x64_83d6e9bca94a64a5d9be3d81cdb182e540285848.msu' -Destination C:\Scripts -ToSession $s

Remove-PSSession –Session $s

 

It failed with:

Copy-Item : Cannot convert 'System.Object[]' to the type
'System.Management.Automation.Runspaces.PSSession' required by parameter
'ToSession'. Specified method is not supported.
At line:5 char:236
+ ... a5d9be3d81cdb182e540285848.msu' -Destination C:\Scripts -ToSession $s
+                                                                        ~~
    + CategoryInfo          : InvalidArgument: (:) [Copy-Item], ParameterBindi
   ngException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Comma
   nds.CopyItemCommand

 

If you look at the syntax

Get-Command Copy-Item -Syntax

 

Copy-Item [-Path] <string[]> [[-Destination] <string>] [-Container]
[-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>]
[-Recurse] [-PassThru] [-Credential <pscredential>] [-WhatIf] [-Confirm]
[-UseTransaction] [-FromSession <PSSession>] [-ToSession <PSSession>]
[<CommonParameters>]

 

Copy-Item [[-Destination] <string>] -LiteralPath <string[]> [-Container]
[-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>]
[-Recurse] [-PassThru] [-Credential <pscredential>] [-WhatIf] [-Confirm]
[-UseTransaction] [-FromSession <PSSession>] [-ToSession <PSSession>]
[<CommonParameters>]

 

the ToSession and FromSession parameters only take a single session as their value.

 

Modify the code to

$computers = 'W16CN01', 'W16CN02'

$sessions = New-PSSession -ComputerName $computers

foreach ($session in $sessions) {
Copy-Item -Path 'C:\Source\Windows 2016 TP5\Cumulative Update for Windows Server 2016 Technical Preview 5 (KB3163016)\AMD64-all-windows10.0-kb3163016-x64_83d6e9bca94a64a5d9be3d81cdb182e540285848.msu' -Destination C:\Scripts -ToSession $session
}

Remove-PSSession -Session $sessions

 

And it works

PowerShell Direct example

Last week I mentioned PowerShell and how you can create a PowerShell Remoting session to a Virtual Machine that’s running on Hyper-V

 

Here’s an example of it in use:

$cred = Get-Credential W16TP5TGT01\Administrator
$s = New-PSSession -VMName W16TP5TGT01 -Credential $cred

 

Create the credential for the VM and then create the remoting session. I prefer to use the VM name rather than the GUID.

 

Once you’ve established the session you can use it. In this case I’m using another PowerShell 5.o innovation to copy a file across the remote session:

Copy-Item -Path 'C:\Source\Windows 2016 TP5\Cumulative Update for Windows Server 2016 Technical Preview 5 (KB3163016)\AMD64-all-windows10.0-kb3163016-x64_83d6e9bca94a64a5d9be3d81cdb182e540285848.msu' -Destination c:\source -ToSession $s

 

Clean up as usual:

Remove-PSSession -Session $s

 

PowerShell Direct is another useful addition to the remoting toolbox. It’ll be especially useful in non-domain remoting situations.