Run Scheduled Tasks with Group Managed Service Accounts

This post describes How to “Run Scheduled Tasks with Group Managed Service Accounts”. A detailed post and video on the topic.

Remember when Windows Server 2008 R2 introduced Managed Service Accounts (MSAs)?
They seemed like a game-changer—offering automatic password management and Service Principal Name (SPN) registration. You imagined replacing all those over-privileged service accounts in your domain—the ones with passwords that haven’t changed in five years. It was a dream come true… until the fine print.

  • MSAs couldn’t be used with Exchange or SQL.
  • They weren’t supported across multiple hosts.
  • They couldn’t even run scheduled tasks.

With all those limitations, many of us gave up before even checking if our third-party applications supported them.

Then came Windows Server 2012 and Group Managed Service Accounts (gMSAs).
Think of gMSAs as the practical, usable version of MSAs. Microsoft addressed many of the original shortcomings:

  • A single gMSA can be used on multiple hosts
  • gMSAs can run scheduled tasks
  • gMSAs are supported by IIS Application Pools, SQL Server 2012, and possibly other apps (vendor support may vary)

Now is the perfect time to explore Group Managed Service Accounts and test how they can improve your service account strategy.

Explroe more in Technical Blogs

running scheduled tasks with group managed service accounts

What is a Group Managed Service Account (gMSA)?

When you extend your Active Directory schema for Windows Server 2012, a new object class is introduced: msDS-GroupManagedServiceAccount. This class represents gMSAs, which are designed to securely manage service account credentials across multiple servers.

Fun fact: gMSAs are derived from the computer class and come with several new attributes specifically designed to support secure, automated password management.


Key Attributes of a gMSA

Here are the core attributes that define how a gMSA works:

  • msDS-GroupMSAMembership
    Specifies which computers (or groups of computers) are authorized to retrieve and use the gMSA password.
  • msDS-ManagedPassword
    A binary blob that includes the current password, previous password, and the password change interval.
  • msDS-ManagedPasswordInterval
    Set at the time of account creation (and cannot be changed later), this determines how frequently the password is changed (in days).
  • msDS-ManagedPasswordID
    A unique identifier used by the Key Distribution Service (KDS) to generate the current password.
  • msDS-ManagedPasswordPreviousID
    The identifier for the previously used password.

How gMSA Passwords Work

Unlike traditional MSAs, gMSA passwords are handled by the Key Distribution Service (KDS) running on Windows Server 2012 domain controllers. This architecture allows multiple servers to securely share and use the same gMSA.

Here’s how the password lifecycle works:

  1. A member server queries the DC to retrieve the current password.
  2. The DC checks whether a password change is due, based on the msDS-ManagedPasswordInterval.
  3. If needed, the DC generates a new password using:
    • A shared root key ID (pre-created by an admin)
    • The current time (converted to an epoch format)
    • The gMSA’s Security Identifier (SID)
  4. The result? A 120-character password, consistent across all KDS instances.

This approach ensures high availability and secure, automated credential management.

Since the gMSA password hash is stored in Active Directory, even down-level domain controllers (e.g., Server 2008 R2) can still respond to Kerberos service ticket requests (TGS-REQs).

A flow depicting how a Managed Service Account works

Requirements to Use gMSAs

To deploy and use gMSAs in your environment, you’ll need the following:

  • At least one Windows Server 2012 domain controller
  • A Windows Server 2012 or Windows 8 machine with the ActiveDirectory PowerShell module to create and manage gMSAs
  • A Windows Server 2012 or Windows 8 domain member to run services using the gMSA

Using Group Managed Service Accounts

Setting up Group Managed Service Accounts (gMSAs) in Windows Server 2012 is straightforward. Like many new features introduced in this release, the process is designed to be simple and efficient. It boils down to three key steps:

  1. Create the KDS Root Key
    This step is only required once per domain and enables the Key Distribution Service to generate gMSA passwords.
  2. Create and Configure the gMSA
    Define the gMSA and specify which computers are authorized to retrieve and use its credentials.
  3. Install and Configure the gMSA on Target Hosts
    Apply the gMSA to the services or tasks running on the designated domain-joined servers.

Let’s walk through an example to see how this works in practice.

Step 1: Create the KDS Root Key (One-Time Setup per Domain)

Before you can create and use Group Managed Service Accounts, you need to initialize the Key Distribution Service (KDS) root key. This key is essential for generating and distributing gMSA passwords across domain controllers.

