Category Archives: Powershell

DSC Resource Kit Release November 2018

This post was originally published on this site

We just released the DSC Resource Kit!

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

The modules updated in this release are:

  • AuditPolicyDsc
  • DFSDsc
  • NetworkingDsc
  • SecurityPolicyDsc
  • SharePointDsc
  • StorageDsc
  • xBitlocker
  • xExchange
  • xHyper-V

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

Our latest community call for the DSC Resource Kit was supposed to be today, November 28, but the public link to the call expired, so the call was cancelled. I will update the link for next time. If there is interest in rescheduling this call, the new call time will be announced on Twitter (@katiedsc or @migreene) The call for the next release cycle is also getting moved a week later than usual to January 9 at 12PM (Pacific standard time). Join us to ask questions and give feedback about your experience with the DSC Resource Kit.

The next DSC Resource Kit release will be on Wednesday, January 9.

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
AuditPolicyDsc 1.3.0.0
  • Update LICENSE file to match the Microsoft Open Source Team standard.
  • Added the AuditPolicyGuid resource.
DFSDsc 4.2.0.0
  • Add support for modifying staging quota size in MSFT_DFSReplicationGroupMembership – fixes Issue 77.
  • Refactored module folder structure to move resource to root folder of repository and remove test harness – fixes Issue 74.
  • Updated Examples to support deployment to PowerShell Gallery scripts.
  • Remove exclusion of all tags in appveyor.yml, so all common tests can be run if opt-in.
  • Added .VSCode settings for applying DSC PSSA rules – fixes Issue 75.
  • Updated LICENSE file to match the Microsoft Open Source Team standard – fixes Issue 79
NetworkingDsc 6.2.0.0
  • Added .VSCode settings for applying DSC PSSA rules – fixes Issue 357.
  • Updated LICENSE file to match the Microsoft Open Source Team standard – fixes Issue 363
  • MSFT_NetIPInterface:
    • Added a new resource for configuring the IP interface settings for a network interface.
SecurityPolicyDsc 2.6.0.0
  • Added SecurityOption – Network_access_Restrict_clients_allowed_to_make_remote_calls_to_SAM
  • Bug fix – Issue 105 – Spelling error in SecurityOption”User_Account_Control_Behavior_of_the_elevation_prompt_for_standard_users”
  • Bug fix – Issue 90 – Corrected value for Microsoft_network_server_Server_SPN_target_name_validation_level policy
