Quantcast
Channel: PowerShell
Viewing all 1519 articles
Browse latest View live

DSC Resource Kit Release June 2018

$
0
0

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)


PowerShell Script Analyzer 1.17.1 Released!

$
0
0

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

PowerShell Core now available as a Snap package

$
0
0

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 Linux, macOS, and Windows 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. For more info, check out Canonical’s blog on our Snap announcement.

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

DSC Resource Kit Release July 2018

$
0
0

We just released the DSC Resource Kit!

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

The modules updated in this release are:

  • ComputerManagementDsc
  • SecurityPolicyDsc
  • SharePointDsc
  • SqlServerDsc
  • xActiveDirectory
  • xDhcpServer
  • xDscResourceDesigner
  • xExchange
  • xPowerShellExecutionPolicy (now deprecated since now in ComputerManagementDsc)
  • xPSDesiredStateConfiguration
  • 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 July 18. A recording of our updates will be available on YouTube soon. Join us for the next call at 12PM (Pacific time) on August 29 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
ComputerManagementDsc 5.2.0.0
  • PowershellExecutionPolicy:
    • Updated to meet HQRM guidelines.
    • Migrated the xPowershellExecutionPolicy from xPowershellExecutionPolicy and renamed to PowershellExecutionPolicy.
    • Moved strings to localization file.
  • Changed the scope from Global to Script in MSFT_ScheduledTask.Integration.Tests.ps1
  • Changed the scope from Global to Script ComputerManagementDsc.Common.Tests.ps1
  • ScheduledTask:
    • Added support for event based triggers, implemented using the ScheduleType OnEvent fixes Issue 167
SecurityPolicyDsc 2.4.0.0
  • Added additional error handling to ConvertTo-Sid helper function.
SharePointDsc 2.4.0.0
  • SPCacheAccounts
    • Fixed issue where the Test method would fail if SetWebAppPolicy was set to false.
  • SPDistributedCacheService
    • Updated resource to allow updating the cache size
  • SPFarm
    • Implemented ability to deploy Central Administration site to a server at a later point in time
  • SPInfoPathFormsServiceConfig
    • Fixed issue with trying to set the MaxSizeOfUserFormState parameter
  • SPProductUpdate
    • Fixed an issue where the resource failed when the search was already paused
  • SPProjectServerLicense
    • Fixed issue with incorrect detection of the license
  • SPSearchContentSource
    • Fixed issue where the Get method returned a conversion error when the content source contained just one address
    • Fixed issue 840 where the parameter StartHour was never taken into account
  • SPSearchServiceApp
    • Fixed issue where the service account was not set correctly when the service application was first created
    • Fixed issue where the Get method throws an error when the service app wasn’t created properly
  • SPSearchTopology
    • Fixed issue where Get method threw an error when the specified service application didn’t exist yet.
  • SPServiceAppSecurity
    • Fixed issue where error was thrown when no permissions were set on the service application
  • SPShellAdmins
    • Updated documentation to specify required permissions for successfully using this resource
  • SPTrustedIdentityTokenIssuerProviderRealms
    • Fixed code styling issues
  • SPUserProfileServiceApp
    • Fixed code styling issues
SqlServerDsc 11.4.0.0
  • Changes to SqlServerDsc
    • Updated helper function Restart-SqlService to have to new optional parameters SkipClusterCheck and SkipWaitForOnline. This was to support more aspects of the resource SqlServerNetwork.
    • Updated helper function Import-SQLPSModule
      • To only import module if the module does not exist in the session.
      • To always import the latest version of “SqlServer” or “SQLPS” module, if more than one version exist on the target node. It will still prefer to use “SqlServer” module.
    • Updated all the examples and integration tests to not use PSDscAllowPlainTextPassword, so examples using credentials or passwords by default are secure.
  • Changes to SqlAlwaysOnService
    • Integration tests was updated to handle new IPv6 addresses on the AppVeyor build worker (issue 1155).
  • Changes to SqlServerNetwork
    • Refactor SqlServerNetwork to not load assembly from GAC (issue 1151).
    • The resource now supports restarting the SQL Server service when both enabling and disabling the protocol.
    • Added integration tests for this resource (issue 751).
  • Changes to SqlAG
    • Removed excess Import-SQLPSModule call.
  • Changes to SqlSetup
    • Now after a successful install the “SQL PowerShell module” is reevaluated and forced to be reimported into the session. This is to support that a never version of SQL Server was installed side-by-side so that SQLPS module should be used instead.
xActiveDirectory 2.20.0.0
xDhcpServer 2.0.0.0
xDscResourceDesigner 1.12.0.0
  • Fixed Test-MockSchema to return True if class name matches resource name when there are multiple embeded classes in the schema mof. issue 123.
xExchange 1.22.0.0
  • Fixed issue in xExchInstall where winrm config command fails to execute
  • Fixed issue in xExchInstall where a failed Exchange setup run is not reported, and subsequent DSC resources are allowed to run
  • Fixed issue in xExchAutoMountPoint where Test-TargetResource fails after mount points have been successfully configured.
  • Fixed issue in xExchAutoMountPoint where Set-TargetResource fails if EnsureExchangeVolumeMountPointIsLast parameter is specified.
  • Updated xExchAutoMountPoint, xExchJetstressCleanup, and related DiskPart functions to not use global variables.
  • Fixes broken tests in: MSFT_xExchDatabaseAvailabilityGroup.Integration.Tests.ps1, MSFT_xExchExchangeCertificate.Integration.Tests.ps1, MSFT_xExchOutlookAnywhere.Integration.Tests.ps1, MSFT_xExchPopSettings.Integration.Tests.ps1, xExchangeConfigHelper.Unit.Tests.ps1
  • Update most Test-TargetResource functions to output all invalid settings, instead of just the first detected invalid setting