On a Windows Server 2012 Domain Controller, or a Windows Server 2012 / Windows 8 machine with the ActiveDirectory PowerShell module, run the following command:

EditAdd-KDSRootKey –EffectiveImmediately

Note: Despite the –EffectiveImmediately parameter, the key won’t be truly effective right away. It can take up to 10 hours for the key to propagate across all domain controllers. This delay is intentional—it ensures proper replication and avoids inconsistencies in password generation.

Yes, this means you can run the command, go home, and pick things up tomorrow. 😄

If you’re working in a lab or test environment and want to skip the wait, there is a workaround to bypass this safety delay—but it’s not recommended for production use.

Skipping the Wait (Lab Environments Only)

In a non-production or lab environment, you can bypass the 10-hour replication delay by setting the effective time of the KDS root key to a point in the past. This is not recommended for production, as it may lead to inconsistent behavior if domain controllers haven’t fully replicated.

To skip the delay, run:

Add-KDSRootKey –EffectiveTime ((Get-Date).AddHours(-10))

⚠️ Warning: Use this only in isolated test environments. In production, always allow time for replication by using –EffectiveImmediately and waiting the full replication interval.

Step 2: Create and Configure the gMSA

First, decide which computers will be allowed to use the gMSA. While you can assign permissions to individual computer accounts, it’s best to create a security group and add the relevant computer objects to it. This makes future administration easier and more scalable.

💡 Pro Tip: The only catch when using a group is that membership changes require a reboot on the affected hosts for the changes to take effect.

In this example, we’re using Domain Controllers to run on servers // and Domain Computers to run on client PCs as the target hosts, and since all DCs are already part of the built-in Domain Controllers and all computers joining the Network are a part of Domain Computers group. We will create an OU for Client computers to apply group policy. We’ll use that group to authorize gMSA usage:


Next, use PowerShell with the ActiveDirectory module (available on Windows Server 2012 or Windows 8) to create the gMSA.

You’ll need to specify:

  • Name (SAMAccountName) of the service account
  • DNSHostName (FQDN of the service)
  • PrincipalsAllowedToRetrieveManagedPassword (the group allowed to use the gMSA)
  • Optionally: ServicePrincipalNames (SPNs) if the service needs them

Here’s the command:

New-ADServiceAccount -Name <ServiceAccountName> `
-DNSHostName <FQDN> `
-PrincipalsAllowedToRetrieveManagedPassword <GroupName> `
-ServicePrincipalNames <SPN1,SPN2,...>

In our example, we’ll keep it simple and just provide the name, DNS host name, and the security group:

New-ADServiceAccount -Name MyServiceAccount `
-DNSHostName myservice.domain.com `
-PrincipalsAllowedToRetrieveManagedPassword "Domain Computers"

Got a “key does not exist” error?
That means Step 1 was skipped or the KDS root key hasn’t fully propagated yet. Be patient—or double-check your lab shortcut.


Once the command completes successfully, you’ll see a new gMSA object in Active Directory > Managed Service Accounts OU:

Step 3: Configure the gMSA on the Host

Now that the gMSA has been created, it’s time to configure it on the target host.

Install and Test the gMSA

Although not always required, it’s best practice to verify that the gMSA is properly configured and accessible from the host. Run the following PowerShell commands on the host that will be using the gMSA:

Install-ADServiceAccount <gMSA>
Test-ADServiceAccount <gMSA>

If Test-ADServiceAccount returns True, you’re good to go!
If it returns False, you’ll get a detailed error message to help you troubleshoot.

Step 4: Create a Group Policy for “Logon as Batch Job”

In Domain controller, open group policy editor and create a Group policy for the OU created for computers.

So, I created an OU and added the PC. The domain Joined PCs are automatically as part of Domain Computers… So, the group I used was Domain Computers. I created an OU for client PCs and added the PCs there.

Now on Domain Controller… GPMC.msc. Group Policy Management Console.

  • User your Domain you can see the OU. Right click on it and Select “Create a Group Policy in this domain and add it here”.
  • Once the Group Policy Object is added, Right click and Click on EDIT
  • Navigate to: Policies >> Windows Settings >> Security Settings >> Local Policies >> User Rights Management
  • Search for Logon as a batch Job. >> Double click it to Open and Select “Define these Policy Settings“.
  • Add User or Group and follow the prompt to add the Managed Service Account.
image 19

Once the Group Policy is created, reboot the client PC.

Step 5: Test Scheduled task with gMSA (Group Managed Service Account)

Create a Folder C:\Scripts and assign Read-Write permission to the Service Account. This is needed because the PowerShell script we put in the folder should be accessible to the Service Account. Moreover, in this example the PowerShell script is designed to create a text file on every logon. To create the text file, write permission should be granted.

Sample PowerShell code to create a Logfile

<#
.SYNOPSIS
Creates a timestamped log file in C:\scripts that works in scheduled tasks
#>

# 1. Define absolute paths (critical for scheduled tasks)
$logDirectory = "C:\scripts"
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$logFile = "TaskLog_$timestamp.txt"
$fullPath = "$logDirectory\$logFile"  # Scheduled tasks handle basic paths better than Join-Path

# 2. Create directory with explicit error handling
if (-not (Test-Path -Path $logDirectory)) {
    try {
        $null = New-Item -Path $logDirectory -ItemType Directory -Force -ErrorAction Stop
    }
    catch {
        # Write to Windows Event Log if running as system
        Write-EventLog -LogName Application -Source "Application" -EntryType Error -EventId 100 `
            -Message "Failed to create directory $logDirectory. Error: $_" -ErrorAction SilentlyContinue
        exit 1
    }
}