SharePointDsc 3.0.0.0
  • Changes to SharePointDsc
    • Added support for SharePoint 2019
    • Added CredSSP requirement to the Readme files
    • Added VSCode Support for running SharePoint 2019 unit tests
    • Removed the deprecated resources SPCreateFarm and SPJoinFarm (replaced in v2.0 by SPFarm)
  • SPBlobCacheSettings
    • Updated the Service Instance retrieval to be language independent
  • SPConfigWizard
    • Fixed check for Ensure=Absent in the Set method
  • SPInstallPrereqs
    • Added support for detecting updated installation of Microsoft Visual C++ 2015/2017 Redistributable (x64) for SharePoint 2016 and SharePoint 2019.
  • SPSearchContentSource
    • Added support for Business Content Source Type
  • SPSearchMetadataCategory
    • New resource added
  • SPSearchServiceApp
    • Updated resource to make sure the presence of the service app proxy is checked and created if it does not exist
  • SPSecurityTokenServiceConfig
    • The resource only tested for the Ensure parameter. Added more parameters
  • SPServiceAppSecurity
    • Added support for specifying array of access levels.
    • Changed implementation to use Grant-SPObjectSecurity with Replace switch instead of using a combination of Revoke-SPObjectSecurity and Grant-SPObjectSecurity
    • Added all supported access levels as available values.
    • Removed unknown access levels: Change Permissions, Write, and Read
  • SPUserProfileProperty
    • Removed obsolete parameters (MappingConnectionName, MappingPropertyName, MappingDirection) and introduced new parameter PropertyMappings
  • SPUserProfileServiceApp
    • Updated the check for successful creation of the service app to throw an error if this is not done correctly The following changes will break v2.x and earlier configurations that use these resources:
  • Implemented IsSingleInstance parameter to force that the resource can only be used once in a configuration for the following resources:
    • SPAntivirusSettings
    • SPConfigWizard
    • SPDiagnosticLoggingSettings
    • SPFarm
    • SPFarmAdministrators
    • SPInfoPathFormsServiceConfig
    • SPInstall
    • SPInstallPrereqs
    • SPIrmSettings
    • SPMinRoleCompliance
    • SPPasswordChangeSettings
    • SPProjectServerLicense
    • SPSecurityTokenServiceConfig
    • SPShellAdmin
  • Standardized Url/WebApplication parameter to default WebAppUrl parameter for the following resources:
    • SPDesignerSettings
    • SPFarmSolution
    • SPSelfServiceSiteCreation
    • SPWebAppBlockedFileTypes
    • SPWebAppClientCallableSettings
    • SPWebAppGeneralSettings
    • SPWebApplication
    • SPWebApplicationAppDomain
    • SPWebAppSiteUseAndDeletion
    • SPWebAppThrottlingSettings
    • SPWebAppWorkflowSettings
  • Introduced new mandatory parameters
    • SPSearchResultSource: Added option to create Result Sources at different scopes.
    • SPServiceAppSecurity: Changed parameter AccessLevel to AccessLevels in MSFT_SPServiceAppSecurityEntry to support array of access levels.
    • SPUserProfileProperty: New parameter PropertyMappings
SharePointDsc 3.1.0.0
  • Changes to SharePointDsc
    • Updated LICENSE file to match the Microsoft Open Source Team standard.
  • ProjectServerConnector
    • Added a file hash validation check to prevent the ability to load custom code into the module.
  • SPFarm
    • Fixed localization issue where TypeName was in the local language.
  • SPInstallPrereqs
    • Updated links in the Readme.md file to docs.microsoft.com.
    • Fixed required prereqs for SharePoint 2019, added MSVCRT11.
  • SPManagedMetadataServiceApp
    • Fixed issue where Get-TargetResource method throws an error when the service app proxy does not exist.
  • SPSearchContentSource
    • Corrected issue where the New-SPEnterpriseSearchCrawlContentSource cmdlet was called twice.
  • SPSearchServiceApp
    • Fixed issue where Get-TargetResource method throws an error when the service application pool does not exist.
    • Implemented check to make sure cmdlets are only executed when it actually has something to update.
    • Deprecated WindowsServiceAccount parameter and moved functionality to new resource (SPSearchServiceSettings).
  • SPSearchServiceSettings
    • Added new resource to configure search service settings.
  • SPServiceAppSecurity
    • Fixed unavailable utility method (ExpandAccessLevel).
    • Updated the schema to no longer specify username as key for the sub class.
  • SPUserProfileServiceApp
    • Fixed issue where localized versions of Windows and SharePoint would throw an error.
  • SPUserProfileSyncConnection
    • Corrected implementation of Ensure parameter.
StorageDsc 4.3.0.0
  • WaitForDisk:
    • Added readonly-property isAvailable which shows the current state of the disk as a boolean – fixes Issue 158.
xBitlocker 1.3.0.0
  • Update appveyor.yml to use the default template.
  • Added default template files .gitattributes, and .vscode settings.
  • Fixes most PSScriptAnalyzer issues.
  • Fix issue where AutoUnlock is not set if requested, if the disk was originally encrypted and AutoUnlock was not used.
  • Add remaining Unit Tests for xBitlockerCommon.
  • Add Unit tests for MSFT_xBLTpm
  • Add remaining Unit Tests for xBLAutoBitlocker
  • Add Unit tests for MSFT_xBLBitlocker
  • Moved change log to CHANGELOG.md file
  • Fixed Markdown validation warnings in README.md
  • Added .MetaTestOptIn.json file to root of module
  • Add Integration Tests for module resources
  • Rename functions with improper Verb-Noun constructs
  • Add comment based help to any functions without it
  • Update Schema.mof Description fields
  • Fixes issue where Switch parameters are passed to Enable-Bitlocker even if the corresponding DSC resource parameter was set to False (Issue 12)