xPowerShellExecutionPolicy 3.1.0.0
  • Deprecated this module. This resource module will no longer be released. Please use the PowerShellExecutionPolicy resource in ComputerManagementDsc instead.
xPSDesiredStateConfiguration 8.4.0.0
  • Changes to xPSDesiredStateConfiguration
    • Opt-in for the common tests validate module files and script files.
    • All files change to encoding UTF-8 (without byte order mark).
    • Opt-in for the common test for example validation.
    • Added Visual Studio Code workspace settings that helps with formatting against the style guideline.
    • Update all examples for them to be able pass the common test validation.
  • xEnvironment path documentation update demonstrating usage with multiple values (issue 415. Alex Kokkinos (@alexkokkinos)
  • Changes to xWindowsProcess
    • Increased the wait time in the integration tests since the tests still failed randomly (issue 420).
  • Renamed and updated examples to be able to publish them to PowerShell Gallery.
    • Sample_xScript.ps1 to xScript_WatchFileContentConfig.ps1
    • Sample_xService_UpdateStartupTypeIgnoreState.ps1 to xService_UpdateStartupTypeIgnoreStateConfig.ps1
    • Sample_xWindowsProcess_Start.ps1 to xWindowsProcess_StartProcessConfig.ps1
    • Sample_xWindowsProcess_StartUnderUser.ps1 to xWindowsProcess_StartProcessUnderUserConfig.ps1
    • Sample_xWindowsProcess_Stop.ps1 to xWindowsProcess_StopProcessConfig.ps1
    • Sample_xWindowsProcess_StopUnderUser.ps1 to xWindowsProcess_StopProcessUnderUserConfig.ps1
    • Sample_xUser_CreateUser.ps1.ps1 to xUser_CreateUserConfig.ps1
    • Sample_xUser_Generic.ps1.ps1 to xUser_CreateUserDetailedConfig.ps1
    • Sample_xWindowsFeature.ps1 to xWindowsFeature_AddFeatureConfig.ps1
    • Sample_xWindowsFeatureSet_Install.ps1 to xWindowsFeatureSet_AddFeaturesConfig.ps1
    • Sample_xWindowsFeatureSet_Uninstall.ps1 to xWindowsFeatureSet_RemoveFeaturesConfig.ps1
    • Sample_xRegistryResource_AddKey.ps1 to xRegistryResource_AddKeyConfig.ps1
    • Sample_xRegistryResource_RemoveKey.ps1 to xRegistryResource_RemoveKeyConfig.ps1
    • Sample_xRegistryResource_AddOrModifyValue.ps1 to xRegistryResource_AddOrModifyValueConfig.ps1
    • Sample_xRegistryResource_RemoveValue.ps1 to xRegistryResource_RemoveValueConfig.ps1
    • Sample_xService_CreateService.ps1 to xService_CreateServiceConfig.ps1
    • Sample_xService_DeleteService.ps1 to xService_RemoveServiceConfig.ps1
    • Sample_xServiceSet_StartServices.ps1 to xServiceSet_StartServicesConfig.ps1
    • Sample_xServiceSet_BuiltInAccount to xServiceSet_EnsureBuiltInAccountConfig.ps1
    • Sample_xWindowsPackageCab to xWindowsPackageCab_InstallPackageConfig
    • Sample_xWindowsOptionalFeature.ps1 to xWindowsOptionalFeature_EnableConfig.ps1
    • Sample_xWindowsOptionalFeatureSet_Enable.ps1 to xWindowsOptionalFeatureSet_EnableConfig.ps1
    • Sample_xWindowsOptionalFeatureSet_Disable.ps1 to xWindowsOptionalFeatureSet_DisableConfig.ps1
    • Sample_xRemoteFileUsingProxy.ps1 to xRemoteFile_DownloadFileUsingProxyConfig.ps1
    • Sample_xRemoteFile.ps1 to xRemoteFile_DownloadFileConfig.ps1
    • Sample_xProcessSet_Start.ps1 to xProcessSet_StartProcessConfig.ps1
    • Sample_xProcessSet_Stop.ps1 to xProcessSet_StopProcessConfig.ps1
    • Sample_xMsiPackage_UninstallPackageFromHttps.ps1 to xMsiPackage_UninstallPackageFromHttpsConfig.ps1
    • Sample_xMsiPackage_UninstallPackageFromFile.ps1 to xMsiPackage_UninstallPackageFromFileConfig.ps1
    • Sample_xMsiPackage_InstallPackageFromFile to xMsiPackage_InstallPackageConfig.ps1
    • Sample_xGroup_SetMembers.ps1 to xGroup_SetMembersConfig.ps1
    • Sample_xGroup_RemoveMembers.ps1 to xGroup_RemoveMembersConfig.ps1
    • Sample_xGroupSet_AddMembers.ps1 to xGroupSet_AddMembersConfig.ps1
    • Sample_xFileUpload.ps1 to xFileUpload_UploadToSMBShareConfig.ps1
    • Sample_xEnvironment_CreateMultiplePathVariables.ps1 to xEnvironment_AddMultiplePathsConfig.ps1
    • Sample_xEnvironment_RemovePathVariables.ps1 to xEnvironment_RemoveMultiplePathsConfig.ps1
    • Sample_xEnvironment_CreateNonPathVariable.ps1 to xEnvironment_CreateNonPathVariableConfig.ps1
    • Sample_xEnvironment_Remove.ps1 to xEnvironment_RemoveVariableConfig.ps1
    • Sample_xArchive_ExpandArchiveChecksumAndForce.ps1 to xArchive_ExpandArchiveChecksumAndForceConfig.ps1
    • Sample_xArchive_ExpandArchiveDefaultValidationAndForce.ps1 to xArchive_ExpandArchiveDefaultValidationAndForceConfig.ps1
    • Sample_xArchive_ExpandArchiveNoValidation.ps1 to xArchive_ExpandArchiveNoValidationConfig.ps1
    • Sample_xArchive_ExpandArchiveNoValidationCredential.ps1 to xArchive_ExpandArchiveNoValidationCredentialConfig.ps1
    • Sample_xArchive_RemoveArchiveChecksum.ps1 to xArchive_RemoveArchiveChecksumConfig.ps1
    • Sample_xArchive_RemoveArchiveNoValidation.ps1 to xArchive_RemoveArchiveNoValidationConfig.ps1
    • Sample_InstallExeCreds_xPackage.ps1 to xPackage_InstallExeUsingCredentialsConfig.ps1
    • Sample_InstallExeCredsRegistry_xPackage.ps1 to xPackage_InstallExeUsingCredentialsAndRegistryConfig.ps1
    • Sample_InstallMSI_xPackage.ps1 to xPackage_InstallMsiConfig.ps1
    • Sample_InstallMSIProductId_xPackage.ps1 to xPackage_InstallMsiUsingProductIdConfig.ps1
  • New examples
    • xUser_RemoveUserConfig.ps1
    • xWindowsFeature_AddFeatureUsingCredentialConfig.ps1
    • xWindowsFeature_AddFeatureWithLogPathConfig.ps1
    • xWindowsFeature_RemoveFeatureConfig.ps1
    • xService_ChangeServiceStateConfig.ps1
    • xWindowsOptionalFeature_DisableConfig.ps1
    • xPSEndpoint_NewConfig.ps1
    • xPSEndpoint_NewWithDefaultsConfig.ps1
    • xPSEndpoint_RemoveConfig.ps1
    • xPSEndpoint_NewCustomConfig.ps1
  • Removed examples
    • Sample_xPSSessionConfiguration.ps1 – This file was split up in several examples, those starting with “xPSEndpoint*”.
    • Sample_xMsiPackage_InstallPackageFromHttp – This was added to the example xMsiPackage_InstallPackageConfig.ps1 so the example sows either URI scheme.
    • Sample_xEnvironment_CreatePathVariable.ps1 – Same as the new example xEnvironment_AddMultiplePaths.ps1
xRemoteDesktopSessionHost 1.7.0.0
  • Added additional resources, copied from the Azure RDS quickstart templates.
  • xRDSessionCollection:
    • Fixed call to Add-RDSessionHost in Set-TargetResource by properly removing CollectionDescription from PSBoundParameters (issue 28)
    • Fixed bug on Get-TargetResource that did return any collection instead of the one collection the user asked for (issue 27)
    • Added unit tests to test Get, Test and Set results in this resource
xWebAdministration 2.1.0.0
  • Added new resources xWebConfigProperty and xWebConfigPropertyCollection extending functionality provided by xWebConfigKeyValue, addresses 249.
  • Fixed Get-DscConfiguration throw in xWebSite; addresses 372. Reggie Gibson (@regedit32)
  • Added WebApplicationHandler resource for creating and modifying IIS Web Handlers. Fixes 337
  • Added WebApplicationHandler integration tests
  • Added WebApplicationHandler unit tests
  • Deprecated xIISHandler resource. This resource will be removed in future release

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)

