Category Archives: Powershell

Announcing PowerShell Core 6.1

This post was originally published on this site

We’re proud to announce that the latest version of PowerShell has been released! This marks our second supported release of PowerShell Core, the open-source edition of PowerShell that works on Linux, macOS, and Windows!

By far, the biggest feature of this release is compatibility of built-in Windows modules with PowerShell Core. This means that you can natively run those modules/cmdlets with PowerShell Core and easily transition from Windows PowerShell.

Thanks to everyone that made this release possible, including our contributors, users, and anyone who filed issues and submitted feedback.

Just give me the bits!

For info on installing PowerShell Core 6.1, check out our installation docs.

What’s new?

We’ve released a slew of new features in 6.1, including:

  • Compatibility with 1900+ existing cmdlets in Windows 10 and Windows Server 2019
  • Built on top of .NET Core 2.1
  • Support for the latest versions of Windows, macOS, and Linux
    (see below)
  • Significant performance improvements
    • Markdown cmdlets
  • Experimental feature flags

For a more in-depth look at what’s included, take a look at our release notes, or for a complete list of changes, check out our CHANGELOG on GitHub.

Operating system support

You can always find an up-to-date list of support operating systems and PowerShell Core versions at https://aka.ms/pslifecycle.

On release, PowerShell Core 6.1 supports:

  • Windows 7/8.1/10
  • Windows Server 2008R2/2012/2012R2/2016 (and 2019 on release)
  • Windows Server Semi-Annual Channel (SAC)
  • macOS 10.12+
  • Ubuntu 14.04/16.04/18.04
  • Debian 8.7+/9
  • CentOS 7
  • Red Hat Enterprise Linux (RHEL) 7
  • OpenSUSE 42.3
  • Fedora 27/28

Platforms with unofficial “community” support also include:

  • Ubuntu 18.10
  • Arch Linux
  • Raspbian (ARM32)
  • Kali Linux
  • Alpine (experimental Docker image coming soon)

How can I provide feedback?

As always, you can file issues on GitHub to let us know about any features you’d like added or bugs that you encounter. Additionally, you can join us for the PowerShell Community Call on the 3rd Thursday of every month. The Community Call is a great opportunity to talk directly to the team, hear about the latest developments in PowerShell, and to voice your opinions into ongoing feature design.

Of course, we’re always looking for contributions that make PowerShell better. We love when our community helps out with code contributions, but you don’t have to be a rockstar developer to make a difference in PowerShell, as we’re also happy to accept test and documentation contributions as well.

Thanks, and enjoy PowerShell 6.1!

Joey Aiello
Program Manager, PowerShell

New Look and Features for PowerShell Gallery

This post was originally published on this site

The PowerShell Gallery and PowerShellGet have just been updated to provide new features, performance improvements, and a new modern design.  

NOTE: This post has important information for publishers in the “Accounts and publishing” section. 

PowerShell Gallery Home Page

PowerShell Gallery Home Page

The PowerShell Gallery is the place to find PowerShell code that is shared by the community, Microsoft, and other companies. The site has averaged over 21 million downloads per month for the past 6 months, and has more than 3,800 unique packages available for use. It’s amazing when we consider we were handling just under 4 million downloads in July 2017. We clearly needed to invest in the PowerShell Gallery to support that kind of growth.

We have been working for some time to improve the performance of the PowerShell Gallery. The result is now available to everyone, and includes new features, performance enhancements, security improvements to accounts and publishing keys, and better alignment with the NuGet.org codebase that we rely on for our service and cmdlets.

New features and performance enhancements

Most users should see an improvement in package download speeds from the PowerShell Gallery. The new release takes advantage of CDN to provide faster downloads, particularly for those outside the United States. This should be most noticeable when installing a module with many dependencies.  

The new updates include things users have requested for a long time, including:

  • A manual download option from the PowerShell Gallery. It cannot replace install-module / install-script, but does solve some specific issues for those with private repositories or older versions of PowerShell.
  • A change to Install-Module and Install-Script to simply install to the current user scope when not running in an elevated PowerShell session.

The new user experience is more than just a face-lift, as providing a modern UI also improves the performance. The PowerShell Gallery pages now display only the most critical information initially, and move the details to expanding sections in the UI. This makes the pages faster and easier for users to find the content they want to see.

Accounts and publishing improvements

The changes with the most immediate impact in this release are for publishers and users with PowerShell Gallery accounts.   

Most important: Publishers must update to PowerShellGet module version 1.6.8 or higher to publish to the PowerShell Gallery. Older versions of PowerShellGet are fine for find, save, install, and update functions, but not for publishing.    

The PowerShell Gallery implemented several security best practices:

  • New API keys you create will have an expiration that ranges from 1 to 365 days.
  • We will not show the value of an API key in the UI, and the value must be copied immediately after creating or regenerating it.
  • Multiple API keys can be created, and defined for specific uses – such as only being available to publish packages with specific names.
  • Your existing API key will still work, and will be listed as a “Full access API key”. However, you will not be able to view the current API key value or refresh it. If you lose the key value, you will need to create a new key that has an expiration date.

These changes are explained in more detail in the PowerShell Gallery documentation, and are the most significant changes included in this release.

Account management in the Powershell Gallery is also improved, and adds support for

  • Two factor authentication for accessing the PowerShell Gallery account. This is a security best practice and is highly recommended.
  • Changing the email address or login account associated with their PowerShell Gallery ID

You can find out more about the new Account settings features here.

Aligning with NuGet

The previous versions of PowerShell Gallery and PowerShellGet were based on older versions of NuGet. With this change we are aligning much more closely with the current state of the NuGet server and client. Many of the changes listed above – including the account and API key management – came directly from the NuGet updates. Another feature NuGet implemented is the ability to delete a package they have published accidentally, within the first hour after publishing.

 As we move closer to alignment with how NuGet.org works, we expect to provide new features that are available from the NuGet team.  Other changes we are considering that are available today at NuGet.org include support for namespaces and organizational accounts.

Let us know what you think

If you have any feedback on the changes we have made, or future changes we should consider, please do let us know. Visit https://aka.ms/PowerShellGalleryIssues to review what others are saying, or to let us know of other things we should be looking into.

 

DSC Resource Kit Release September 2018

This post was originally published on this site

We just released the DSC Resource Kit!

This release includes updates to 11 DSC resource modules. In the past 6 weeks, 146 pull requests have been merged and 105 issues have been closed, all thanks to our amazing community!

The modules updated in this release are:

  • CertificateDsc
  • NetworkingDsc
  • SecurityPolicyDsc
  • SharePointDsc
  • SqlServerDsc
  • StorageDsc
  • xActiveDirectory
  • xDatabase
  • xExchange
  • xRemoteDesktopSessionHost
  • xWebAdministration

For a detailed list of the resource modules and fixes in this release, see the Included in this Release section below.

Our last community call for the DSC Resource Kit was on August 29. A recording of our updates will be available on YouTube soon. Join us for the next call at 12PM (Pacific time) on October 10 to ask questions and give feedback about your experience with the DSC Resource Kit.

The next DSC Resource Kit release will be going out one week later than usual on Wednesday, October 24, 2018. This will not shift any other dates, so the community call will still be on October 10, and the following release will be on November 28.

We strongly encourage you to update to the newest version of all modules using the PowerShell Gallery, and don’t forget to give us your feedback in the comments below, on GitHub, or on Twitter (@PowerShell_Team)!

Please see our documentation here for information on the support of these resource modules.

Included in this Release

You can see a detailed summary of all changes included in this release in the table below. For past release notes, go to the README.md or CHANGELOG.md file on the GitHub repository page for a specific module (see the How to Find DSC Resource Modules on GitHub section below for details on finding the GitHub page for a specific module).

Module Name Version Release Notes
CertificateDsc 4.2.0.0
  • Added a CODE_OF_CONDUCT.md with the same content as in the README.md – fixes Issue 139.
  • Refactored module folder structure to move resource to root folder of repository and remove test harness – fixes Issue 142.
  • Updated Examples to support deployment to PowerShell Gallery scripts.
  • Correct configuration names in Examples – fixes Issue 150.
  • Correct filename case of CertificateDsc.Common.psm1 – fixes Issue 149.
  • Remove exclusion of all tags in appveyor.yml, so all common tests can be run if opt-in.
  • PfxImport:
    • Added requirements to README.MD to specify cryptographic algorithm support – fixes Issue 153.
    • Changed Path parameter to be optional to fix error when ensuring certificate is absent and certificate file does not exist on disk – fixes Issue 136.
    • Removed ShouldProcess because it is not required by DSC Resources.
    • Minor style corrections.
    • Changed unit tests to be non-destructive.
    • Improved naming and description of example files.
    • Added localization string ID suffix for all strings.
  • Added .VSCode settings for applying DSC PSSA rules – fixes Issue 157.
