ansible.windows.win_powershell module – Run PowerShell scripts
Note
This module is part of the ansible.windows collection (version 1.14.0).
You might already have this collection installed if you are using the ansible
package.
It is not included in ansible-core
.
To check whether it is installed, run ansible-galaxy collection list
.
To install it, use: ansible-galaxy collection install ansible.windows
.
To use it in a playbook, specify: ansible.windows.win_powershell
.
New in ansible.windows 1.5.0
Synopsis
Runs a PowerShell script and outputs the data in a structured format.
Use ansible.windows.win_command or ansible.windows.win_shell to run a tranditional PowerShell process with stdout, stderr, and rc results.
Parameters
Parameter |
Comments |
---|---|
A list of arguments to pass to executable when running a script in another PowerShell process. These are not arguments to pass to script, use parameters for that purpose. |
|
The PowerShell location to set when starting the script. This can be a location in any of the PowerShell providers. The default location is dependent on many factors, if relative paths are used then set this option. |
|
A path or path filter pattern; when the referenced path exists on the target host, the task will be skipped. |
|
How deep the return values are serialized for This also controls the depth of the diff output set by Setting this to a higher value can dramatically increase the amount of data that needs to be returned. Default: |
|
The
Choices:
|
|
A custom PowerShell executable to run the script in. When not defined the script will run in the current module PowerShell interpreter. Both the remote PowerShell and the one specified by executable must be running on PowerShell v5.1 or newer. Setting this value may change the values returned in the |
|
Parameters to pass into the script as key value pairs. The key corresponds to the parameter name and the value is the value for that parameter. |
|
A path or path filter pattern; when the referenced path does not exist on the target host, the task will be skipped. |
|
The PowerShell script to run. |
Notes
Note
The module is set as failed when a terminating exception is throw, or
error_action=stop
and a normal error record is raised.The output values are processed using a custom filter and while it mostly matches the
ConvertTo-Json
result the following value types are different.DateTime
will be an ISO 8601 string in UTC,DateTimeOffset
will have the offset as specified by the value.Enum
will contain a dictionary withType
,String
,Value
being the type name, string representation and raw integer value respectively.Type
will contain a dictionary withName
,FullName
,AssemblyQualifiedName
,BaseType
being the type name, the type name including the namespace, the full assembly name the type was defined in and the base type it derives from.The script has access to the
$Ansible
variable where it can setResult
,Changed
,Failed
,Diff
, or accessTmpdir
.$Ansible.Result
is a value that is returned back to the controller as is.$Ansible.Diff
was added in the1.12.0
release ofansible.windows
and is a dictionary that is set to the diff result that can be interepreted by Ansible.$Ansible.Changed
can be set totrue
orfalse
to reflect whether the module made a change or not. By default this is set totrue
.$Ansible.Failed
can be set totrue
if the script wants to return the failure back to the controller.$Ansible.Tmpdir
is the path to a temporary directory to use as a scratch location that is cleaned up after the module has finished.$Ansible.Verbosity
reveals Ansible’s verbosity level for this play. Allows the script to set VerbosePreference/DebugPreference based on verbosity. Added in1.9.0
.Any host/console direct output like
Write-Host
or[Console]::WriteLine
is not considered an output object, they are returned as a string in host_out and host_err.Any output stream object is instead returned as a list in output. This is true not only for
Write-Output
and its built-in aliasecho
, but also for implicit output; i.e.Write-Output "foo"
and"foo"
give the same result.The module will skip running the script when in check mode unless the script defines
[CmdletBinding(SupportsShouldProcess
]).
See Also
See also
- ansible.windows.win_command
Executes a command on a remote Windows node.
- ansible.windows.win_shell
Execute shell commands on target hosts.
Examples
- name: Run basic PowerShell script
ansible.windows.win_powershell:
script: |
echo "Hello World"
- name: Run PowerShell script with parameters
ansible.windows.win_powershell:
script: |
[CmdletBinding()]
param (
[String]
$Path,
[Switch]
$Force
)
New-Item -Path $Path -ItemType Directory -Force:$Force
parameters:
Path: C:\temp
Force: true
- name: Run PowerShell script that modifies the module changed result
ansible.windows.win_powershell:
script: |
if (Get-Service -Name test -ErrorAction SilentlyContinue) {
Remove-Service -Name test
}
else {
$Ansible.Changed = $false
}
- name: Run PowerShell script in PowerShell 7
ansible.windows.win_powershell:
script: |
$PSVersionTable.PSVersion.Major
executable: pwsh.exe
arguments:
- -ExecutionPolicy
- ByPass
register: pwsh_output
failed_when:
- pwsh_output.output[0] != 7
- name: Run code in check mode
ansible.windows.win_powershell:
script: |
[CmdletBinding(SupportsShouldProcess)]
param ()
# Use $Ansible to detect check mode
if ($Ansible.CheckMode) {
echo 'running in check mode'
}
else {
echo 'running in normal mode'
}
# Use builtin ShouldProcess (-WhatIf)
if ($PSCmdlet.ShouldProcess('target')) {
echo 'also running in normal mode'
}
else {
echo 'also running in check mode'
}
check_mode: yes
- name: Return a failure back to Ansible
ansible.windows.win_powershell:
script: |
if (Test-Path C:\bad.file) {
$Ansible.Failed = $true
}
- name: Define when the script made a change or not
ansible.windows.win_powershell:
script: |
if ((Get-Item WSMan:\localhost\Service\Auth\Basic).Value -eq 'true') {
Set-Item WSMan:\localhost\Service\Auth\Basic -Value false
}
else {
$Ansible.Changed = $true
}
- name: Define when to enable Verbose/Debug output
ansible.windows.win_powershell:
script: |
if ($Ansible.Verbosity -ge 3) {
$VerbosePreference = "Continue"
}
if ($Ansible.Verbosity -eq 5) {
$DebugPreference = "Continue"
}
Write-Output "Hello World!"
Write-Verbose "Hello World!"
Write-Debug "Hello World!"
Return Values
Common return values are documented here, the following are the fields unique to this module:
Key |
Description |
---|---|
A list of warning messages created by the script. Debug messages only appear when Returned: always Sample: |
|
A list of error records created by the script. Returned: always |
|
More information about the error record. Returned: success |
|
Description of the operation which encountered the error. Returned: always Sample: |
|
The category name of the error record. Returned: always Sample: |
|
The integer representation of the category. Returned: always Sample: |
|
Description of the error. Returned: always Sample: |
|
Description of the target object. Can be an empty string if no target was specified. Returned: always Sample: |
|
Description of the type of the target object. Can be an empty string if no target object was specified. Returned: always Sample: |
|
Additional details about an ErrorRecord. Can be null if there are not additional details. Returned: success |
|
Message for the error record. Returned: always Sample: |
|
Recommended action in the even that this error occurs. This is empty unless the code which generates the error adds this explicitly. Returned: always Sample: |
|
Details about the exception behind the error record. Returned: success |
|
A link to the help details for the exception. May not be set as it’s dependent on whether the .NET exception class provides this info. Returned: always Sample: |
|
The signed integer assigned to this exception. May not be set as it’s dependent on whether the .NET exception class provides this info. Returned: always Sample: |
|
The inner exception details if there is one present. The dict contains the same keys as a normal exception. Returned: always |
|
The exception message. Returned: always Sample: |
|
Name of the application or object that causes the error. This may be an empty string as it’s dependent on the code that raises the exception. Returned: always Sample: |
|
The full .NET type of the Exception class. Returned: always Sample: |
|
The unique identifier for the error condition May be null if no id was specified when the record was created. Returned: always Sample: |
|
The formatted error record message as typically seen in a PowerShell console. Returned: always Sample: |
|
The status of the pipeline when this record was created. The values are 0 index based. Each element entry represents the command index in a pipeline statement. The value of each element represents the pipeline input idx in that command. For Example Returned: always Sample: |
|
The script stack trace for the error record. Returned: always Sample: |
|
The object which the error occured. May be null if no object was specified when the record was created. Type type of this object depends on the error record itself. If the value is a complex type, it will follow the Returned: always Sample: |
|
The strings written to the host error output, typically the stderr. This is not the same as objects sent to the error stream in PowerShell. Returned: always Sample: |
|
The strings written to the host output, typically the stdout. This is not the same as objects sent to the output stream in PowerShell. Returned: always Sample: |
|
A list of information records created by the script. The information stream was only added in PowerShell v5, older versions will always have an empty list as a value. Returned: always |
|
Message data associated with the record. The value here can be of any type. Returned: always Sample: |
|
The source of the record. Returned: always Sample: |
|
A list of tags associated with the record. Returned: always Sample: |
|
The time the record was generated. This is the time in UTC as an ISO 8601 formatted string. Returned: always Sample: |
|
A list containing all the objects outputted by the script. The list elements can be anything as it is based on what was ran. Returned: always Sample: |
|
The values that were set by Defaults to an empty dict but can be set to anything by the script. Returned: always Sample: |
|
A list of warning messages created by the script. Verbose messages only appear when Returned: always Sample: |
|
A list of warning messages created by the script. Warning messages only appear when Returned: always Sample: |