Increased Windows Modules coverage with PowerShell Core 6.1

$
0
0

During the May 2018 Community Call and a tweet a few weeks later, we mentioned that PowerShell team was spending significant time in the Windows codebase. We even demoed using the Active Directory PowerShell Module from PowerShell Core 6 during the PowerShell Community Call.

We started investigating some of the top requested modules that ship with Windows to see how to get them working in PowerShell Core 6. Our eventual goal is to have near 100% parity with Windows PowerShell for the in-box modules, but we expect this effort to span across multiple releases of Windows as there are many modules and PowerShell team is working with each feature team on an individual basis to port and validate their modules. The good news is that you can pick up newly compatible modules with frequent updates to Windows 10, and Windows Insiders will see them even sooner.

TL;DR; (Too Long; Didn’t Read)

Starting with Windows 10 Insiders build 17711 or newer, you can use many Windows PowerShell modules with PowerShell Core 6.1-Preview.4 and if you see an issue or difference compared to Windows PowerShell 5.1, please open an issue in the PowerShellModuleCoverage repository.

The Journey to Porting Windows PowerShell modules

Prioritizing Windows PowerShell Modules

Windows ships with many PowerShell modules. We created a prioritized list of Windows PowerShell modules to investigate compatibility and portability based on customer and partner requests.
We ended up with a list of what we thought would have maximum customer impact. For example, the top requested module was the Active Directory PowerShell Module, so we made sure to partner with the AD team and investigate their module first. After investigation, we also deferred work on certain modules that were infeasible to port to PowerShell Core given our time frame and expertise.

ApiPort

First, we looked at was using ApiPort to identify APIs used by Windows PowerShell modules that were not available in .NET Core. Depending on the API, we were able to include additional .NET Core compatible assemblies, and in others, we rewrote the code to use a different API that is functionally equivalent. In some cases, the API was simply unavailable, so we could only mark the module as incompatible by setting CompatiblePSEditions to just Desktop in the module manifest. The initial investigation showed that >95% of the APIs used by Windows PowerShell modules were available in .NET Standard (or compatible assemblies).

.NET Standard 2.0

.NET Standard is a formal specification of .NET APIs intended to be available on all .NET implementations. For example, .NET Framework 4.6.1+ used by Windows PowerShell and .NET Core 2.0+ used by PowerShell Core 6 both implement APIs specified by .NET Standard 2.0. By rebuilding existing source code for Windows PowerShell modules to target .NET Standard instead of .NET Framework, we would get compile-time errors if an API wasn’t available and shouldn’t be used.

The Windows build environment is self-contained and did not support building code targeting .NET Standard. The next work item was to work with the folks on the Windows Engineering System team to enable building managed assemblies and target .NET Standard 2.0. They were excellent partners, and together, we built a simple PowerShell module against .NET Standard 2.0 that worked in both Windows PowerShell 5.1 and PowerShell Core 6.

Windows Compatibility Pack

Although the proof of concept to use the Windows build environment to produce a .NET Standard assembly worked, actual Windows PowerShell modules used many APIs beyond just what is in the formal .NET Standard 2.0 specification (and associated reference assembly). To help developers move from .NET Framework to .NET Core, the .NET team published a set of assemblies called the Windows Compatibility Pack as an extension to .NET Standard. The Windows Compatibility Pack brought back important namespaces like System.DirectoryServices, that Windows PowerShell modules required.

To make this work with PowerShell Core 6, we added the Windows Compatibility Pack 2.0.0 assemblies into PowerShell Core 6.1. This also means that any module author who wants to leverage the Windows Compatibility Pack will not need to redistribute the Windows Compatibility Pack assemblies with their modules, as they are now built into PowerShell Core 6.1 (.NET Framework would already have its own implementations of the same APIs).

Trouble in Paradise

Things were moving along getting the infrastructure ready for the porting work. However, we were also up against a strict timeline. We made a tactical decision to minimize risk of not getting our changes into Windows by moving away from targeting .NET Standard 2.0 and Windows Compatibility Pack explicitly. Building against .NET Standard 2.0 and relying on Windows Compatibility Pack meant we had to ship the Windows Compatibility Pack facade assemblies in Windows so that .NET Framework knew how to find the actual implementation assembly to work correctly. Adding new assemblies in the Windows build environment is easy compared to adding new assemblies into Windows itself. Adding new binaries to Windows require making changes to specific files in the code base and you can only validate it worked successfully when you have a complete build of Windows. Windows code base is huge and takes a long time to build on a developer machine. A complete build may not be successful due to other changes happening in the overall code base which is what happened to us.

In addition, we also hit issues where other assemblies in the Windows code base had a dependency on the Windows PowerShell module assembly (like a graphical user interface sitting on top of PowerShell) and would break the build since the GUI code built with .NET Framework didn’t know how to reference a .NET Standard built assembly.

Since we could not successfully get a working build of Windows with our assembly additions, we decided to abandon that work and go without .NET Standard compilation.

Moving Forward

Because .NET Standard is an API contract (like a C/C++ header file), we did not need to formally rebuild Windows PowerShell modules with .NET Standard to have them work in .NET Core and thus PowerShell Core 6. What .NET Standard gives us is some assurance that future additions to Windows PowerShell modules would catch new API usage that is not part of .NET Standard or Windows Compatibility Pack. However, although .NET Standard indicates that an API is available, we found out during testing that even if the API exists, it may throw PlatformNotSupportedException at runtime which prevents the Windows PowerShell module from working correctly in PowerShell Core 6. As we found these, we’ve had to make code changes in the modules to handle these cases appropriately during runtime whether it’s running within Windows PowerShell or PowerShell Core 6.

Changes in PowerShell Core 6.1

In anticipation of the changes we were making in Windows PowerShell modules, we also needed changes in PowerShell Core 6.1 to make the experience seamless. In mid-June we published an RFC to get community feedback on the user experience we would enable for using compatible Windows PowerShell modules from PowerShell Core 6.

Basically, with PowerShell Core 6.1-Preview.4 the PowerShell engine will look in $env:WinDir\System32\WindowsPowerShell\v1.0\Modules as part of enumerating available modules from $env:PSModulePath. However, by default, only Windows PowerShell module manifests that explicitly indicate Core as a supported in the CompatiblePSEditions property. Windows PowerShell module manifests that don’t have the CompatiblePSEditions property or only has Desktop will not show up as an available module by default. The -SkipEditionCheck switch on Import-Module can be used to override this behavior. It is important to reiterate that this logic only applies to modules in $env:WinDir\System32\WindowsPowerShell\v1.0\Modules path. If you used Install-Module to install a module from the PowerShell Gallery and its module manifest either doesn’t contain CompatiblePSEditions nor includes Core, the PSEdition check logic doesn’t apply and that module will show up as available since it was explicitly installed from PowerShell Core 6.

Availability of changes in Windows

The Windows PowerShell module changes we’ve made will start showing up in Windows 10 Insiders Build 17711. This means that with that build of Windows 10 and PowerShell Core 6.1-Preview.4 you can start using some of the Windows PowerShell modules we’ve identified as Core compatible. A reminder that as we continue to make changes in Windows, they will show up in newer builds of Windows 10 Insiders. Our target is to get >65% of the Windows PowerShell in-box modules compatible with PowerShell Core 6.1 within the next Windows 10 release. We’ll continue to work with Windows partner teams to get the number of compatible modules closer to 100%.

Community Feedback

We work with individual Windows teams who are the owners of their modules to validate our changes as much as possible with PowerShell Core 6. However, due to how they wrote their tests, it’s not as simple as rerunning their existing tests within PowerShell Core 6 and in many cases, we opted to do some limited manual validation. This means that although we’ve made some effort to validate Windows PowerShell modules marked as compatible with Core, we cannot guarantee they are fully compatible (see the note about runtime issues above) and we would treat them as bugs.

Here the community can help start using Windows PowerShell modules in PowerShell Core 6.1-Preview.4 and if you see an issue or difference compared to Windows PowerShell 5.1, please open an issue in the PowerShellModuleCoverage repository. We are only using that repository for issue tracking. If someone else has opened an issue on a module (or identified a module they need but isn’t ported yet), please give it a ?? (thumbs up) to up-vote the issue which helps us prioritize the work.