NetworkingDsc 6.1.0.0
  • MSFT_Firewall:
    • Added full stop to end of MOF field descriptions.
    • Support for [, ] and * characters in the Name property added – fixes Issue 348.
    • Improved unit tests to meet style guidelines.
SecurityPolicyDsc 2.5.0.0
  • Added handler for null value in SecurityOption
  • Moved the helper module out from DSCResource folder to the Modules folder.
  • Fixed SecurityPolicyResourceHelper.Tests.ps1 so it possible to run the tests locally.
  • Fixed minor typos.
SharePointDsc 2.5.0.0
  • SPAppCatalog
    • Updated resource to retrieve the Farm account instead of requiring it to be specifically used
  • SPDatabaseAAG
    • Updated readme.md to specify that this resource also updates the database connection string
  • SPDiagnosticsProvider
    • Fixed issue where enabling providers did not work
  • SPFarm
    • Added ability to check and update CentralAdministrationPort
  • SPLogLevel
    • Added High as TraceLevel, which was not included yet
  • SPRemoteFarmTrust
    • Updated readme.md file to add a link that was lost during earlier updates
  • SPSearchServiceApp
    • Updated Set method to check if service application pool exists. Resource will throw an error if it does not exist
  • SPSearchTopology
    • Fixed issue where Get method threw an error when the specified service application didn’t exist yet
    • Fixed issue where the resource would fail is the FQDN was specified
  • SPShellAdmins
    • Added ExcludeDatabases parameter for AllDatabases
  • SPSite
    • Added ability to check and update QuotaTemplate, OwnerAlias and SecondaryOwnerAlias
  • SPSiteUrl
    • New resource to manage site collection urls for host named site collections
  • SPTrustedIdentityTokenIssuerProviderRealm
    • Fixed issue where Get method threw an error when the realm didn’t exist yet
  • SPUserProfileServiceApp
    • Fix for issue where an update conflict error was thrown when new service application was created
    • Added SiteNamingConflictResolution parameter to the resource