xExchange 1.25.0.0
  • Opt-in for the common test flagged Script Analyzer rules (issue 234).
  • Opt-in for the common test testing for relative path length.
  • Removed the property PSDscAllowPlainTextPassword from all examples so the examples are secure by default. The property PSDscAllowPlainTextPassword was previously needed to (test) compile the examples in the CI pipeline, but now the CI pipeline is using a certificate to compile the examples.
  • Opt-in for the common test that validates the markdown links.
  • Fix typo of the word “Certificate” in several example files.
  • Add spaces between array members.
  • Add initial set of Unit Tests (mostly Get-TargetResource tests) for all remaining resource files.
  • Add WaitForComputerObject parameter to xExchWaitForDAG
  • Add spaces between comment hashtags and comments.
  • Add space between variable types and variables.
  • Fixes issue where xExchMailboxDatabase fails to test for a Journal Recipient because the module did not load the Get-Recipient cmdlet (335).
  • Fixes broken Integration tests in MSFT_xExchMaintenanceMode.Integration.Tests.ps1 (336).
  • Fix issue where Get-ReceiveConnector against an Absent connector causes an error to be logged in the MSExchange Management log.
  • Rename poorly named functions in xExchangeDiskPart.psm1 and MSFT_xExchAutoMountPoint.psm1, and add comment based help.
xHyper-V 3.14.0.0
  • MSFT_xVMHost:
    • Added support to Enable / Disable VM Live Migration. Fixes Issue 155.

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 Kragenbrink
Software Engineer
PowerShell DSC Team
@katiedsc (Twitter)
@kwirkykat (GitHub)

PowerShell Constrained Language mode and the Dot-Source Operator

This post was originally published on this site

PowerShell Constrained Language mode and the Dot-Source Operator

PowerShell works with application control systems, such as AppLocker and Windows Defender Application Control (WDAC), by automatically running in
ConstrainedLanguage mode. ConstrainedLanguage mode restricts some exploitable aspects of PowerShell while still giving you a rich shell to run commands and scripts in. This is different from usual application white listing rules, where an application is either allowed to run or not.

But there are times when the full power of PowerShell is needed, so we allow script files to run in FullLanguage mode when they are trusted by the policy. Trust can be indicated through file signing or other policy mechanisms such as file hash. However, script typed into the interactive shell is always run constrained.

Since PowerShell can run script in both Full and Constrained language modes, we need to protect the boundary between them. We don’t want to leak variables or functions between sessions running in different language modes.

The PowerShell dot-source operator brings script files into the current session scope. It is a way to reuse script. All script functions and variables defined in the script file become part of the script it is dot sourced into. It is like copying and pasting text from the script file directly into your script.

# HelperFn1, HelperFn2 are defined in HelperFunctions.ps1
# Dot-source the file here to get access to them (no need to copy/paste)
. c:ScriptsHelperFunctions.ps1
HelperFn1
HelperFn2

This presents a problem when language modes are in effect with system application control. If an untrusted script is dot-sourced into a script with full trust then it has access to all those functions that run in FullLanguage mode, which can result in application control bypass through arbitrary code execution or privilege escalation. Consequently, PowerShell prevents this by throwing an error when dot-sourcing is attempted across language modes.

Example 1:

System is in WDAC policy lock down. To start with, neither script is trusted and so both run in ConstrainedLanguage mode. But the HelperFn1 function uses method invocation which isn’t allowed in that mode.