Note that if there are other Windows PowerShell modules by Microsoft that aren’t in-box in Windows that you think is a priority to port, please open an issue in that repo! PowerShell Core compatibility will help us with engagements with those partner teams if we can show them the demand for it.

Windows Compatibility Module

As we continue this journey porting Windows PowerShell modules which I expect to take multiple Windows releases, you can use any Windows PowerShell module from PowerShell Core 6 without waiting for a port. A significant majority of the Windows codebase is written in C/C++ (95+%!). A number of teams who are primarily native code developers wrote their PowerShell modules in Managed C++. However, there are currently no plans to support Managed C++ in .NET Core. For these sets of modules and those waiting to be ported, we published the Windows Compatibility module which leverages implicit remoting from PowerShell Core 6 to Windows PowerShell, so it makes the cmdlets from that module available in PowerShell Core 6 but executes it within Windows PowerShell.

You can use this today with the stable release of PowerShell Core 6.0.3 and doesn’t require using PowerShell Core 6.1-Preview builds. If you find issues with this module, please open issues in the Windows Compatibility repo.

Summary

The initial goal of the PowerShell Core 6.0 release was to provide a cross-platform automation platform. I expect by end of July, we should hit a new high of 3 million startups of PowerShell Core 6!
Approximately 80% of the usage is on Linux, so I consider us working with the community to have achieved our first goal.

The goal of PowerShell Core 6.1 release (targeting end of August for General Availability) is to help move Windows PowerShell users forward to PowerShell Core 6 by providing compatibility with in-box Windows PowerShell modules that they depend upon. It is important to understand that the Windows PowerShell module porting work won’t be complete by the time PowerShell Core 6.1 GA nor when the next version of Windows 10 is released, and we expect to continue this work as needed to eventually get complete coverage.

Thanks to all the feedback and contributions from the community helping PowerShell move forward!

Steve Lee
Principal Software Engineering Manager
PowerShell Team
Azure Compute
https://twitter.com/Steve_MSFT

PowerShell Injection Hunter: Security Auditing for PowerShell Scripts

$
0
0

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 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:\Lee\WindowsPowerShell\Modules\InjectionHunter\1.0.0\InjectionHunter.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:\Lee\WindowsPowerShell\Modules\InjectionHunter\1.0.0\InjectionHunter.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 Standard Library: Build single module that works across Windows PowerShell and PowerShell Core

$
0
0

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:\Users\James\.templateengine\dotnetcli\v2.1.302\scratch\restore.csproj...
  Installing Microsoft.PowerShell.Standard.Module.Template 0.1.3.
  Generating MSBuild file C:\Users\James\.templateengine\dotnetcli\v2.1.302\scratch\obj\restore.csproj.nuget.g.props.
  Generating MSBuild file C:\Users\James\.templateengine\dotnetcli\v2.1.302\scratch\obj\restore.csproj.nuget.g.targets.
  Restore completed in 1.66 sec for C:\Users\James\.templateengine\dotnetcli\v2.1.302\scratch\restore.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:\Users\James
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 8/3/2018 2:41 PM myModule
PS> cd myModule
PS C:\Users\James\myModule> dotnet new psmodule
The template "PowerShell Standard Module" was created successfully.

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

Restore succeeded.

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

PS C:\Users\James\myModule> dir


    Directory: C:\Users\James\myModule


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:\Users\James\myModule> 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:\Users\James\myModule\myModule.csproj.
  myModule -> C:\Users\James\myModule\bin\Debug\netstandard2.0\myModule.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:\Users\James\myModule> ipmo .\bin\Debug\netstandard2.0\myModule.dll
PS C:\Users\James\myModule> Test-SampleCmdlet -?

NAME
    Test-SampleCmdlet

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


ALIASES
    None


REMARKS
    None



PS C:\Users\James\myModule> 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 Module Exporting Functions in Constrained Language

$
0
0

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 TestModule\TestModule.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 Function Export in Constrained Language

$
0
0

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 TestModule\TestModule.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

DSC Resource Kit Release September 2018

$
0
0

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)

New Look and Features for PowerShell Gallery

$
0
0

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.

 

Desired State Configuration (DSC) Planning Update – September 2018

$
0
0

2018 has been the most active year ever for the DSC community. The DSC team is taking on major new areas of work in Azure, and we have made significant progress in development of the new DSC platform.

In this Planning Update for DSC, I want to cover these topics in detail and share major changes to the timing of our Open Source plans for the DSC platform.

Increase in DSC Community contributions

Since January 1st, across modules that are linked from the DscResources repo, over 475 Pull Requests have been merged to accept community contributions and over 300 issues have been closed. The number of DSC Resources in the PowerShell Gallery almost doubled over the course of the summer. We now have over 1300! You can verify this by running the following command.

(find-dscresource).count

This represents a new level of activity from the DSC community. Thank you to all of the community contributors and maintainers who made this possible. I would encourage you to visit the Maintainers list and pass on gratitude via Twitter if their work is making you successful.

I would especially like to thank Johan Ljunggren who has been assisting the PowerShell team with this effort and providing us with thoughts and guidance on how we can continue supporting the community effort.

If you are interested in getting involved but not sure where to start, you are welcome to joining the monthly Community Call for DSC.

Expanding the use of DSC in Azure

As part of joining the Azure Compute organization, the DSC engineering team has taken on significant new responsibilities. This is a really positive and healthy journey for the DSC platform. Much of this work is happening “behind the scenes” but I am optimistic that these investments in DSC at cloud scale will result in a more optimized platform in the future.

New Azure State Configuration interface generally available

