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.

Capture

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

- name: Configure GPO
        hosts: winserver
        tasks: 
          - name: Set ScreenSaver Timeout
            win_shell: | 
              New-GPLink -Name "BO-1-Desktops" -Target 
 "OU=test,DC=ad,DC=contoso,DC=com";
              Set-GPRegistryValue -Name "BO-1-Desktops" -KEY "HKCU\Software\Policies\Microsoft\Windows\Control Panel\Desktop" -ValueName "ScreenSaveTimeOut" -Type DWORD      -Value 900 > C:\screensaverGPO.txt
            args: 
              creates: C:\screensaverGPO.txt

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

Example for creating DNS zone

- name: Create DNS
  hosts: winserver
  tasks:
   - name: Create Forward lookup zone
     win_shell: |
       try {$getdns=Get-DnsServerZone -Name "west01.contoso.com" -ErrorAction SilentlyContinue
       if ($getdns -eq $null) {Add-DnsServerPrimaryZone -Name "west01.contoso.com"       -ReplicationScope "Forest" -PassThru > c:\dnszone.log}
       } catch {write-host "ok"}
     args:
       creates: C:\dnszone.log
Comments
  1. 168bbs@gmail.com 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

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

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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