# 3. Create log file with explicit output
try {
    @"
Scheduled Task Log
==================
Created: $(Get-Date)
Computer: $env:COMPUTERNAME
User: $env:USERNAME
Task: $($MyInvocation.MyCommand.Name)
"@ | Out-File -FilePath $fullPath -Encoding UTF8 -Force -ErrorAction Stop

    # Verify by reading back
    if (-not (Test-Path -Path $fullPath -PathType Leaf)) {
        throw "File verification failed"
    }
}
catch {
    Write-EventLog -LogName Application -Source "Application" -EntryType Error -EventId 101 `
        -Message "Failed to create log file $fullPath. Error: $_" -ErrorAction SilentlyContinue
    exit 1
}

# 4. Success indicator
"SUCCESS" | Out-File -Append -FilePath $fullPath
exit 0

Script for Scheduled task [this is an example]

You can use your scripting expertise and scheduled task to create as per your requirements.

# Define task parameters
$taskName = "RunScriptAtLogon"
$scriptPath = "C:\scripts\edge.ps1"  # Replace with your actual script path
$gMSAAccount = "root\gmsa3$"  # Your gMSA account

# Create task action (powershell.exe with your script)
$action = New-ScheduledTaskAction `
    -Execute "powershell.exe" `
    -Argument "-NoLogo -ExecutionPolicy Bypass -NoProfile -File `"$scriptPath`""

# Create logon trigger
$trigger = New-ScheduledTaskTrigger -AtLogOn

# Configure principal for gMSA account
$principal = New-ScheduledTaskPrincipal `
    -UserID $gMSAAccount `
    -LogonType Password `
    -RunLevel Highest

# Configure task settings
$settings = New-ScheduledTaskSettingsSet `
    -AllowStartIfOnBatteries `
    -DontStopIfGoingOnBatteries `
    -StartWhenAvailable `
    -DontStopOnIdleEnd

# Register the task
Register-ScheduledTask `
    -TaskName $taskName `
    -Action $action `
    -Trigger $trigger `
    -Principal $principal `
    -Settings $settings `
    -Force

# Verify task creation
if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) {
    Write-Host "Task '$taskName' created successfully!" -ForegroundColor Green
} else {
    Write-Host "Failed to create task '$taskName'" -ForegroundColor Red
}

Now that Scheduled Task is created. Try to Log Off and Log in and check the C:\Script folder … You should see the logfile created.


These are sample scripts created, you can modify it as per your requirement. If this blog post is not clear… see the full Video on How to Run Schedules Tasks with Group Managed Service Accounts.


Explore our Literature YouTube Channels:

Hindi Sahitya 1

YouTube Channel Link:

@hindi_sahitya_01

DALL·E 2024 11 04 12.55.23 A stylish and inviting logo for The Literature Lounge YouTube channel. Features an open book with elegant curling pages and a vintage feather quill

YouTube Channel Link:

@The_Literature_Lounge

Designer 40

YouTube Channel Link:

@techno_tips_learning

niteshsinhaofficial e1738723497984

YouTube Channel Link

@nitesh_sinha_official

Leave a Comment

Scroll to Top