PS> type c:MyScript.ps1
Write-Output "Dot sourcing MyHelper.ps1 script file"
. c:MyHelper.ps1
HelperFn1
PS> type c:MyHelper.ps1
function HelperFn1
{
    "Language mode: $($ExecutionContext.SessionState.LanguageMode)"
    [System.Console]::WriteLine("This can only run in FullLanguage mode!")
}
PS> c:MyScript.ps1
Dot sourcing MyHelper.ps1 script file
Language mode: ConstrainedLanguage
Cannot invoke method. Method invocation is supported only on core types in this language mode.
At C:MyHelper.ps1:4 char:5
+     [System.Console]::WriteLine("This cannot run in ConstrainedLangua ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodInvocationNotSupportedInConstrainedLanguage

Both scripts are untrusted and run in ConstrainedLanguage mode, so dot-sourcing the MyHelper.ps1 file works. However, the HelperFn1 function performs method invocation that is not allowed in ConstrainedLanguage and fails when run. MyHelper.ps1 needs to be signed as trusted so it can run at FullLanguage.

Next we have mixed language modes. MyHelper.ps1 is signed and trusted, but MyScript.ps1 is not.

PS> c:MyScript.ps1
Dot sourcing MyHelper.ps1 script file
C:MyHelper.ps1 : Cannot dot-source this command because it was defined in a different language mode. To invoke this command without importing its contents, omit the '.' operator.
At C:MyScript.ps1:2 char:1
+ . 'c:MyHelper.ps1'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [MyHelper.ps1], NotSupportedException
    + FullyQualifiedErrorId : DotSourceNotSupported,MyHelper.ps1
...

And we get a dot-source error because we are trying to dot-source script that has a different language mode than the session it is being dot-sourced into.

Finally, we sign as trusted both script files and everything works.

PS> c:MyScript.ps1
Dot sourcing MyHelper.ps1 script file
Language mode: FullLanguage
This can only run in FullLanguage mode!

The lesson here is to ensure all script components run in the same language mode on policy locked down systems. If one component must run in FullLanguage mode, then all components should run in FullLanguage mode. This means validating that each component is safe to run in FullLanguage and indicating they are trusted to the application control policy.

So this solves all language mode problems, right? If FullLanguage is not needed then just ensure all script components run untrusted, which is the default condition. If they require FullLanguage then carefully validate all components and mark them as trusted. Unfortuantely, there is one case where this best practice doesn’t work.

PowerShell Profile File

The PowerShell profile file (profile.ps1) is loaded and run at PowerShell start up. If that script requires FullLanguage mode on policy lock down systems, you just validate and sign the file as trusted, right?

Example 2:

PS> type c:users<user>DocumentsWindowsPowerShellprofile.ps1
Write-Output "Running Profile"
[System.Console]::WriteLine("This can only run in FullLanguage!")
# Sign file so it is trusted and will run in FullLanguage mode
PS> Set-AuthenticodeSignature -FilePath .Profile.ps1 -Certificate $myPolicyCert
# Start a new PowerShell session and run the profile script
PS> powershell.exe
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
C:Users<user>DocumentsWindowsPowerShellprofile.ps1 : Cannot dot-source this command because it was defined in a different language mode. To invoke this command without importing its contents, omit the '.' operator.
At line:1 char:1
+ . 'C:Users<user>DocumentsWindowsPowerShellprofile.ps1'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [profile.ps1], NotSupportedException
    + FullyQualifiedErrorId : DotSourceNotSupported,profile.ps1

What gives? The profile.ps1 file was signed and is policy trusted. Why the error?
Well, the issue is that PowerShell dot-sources the profile.ps1 file into the default PowerShell session, which must run in ConstrainedLanguage because of the policy. So we are attempting to dot-source a FullLanguage script into a ConstrainedLanguage session, and that is not allowed. This is a catch 22 because if the profile.ps1 is not signed, it may not run if it needs FullLanguage privileges (e.g., invoke methods). But if you sign it, it still won’t run because of how it is dot-sourced into the current ConstrainedLanguage interactive session.

Unfortunately, the only solution is to keep the profile.ps1 file fairly simple so that it does not need FullLanguage, and refrain from making it trusted. Keep in mind that this is only an issue when running with application control policy. Otherwise, language modes do not come into play and PowerShell profile files run normally.

Paul Higinbotham
Senior Software Engineer
PowerShell Team

Announcing General Availability of the Windows Compatibility Module 1.0.0

This post was originally published on this site

The Windows Compatibility module (WindowsCompatibility) is a PowerShell module that lets PowerShell Core 6 scripts access Windows PowerShell modules that are not yet natively available on PowerShell Core. (Note: the list of unavailable commands is getting smaller with each new release of PowerShell Core. This module is just for things aren’t natively supported yet.)

You can install the module from the PowerShell Gallery using the command

Install-Module WindowsCompatibility

and the source code is available on GitHub. (This is where you should open issues or make suggestions.)

Once you have WindowsCompatibility installed, you can start using it. The first thing you might want to run is Get-WinModule which will show you the list of available modules. From that list, choose a module, say PKI and and load it. To do this, run the following command:

Import-WinModule PKI

and you’ll have the commands exported by the PKI module in your local session. You can run them just like any other command. For example:

New-SelfSignedCertificate -DnsName localhost

As always, you can see what a module exported by doing:

Get-Command -module PKI

just like any other module.

These are the most important commands but the WindowsCompatibility module provides some others:

  • Invoke-WinCommand allows you to invokes a one-time command in the compatibility session.
  • Add-WinFunction allows you to define new functions that operate implicitly in the compatibility session.
  • Compare-WinModule lets you compare what you have against what’s available.
  • Copy-WinModule will let you copy Window PowerShell modules that are known to work in PowerShell 6 to the PowerShell 6 command path.
  • Initialize-WinSession gives you more control on where and how the compatibility session is created. For example. it will allow you to place the compatibility session on another machine.

(See the module’s command help for more details and examples on how to use the WindowsCompatibility functions.)

How It Works

The WindowsCompatibility module takes advantage of the ‘Implicit Remoting‘ feature that has been available in PowerShell since version 2. Implicit remoting works by retrieving command metadata from a remote session and synthesizing proxy functions in the local session. When you call one of these proxy function, it takes all of the parameters passed to it and forwards them to the real command in the “remote” session. Wait a minute you may be thinking – what does remoting have to do with the WindowsCompatibility module? WindowsCompatibility automatically creates and manages a ‘local remote’ session, called the ‘compatibility session’ that runs with Windows PowerShell on the local machine. It imports the specified module and then creates local proxy functions for all of commands defined in that module.

OK – what about modules that exist in both Windows PowerShell and PowerShell core? Yes – you can import them. After all, there are still a fair number of base cmdlets that aren’t available in PowerShell core yet.

So how does this work? WindowsCompatibility is very careful to not overwrite native PowerShell core commands. It only imports the ones that are available with Windows PowerShell but not with PowerShell Core. For example, the following will import the PowerShell default management module

 Import-WinModule  Microsoft.PowerShell.Management

which contains, among others, the Get-EventLog cmdlet. None of the native PowerShell Core cmdlets get overwritten but now you have Get-EventLog available in your session.

At this point, if you call Get-Module, you will see something a bit strange:

Get-Module | ForEach-Object Name

results in output that looks like:

Microsoft.PowerShell.Management
Microsoft.PowerShell.Management.WinModule
Microsoft.PowerShell.Utility
NetTCPIP

Import-WinModule renames the compatibility module at load time to prevent collisions with identically named modules. This is so the module qualified commands will resolve against the current module. In fact, if you want to see what additional commands were imported, you can run:

Get-Command -Module  Microsoft.PowerShell.Management.WinModule

Limitations

Because WindowsCompatibility is based on implicit remoting, there are a number of significant limitations on the cmdlets imported by the module. First, because everything is done using the remoting protocol, the imported cmdlets will return deserialized objects that only contain properties. Much of the time, this won’t matter because the parameter binder binds by property name rather than by object type. As long as the required properties are present on the object, it doesn’t matter what type the object actually is. There are, however, cases where the cmdlet actually requires that the object be of a specific type or that it have methods. WindowsCompatibility won’t work for these cmdlets.

Windows Forms and other graphical tools

The remoting session is considered non-interactive so graphical tools such as notepad or Winforms scripts will either fail, or worse hang.

Linux and Mac support

This module depends on WinRM and the client libraries on these platforms are known to be unstable and limited. So for this release, only PowerShell Core running on Windows is supported. (This may change in the future. But you’ll still need a Windows machine with Windows PowerShell to host the compatibility session.)

PowerShell 6.1 Dependency

WindowsCompatibility depends on a feature introduced in PowerShell Core 6.1 for keeping the current working directory in both the local and compatibility sessions synchronized. Earlier versions of PowerShell will work with WindowsCompatibility but won’t have this directory synchronization feature. So if you’re running PowerShell Core 6.0, import a command that writes to files, do Set-Location to a new directory, then use that command to write to a file with an unqualified path; it will use the original path from when the module was imported rather than your sessions current working directory. On PowerShell Core 6.1, it will correctly use the current working directory.

Summary

To sum it all up, the WindowsCompatibility module provides a set of commands that allow you to access Window PowerShell modules from PowerShell Core 6. There are however, some limitations that make it unsuitable for all scenarios. Over time, as more and more modules are ported to .NET Core/PowerShell 6 natively there will be less need for this module.

Cheers!
Bruce Payette,
PowerShell Team.

DSC Resource Kit Release October 2018

This post was originally published on this site

We just released the DSC Resource Kit!

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

The modules updated in this release are:

  • ComputerManagementDsc
  • SharePointDsc
  • StorageDsc
  • SqlServerDsc
  • xActiveDirectory
  • xExchange
  • xFailOverCluster
  • xHyper-V
  • xWebAdministration

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

xPSDesiredStateConfiguration is also in the pipeline for a release, but the xArchive resource is failing its tests, so that module is currently on hold and will be released when all the tests are passing once again.

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

The next DSC Resource Kit release will be on Wednesday, 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
ComputerManagementDsc 6.0.0.0
  • ScheduledTask:
    • Added support for Group Managed Service Accounts, implemented using the ExecuteAsGMSA parameter. Fixes Issue 111
    • Added support to set the Synchronize Across Time Zone option. Fixes Issue 109
  • Added .VSCode settings for applying DSC PSSA rules – fixes Issue 189.
  • BREAKING CHANGE: PowerPlan:
    • Added IsActive Read-Only Property – Fixes Issue 171.
    • InActive power plans are no longer returned with their Name set to null. Now, the name is always returned and the Read-Only property of IsActive is set accordingly.
SharePointDsc 2.6.0.0
  • SPFarm
    • Fixed issue where Central Admin service was not starting for non-english farms
  • SPManagedMetadataServiceApp
    • Added additional content type settings (ContentTypePushdownEnabled & ContentTypeSyndicationEnabled).
    • Fixed issue where Get method would throw an error when the proxy did not exist.
    • Fixed an issue where the resource checks if the proxy exists and if not, it is created.
  • SPSearchContentSource
    • Fixed issue with numerical Content Sources name
    • Fixed issue where the code throws an error when the content source cannot be successfully created
  • SPSearchManagedProperty
    • Added a new resource to support Search Managed Properties
    • Fix for multiple aliases
  • SPSearchResultSource
    • Added a new ScopeUrl parameter to allow for local source creation
  • SPSearchTopology
    • Updated Readme.md to remove some incorrect information
    • Fixed logic to handle the FirstPartitionDirectory in Get-TargetResource
  • SPSelfServiceSiteCreation
    • New resource to manage self-service site creation
  • SPServiceAppSecurity
    • Added local farm token.
    • Fixed issues that prevented the resource to work as expected in many situations.
  • SPSite
    • Added the possibility for creating the default site groups
    • Added the possibility to set AdministrationSiteType
    • Fixed test method that in some cases always would return false
    • Fixed a typo in the values to check for AdministrationSiteType
    • Fixed an access denied issue when creating default site groups when the run as account does not have proper permissions for the site
  • SPTrustedIdentityTokenIssuer
    • Added parameter UseWReplyParameter
  • SPUserProfileServiceApp
    • Fixed issue which was introduced in v2.5 where the service application proxy was not created.
    • Updated resource to grant the InstallAccount permissions to a newly created service application to prevent issues in the Get method.
  • SPUserProfileSyncConnection
    • Fixed issue where empty IncludedOUs and ExcludedOUs would throw an error
  • SPWebAppClientCallableSettings
    • New resource to manage web application client callable settings including proxy libraries.
  • SPWebAppPropertyBag
    • New resource to manage web application property bag
  • SPWebAppSuiteBar
    • Fixed incorrect test method that resulted in this resource to never apply changes.
    • Enable usage of SuiteBarBrandingElementHtml for SharePoint 2016 (only supported if using a SharePoint 2013 masterpage)
SqlServerDsc 12.1.0.0
  • Changes to SqlServerDsc
    • Add support for validating the code with the DSC ResourceKit Script Analyzer rules, both in Visual Studio Code and directly using Invoke-ScriptAnalyzer.
    • Opt-in for common test “Common Tests – Validate Markdown Links”.
    • Updated broken links in README.md and in ExamplesREADME.md
    • Opt-in for common test “Common Tests – Relative Path Length”.
    • Updated the Installation section in the README.md.
    • Updated the Contributing section in the README.md after Style Guideline and Best Practices guidelines has merged into one document.
    • To speed up testing in AppVeyor, unit tests are now run in two containers.
    • Adding the PowerShell script Assert-TestEnvironment.ps1 which must be run prior to running any unit tests locally with Invoke-Pester. Read more in the specific contributing guidelines, under the section Unit Tests.
  • Changes to SqlServerDscHelper
    • Fix style guideline lint errors.
    • Changes to Connect-SQL
      • Adding verbose message in Connect-SQL so it now shows the username that is connecting.
    • Changes to Import-SQLPS
      • Fixed so that when importing SQLPS it imports using the path (and not the .psd1 file).
      • Fixed so that the verbose message correctly shows the name, version and path when importing the module SQLPS (it did show correctly for the SqlServer module).
  • Changes to SqlAg, SqlAGDatabase, and SqlAGReplica examples
    • Included configuration for SqlAlwaysOnService to enable HADR on each node to avoid confusion (issue 1182).
  • Changes to SqlServerDatabaseMail
    • Minor update to Ensure parameter description in the README.md.
  • Changes to Write-ModuleStubFile.ps1
    • Create aliases for cmdlets in the stubbed module which have aliases (issue 1224). Dan Reist (@randomnote1)
    • Use a string builder to build the function stubs.
    • Fixed formatting issues for the function to work with modules other than SqlServer.
  • New DSC resource SqlServerSecureConnection
    • New resource to configure a SQL Server instance for encrypted SQL connections.
  • Changes to SqlAlwaysOnService
    • Updated integration tests to use NetworkingDsc (issue 1129).
  • Changes to SqlServiceAccount
    • Fix unit tests that didn”t mock some of the calls. It no longer fail when a SQL Server installation is not present on the node running the unit test (issue 983).
StorageDsc 4.2.0.0
  • Disk:
    • Added PartitionStyle parameter – Fixes Issue 137.
    • Changed MOF name from MSFT_Disk to MSFTDSC_Disk to remove conflict with Windows built-in CIM class – Fixes Issue 167.
  • Opt-in to Common Tests:
    • Common Tests – Validate Example Files To Be Published
    • Common Tests – Validate Markdown Links
    • Common Tests – Relative Path Length
  • Added .VSCode settings for applying DSC PSSA rules – fixes Issue 168.
  • Disk:
    • Added “defragsvc” service conflict known issue to README.MD – fixes Issue 172.
  • Corrected style violations in StorageDsc.Common module – fixes Issue 153.
  • Corrected style violations in StorageDsc.ResourceHelper module.
xActiveDirectory 2.22.0.0
  • Add PasswordNeverResets parameter to xADUser to facilitate user lifecycle management
  • Update appveyor.yml to use the default template.
  • Added default template files .gitattributes, and .gitignore, and .vscode folder.
  • Added xADForestProperties: New resource to manage User and Principal Name Suffixes for a Forest.
xExchange 1.24.0.0
  • xExchangeHelper.psm1: Renamed common functions to use proper Verb-Noun format. Also addresses many common style issues in functions in the file, as well as in calls to these functions from other files.
  • MSFT_xExchTransportService: Removed functions that were duplicates of helper functions in xExchangeHelper.psm1.
  • Fixes an issue where only objects of type Mailbox can be specified as a Journal Recipient. Now MailUser and MailContact types can be used as well.
  • Update appveyor.yml to use the default template.
  • Added default template files .codecov.yml, .gitattributes, and .gitignore, and .vscode folder.
  • Add Unit Tests for xExchAntiMalwareScanning
  • Add remaining Unit Tests for xExchInstall, and for most common setup functions
  • Added ActionForUnknownFileAndMIMETypes,WSSAccessOnPublicComputersEnabled, WSSAccessOnPrivateComputersEnabled,UNCAccessOnPublicComputersEnabled UNCAccessOnPrivateComputersEnabled and GzipLevel to xExchOwaVirtualDirectory.
  • Added GzipLevel and AdminEnabled to xExchEcpVirtualDirectory.
  • Added OAuthAuthentication to xExchOabVirtualDirectory.
  • Updated readme with the new parameters and removed a bad parameter from xExchOwaVirtualDirectory that did not actually exist.
  • Updated .gitattributes to allow test .pfx files to be saved as binary
  • Added Cumulative Update / Exchange update support to xExchInstall resource.
  • Add remaining Unit Tests for all xExchangeHelper functions that don”t require the loading of Exchange DLL”s.
  • Renamed and moved file Examples/HelperScripts/ExchangeConfigHelper.psm1 to Modules/xExchangeCalculatorHelper.psm1. Renamed functions within the module to conform to proper function naming standards. Added remaining Unit tests for module.
xFailOverCluster 1.11.0.0
  • Changes to xFailOverCluster
    • Update appveyor.yml to use the default template.
    • Added default template files .codecov.yml, .gitattributes, and .gitignore, and .vscode folder.
    • Added FailoverClusters2012.stubs.psm1 from Windows Server 2012 and renamed existing test stub file to FailoverClusters2016.stubs.psm1.
    • Modified Pester Describe blocks to include which version of the FailoverClusters module is being tested.
    • Modified Pester tests to run against 2012 and 2016 stubs in sequence.
  • Changes to xCluster
    • Fixed cluster creation on Windows Server 2012 by checking if the New-Cluster command supports -Force before using it (issue 188).
  • Changes to xClusterQuorum
    • Changed some internal parameter names from the Windows Server 2016 version aliases which are compatible with Windows Server 2012.
  • Changes to xClusterNetwork
    • Fixed Set-TargetResource for Windows Server 2012 by removing call to Update method as it doesn”t exist on this version and updates automatically.
xHyper-V 3.13.0.0
  • MSFT_xVMSwitch:
    • Changed “Id” parameter form read only to optional so the VMSwitch ID can be set on Windows Server 2016. This is important for SDN setups where the VMSwitch ID must remain the same when a Hyper-V host is re-installed.
    • Update appveyor.yml to use the default template.
    • Added default template files .codecov.yml, .gitattributes, and .gitignore, and .vscode folder.
xWebAdministration 2.3.0.0
  • Update appveyor.yml to use the default template.
  • Added default template file .gitattributes, and added default settings for Visual Studio Code.
  • Line endings was fixed in files that was committed with wrong line ending.

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)

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