Run Powershell commands using Ansible

Posted: November 20, 2018 in ansible, Windows Server

Ansible have no module for setting Domain Group Policies,but we can use PowerShell commands. If we need to create Custom GPO and link it to some GPO, we can do it also by Powers shell – by setting Registry Values.

The key must be in one of the two following registry hives:

  • HKEY_LOCAL_MACHINE (HKLM) for a registry-based policy setting in Computer Configuration.
  • HKEY_CURRENT_USER (HKCU) for a registry-based policy setting in User Configuration.

Bellow is example for setting Screen Saver TimeOut to 900 seconds for User Configuration Settings GPO.


New GPO named BO-1-Desktops is created and linked to test OU.

- name: Configure GPO
        hosts: winserver
          - name: Set ScreenSaver Timeout
            win_shell: | 
              New-GPLink -Name "BO-1-Desktops" -Target 
              Set-GPRegistryValue -Name "BO-1-Desktops" -KEY "HKCU\Software\Policies\Microsoft\Windows\Control Panel\Desktop" -ValueName "ScreenSaveTimeOut" -Type DWORD      -Value 900 > C:\screensaverGPO.txt
              creates: C:\screensaverGPO.txt

Script won’t be executed if C:\screensaverGPO.txt exists.

Example for creating DNS zone

- name: Create DNS
  hosts: winserver
   - name: Create Forward lookup zone
     win_shell: |
       try {$getdns=Get-DnsServerZone -Name "" -ErrorAction SilentlyContinue
       if ($getdns -eq $null) {Add-DnsServerPrimaryZone -Name ""       -ReplicationScope "Forest" -PassThru > c:\dnszone.log}
       } catch {write-host "ok"}
       creates: C:\dnszone.log
  1. says:

    how can I user powershell to shutdown the hyper-v guest?

    powershell script:
    $a = Get-ClusterGroup | Where-Object {$_.Name -like “server1” -and $_.State -eq ‘Online’}
    $b = $a.OwnerNode
    Stop-VM -Name “vm1” -ComputerName $b

    my playbook….but not wotk
    – name: Hyper-V shutdown VM
    hosts: all
    gather_facts: no

    – win_shell: |
    $a = Get-ClusterGroup | Where-Object {$_.Name -like “{{ vm }}” -and $_.State -eq ‘Online’}
    $b = $a.OwnerNode
    Stop-VM -Name “{{ vm }}” -ComputerName $b


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s