SqlServerDsc 12.0.0.0
  • Changes to SqlServerDatabaseMail
    • DisplayName is now properly treated as display name for the originating email address (issue 1200). Nick Reilingh (@NReilingh)
      • DisplayName property now defaults to email address instead of server name.
      • Minor improvements to documentation.
  • Changes to SqlAGDatabase
  • Changes to SqlDatabaseOwner
    • BREAKING CHANGE: Support multiple instances on the same node. The parameter InstanceName is now Key and cannot be omitted (issue 1197).
  • Changes to SqlSetup
    • Added new parameters to allow to define the startup types for the Sql Engine service, the Agent service, the Analysis service and the Integration Service. The new optional parameters are respectively SqlSvcStartupType, AgtSvcStartupType, AsSvcStartupType, IsSvcStartupType and RsSvcStartupType (issue 1165. Maxime Daniou (@mdaniou)
StorageDsc 4.1.0.0
  • Enabled PSSA rule violations to fail build – Fixes Issue 149.
  • Fixed markdown rule violations in CHANGELOG.MD.
  • Disk:
    • Corrected message strings.
    • Added message when partition resize required but AllowDestructive parameter is not enabled.
    • Fix error when Size not specified and AllowDestructive is $true and partition can be expanded – Fixes Issue 162.
    • Fix incorrect error displaying when newly created partition is not made Read/Write.
    • Change verbose messages to show warnings when a partition resize would have occured but the AllowDestructive flag is set to $false.
xActiveDirectory 2.21.0.0
xDatabase 1.9.0.0
  • xDatabase Test-TargetResource will now check DacPacVersion if DacPacPath parameter and DB exist. If the DacPacApplicationVersion is supplied and matches the deployed version we will return $true. (issue 41)
xExchange 1.23.0.0
  • Fixes issue with xExchMaintenanceMode on Exchange 2016 where the cluster does not get paused when going into maintenance mode. Also fixes issue where services fail to stop, start, pause, or resume.
  • Explicitly cast member types in Get-DscConfiguration return hashtables to align with the types defined in the resource schemas. Fixes an issue where Get-DscConfiguration fails to return a value.
  • xExchClientAccessServer: Fixes issue where AlternateServiceAccountConfiguration or RemoveAlternateServiceAccountCredentials parameters can”t be used at the same time as other optional parameters.
  • xExchInstall: Fixes issue where Test-TargetResource returns true if setup is running. Fixes issue where setup is not detected as having been successfully completed even if setup was successful. Adds initial set of unit tests for xExchInstall and related functions.
  • Remove VerbosePreference from function parameters and update all calls to changed functions.
  • Fixes multiple PSScriptAnalyzer issues. Specifically, fixes all instances of PSAvoidTrailingWhitespace, PSAvoidGlobalVars, PSAvoidUsingConvertToSecureStringWithPlainText, PSUseSingularNouns, and fixes many instances of PSUseDeclaredVarsMoreThanAssignments.
  • Add support for Exchange Server 2019 – Preview
xRemoteDesktopSessionHost 1.8.0.0
  • Changes to xRDSessionDeployment
    • Fixed issue where an initial deployment failed due to a convert to lowercase (issue 39).
    • Added unit tests to test Get, Test and Set results in this resource.
  • Change to xRDRemoteApp
    • Fixed issue where this resource ignored the CollectionName provided in the parameters (issue 41).
    • Changed key values in schema.mof to only Alias and CollectionName, DisplayName and FilePath are not key values.
    • Added Ensure property (Absent or Present) to enable removal of RemoteApps.
    • Added unit tests to test Get, Test and Set results in this resource.
xWebAdministration 2.2.0.0
  • Added new parameter “Location” to WebApplcationHandler extending functionality to address [392]
  • Changes to xWebAdministration
    • Update section header for WebApplicationHandler in README.
    • Fix tests for helper function Get-LocalizedData in Helper.Tests.ps1 that referenced the wrong path.
  • Remove duplication in MSFT_xWebsite.psm1. Krzysztof Morcinek (@kmorcinek)
  • Updates xIISMimeTypeMapping to add MIME type mapping for nested paths

How to Find Released DSC Resource Modules

To see a list of all released DSC Resource Kit modules, go to the PowerShell Gallery and display all modules tagged as DSCResourceKit. You can also enter a module’s name in the search box in the upper right corner of the PowerShell Gallery to find a specific module.

Of course, you can also always use PowerShellGet (available starting in WMF 5.0) to find modules with DSC Resources:

# To list all modules that tagged as DSCResourceKit
Find-Module -Tag DSCResourceKit 
# To list all DSC resources from all sources 
Find-DscResource

Please note only those modules released by the PowerShell Team are currently considered part of the ‘DSC Resource Kit’ regardless of the presence of the ‘DSC Resource Kit’ tag in the PowerShell Gallery.

To find a specific module, go directly to its URL on the PowerShell Gallery:
http://www.powershellgallery.com/packages/< module name >
For example:
http://www.powershellgallery.com/packages/xWebAdministration

How to Install DSC Resource Modules From the PowerShell Gallery

We recommend that you use PowerShellGet to install DSC resource modules:

Install-Module -Name < module name >

For example:

Install-Module -Name xWebAdministration

To update all previously installed modules at once, open an elevated PowerShell prompt and use this command:

Update-Module

After installing modules, you can discover all DSC resources available to your local system with this command:

Get-DscResource

How to Find DSC Resource Modules on GitHub

All resource modules in the DSC Resource Kit are available open-source on GitHub.
You can see the most recent state of a resource module by visiting its GitHub page at:
https://github.com/PowerShell/< module name >
For example, for the CertificateDsc module, go to:
https://github.com/PowerShell/CertificateDsc.

All DSC modules are also listed as submodules of the DscResources repository in the DscResources folder and the xDscResources folder.

How to Contribute

You are more than welcome to contribute to the development of the DSC Resource Kit! There are several different ways you can help. You can create new DSC resources or modules, add test automation, improve documentation, fix existing issues, or open new ones.
See our contributing guide for more info on how to become a DSC Resource Kit contributor.

If you would like to help, please take a look at the list of open issues for the DscResources repository.
You can also check issues for specific resource modules by going to:
https://github.com/PowerShell/< module name >/issues
For example:
https://github.com/PowerShell/xPSDesiredStateConfiguration/issues

Your help in developing the DSC Resource Kit is invaluable to us!

Questions, comments?

If you’re looking into using PowerShell DSC, have questions or issues with a current resource, or would like a new resource, let us know in the comments below, on Twitter (@PowerShell_Team), or by creating an issue on GitHub.

Katie Keim
Software Engineer
PowerShell DSC Team
@katiedsc (Twitter)
@kwirkykat (GitHub)

PowerShell Module Function Export in Constrained Language

This post was originally published on this site

PowerShell Module Exporting Functions in Constrained Language

PowerShell offers a number of ways to expose functions in a script module. But some options have serious performance or security drawbacks. In this blog I describe these issues and provide simple guidance for creating performant and secure script modules. Look for a module soon in PSGallery that helps you update your modules to be compliant with this guidance.

When PowerShell is running in Constrained Language mode it adds some restrictions in how module functions can be exported. Normally, when PowerShell is not running in Constrained Language, all script functions defined in the module are exported by default.

# TestModule.psm1
function F1 { }
function F2 { }
function F3 { }

# TestModule.psd1
@{ ModuleVersion = '1.0'; RootModule = 'TestModule.psm1' }

# All functions (Function1, Function2, Function3) are exported and available
Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions

F1
F2
F3

This is handy and works well for simple modules. However, it can cause problems for more complex modules.

Performance Degradation

Command discovery is much slower when script functions are exported implicitly or explicitly using wildcard characters. This is because PowerShell has to parse all module script content to look for available functions and then match the found function names with a wildcard pattern. If the module uses explicit function export lists, then this parsing during discovery is not necessary. If you have a lot of custom script modules with many functions, the performance hit can become very noticeable. This principal also applies to exporting any other script element such as cmdlets, variables, aliases, and DSC resources.

# TestModule.psm1
function F1 { }
function F2 { }
function F3 { }
...
# This wildcard function export has the same behavior as the default behavior, all module functions are exported and PowerShell has to parse all script to discover available functions
Export-ModuleMember -Function '*'

Confused Intent

For large complex modules, exporting all defined functions is confusing to users as to how the module is intended to be used. The number of defined functions can be very large and the handful of user cmdlets can get lost in the noise. It is much better to export just the functions intended for the user and hide all helper functions.

# TestModule.psm1
function Invoke-Program { }
function F1 { }
function F2 { }
...
function F100 { }

# TestModule.psd1
@{ ModuleVersion = '1.0'; RootModule = 'TestModule.psm1'; FunctionsToExport = 'Invoke-Program' }

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions

Invoke-Program

Security

PowerShell runs in Constrained Language mode when a DeviceGuard or AppLocker policy is enforced on the system. This provides a good user shell experience while allowing trusted script modules to run in Full Language so that system management can still be done. For example, a user from the command line cannot use Add-Type to create and run arbitrary C# types, but a trusted script can.

So, it is important that a trusted script does not expose any vulnerabilities such as script injection or arbitrary code execution. Another type of vulnerability is leaking dangerous module functions not intended for public use. A helper function might take arbitrary source code and create a type intended to be used privately in a trusted context. But, if that helper function becomes publically available it exposes a code execution vulnerability.

# TestModule.psm1
function Invoke-Program { }
# Private helper function
function Get-Type
{
    param( [string] $source )
    Add-Type -TypeDefinition $source -PassThru
}

# Exposes *all* module functions!
Export-ModuleMember -Function '*'

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions

Invoke-Program
Get-Type

In the above example, Get-Type module helper function is exported via wildcard along with the intended Invoke-Program function. Since this is a trusted module Get-Type runs in Full Language and exposes the ability to create arbitrary types.

Unintended Consequences

A major problem with exporting module functions using wildcards is that you may end up exporting functions unintentionally. For example, your module may specify other nested modules, or it may explicitly import other modules, or it may dot source script files into the module scope. All of those script functions will become publicly available if wild cards are used to export module functions.

# TestModule.psm1
import-Module HelperMod1
. .CSharpHelpers.ps1
function Invoke-Program { }

# Exposes *all* module functions!
Export-ModuleMember -Function '*'

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions
Invoke-Program
HelperFn1
HelperFn2
Compile-CSharp

Module Function Export Restrictions

When PowerShell detects that an application whitelisting policy is enforced it runs in Constrained Language mode as mentioned previously, but it also applies some function export restrictions for imported modules. Remember that these restrictions only apply when PowerShell is running under DeviceGuard or AppLocker policy enforcement mode. Otherwise module function export works as before.

  • Wildcards are not allowed with the FunctionsToExport keyword in a module manifest (.psd1 file). If a wildcard is found in the keyword argument then no functions are exported in that module.
  • Wildcards are allowed in a module script file (.psm1). This is to provide backward compatibility but we strongly discourage it.
  • A module that uses wildcards to export functions, and at the same time dot sources script files into the module scope, will throw an error during module loading time. Note that if a psm1 file exports functions via wildcard, but it is imported under a manifest (psd1 file) that exports functions explicitly by name, then no error is thrown because the psd1 overrides any function export done within a psm1 file associated with the manifest. But if the psm1 file is imported directly (without the psd1 manifest file) then the error is thrown (see example below). Basically, the dot source operator cannot be used in module script along with wildcard based function export. It is too easy to inadvertently expose unwanted functions.

These restrictions are to help prevent inadvertent exposure of functions. By using wildcard based function export, you may be exposing dangerous functions without knowing it.

# TestModule.psm1
Import-Module HelperMod1
. .CSharpHelpers.ps1
function Invoke-Program { }
Export-ModuleMember -Function '*'

# TestModule.psd1
@{ ModuleVersion='1.0'; RootModule='TestModule.psm1'; FunctionsToExport='Invoke-Program' }

# Importing the psm1 file directly results in error because of the wildcard function export and use of dot source operator
Import-Module -Name TestModuleTestModule.psm1
Error:
'This module uses the dot-source operator while exporting functions using wildcard characters, and this is disallowed when the system is under application verification enforcement.'

# But importing using the module manifest succeeds since the manifest explicitly exports functions by name without wildcards
Import-Module TestModule
Get-Module -Name TestModule | Select -ExpandProperty ExportedFunctions
Invoke-Program

Module Function Export Best Practices

Best practices for module function exporting is pretty simple. Always export module functions explicitly by name. Never export using wild card names. This will yield the best performance and ensure you don’t expose functions you don’t intend to expose. It makes your module safer to use as trusted in a DeviceGuard policy enforcement environment.

# TestModule.psm1
Import-Module HelperMod1
. .CSharpHelpers.ps1
function Invoke-Program { }

# TestModule.psd1
@ { ModuleVersion='1.0'; RootModule='TestModule.psm1'; FunctionsToExport='Invoke-Program' }

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions
Invoke-Program

Paul Higinbotham
Senior Software Engineer
PowerShell Team

PowerShell Module Exporting Functions in Constrained Language

This post was originally published on this site

PowerShell Module Exporting Functions in Constrained Language

PowerShell offers a number of ways to expose functions in a script module. But some options have serious performance or security drawbacks. In this blog I describe these issues and provide simple guidance for creating performant and secure script modules. Look for a module soon in PSGallery that helps you update your modules to be compliant with this guidance.

When PowerShell is running in Constrained Language mode it adds some restrictions in how module functions can be exported. Normally, when PowerShell is not running in Constrained Language, all script functions defined in the module are exported by default.

# TestModule.psm1
function F1 { }
function F2 { }
function F3 { }

# TestModule.psd1
@{ ModuleVersion = '1.0'; RootModule = 'TestModule.psm1' }

# All functions (Function1, Function2, Function3) are exported and available
Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions

F1
F2
F3

This is handy and works well for simple modules. However, it can cause problems for more complex modules.

Performance Degradation

Command discovery is much slower when script functions are exported implicitly or explicitly using wildcard characters. This is because PowerShell has to parse all module script content to look for available functions and then match the found function names with a wildcard pattern. If the module uses explicit function export lists, then this parsing during discovery is not necessary. If you have a lot of custom script modules with many functions, the performance hit can become very noticeable. This principal also applies to exporting any other script element such as cmdlets, variables, aliases, and DSC resources.

# TestModule.psm1
function F1 { }
function F2 { }
function F3 { }
...
# This wildcard function export has the same behavior as the default behavior, all module functions are exported and PowerShell has to parse all script to discover available functions
Export-ModuleMember -Function '*'

Confused Intent

For large complex modules, exporting all defined functions is confusing to users as to how the module is intended to be used. The number of defined functions can be very large and the handful of user cmdlets can get lost in the noise. It is much better to export just the functions intended for the user and hide all helper functions.

# TestModule.psm1
function Invoke-Program { }
function F1 { }
function F2 { }
...
function F100 { }

# TestModule.psd1
@{ ModuleVersion = '1.0'; RootModule = 'TestModule.psm1'; FunctionsToExport = 'Invoke-Program' }

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions

Invoke-Program

Security

PowerShell runs in Constrained Language mode when a DeviceGuard or AppLocker policy is enforced on the system. This provides a good user shell experience while allowing trusted script modules to run in Full Language so that system management can still be done. For example, a user from the command line cannot use Add-Type to create and run arbitrary C# types, but a trusted script can.

So, it is important that a trusted script does not expose any vulnerabilities such as script injection or arbitrary code execution. Another type of vulnerability is leaking dangerous module functions not intended for public use. A helper function might take arbitrary source code and create a type intended to be used privately in a trusted context. But, if that helper function becomes publically available it exposes a code execution vulnerability.

# TestModule.psm1
function Invoke-Program { }
# Private helper function
function Get-Type
{
    param( [string] $source )
    Add-Type -TypeDefinition $source -PassThru
}

# Exposes *all* module functions!
Export-ModuleMember -Function '*'

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions

Invoke-Program
Get-Type

In the above example, Get-Type module helper function is exported via wildcard along with the intended Invoke-Program function. Since this is a trusted module Get-Type runs in Full Language and exposes the ability to create arbitrary types.

Unintended Consequences

A major problem with exporting module functions using wildcards is that you may end up exporting functions unintentionally. For example, your module may specify other nested modules, or it may explicitly import other modules, or it may dot source script files into the module scope. All of those script functions will become publicly available if wild cards are used to export module functions.

# TestModule.psm1
import-Module HelperMod1
. .CSharpHelpers.ps1
function Invoke-Program { }

# Exposes *all* module functions!
Export-ModuleMember -Function '*'

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions
Invoke-Program
HelperFn1
HelperFn2
Compile-CSharp

Module Function Export Restrictions

When PowerShell detects that an application whitelisting policy is enforced it runs in Constrained Language mode as mentioned previously, but it also applies some function export restrictions for imported modules. Remember that these restrictions only apply when PowerShell is running under DeviceGuard or AppLocker policy enforcement mode. Otherwise module function export works as before.

  • Wildcards are not allowed with the FunctionsToExport keyword in a module manifest (.psd1 file). If a wildcard is found in the keyword argument then no functions are exported in that module.
  • Wildcards are allowed in a module script file (.psm1). This is to provide backward compatibility but we strongly discourage it.
  • A module that uses wildcards to export functions, and at the same time dot sources script files into the module scope, will throw an error during module loading time. Note that if a psm1 file exports functions via wildcard, but it is imported under a manifest (psd1 file) that exports functions explicitly by name, then no error is thrown because the psd1 overrides any function export done within a psm1 file associated with the manifest. But if the psm1 file is imported directly (without the psd1 manifest file) then the error is thrown (see example below). Basically, the dot source operator cannot be used in module script along with wildcard based function export. It is too easy to inadvertently expose unwanted functions.

These restrictions are to help prevent inadvertent exposure of functions. By using wildcard based function export, you may be exposing dangerous functions without knowing it.

# TestModule.psm1
Import-Module HelperMod1
. .CSharpHelpers.ps1
function Invoke-Program { }
Export-ModuleMember -Function '*'

# TestModule.psd1
@{ ModuleVersion='1.0'; RootModule='TestModule.psm1'; FunctionsToExport='Invoke-Program' }

# Importing the psm1 file directly results in error because of the wildcard function export and use of dot source operator
Import-Module -Name TestModuleTestModule.psm1
Error:
'This module uses the dot-source operator while exporting functions using wildcard characters, and this is disallowed when the system is under application verification enforcement.'

# But importing using the module manifest succeeds since the manifest explicitly exports functions by name without wildcards
Import-Module TestModule
Get-Module -Name TestModule | Select -ExpandProperty ExportedFunctions
Invoke-Program

Module Function Export Best Practices

Best practices for module function exporting is pretty simple. Always export module functions explicitly by name. Never export using wild card names. This will yield the best performance and ensure you don’t expose functions you don’t intend to expose. It makes your module safer to use as trusted in a DeviceGuard policy enforcement environment.

# TestModule.psm1
Import-Module HelperMod1
. .CSharpHelpers.ps1
function Invoke-Program { }

# TestModule.psd1
@ { ModuleVersion='1.0'; RootModule='TestModule.psm1'; FunctionsToExport='Invoke-Program' }

Get-Module -Name TestModule -List | Select -ExpandProperty ExportedFunctions
Invoke-Program

Paul Higinbotham
Senior Software Engineer
PowerShell Team

PowerShell Standard Library: Build single module that works across Windows PowerShell and PowerShell Core

This post was originally published on this site

This is the first of a series of blog posts that will help you take advantage of a new NuGet package PowerShellStandard Library 5.1.0. This package allows developers to create modules that are portable between Windows PowerShell 5.1 and PowerShell Core 6.0. This means that you can create PowerShell modules that run on Windows, Linux, and macOS with a single binary!

The version of PowerShell Standard Library indicates the lowest version of PowerShell that it is compatible with. The community promise is that it is always forward compatible. So a module built against PowerShell Standard Library v3 is compatible with Windows PowerShell v3, v4, v5.1, PowerShell Core 6, and the upcoming PowerShell Core 6.1. Compatibility is achieved by providing a subset of the APIs common across all those versions of PowerShell. This reference assembly is the equivalent to a header file for C/C++ where it has the APIs defined, but no implementation. During runtime, the module would use the version of System.Management.Automation.dll that is used by the PowerShell host.

Creating a PowerShell Module

In this post, I’ll walk through the steps for creating a simple C# module with a single cmdlet. I will also be using the DotNet CLI tools for creating everything I need.

Installing the PowerShell Standard Module Template

First, we can leverage a new template that we published for DotNet CLI, but we need to install it first:

PS> dotnet new -i Microsoft.PowerShell.Standard.Module.Template
  Restoring packages for C:UsersJames.templateenginedotnetcliv2.1.302scratchrestore.csproj...
  Installing Microsoft.PowerShell.Standard.Module.Template 0.1.3.
  Generating MSBuild file C:UsersJames.templateenginedotnetcliv2.1.302scratchobjrestore.csproj.nuget.g.props.
  Generating MSBuild file C:UsersJames.templateenginedotnetcliv2.1.302scratchobjrestore.csproj.nuget.g.targets.
  Restore completed in 1.66 sec for C:UsersJames.templateenginedotnetcliv2.1.302scratchrestore.csproj.

Usage: new [options]

Options:
  -h, --help          Displays help for this command.
  -l, --list          Lists templates containing the specified name. If no name is specified, lists all templates.
  -n, --name          The name for the output being created. If no name is specified, the name of the current directory is used.
  -o, --output        Location to place the generated output.
  -i, --install       Installs a source or a template pack.
  -u, --uninstall     Uninstalls a source or a template pack.
  --nuget-source      Specifies a NuGet source to use during install.
  --type              Filters templates based on available types. Predefined values are "project", "item" or "other".
  --force             Forces content to be generated even if it would change existing files.
  -lang, --language   Filters templates based on language and specifies the language of the template to create.


Templates                                         Short Name         Language          Tags                             
----------------------------------------------------------------------------------------------------------------------------
Console Application                               console            [C#], F#, VB      Common/Console                   
Class library                                     classlib           [C#], F#, VB      Common/Library                   
PowerShell Standard Module                        psmodule           [C#]              Library/PowerShell/Module    
...

A new template called psmodule is now available making it easy to start a new C# based PowerShell module. Any issues, feedback, or suggestions for this template should be opened in the PowerShell Standard repo.

Creating a new project

We need to create a location for our new project and then use the template to create the project:

PS> mkdir myModule
Directory: C:UsersJames
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 8/3/2018 2:41 PM myModule
PS> cd myModule
PS C:UsersJamesmyModule> dotnet new psmodule
The template "PowerShell Standard Module" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on C:UsersJamesmyModulemyModule.csproj...
  Restoring packages for C:UsersJamesmyModulemyModule.csproj...
  Installing PowerShellStandard.Library 5.1.0-preview-06.
  Generating MSBuild file C:UsersJamesmyModuleobjmyModule.csproj.nuget.g.props.
  Generating MSBuild file C:UsersJamesmyModuleobjmyModule.csproj.nuget.g.targets.
  Restore completed in 1.76 sec for C:UsersJamesmyModulemyModule.csproj.

Restore succeeded.

You can see that the dotnet cli has created a source file and .csproj file for my project:

PS C:UsersJamesmyModule> dir


    Directory: C:UsersJamesmyModule


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         8/3/2018   1:48 PM                obj
-a----         8/3/2018   1:48 PM            376 myModule.csproj
-a----         8/3/2018   1:48 PM           1698 TestSampleCmdletCommand.cs

The sample from the template demonstrates a simple cmdlet with two parameters that outputs results with a custom class.

Building the module

Building the sample is code is easy with DotNet CLI:

PS C:UsersJamesmyModule> dotnet build
Microsoft (R) Build Engine version 15.7.179.6572 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 76.85 ms for C:UsersJamesmyModulemyModule.csproj.
  myModule -> C:UsersJamesmyModulebinDebugnetstandard2.0myModule.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:05.40

Testing the built module

To test this sample module, we just need to import it. We can check to see what it supports and try running it:

PS C:UsersJamesmyModule> ipmo .binDebugnetstandard2.0myModule.dll
PS C:UsersJamesmyModule> Test-SampleCmdlet -?

NAME
    Test-SampleCmdlet

SYNTAX
    Test-SampleCmdlet [-FavoriteNumber] <int> [[-FavoritePet] {Cat | Dog | Horse}] [<CommonParameters>]


ALIASES
    None


REMARKS
    None



PS C:UsersJamesmyModule> Test-SampleCmdlet -FavoriteNumber 7 -FavoritePet Cat

FavoriteNumber FavoritePet
-------------- -----------
             7 Cat

This sample is pretty simple as it’s intended to just show how to get started on writing a PowerShell module from scratch. The important point is that using PowerShell Standard Library, this assembly can be used in both PowerShell Core 6 as well as Windows PowerShell. This sample will even work on Windows, Linux, or macOS without any changes.

In the next part of this series, I’ll cover other aspects of PowerShell module authoring such as module manifests and writing Pester tests.

James Truher
Senior Software Engineer
PowerShell Team

PowerShell Injection Hunter: Security Auditing for PowerShell Scripts

This post was originally published on this site

At the DEFCON security conference last year, we presented the session: “Get $pwnd: Attacking Battle Hardened Windows Server“.

In this talk, we went through some of the incredibly powerful ways that administrators can secure their high-value systems (for example, Just Enough Administration) and also dove into some of the mistakes that administrators sometimes make when exposing their their PowerShell code to an attacker. The most common form of mistake is script injection, where a script author takes a parameter value (supplied by an attacker) and runs it in a trusted context (such as a function exposed in a Just Enough Administration endpoint). Here’s an example:

 

There are many coding patterns that can introduce security flaws like this, all of which have secure alternatives. The presentation goes into these in great detail, and what we also promised to release is a tool to help you detect them as you are writing the scripts. We’ve now released this tool, and you can download it from the PowerShell Gallery:

Using it this way from the command line is an excellent way to automate security analysis during builds, continuous integration processes, deployments, and more.

Wouldn’t it be REALLY cool if you could detect these dangers while writing your scripts? I’m glad you asked!

PowerShell’s Visual Studio Code plugin already does live script analysis to help you discover issues like unassigned variables, and we can customize that rule set to include InjectionHunter capabilities. Here’s what Visual Studio Code looks like with this running:

Here’s how to get this on your system:

First, find out the location of the InjectionHunter module. You can do this by typing:

Get-Module InjectionHunter -List | Foreach-Object Path

On my system, this returns:

D:LeeWindowsPowerShellModulesInjectionHunter1.0.0InjectionHunter.psd1

Next, create a file – ‘PSScriptAnalyzerSettings.psd1’ in a location of your choice. Use the following for the content – replacing the path to InjectionHunter with the one on your system.

@{
 IncludeDefaultRules = $true
 CustomRulePath = "D:LeeWindowsPowerShellModulesInjectionHunter1.0.0InjectionHunter.psd1"
}
Finally, update your Visual Studio Code user settings to tell the PowerShell plugin to use your custom settings. You can get to these by typing Control+Comma, or through File | Preferences | Settings.
I’ve got some settings that match my personal preferences already, so the critical line to add is:
"powershell.scriptAnalysis.settingsPath""c:/users/lee/PSScriptAnalyzerSettings.psd1"
Where the path to PSScriptAnalyzerSettings.psd1 is the path that you saved your file earlier. When you open a PowerShell script with possible code injection risks, you should now see Script Analyzer warnings that highlight what they are and how to fix them.
Happy hunting!

PowerShell Core now available as a Snap package

This post was originally published on this site

The goal of PowerShell Core is to be the ubiquitous language for managing your assets in the hybrid cloud. That’s why we’ve worked to make it available on many operating systems, architectures, and flavors of Windows, Linux, and macOS as possible.

Today, we’re happy to announce an addition to our support matrix: PowerShell Core is now available as a Snap package.

What’s a Snap package?

Snap packages are containerized applications that can be installed on many Linux distributions.

What does this do for me?

Snap packages have a number of benefits over traditional Linux software packages (e.g. DEB or RPM):

  • Snap packages carry all of their own dependencies, so you don’t need to worry about the specific versions of shared libraries installed on your machine
  • Snap packages can be installed without giving the publisher root access to the host
  • Snap packages are “safe to run” as they don’t interact with other applications or system files without your permission
  • Updates to Snaps happen automatically, and include the delta of changes between updates

How do I get it?

First, you need to make sure you’ve installed snapd.

Then, just run:

snap install powershell --classic

Now you’ve got PowerShell Core installed as a Snap! Simply start pwsh from your favorite terminal, and you’re in!

Interested in our latest preview bits?

If you live on the bleeding edge and want to grab the latest PowerShell preview, just install powershell-preview instead of powershell:

snap install powershell-preview --classic

Now you can launch PowerShell Core’s latest preview as a Snap by launching pwsh-preview from your terminal.

What about your other Linux packages?

We will continue to support our “traditional” standalone Linux packages that ship on https://packages.microsoft.com/, and we have no plans to discontinue that support.

However, we highly encourage you to check out the Snap package as a way to simplify your updates and reduce the permission set required for installation.

Happy Snapping!

Joey Aiello
PM, PowerShell

PowerShell Script Analyzer 1.17.1 Released!

This post was originally published on this site

Summary: A new version of PSScriptAnalyzer is now available with many new features, rules, fixes and improvements.

You might remember me from my previous cross-platform remoting blog post, but just to introduce myself: I am Christoph Bergmeister, a full stack .Net developer in the London area and since the start of this year I am now also an official PSScriptAnalyzer maintainer although I do not work at Microsoft.
On GitHub, you can find me as @bergmeister.

After half a year, a new version of PSScriptAnalyzer (also known as PSSA) has been published and is now available on the PSGallery.
Some of you might have been wondering what has happened.
First, the former maintainer has switched projects, therefore it took some time for finding and arranging a hand over.
PSScriptAnalyzer is now mainly being maintained by @JamesWTruher from the Microsoft side and myself as a community maintainer.
After having already contributed to the PowerShell Core project, I started doing development on PSScriptAnalyzer last autumn and since then have added a lot of new features.

New Parameters

Invoke-ScriptAnalyzer now has 3 new switch parameters:

  • -Fix (only on the -Path parameter set)
  • -ReportSummary
  • -EnableExit

The -Fix switch was the first and probably most challenging feature that I added.
Similar to how one can already get fixes for a subset of warnings (e.g. for AvoidUsingCmdletAlias) in VSCode, this feature allows to auto-fix the analysed files, which can be useful to tidy up a big code base.
When using this switch, one must still inspect the result and possibly make adaptions.
The AvoidUsingConvertToSecureStringWithPlainText rule for example will change a String to a SecureString, which means that you must create or get it in the first place.
A small warning should be given about encoding: Due to the way how the engine works, it was not possible to always conserve the encoding, therefore before checking in the changes, it is also recommended to check for a change in that in case scripts are sensitive to that.

The -ReportSummary switch was implemented first by the community member @StingyJack, thanks for that.
The idea is to see a summary, like Pester but since it writes to host, we decided to not enable it by default but rather have a switch for it to start with.
It got refined a bit later to use the same colouring for warnings/errors as currently configured in the PowerShell host.

The -EnableExit was an idea being proposed by the community member @BatmanAMA as well and the idea is to have a simpler, faster to write CI integration.
The switch will return an exit code equivalent to the number of rule violations to signal success/failure to the CI system.
Of course, it is still best practice to have a Pester test (for each file and/or rule) for it due Pester’s ability to produce result files that can be interpreted by CI systems for more detailed analysis.

New Rules

AvoidAssignmentToAutomaticVariable

PowerShell has built-in variables, also known as automatic variables.
Some of them are read-only and PowerShell would throw an error at runtime.
Therefore, the rule warns against assignment of those variables.
Some of them, like e.g. $error are very easy to assign to by mistake, especially for new users who are not aware.
In the future more automatic variables will be added to the ‘naughty’ list but since some automatic variables can be assigned to (by design), the process of determining the ones to warn against is still in process and subject to future improvement.

PossibleIncorrectUsageOfRedirectionOperator and PossibleIncorrectUsageOfAssignmentOperator

I have written those rules mainly for myself because as a C# programmer, I have to switch between different languages quite often and it happened to me and my colleagues quite often that we forgot simple syntax and were using e.g. if ($a > $b) when in fact what we meant was if ($a -gt $b) and similar for the ambiguity of the assignment operator = that can easily be used by accident instead of the equality operator that was probably intended.
Since this only applies to if/elseif/while/do-while statements, I could limit the search scope for it.
To avoid false positives, a lot of intelligent logic went into it.
For example, the rule is clever enough to know that if ($a = Get-Something) is assignment by design as this is a common coding pattern and therefore excluded from this rule.
I received some interesting feedback from the community and because PSSA does not support suppression on a per line basis at the moment, the rule offers implicit suppression in CLANG style whereby wrapping the expression in extra parenthesis tells the rule that the assignment is by design.
Thanks for this idea, which came from the community by @imfrancisd

AvoidTrailingWhiteSpace

This rule was implemented by the well known community member @dlwyatt and really does what it says on the tin.
The idea behind this was especially to prevent problems that can be caused by whitespace after the backtick.
Personally, I have the following setting in my settings.json for VSCode file that trims trailing whitespace automatically upon saving the file.

    "": {
        "files.trimTrailingWhitespace": true
    },

AvoidUsingCmdletAliases

This rule is not new but a new feature has been added:
If one types a command like e.g. ‘verb’ and PowerShell cannot find it, it will try to add a ‘Get-‘ to the beginning of it and search again.
This feature was already present in PowerShell v1 by the way.
However, although ‘service’ might work on Windows, but on Linux ‘service’ is a native binary that PowerShell would call.
Therefore it is not only the implicit aliasing that makes it dangerous to omit ‘Get-‘, but also the ambiguity on different operating systems that can cause undesired behavior.
The rule is intelligent enough to check if the native binary is present on the given OS and therefore warns when using ‘service’ on Windows only.

Miscellaneous engine improvements and fixes

A lot of fixes for thrown exception, false positives, false negatives, etc. are part of this release as well.
Some are notable:

  • The PowerShell extension of VSCode uses PowerShellEditorServices, which in turn calls into PSScriptAnalyzer for displaying the warnings using squiggles and also uses its formatting capabilities (shortcut: Ctrl+K+F on the selection).
    There was one bug whereby if a comment was at the end of e.g. an if statement and the statement got changed to have the brace on the same line, the formatter placed the comment before the brace, which resulted in invalid syntax.
    This is fixed now.
    The PSUseConsistentWhiteSpace was also tweaked to take unary operators into account to have formatting that naturally looks better to humans rather than having a strict rule.
  • The engine is now being built using the .Net Core SDK version 2 and targets .Net Standard 2.0 for PowerShell Core builds.
    The used referenced for the PowerShell Parser also got updated to the latest version or the corresponding reference assemblies for Windows PowerShell, which highly improved the behaviour of PSScriptAnalyzer on PowerShell 3.
  • Various parsing issues existed with the -Settings parameter when it was not a string that was already resolved.
    This got fixed and should now work in any scenario.
  • PSSA has a UseCompatibleCmdlet rule and command data files are now present for all versions of Windows PowerShell and even OS specific for PowerShell Core 6.0.2.
    In effect the rule allows you to get warnings when calling cmdlets that are not present in the chosen PowerShell versions.
    More improvements to analyse type usage as well is planned.
  • The PSUseDeclaredVarsMoreThanAssignments rule has been a pet peeve for many in the past due to its many false positves.
    The rule received a few improvements.
    Some of its limitations (it is e.g. not aware of the scriptblock scope) are still present but overall, there should be less false positives.
  • Lots of internal build and packaging improvements were made and PSScriptAnalyzer pushed the envelope as far as using AppVeyor’s Ubuntu builds, which are currently in private Beta.
    Many thanks to @IlyaFinkelshteyn for allowing us to use it and the great support.
    We are now testing against PowerShell 4, 5.1 and 6.0 (Windows and Ubuntu) in CI.
  • Many community members added documentation fixes, thank you all for that!
  • Parser errors are now returned as diagnostic messages
  • Using ScriptAnalyzer with PowerShell Core requires at least version 6.0.2

Enjoy the new release and let us know how you find it.
PSScriptAnalyzer is also open to PRs if you want to add features or fix something.
Let me know if there are other PSScriptAnalyzer topics that you would like me to write about, such as e.g. custom rules or PSScriptAnalyzer setting files and VSCode integration.

Christopher Bergmeister
PSScriptAnalyzer Maintainer

DSC Resource Kit Release June 2018

This post was originally published on this site

We just released the DSC Resource Kit!

This is our biggest release yet!
It takes the records for the most merged pull requests in a release and the most modules we have ever released at once from GitHub!

This release includes updates to 27 DSC resource modules. In the past 6 weeks, 165 pull requests have been merged and 115 issues have been closed, all thanks to our amazing community!

The modules updated in this release are:

  • ActiveDirectoryCSDsc
  • AuditPolicyDsc
  • CertificateDsc
  • ComputerManagementDsc
  • DFSDsc
  • NetworkingDsc (previously xNetworking)
  • SecurityPolicyDsc
  • SharePointDsc
  • SqlServerDsc
  • xActiveDirectory
  • xBitlocker
  • xDatabase
  • xDhcpServer
  • xDismFeature
  • xDnsServer
  • xDscDiagnostics
  • xDSCResourceDesigner
  • xExchange
  • xHyper-V
  • xPowerShellExecutionPolicy
  • xPSDesiredStateConfiguration
  • xRemoteDesktopSessionHost
  • xSCSMA
  • xSystemSecurity
  • xTimeZone (deprecated since now included in ComputerManagementDsc)
  • xWebAdministration
  • xWinEventLog

For a detailed list of the resource modules and fixes in this release, see the Included in this Release section below.

Our last community call for the DSC Resource Kit was on June 6. A recording of our updates is available on YouTube here. Join us for the next call at 12PM (Pacific time) on July 18 to ask questions and give feedback about your experience with the DSC Resource Kit.

We strongly encourage you to update to the newest version of all modules using the PowerShell Gallery, and don’t forget to give us your feedback in the comments below, on GitHub, or on Twitter (@PowerShell_Team)!

Please see our documentation here for information on the support of these resource modules.

Included in this Release

You can see a detailed summary of all changes included in this release in the table below. For past release notes, go to the README.md or Changelog.md file on the GitHub repository page for a specific module (see the How to Find DSC Resource Modules on GitHub section below for details on finding the GitHub page for a specific module).

Module Name Version Release Notes
ActiveDirectoryCSDsc 3.0.0.0
  • Changed Assert-VerifiableMocks to be Assert-VerifiableMock to meet Pester standards.
  • Updated license year in LICENSE.MD and module manifest to 2018.
  • Removed requirement for Pester maximum version 4.0.8.
  • Added new resource EnrollmentPolicyWebService – see issue 43.
  • BREAKING CHANGE: New Key for AdcsCertificationAuthority, IsSingleInstance – see issue 47.
  • Added:
    • MSFT_xADCSOnlineResponder resource to install the Online Responder service.
  • Corrected filename of MSFT_AdcsCertificationAuthority integration test file.
AuditPolicyDsc 1.2.0.0
  • Moved auditpol call in the helper module to an external process to better control output
  • auditpol output is now converted to CSV to remove the need to parse the text output
  • All resources have been updated to use the new helper module functionality
  • Added the Ensure parameter default value of Present to the AuditPolicySubcategory resource Test-TargetResource function
CertificateDsc 4.1.0.0
  • PfxImport:
    • Changed so that PFX will be reimported if private key is not installed – fixes Issue 129.
    • Corrected to meet style guidelines.
    • Corrected path parameter description – fixes Issue 125.
    • Refactored to remove code duplication by creating Get-CertificateStorePath.
    • Improved unit tests to meet standards and provide better coverage.
    • Improved integration tests to meet standards and provide better coverage.
  • CertificateDsc.Common:
    • Corrected to meet style guidelines.
    • Added function Get-CertificateStorePath for generating Certificate Store path.
    • Remove false verbose message from Test-Thumbprint – fixes Issue 127.
  • CertReq:
    • Added detection for FIPS mode in Test-Thumbprint – fixes Issue 107.
ComputerManagementDsc 5.1.0.0
  • TimeZone:
  • Moved Test-Command from ComputerManagementDsc.ResourceHelper to ComputerManagementDsc.Common module to match what TimeZone requires. It was not exported in ComputerManagementDsc.ResourceHelper and not used.
DFSDsc 4.1.0.0
  • Added Hub and Spoke replication group example – fixes Issue 62.
  • Enabled PSSA rule violations to fail build – fixes Issue 320.
  • Allow null values in resource group members or folders – fixes Issue 27.
  • Added a CODE_OF_CONDUCT.md with the same content as in the README.md – fixes Issue 67.
NetworkingDsc
(previously xNetworking)
6.0.0.0
  • New Example 2-ConfigureSuffixSearchList.ps1 for multiple SuffixSearchList entries for resource DnsClientGlobalSetting.
  • BREAKING CHANGE:
    • Renamed xNetworking to NetworkingDsc – fixes Issue 119.
    • Changed all MSFT_xResourceName to MSFT_ResourceName.
    • Updated DSCResources, Examples, Modules and Tests with new naming.
    • Updated Year to 2018 in License and Manifest.
    • Updated README.md from xNetworking to NetworkingDsc.
  • MSFT_IPAddress:
    • Updated to allow setting multiple IP Addresses when one is already set – Fixes Issue 323
  • Corrected CHANGELOG.MD to report that issue with InterfaceAlias matching on Adapter description rather than Adapter Name was released in 5.7.0.0 rather than 5.6.0.0 – See Issue 315.
  • MSFT_WaitForNetworkTeam:
    • Added a new resource to set the wait for a network team to become “Up”.
  • MSFT_NetworkTeam:
    • Improved detection of environmemt for running network team integration tests.
  • MSFT_NetworkTeamInterface:
    • Improved detection of environmemt for running network team integration tests.
  • Added a CODE_OF_CONDUCT.md with the same content as in the README.md – fixes Issue 337.
SecurityPolicyDsc 2.3.0.0
  • Updated documentation.
    • Add example of applying Kerberos policies
    • Added hyper links to readme
  • Refactored the SID translation process to not throw a terminating error when called from Test-TargetResource
  • Updated verbose message during the SID transliation process to identiy the policy where an orphaned SID exists
SharePointDsc 2.3.0.0
      • Changes to SharePointDsc
        • Added a Branches section to the README.md with Codecov and build badges for both master and dev branch.
      • All Resources
        • Added information about the Resource Type in each ReadMe.md files.
      • SPFarm
        • Fixed issue where the resource throws an exception if the farm already exists and the server has been joined using the FQDN (issue 795)
      • SPTimerJobState
        • Fixed issue where the Set method for timerjobs deployed to multiple web applications failed.
      • SPTrustedIdentityTokenIssuerProviderRealms
        • Added the resource.
      • SPUserProfileServiceApp
        • Now supported specifying the host Managed path, and properly sets the host.
        • Changed error for running with Farm Account into being a warning
      • SPUserProfileSyncConnection
        • Added support for filtering disabled users
        • Fixed issue where UseSSL was set to true resulted in an error
        • Fixed issue where the connection was recreated when the name contained a dot (SP2016)
SqlServerDsc 11.3.0.0
  • Changes to SqlServerDsc
    • Moved decoration for integration test to resolve a breaking change in DscResource.Tests.
    • Activated the GitHub App Stale on the GitHub repository.
    • Added a CODE_OF_CONDUCT.md with the same content as in the README.md issue 939.
    • New resources:
    • Fix for issue 779 Paul Kelly (@prkelly)
xActiveDirectory 2.19.0.0
  • Changes to xActiveDirectory
    • Activated the GitHub App Stale on the GitHub repository.
    • The resources are now in alphabetical order in the README.md (issue 194).
    • Adding a Branches section to the README.md with Codecov badges for both master and dev branch (issue 192).
    • xADGroup no longer resets GroupScope and Category to default values (issue 183).
    • The helper function script file MSFT_xADCommon.ps1 was renamed to MSFT_xADCommon.psm1 to be a module script file instead. This makes it possible to report code coverage for the helper functions (issue 201).
xBitlocker 1.2.0.0
  • Converted appveyor.yml to install Pester from PSGallery instead of from Chocolatey.
  • Added Codecov support.
  • Updated appveyor.yml to use the one in template.
  • Added folders for future unit and integration tests.
  • Added Visual Studio Code formatting settings.
  • Added .gitignore file.
  • Added markdown lint rules.
  • Fixed encoding on README.md.
  • Added PowerShellVersion = "4.0", and updated copyright information, in the module manifest.
  • Fixed issue which caused Test to incorrectly succeed on fully decrypted volumes when correct Key Protectors were present (issue 13)
  • Fixed issue which caused xBLAutoBitlocker to incorrectly detect Fixed vs Removable volumes. (issue 11)
  • Fixed issue which made xBLAutoBitlocker unable to encrypt volumes with drive letters assigned. (issue 10)
  • Fixed an issue in CheckForPreReqs function where on Server Core the installation of the non existing Windows Feature “RSAT-Feature-Tools-BitLocker-RemoteAdminTool” was erroneously checked. (issue 8)
xDatabase 1.8.0.0
  • Added support for SQL Server 2017
  • xDBPackage now uses the shared function to identify the paths for the different SQL server versions
xDhcpServer 1.7.0.0
  • Changes to xDhcpServer
    • Updated year in LICENSE file.
    • Updated year in module manifest.
    • Added Codecov and status badges to README.md.
    • Update appveyor.yml to use the default template.
  • Added xDhcpServerOptionDefinition
xDismFeature 1.3.0.0
  • Added unit test
  • Fixed issue that Test-TargetResource always fails on non-English OS 11
xDnsServer 1.11.0.0
  • Changes to xDnsServer
    • Updated appveyor.yml to use the default template and add CodeCov support (issue 73).
    • Adding a Branches section to the README.md with Codecov badges for both master and dev branch (issue 73).
    • Updated description of resource module in README.md.
  • Added resource xDnsServerZoneAging. Claudio Spizzi (@claudiospizzi)
  • Changes to xDnsServerPrimaryZone
  • Changes to xDnsRecord
xDscDiagnostics 2.7.0.0
  • Fixed help formatting.
xDSCResourceDesigner 1.11.0.0
  • Added support for Codecov.
  • Fix Test-xDscSchema failing to call Remove-WmiObject on PowerShell Core. The cmdlet Remove-WmiObject was removed from the code, instead the temporary CIM class is now removed by using mofcomp.exe and the preprocessor command pragma deleteclass (issue 67).
xExchange 1.21.0.0
  • Added CHANGELOG.md file
  • Added .markdownlint.json file
  • Updated README.md and CHANGELOG.md files to respect MD009, MD0013 and MD032 rules
  • Added .MetaTestOptIn.json file
  • Updated appveyor.yml file
  • Added .codecov.yml file
  • Renamed Test folder to Tests
  • Updated README.md: Add codecov badges
  • Fixed PSSA required rules in:
    • xExchClientAccessServer.psm1
    • xExchInstall.psm1
    • xExchMaintenanceMode.psm1
    • TransportMaintenance.psm1
    • xExchTransportService.psm1
  • Fixed Validate Example files in:
    • ConfigureAutoMountPoints-FromCalculator.ps1
    • ConfigureAutoMountPoints-Manual.ps1
    • ConfigureDatabases-FromCalculator.ps1
    • InternetFacingSite.ps1
    • RegionalNamespaces.ps1
    • SingleNamespace.ps1
    • ConfigureVirtualDirectories.ps1
    • CreateAndConfigureDAG.ps1
    • EndToEndExample 1 to 10 files
    • JetstressAutomation
    • MaintenanceMode
    • PostInstallationConfiguration.ps1
    • InstallExchange.ps1
    • QuickStartTemplate.ps1
    • WaitForADPrep.ps1
  • Remove default value for Switch Parameter in TransportMaintenance.psm1 for functions:
    • Clear-DiscardEvent
    • LogIfRemain
    • Wait-EmptyEntriesCompletion
    • Update-EntriesTracker
    • Remove-CompletedEntriesFromHashtable
  • Fixed PSSA custom rules in:
    • xExchActiveSyncVirtualDirectory.psm1
    • xExchAntiMalwareScanning.psm1
    • xExchAutodiscoverVirtualDirectory.psm1
    • xExchAutoMountPoint.psm1
    • xExchClientAccessServer.psm1
    • xExchDatabaseAvailabilityGroup.psm1
    • xExchDatabaseAvailabilityGroupMember.psm1
    • xExchDatabaseAvailabilityGroupNetwork.psm1
    • xExchEcpVirtualDirectory.psm1
    • xExchEventLogLevel.psm1
    • xExchExchangeCertificate.psm1
    • xExchExchangeServer.psm1
    • xExchImapSettings.psm1
    • xExchInstall.psm1
    • xExchJetstress.psm1
    • xExchJetstressCleanup.psm1
    • xExchMailboxDatabase.psm1
    • xExchMailboxDatabaseCopy.psm1
    • xExchMailboxServer.psm1
    • xExchMailboxTransportService.psm1
    • xExchMaintenanceMode.psm1
    • xExchMapiVirtualDirectory.psm1
    • xExchOabVirtualDirectory.psm1
    • xExchOutlookAnywhere.psm1
    • xExchOwaVirtualDirectory.psm1
    • xExchPopSettings.psm1
    • xExchPowerShellVirtualDirectory.psm1
    • xExchReceiveConnector.psm1
    • xExchUMCallRouterSettings.psm1
    • xExchUMService.psm1
    • xExchWaitForADPrep.psm1
    • xExchWaitForDAG.psm1
    • xExchWaitForMailboxDatabase.psm1
    • xExchWebServicesVirtualDirectory.psm1
  • Updated xExchange.psd1
  • Added issue template file (ISSUE_TEMPLATE.md) for “New Issue” and pull request template file (PULL_REQUEST_TEMPLATE.md) for “New Pull Request”.
  • Fix issue Diagnostics.CodeAnalysis.SuppressMessageAttribute best practices
  • Renamed xExchangeCommon.psm1 to xExchangeHelper.psm1
  • Renamed the folder MISC (that contains the helper) to Modules
  • Added xExchangeHelper.psm1 in xExchange.psd1 (section NestedModules)
  • Removed all lines with Import-Module xExchangeCommon.psm1
  • Updated .MetaTestOptIn.json file with Custom Script Analyzer Rules
  • Added Integration, TestHelpers and Unit folder
  • Moved Data folder in Tests
  • Moved Integration tests to Integration folder
  • Moved Unit test to Unit folder
  • Renamed xEchange.Tests.Common.psm1 to xExchangeTestHelper.psm1
  • Renamed xEchangeCommon.Unit.Tests.ps1 to xExchangeCommon.Tests.ps1
  • Renamed function PrepTestDAG to Initialize-TestForDAG
  • Moved function Initialize-TestForDAG to xExchangeTestHelper.psm1
  • Fix error-level PS Script Analyzer rules for TransportMaintenance.psm1
xHyper-V 3.12.0.0
  • Changes to xHyper-V
    • Removed alignPropertyValuePairs from the Visual Studio Code default style formatting settings (issue 110).
xPowerShellExecutionPolicy 3.0.0.0
xPSDesiredStateConfiguration 8.3.0.0
  • Changes to xPSDesiredStateConfiguration
  • Changes to xWindowsProcess
    • Integration tests for this resource should no longer fail randomly. A timing issue made the tests fail in certain scenarios (issue 420).
  • Changes to xDSCWebService
    • Added the option to use a certificate based on it”s subject and template name instead of it”s thumbprint. Resolves issue 205.
    • xDSCWebService: Fixed an issue where Test-WebConfigModulesSetting would return $true when web.config contains a module and the desired state was for it to be absent. Resolves issue 418.
  • Updated the main DSCPullServerSetup readme to read easier, then updates the PowerShell comment based help for each function to follow normal help standards. James Pogran (@jpogran)
  • xRemoteFile: Remove progress bar for file download. This resolves issues 165 and 383 Claudio Spizzi (@claudiospizzi)
xRemoteDesktopSessionHost 1.6.0.0
  • xRDSessionCollectionConfiguration: Add support to configure UserProfileDisks on Windows Server 2016
xSCSMA 2.0.0.0
  • Added MSI install logging for MSFT_xSCSMARunbookWorkerServerSetup and MSFT_xSCSMARunbookWorkerServerSetup
  • Added missing -Port parameter argument for New-SmaRunbookWorkerDeployment in MSFT_xSCSMARunbookWorkerServerSetup
  • Fixed MSFT_xSCSMARunbookWorkerServerSetup and MSFT_xSCSMAWebServiceServerSetup using incorrect executable for version checking
  • Remove System Center Technical Preview 5 support. Close issue 18
  • Close issue 19 (always install self-signed certificate)
  • BREAKING CHANGE: change SendCEIPReports parameter to SendTelemetryReports. Close issue 20
  • Added description for new parameters at README.md
  • Fix return state of the current SendTelemetryReports
  • Fix syntax at source code
xSystemSecurity 1.4.0.0
xTimeZone 1.8.0.0
  • THIS MODULE HAS BEEN DEPRECATED. It will no longer be released. Please use the “TimeZone” resource in ComputerManagementDsc instead.
  • Fixed xTimeZone Examples link in README.md.
xWebAdministration 2.0.0.0
  • Changes to xWebAdministration
    • Moved file Codecov.yml that was added to the wrong path in previous release.
  • Updated xWebSite to include ability to manage custom logging fields. Reggie Gibson (@regedit32)
  • Updated xIISLogging to include ability to manage custom logging fields (issue 267). @ldillonel
  • BREAKING CHANGE: Updated xIisFeatureDelegation to be able to manage any configuration section. Reggie Gibson (@regedit32)
xWinEventLog 1.2.0.0
  • Converted appveyor.yml to install Pester from PSGallery instead of from Chocolatey.
  • Fix PSSA errors.

How to Find Released DSC Resource Modules

To see a list of all released DSC Resource Kit modules, go to the PowerShell Gallery and display all modules tagged as DSCResourceKit. You can also enter a module’s name in the search box in the upper right corner of the PowerShell Gallery to find a specific module.

Of course, you can also always use PowerShellGet (available starting in WMF 5.0) to find modules with DSC Resources:

# To list all modules that tagged as DSCResourceKit
Find-Module -Tag DSCResourceKit 
# To list all DSC resources from all sources 
Find-DscResource

Please note only those modules released by the PowerShell Team are currently considered part of the ‘DSC Resource Kit’ regardless of the presence of the ‘DSC Resource Kit’ tag in the PowerShell Gallery.

To find a specific module, go directly to its URL on the PowerShell Gallery:
http://www.powershellgallery.com/packages/< module name >
For example:
http://www.powershellgallery.com/packages/xWebAdministration

How to Install DSC Resource Modules From the PowerShell Gallery

We recommend that you use PowerShellGet to install DSC resource modules:

Install-Module -Name < module name >

For example:

Install-Module -Name xWebAdministration

To update all previously installed modules at once, open an elevated PowerShell prompt and use this command:

Update-Module

After installing modules, you can discover all DSC resources available to your local system with this command:

Get-DscResource

How to Find DSC Resource Modules on GitHub

All resource modules in the DSC Resource Kit are available open-source on GitHub.
You can see the most recent state of a resource module by visiting its GitHub page at:
https://github.com/PowerShell/< module name >
For example, for the xCertificate module, go to:
https://github.com/PowerShell/xCertificate.

All DSC modules are also listed as submodules of the DscResources repository in the xDscResources folder.

How to Contribute

You are more than welcome to contribute to the development of the DSC Resource Kit! There are several different ways you can help. You can create new DSC resources or modules, add test automation, improve documentation, fix existing issues, or open new ones.
See our contributing guide for more info on how to become a DSC Resource Kit contributor.

If you would like to help, please take a look at the list of open issues for the DscResources repository.
You can also check issues for specific resource modules by going to:
https://github.com/PowerShell/< module name >/issues
For example:
https://github.com/PowerShell/xPSDesiredStateConfiguration/issues

Your help in developing the DSC Resource Kit is invaluable to us!

Questions, comments?

If you’re looking into using PowerShell DSC, have questions or issues with a current resource, or would like a new resource, let us know in the comments below, on Twitter (@PowerShell_Team), or by creating an issue on GitHub.

Katie Keim
Software Engineer
PowerShell DSC Team
@katiedsc (Twitter)
@kwirkykat (GitHub)