Earlier this year we received feedback that when managing many thousands VM’s from Azure Automation, the interface was not optimized for finding and using information. As a result we have completely revised the experience in the Azure portal. The previous items in the Table of Contents including Nodes, Configurations, and Node Configurations, have been consolidated in to a single tabbed view that pages. The information is interactive and can be navigated by right-clicking rows to filter for correlation such as other nodes using the same configuration. The new interface is now generally available and enabled by default.

You will also find a new authoring experience from the Configurations tab. From here you can select among composite resources, either built-in or any that you have added as modules in Azure Automation. This is designed to help new users of DSC understand configuration authoring without the need to start from a ‘blank page’ in an editor. As always, configurations generated by this experience can be saved locally and added to source control.

Starting this week, we now have a preview that extends this experience to the Virtual Machine page in Azure.  You will find a new item, “State configuration (Preview)” listed under “Operations”. This makes it much easier to onboard to the DSC solution. You will find features like the new reporting and authoring experiences are also available from this single-VM view. The intent of this effort is to make it easier for anyone new to get started with configuration as code.  Note that based on feedback we will soon be renaming this item on the VM table of contents to “Configuration management”.

You can learn more in the following video:

Azure Fridays – Azure State Configuration experience

Thank you to everyone that has provided feedback and helped us to improve. If you have thoughts and opinions to share please create a new item in on our feedback page.  You can also mention @powershell_team on Twitter or post to the DSC forum on PowerShell.org.

Improving integration between Azure Automation and Azure DevOps

Very soon you will see tasks available in the Visual Studio marketplace to provide integration with Azure Automation. This includes tasks for Build and Release Management phases to publish runbooks, modules, and configurations to an Azure Automation account, and to assign configurations to registered nodes.

This is the first of multiple steps we are planning to reduce the complexity of getting started with release pipeline (CI/CD) scenarios.

Guest Configuration feature coming to Azure Policy

Very soon we will be releasing a new feature for Azure Policy that will help people to audit settings inside Linux and Windows servers. Much like the services for Inventory, Change Tracking, Update Management, and Security, this new capability includes features built on the DSC v2 platform.

I have heard the following question times:

I am using Group Policy to manage Windows Server in my private datacenter. Now I have application owners deploying to servers in the cloud. If the servers are not domain members and they are re-deployed frequently, what does Microsoft recommend I use to verify the servers meet our security requirements?”

If you are facing this challenge, Azure Policy Guest Configuration is the path to success.

The new feature will focus on auditing servers after they are deployed. To deploy servers with the correct operational and security settings, customers can use their existing configuration management tools such as DSC, Chef, Puppet, Ansible, Salt, etc.

Over the next couple of months we will be providing more information. I look forward to hearing feedback to help shape future work in this area.

New features for DSC coming in Server 2019

Some of the top requests for DSC will ship as new features in Server 2019.

  • Servers registered to Azure Automation State Configuration will automatically rotate certificates without requiring re-registration
  • To further increase security, during the process of applying configurations no temporary files will be written to disk -A new mode will be available to monitor DSC configurations without applying settings (the full list of modes will be MonitorOnly, ApplyOnly, ApplyandMonitor, ApplyandAutoCorrect)
  • ESENT database settings in Windows Pull Server will be configurable including max length of download file
  • To further increase security when Device Guard is enabled in Windows, DSC will no longer allow the built-in Script resource (MSFT_ScriptResource)
  • Windows Pull Server will support using SQL as a database

Unfortunately these will not be back-ported to previous versions of DSC that shipped with Windows. We are taking this in to consideration for future releases of the DSC platform.

Security update for DSC in Windows

As part of the September 2018 updates for Windows (server and workstation) we have released an update that applies to all existing versions of DSC in Windows.  This addresses a concern where in rare situations the configuration would remain in the system temp folder after it is applied. The risk is mitigated by multiple factors.

Once this update has been applied, DSC will no longer write any temp files during the process of applying a configuration.  The update is included in KB4457128.

Changes to timing for next DSC platform to be Open Source

At the PowerShell and DevOps Global Summit and PowerShell Conference EU, I presented on future plans for the DSC platform including our intention to publish a new version of DSC as an Open Source project. At the time I hoped that the project would be published by late summer. I also said that we would not begin the project until we could be responsible project maintainers, and that I am not interested in simply “sharing code”. I insist that when we make DSC a public project we must be ready to manage incoming contributions from the community to show respect for their time and effort in helping us to make the solution the best it can be.

Soon after those events our team took on additional responsibility. We determined it would not be feasible for engineering to meet these new commitments if, during the same time, we delivered on our plans to maintain a new Open Source project. So, we had to change our plans.

We still expect to make the new DSC platform an Open Source project. The codebase is already in use across services in Azure and will be part of new services we introduce this year. Our long term goal is to have a single DSC platform in use everywhere. Our plans for features of the next generation of the DSC platform were given in the last planning update post.

Just to make a clear distinction, this new DSC platform is where we are making future investments and we want it to be available for configuring both Windows and Linux in the future. We will also continue to support the existing version of DSC following the Windows Server support lifecycle.

Unfortunately I am not ready to set a new date on when the project can become public. To set a date now would be premature and would risk needing to make changes again in the future. In the meantime, I hope to publish RFC (Request for Comments) and continue our commitment to the DSC open source community for Resources, Configurations, and Tooling. As soon as our engineering schedule allows us to maintain the project as a public repo, I will follow up here with more information.

Thank you!
Michael Greene
Principal Program Manager
Azure Security & Management Services
@migreene

Announcing PowerShell Core 6.1

$
0
0

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

DSC Resource Kit Release October 2018

$
0
0

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 \Examples\README.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 General Availability of the Windows Compatibility Module 1.0.0

$
0
0

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.


PowerShell Constrained Language mode and the Dot-Source Operator

$
0
0

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:\Scripts\HelperFunctions.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>\Documents\WindowsPowerShell\profile.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>\Documents\WindowsPowerShell\profile.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>\Documents\WindowsPowerShell\profile.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

