Ansible, Windows and PowerShell: the Basics – Part 4, Invoking PowerShell Code

In Part 4 of this series we’ll continue our journey with Ansible, Windows and PowerShell and look at how we can use Ansible to invoke PowerShell code directly.

Our job template in AWX to test out the possible different scenarios is _3_invoke-powershell

The contents of _3_invoke-powershell.yml are are follows:

There are three main options we can take for approaching invoking PowerShell code, all using the win_shell module in some form.

Run a single line of PowerShell

If the requirement is only to run a simple / single command in PowerShell, then it probably doesn’t make sense to have the code for that contained in a script, copied to the Windows machine, then executed. The win_shell module enables you to do that inline:

Run multi-lined PowerShell commands

If the requirement is to run multiple lines of PowerShell code then it is still possible to include the code inline, it just needs to be laid out as follows across multiple lines in the playbook:

Run a PowerShell script

If the requirement is to run more code than the above, then the best option may be to put all of that code into a PowerShell script, get it onto the Windows machine and have Ansible execute it. There are of course many ways to get the script onto the machine, in this instance I am using the built-in variable playbook_dir as a known location to copy it from on the Ansible server. The script is in a files sub-folder of the playbook repository:

The code within the test.ps1 script:

Running a job from the _3_invoke-powershell job template produces a successful result:

Run a single line of PowerShell

Viewing the log shows us the command that was run:

Checking our vanilla Windows 2016 server we can observe the presence and content of the test.txt file:

Run multi-lined PowerShell commands

Viewing the log shows us the command that was run:

Checking our vanilla Windows 2016 server we can observe the presence and content of the test2.txt file:

Run a PowerShell script

Viewing the log shows us the command that was run:

Checking our vanilla Windows 2016 server we can observe the presence and content of the test3.txt file:

So those are the basics for invoking PowerShell code. You may also be interested in two other related posts I have in this area which I won’t be covering in this basics series: