Public/SSM/Set-ATSSMWindowsAdminUser.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function Set-ATSSMWindowsAdminUser
{
<#
    .SYNOPSIS
        Use SSM to set up an admin user on one or more Windows instances

    .DESCRIPTION
        Uses SSM to set up a user from the given credentials as a local administrator on the target instances.
        Instances are checked for being Windows, running, passed status checks and SSM enabled.
        This is good for instances created without a key pair, or just to create a user that isn't Administrator.

    .PARAMETER InstanceId
        List of instance IDs on which to set credential

    .PARAMETER Username
        Username to set

    .PARAMETER Password
        Password to set

    .PARAMETER Credential
        PSCredential containing credentials to set.

    .EXAMPLE
        Get-Credential | Set-ATSSMWindowsAdminUser -InstanceId i-00000000,i-00000001
        Prompt for credential and add as an admin user on given instances.

    .EXAMPLE
        Set-ATSSMWindowsAdminUser -InstanceId i-00000000,i-00000001 -Username jdoe -Password Password1
        Add given user with password as admin on given instances.
#>

    param
    (
        [Parameter(Mandatory = $true)]
        [string[]]$InstanceId,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByUserName')]
        [string]$Username,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByUserName')]
        [string]$Password,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByCredential', ValueFromPipeline = $true)]
        [PSCredential]$Credential
    )

    $instanceTypes = Get-SSMEnabledInstances -InstanceId $InstanceId

    if (-not $instanceTypes.Windows)
    {
        Write-Warning "No instances found that are Windows, running, passed status checks, SSM enabled and ready."
        return
    }

    Write-Host "Setting credentials on $($instanceTypes.Windows -join ', ')"

    if ($PSCmdlet.ParameterSetName -eq 'cred')
    {
        $nc = $Credential.GetNetworkCredential()
        $Username = $nc.UserName
        $Password = $nc.Password
    }

    $script = "net user $Username `"$Password`" /add ; net localgroup Administrators $Username /add"

    Invoke-ATSSMPowerShellScript -InstanceIds $InstanceId -ScriptBlock ([scriptblock]::Create($script)) -AsText
    $script = $null
}