DSC Resource Kit Release November 2018

$
0
0

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)

The PowerShell-Docs repo is moving

$
0
0

On January 16, 2019 at 5:00PM PDT, the PowerShell-Docs repositories are moving from the PowerShell
organization to the MicrosoftDocs organization in GitHub.

The tools we use to build the documentation are designed to work in the MicrosoftDocs org. Moving
the repository lets us build the foundation for future improvements in our documentation experience.

Impact of the move

During the move there may be some downtime. The affected repositories will be inaccessible during
the move process. Also, the documentation processes will be paused. After the move, we need to test
access permissions and automation scripts.

After these tasks are complete, access and operations will return to normal. GitHub automatically
redirects requests to the old repo URL to the new location.

For more information about transferring repositories in GitHub,
see About repository transfers.

  • If the transferred repository has any forks, then those forks will remain associated with the
    repository after the transfer is complete.
  • All Git information about commits, including contributions, are preserved.
  • All of the issues and pull requests remain intact when transferring a repository.
  • All links to the previous repository location are automatically redirected to the new location.

When you use git clone, git fetch, or git push on a transferred repository, these commands will
redirect to the new repository location or URL.

However, to avoid confusion, we strongly recommend updating any existing local clones to point to
the new repository URL. You can do this by using git remote on the command line:

git remote set-url origin new_url

For more information, see Changing a remote’s URL.

Which repositories are being moved?

The following repositories are being transferred:

  • PowerShell/PowerShell-Docs
  • PowerShell/powerShell-Docs.cs-cz
  • PowerShell/powerShell-Docs.de-de
  • PowerShell/powerShell-Docs.es-es
  • PowerShell/powerShell-Docs.fr-fr
  • PowerShell/powerShell-Docs.hu-hu
  • PowerShell/powerShell-Docs.it-it
  • PowerShell/powerShell-Docs.ja-jp
  • PowerShell/powerShell-Docs.ko-kr
  • PowerShell/powerShell-Docs.nl-nl
  • PowerShell/powerShell-Docs.pl-pl
  • PowerShell/powerShell-Docs.pt-br
  • PowerShell/powerShell-Docs.pt-pt
  • PowerShell/powerShell-Docs.ru-ru
  • PowerShell/powerShell-Docs.sv-se
  • PowerShell/powerShell-Docs.tr-tr
  • PowerShell/powerShell-Docs.zh-cn
  • PowerShell/powerShell-Docs.zh-tw

Call to action

If you have a fork that you cloned, change your remote configuration to point to the new upstream URL.

Help us make the documentation better.

  • Submit issues when you find a problem in the docs.
  • Suggest fixes to documentation by submitting changes through the PR process.

 

Sean Wheeler
Senior Content Developer for PowerShell
https://github.com/sdwheeler

DSC Resource Kit Release January 2019

$
0
0

We just released the DSC Resource Kit!

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

The modules updated in this release are:

  • ActiveDirectoryCSDsc
  • AuditPolicyDsc
  • CertificateDsc
  • ComputerManagementDsc
  • NetworkingDsc
  • SecurityPolicyDsc
  • SqlServerDsc
  • StorageDsc
  • xActiveDirectory
  • xBitlocker
  • xExchange
  • xFailOverCluster
  • xHyper-V
  • xWebAdministration

Several of these modules were released to remove the hidden files/folders from this issue. This issue should now be fixed for all modules except DFSDsc which is waiting for some fixes to its tests.

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 today, January 9. A recording is available on YouTube here. Join us for the next call at 12PM (Pacific time) on February 13 to ask questions and give feedback about your experience with the DSC Resource Kit.

The next DSC Resource Kit release will be on Wednesday, February 20.

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.1.0.0
  • Updated LICENSE file to match the Microsoft Open Source Team standard.
  • Added .VSCode settings for applying DSC PSSA rules – fixes Issue 60.
  • Added fix for two tier PKI deployment fails on initial deployment, not error – fixes Issue 57.
AuditPolicyDsc 1.4.0.0
  • Explicitly removed extra hidden files from release package
CertificateDsc 4.3.0.0
  • Updated certificate import to only use Import-CertificateEx – fixes Issue 161
  • Update LICENSE file to match the Microsoft Open Source Team standard -fixes Issue 164.
  • Opted into Common Tests – fixes Issue 168:
    • Required Script Analyzer Rules
    • Flagged Script Analyzer Rules
    • New Error-Level Script Analyzer Rules
    • Custom Script Analyzer Rules
    • Validate Example Files To Be Published
    • Validate Markdown Links
    • Relative Path Length
  • CertificateExport:
    • Fixed bug causing PFX export with matchsource enabled to fail – fixes Issue 117
ComputerManagementDsc 6.1.0.0
  • Updated LICENSE file to match the Microsoft Open Source Team standard. Fixes Issue 197.
  • Explicitly removed extra hidden files from release package
NetworkingDsc 6.3.0.0
  • MSFT_IPAddress:
    • Updated to allow retaining existing addresses in order to support cluster configurations as well
SecurityPolicyDsc 2.7.0.0
  • Bug fix – Issue 83 – Network_access_Remotely_accessible_registry_paths_and_subpaths correctly applies multiple paths
  • Update LICENSE file to match the Microsoft Open Source Team standard
SqlServerDsc 12.2.0.0
  • Changes to SqlServerDsc
    • During testing in AppVeyor the Build Worker is restarted in the install step to make sure the are no residual changes left from a previous SQL Server install on the Build Worker done by the AppVeyor Team (issue 1260).
    • Code cleanup: Change parameter names of Connect-SQL to align with resources.
    • Updated README.md in the Examples folder.
      • Added a link to the new xADObjectPermissionEntry examples in ActiveDirectory, fixed a broken link and a typo. Adam Rush (@adamrushuk)
    • Change to SqlServerLogin so it doesn”t check properties for absent logins.
