11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
##2016-11-17 - Supported Release 2.1.0
###Summary

Small release with bugs fixes and another speed improvement.

###Bug Fixes
- Support Windows 2016/WMF 5.1 using named pipes ([MODULES-3690](https://tickets.puppetlabs.com/browse/MODULES-3690))

###Documentation updates
- Document herestring ([DOC-2960](https://tickets.puppetlabs.com/browse/DOC-2960))

##2016-10-05 - Supported Release 2.0.3
###Summary

Expand Down
77 changes: 53 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,17 @@ This module adds a new exec provider capable of executing PowerShell commands.

## Module Description

Puppet provides a built-in `exec` type that is capable of executing commands. This module adds a `powershell` provider to the `exec` type, which enables `exec` parameters, listed below. This module is particularly helpful if you need to run PowerShell commands but don't know the details about how PowerShell is executed, since you can technically run PowerShell commands in Puppet without the module.
Puppet provides a built-in `exec` type that is capable of executing commands. This module adds a `powershell` provider to the `exec` type, which enables `exec` parameters, listed below. This module is particularly helpful if you need to run PowerShell commands but don't know the details about how PowerShell is executed, because you can run PowerShell commands in Puppet without the module.

## Setup

### Setup Requirements
### Requirements

This module requires PowerShell to be installed and the `powershell.exe` to be available in the system PATH.

### Beginning with powershell

The powershell module adapts the Puppet [exec](http://docs.puppet.com/references/stable/type.html#exec) resource to run PowerShell commands. To get started, simply install the module and declare 'powershell' in `provider` with the applicable command.
The powershell module adapts the Puppet [exec](http://docs.puppet.com/references/stable/type.html#exec) resource to run PowerShell commands. To get started, install the module and declare 'powershell' in `provider` with the applicable command.

~~~ puppet
exec { 'RESOURCENAME':
Expand All @@ -42,7 +43,7 @@ exec { 'RESOURCENAME':

When using `exec` resources with the `powershell` provider, the `command` parameter must be single-quoted to prevent Puppet from interpolating `$(..)`.

For instance, if you wanted to rename the Guest account:
For instance, to rename the Guest account:

~~~ puppet
exec { 'rename-guest':
Expand All @@ -54,9 +55,9 @@ exec { 'rename-guest':

Note that the example uses the `unless` parameter to make the resource idempotent. The `command` is only executed if the Guest account does not exist, as indicated by `unless` returning 0.

**Note:** PowerShell variables (e.g. `$_`), must be escaped in Puppet manifests either using backslashes or single quotes.
**Note:** PowerShell variables (such as `$_`) must be escaped in Puppet manifests either using backslashes or single quotes.

Alternatively, you can put the PowerShell code for the `command`, `onlyif`, and `unless` parameters into separate files and then invoke the file function in the resource. Templates and the `template()` function could also be used here if the PowerShell scripts need to have access to variables from Puppet.
Alternately, you can put the PowerShell code for the `command`, `onlyif`, and `unless` parameters into separate files, and then invoke the file function in the resource. You could also use templates and the `template()` function if the PowerShell scripts need access to variables from Puppet.

~~~ puppet
exec { 'rename-guest':
Expand All @@ -76,19 +77,20 @@ $obj = $(Get-WMIObject Win32_UserAccount -Filter "Name='Guest'")
$obj.Rename("OtherGuest")
~~~

This has the added benefit of not requiring escaping '$' in the PowerShell code. Note that the files need to have DOS linefeeds or they will not work as expected. One tool for converting UNIX linefeeds to DOS linefeeds is [unix2dos](http://freecode.com/projects/dos2unix).
This has the added benefit of not requiring escaping '$' in the PowerShell code. Note that the files must have DOS linefeeds or they will not work as expected. One tool for converting UNIX linefeeds to DOS linefeeds is [unix2dos](http://freecode.com/projects/dos2unix).

### External files and exit codes
If you are calling external files, such as other PowerShell scripts or executables, be aware that the last executed script's exitcode will be used by Puppet to determine whether the command was successful. For example:

Suppose the file `C:\fail.ps1` contains the following PowerShell script
If you are calling external files, such as other PowerShell scripts or executables, be aware that the last executed script's exitcode is used by Puppet to determine whether the command was successful.

For example, if the file `C:\fail.ps1` contains the following PowerShell script:

~~~ powershell
& cmd /c EXIT 5
& cmd /c EXIT 1
~~~

and we use the following Puppet manifest
and we use the following Puppet manifest:

~~~ puppet
exec { 'test':
Expand All @@ -97,9 +99,9 @@ exec { 'test':
}
~~~

The `exec['test']` resource will always fail because the last exit code from the the external file `C:\fail.ps1` is `1`. This behavior may have unintended consequences if you are combining multiple external files.
Then the `exec['test']` resource will always fail, because the last exit code from the external file `C:\fail.ps1` is `1`. This behavior might have unintended consequences if you combine multiple external files.

To stop this behavior ensure that you use explicit `Exit` statements in your PowerShell scripts. For example we changed the Puppet manifest from above to:
To stop this behavior, ensure that you use explicit `Exit` statements in your PowerShell scripts. For example, we changed the Puppet manifest from the above to:

~~~ puppet
exec { 'test':
Expand All @@ -108,10 +110,11 @@ exec { 'test':
}
~~~

It will always succeed because the `Exit 0` statement overrides the exit code from the `C:\fail.ps1` script.
This will always succeed because the `Exit 0` statement overrides the exit code from the `C:\fail.ps1` script.

### Console Error Output
The PowerShell module will internally capture output sent to the .NET `[System.Console]::Error` stream like:

The PowerShell module internally captures output sent to the .NET `[System.Console]::Error` stream like:

~~~ puppet
exec { 'test':
Expand All @@ -120,65 +123,91 @@ exec { 'test':
}
~~~

However, to produce output from a script, prefer to use the `Write-` prefixed cmdlets like `Write-Output`, `Write-Debug` and `Write-Error`

However, to produce output from a script, use the `Write-` prefixed cmdlets such as `Write-Output`, `Write-Debug` and `Write-Error`.

## Reference

#### Provider
* powershell - Adapts the Puppet `exec` resource to run PowerShell commands.

* powershell: Adapts the Puppet `exec` resource to run PowerShell commands.

#### Parameters

All parameters are optional.

##### `creates`
Specifies the file to look for before running the command. The command will only run if the file doesn't exist. **Note: This parameter will not create a file, it will simpy look for one.** Valid options: A string of the path to the file. Default: Undefined.

Specifies the file to look for before running the command. The command runs only if the file doesn't exist. **Note: This parameter does not create a file, it only looks for one.** Valid options: A string of the path to the file. Default: Undefined.

##### `cwd`

Sets the directory from which to run the command. Valid options: A string of the directory path. Default: Undefined.

##### `command`

Specifies the actual PowerShell command to execute. Must either be fully qualified or a search path for the command must be provided. Valid options: String. Default: Undefined.

##### `environment`

Sets additional environment variables to set for a command. Valid options: String, or an array of multiple options. Default: Undefined.

##### `logoutput`
Defines whether to log command output in addition to logging the exit code. If you specify 'on_failure', it only logs the output when the command has an exit code that does not match any value specified by the `returns` attribute. Valid options: 'true', 'false', and 'on_failure'. Default: 'on_failure'.

Defines whether to log command output in addition to logging the exit code. If you specify 'on_failure', it only logs the output when the command has an exit code that does not match any value specified by the `returns` attribute. Valid options: true, false, and 'on_failure'. Default: 'on_failure'.

##### `onlyif`

Runs the exec only if the command returns 0. Valid options: String. Default: Undefined.

##### `path`

Specifies the search path used for command execution. Valid options: String of the path, an array, or a semicolon-separated list. Default: Undefined.

##### `refresh`

Refreshes the command. Valid options: String. Default: Undefined.

##### `refreshonly`
Refreshes the command only when a dependent object is changed. Used with `subscribe` and `notify` [metaparameters](http://docs.puppet.com/references/latest/metaparameter.html). Valid options: 'true', 'false'. Default: 'false'.

Refreshes the command only when a dependent object is changed. Used with `subscribe` and `notify` [metaparameters](http://docs.puppet.com/references/latest/metaparameter.html). Valid options: true, false. Default: false.

##### `returns`
Lists the expected return code(s). An error will be returned if the executed command returns something else. Valid options: An array of acceptable return codes or a single value. Default: 0.

Lists the expected return code(s). If the executed command returns something else, an error is returned. Valid options: An array of acceptable return codes or a single value. Default: 0.

##### `timeout`

Sets the maximum time in seconds that the command should take. Valid options: Number or string representation of a number. Default: 300.

##### `tries`

Determines the number of times execution of the command should be attempted. Valid options: Number or a string representation of a number. Default: '1'.

##### `try_sleep`

Specifies the time to sleep in seconds between `tries`. Valid options: Number or a string representation of a number. Default: Undefined.

##### `unless`

Runs the `exec`, unless the command returns 0. Valid options: String. Default: Undefined.

## Limitations

* Only supported on Windows Server 2008 and above, and Windows 7 and above.
* Only supported on Windows Server 2008 and above, and Windows 7 and above.

* Only supported on Powershell 2.0 and above.

* When using here-strings in inline or templated scripts executed by this module, you must use the double-quote style syntax that begins with `@"` and ends with `"@`. The single-quote syntax that begins with `@'` and ends with `'@` is not supported.

Note that any external .ps1 script file loaded or executed with the call operator `&` is not subject to this limitation and can contain any style here-string. For instance, the script file external-code.ps1 can contain any style of here-string:

* Only supported on Powershell 2.0 and above.
```
exec { 'external-code':
command => '& C:\external-code.ps1',
provider => powershell,
}
```

## Development

Puppet Inc modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad hardware, software, and deployment configurations that Puppet is intended to serve. We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more information, see our [module contribution guide.](https://docs.puppet.com/forge/contributing.html)
Puppet modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad hardware, software, and deployment configurations that Puppet is intended to serve. We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more information, see our [module contribution guide.](https://docs.puppet.com/forge/contributing.html)
36 changes: 26 additions & 10 deletions lib/puppet/provider/exec/powershell.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'puppet/provider/exec'
require File.join(File.dirname(__FILE__), '../../../puppet_x/puppetlabs/powershell/compatible_powershell_version')
require File.join(File.dirname(__FILE__), '../../../puppet_x/puppetlabs/powershell/powershell_manager')

Puppet::Type.type(:exec).provide :powershell, :parent => Puppet::Provider::Exec do
Expand Down Expand Up @@ -27,15 +28,26 @@
EOT

POWERSHELL_UPGRADE_MSG = <<-UPGRADE
The current Puppet version is outdated and uses a library that was
previously necessary on the current Ruby verison to support a colored console.
Currently, the PowerShell module has reduced v1 functionality on this agent
due to one or more of the following conditions:
Unfortunately this library prevents the PowerShell module from using a shared
PowerShell process to dramatically improve the performance of resource
application.
- Puppet 3.x (non-x64 version)
Puppet 3.x uses a Ruby version that requires a library to support a colored
console. Unfortunately this library prevents the PowerShell module from
using a shared PowerShell process to dramatically improve the performance of
resource application.
- PowerShell v2 with .NET Framework 2.0
PowerShell v2 works with both .NET Framework 2.0 and .NET Framework 3.5.
To be able to use the enhancements, we require at least .NET Framework 3.5.
Typically you will only see this on a base Windows Server 2008 (and R2)
install.
To enable these improvements, it is suggested to upgrade to any x64 version of
Puppet (including 3.x), or to a Puppet version newer than 3.x.
Puppet (including 3.x), or to a Puppet version newer than 3.x and ensure you
have at least .NET Framework 3.5 installed.
UPGRADE

def self.upgrade_message
Expand All @@ -44,13 +56,16 @@ def self.upgrade_message
end

def self.powershell_args
ps_args = ['-NoProfile', '-NonInteractive', '-NoLogo', '-ExecutionPolicy', 'Bypass', '-Command']
ps_args << '-' if PuppetX::PowerShell::PowerShellManager.supported?
ps_args = ['-NoProfile', '-NonInteractive', '-NoLogo', '-ExecutionPolicy', 'Bypass']
ps_args << '-Command' if !PuppetX::PowerShell::PowerShellManager.supported?

ps_args
end

def ps_manager
PuppetX::PowerShell::PowerShellManager.instance("#{command(:powershell)} #{self.class.powershell_args.join(' ')}")
debug_output = Puppet::Util::Log.level == :debug
manager_args = "#{command(:powershell)} #{self.class.powershell_args().join(' ')}"
PuppetX::PowerShell::PowerShellManager.instance(manager_args, debug_output)
end

def run(command, check = false)
Expand All @@ -77,6 +92,7 @@ def run(command, check = false)
result = ps_manager.execute(command,timeout_ms,working_dir)

stdout = result[:stdout]
native_out = result[:native_stdout]
stderr = result[:stderr]
exit_code = result[:exitcode]

Expand All @@ -86,7 +102,7 @@ def run(command, check = false)

Puppet.debug "STDERR: #{result[:errormessage]}" unless result[:errormessage].nil?

output = Puppet::Util::Execution::ProcessOutput.new(stdout.to_s || '', exit_code)
output = Puppet::Util::Execution::ProcessOutput.new(stdout.to_s + native_out.to_s, exit_code)

return output, output
end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
require File.join(File.dirname(__FILE__), 'powershell_version')

module PuppetX
module PuppetLabs
module PowerShell
class CompatiblePowerShellVersion
def self.compatible_version?
value = false

powershell_version = PuppetX::PuppetLabs::PowerShell::PowerShellVersion.version

return false if powershell_version.nil?

# PowerShell v1 - definitely not good to go. Really the entire module
# may not even work but I digress
return false if Gem::Version.new(powershell_version) < Gem::Version.new(2)

# PowerShell v3+, we are good to go b/c .NET 4+
# https://msdn.microsoft.com/en-us/powershell/scripting/setup/windows-powershell-system-requirements
# Look at Microsoft .NET Framwork Requirements section.
if Gem::Version.new(powershell_version) >= Gem::Version.new(3)
return true
end

# If we are using PowerShell v2, we need to see what the latest
# version of .NET is that we have
# https://msdn.microsoft.com/en-us/library/hh925568.aspx
if Puppet::Util::Platform.windows?
require 'win32/registry'

begin
# At this point in the check, PowerShell is using .NET Framework
# 2.x family, so we only need to verify v3.5 key exists.
# If we were verifying all compatible types we would look for
# any of these keys: v3.5, v4.0, v4
hive = Win32::Registry::HKEY_LOCAL_MACHINE
# redirection doesn't actually matter here - disable it anyway
hive.open('SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5', Win32::Registry::KEY_READ | 0x100) do |reg|
value = true
end
rescue Win32::Registry::Error => e
value = false
end
end

value
end
end
end
end
end
Loading