Create a new user

This example shows how you can use the User resource to ensure a user exists.

With Ensure set to Present and UserName set to SomeUserName, the resource creates the SomeUserName account if it doesn't exist.

With Password set to the user-provided value for the PasswordCredential parameter, if the resource creates the SomeUserName account, it creates the account with the password set to the value of PasswordCredential. The first time someone logs in as SomeUserName, the system prompts them to change the password.

If SomeUserName exists, the resource doesn't set the password for that account.

With Invoke-DscResource

This script shows how you can use the User resource with the Invoke-DscResource cmdlet to ensure the SomeUserName account exists, creating it with a default password if needed.

[CmdletBinding()]
param(
    [Parameter(Mandatory)]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $PasswordCredential
)

begin {
    $SharedParameters = @{
        Name       = 'User'
        ModuleName = 'PSDscResource'
        Properties = @{
            Ensure   = 'Present'
            UserName = 'SomeUserName'
            Password = $PasswordCredential
        }
    }

    $NonGetProperties = @(
        'Ensure'
        'Password'
    )
}

process {
    $TestResult = Invoke-DscResource -Method Test @SharedParameters

    if ($TestResult.InDesiredState) {
        $QueryParameters = $SharedParameters.Clone()

        foreach ($Property in $NonGetProperties) {
            $QueryParameters.Properties.Remove($Property)
        }

        Invoke-DscResource -Method Get @QueryParameters
    } else {
        Invoke-DscResource -Method Set @SharedParameters
    }
}

With a Configuration

This snippet shows how you can define a Configuration with a Service resource block to ensure the SomeUserName account exists, creating it with a default password if needed.

Configuration Create {
    param (
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $PasswordCredential
    )

    Import-DscResource -ModuleName PSDscResources

    Node localhost {
        User ExampleUser {
            Ensure   = 'Present'
            UserName = 'SomeUserName'
            Password = $PasswordCredential
        }
    }
}