StorageDsc 4.4.0.0
  • Refactored module folder structure to move resource to root folder of repository and remove test harness – fixes Issue 169.
  • Updated Examples to support deployment to PowerShell Gallery scripts.
  • Removed limitation on using Pester 4.0.8 during AppVeyor CI.
  • Moved the Code of Conduct text out of the README.md and into a CODE_OF_CONDUCT.md file.
  • Explicitly removed extra hidden files from release package
xActiveDirectory 2.23.0.0
  • Explicitly removed extra hidden files from release package
xBitlocker 1.4.0.0
  • Change double quoted string literals to single quotes
  • Add spaces between array members
  • Add spaces between variable types and variable names
  • Add spaces between comment hashtag and comments
  • Explicitly removed extra hidden files from release package
xExchange 1.26.0.0
  • Add support for Exchange Server 2019
  • Added additional parameters to the MSFT_xExchUMService resource
  • Rename improperly named functions, and add comment based help in MSFT_xExchClientAccessServer, MSFT_xExchDatabaseAvailabilityGroupNetwork, MSFT_xExchEcpVirtualDirectory, MSFT_xExchExchangeCertificate, MSFT_xExchImapSettings.
  • Added additional parameters to the MSFT_xExchUMCallRouterSettings resource
  • Rename improper function names in MSFT_xExchDatabaseAvailabilityGroup, MSFT_xExchJetstress, MSFT_xExchJetstressCleanup, MSFT_xExchMailboxDatabase, MSFT_xExchMailboxDatabaseCopy, MSFT_xExchMailboxServer, MSFT_xExchMaintenanceMode, MSFT_xExchMapiVirtualDirectory, MSFT_xExchOabVirtualDirectory, MSFT_xExchOutlookAnywhere, MSFT_xExchOwaVirtualDirectory, MSFT_xExchPopSettings, MSFT_xExchPowershellVirtualDirectory, MSFT_xExchReceiveConnector, MSFT_xExchWaitForMailboxDatabase, and MSFT_xExchWebServicesVirtualDirectory.
  • Add remaining unit and integration tests for MSFT_xExchExchangeServer.
xFailOverCluster 1.12.0.0
  • Explicitly removed extra hidden files from release package
xHyper-V 3.15.0.0
  • Explicitly removed extra hidden files from release package
xWebAdministration 2.4.0.0
  • Explicitly removed extra hidden files from release package

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)

Windows Security change affecting PowerShell

$
0
0

Windows Security change affecting PowerShell

January 9, 2019

The recent (1/8/2019) Windows security patch CVE-2019-0543, has introduced a breaking change for a PowerShell remoting scenario. It is a narrowly scoped scenario that should have low impact for most users.

The breaking change only affects local loopback remoting, which is a PowerShell remote connection made back to the same machine, while using non-Administrator credentials.

PowerShell remoting endpoints do not allow access to non-Administrator accounts by default. However, it is possible to modify endpoint configurations, or create new custom endpoint configurations, that do allow non-Administrator account access. So you would not be affected by this change, unless you explicitly set up loopback endpoints on your machine to allow non-Administrator account access.

Example of broken loopback scenario

# Create endpoint that allows Users group access
PS > Register-PSSessionConfiguration -Name MyNonAdmin -SecurityDescriptorSddl 'O:NSG:BAD:P(A;;GA;;;BA)(A;;GA;;;BU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD)' -Force

# Create non-Admin credential
PS > $nonAdminCred = Get-Credential ~\NonAdminUser

# Create a loopback remote session to custom endpoint using non-Admin credential
PS > $session = New-PSSession -ComputerName localhost -ConfigurationName MyNonAdmin -Credential $nonAdminCred

New-PSSession : [localhost] Connecting to remote server localhost failed with the following error message : The WSMan
service could not launch a host process to process the given request.  Make sure the WSMan provider host server and
proxy are properly registered. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ New-PSSession -ComputerName localhost -ConfigurationName MyNonAdmin - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
   gTransportException
    + FullyQualifiedErrorId : -2146959355,PSSessionOpenFailed

The above example fails only when using non-Administrator credentials, and the connection is made back to the same machine (localhost). Administrator credentials still work. And the above scenario will work when remoting off-box to another machine.

Example of working loopback scenario

# Create Admin credential
PS > $adminCred = Get-Credential ~\AdminUser

# Create a loopback remote session to custom endpoint using Admin credential
PS > $session = New-PSSession -ComputerName localhost -ConfigurationName MyNonAdmin -Credential $adminCred
PS > $session

 Id Name            ComputerName    ComputerType    State         ConfigurationName     Availability
 -- ----            ------------    ------------    -----         -----------------     ------------
  1 WinRM1          localhost       RemoteMachine   Opened        MyNonAdmin               Available

The above example uses Administrator credentials to the same MyNonAdmin custom endpoint, and the connection is made back to the same machine (localhost). The session is created successfully using Administrator credentials.

The breaking change is not in PowerShell but in a system security fix that restricts process creation between Windows sessions. This fix is preventing WinRM (which PowerShell uses as a remoting transport and host) from successfully creating the remote session host, for this particular scenario. There are no plans to update WinRM.

This affects Windows PowerShell and PowerShell Core 6 (PSCore6) WinRM based remoting.

This does not affect SSH remoting with PSCore6.

This does not affect JEA (Just Enough Administration) sessions.

A workaround for a loopback connection is to always use Administrator credentials.

Another option is to use PSCore6 with SSH remoting.

Paul Higinbotham
Senior Software Engineer
PowerShell Team

Viewing all 1519 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>