Windows - Add Users to Local Groups

Octopus.Script exported 2015-05-19 by josh3ennett belongs to ‘Windows’ category.

Add a list of users to a list of Local Groups

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

User Names

UserNames

List of user names separated by ;

Group Names

GroupNames

list of group names separated by ;

Script body

Steps based on this template will execute the following PowerShell script.

# Running outside octopus
param(
    [string]$UserNames,
    [string]$GroupNames
) 

$ErrorActionPreference = "Stop" 

function Get-Param($Name, [switch]$Required, $Default) {
    $result = $null

    if ($OctopusParameters -ne $null) {
        $result = $OctopusParameters[$Name]
    }

    if ($result -eq $null) {
        $variable = Get-Variable $Name -EA SilentlyContinue   
        if ($variable -ne $null) {
            $result = $variable.Value
        }
    }

    if ($result -eq $null) {
        if ($Required) {
            throw "Missing parameter value $Name"
        } else {
            $result = $Default
        }
    }

    return $result
}

function IsValidUser ( $user ) {
    
    if($user.Guid -and ($user.SchemaClassName -eq "User")){
        return $true
    }
    
    Write-Host "ERROR - `"WinNT://$($user.Name)`" not found"
    return $false
}

function IsValidGroup ( $group ) {
    
    if( $group.Guid -and ($group.SchemaClassName -eq "Group") ) {
        Write-Host "the group $($group.Guid) was found" -ForegroundColor green
        return $true
    }

    Write-Host "ERROR - `"WinNT://$($Env:COMPUTERNAME)/$($group.Name)`" not found" -ForegroundColor red
    return $false
}

function IsUserInGroup($user, $groupName){

    Write-Host "Checking to see if $($user.Name) is in $($group.Name)"

    if(!(isValidGroup $group)){
        throw "Could not find group $($group.Name)"
    }

    $members = @($group.psbase.Invoke("Members")) 
    
    Write-Host "There are $($members.Count) members in $($group.Name)"
    
    $isInGroup = ($members | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}) -contains "$($user.Name)"
        
    if($isInGroup) {
        Write-Host "User $($user.Name) is already a part of `"$($group.Name)`"" -ForegroundColor Yellow
    } else {
        Write-Host "User $($user.Name) is not a part of `"$($group.Name)`"" -ForegroundColor Green
    }
    
    return $isInGroup
}

function FormatUserNameForQuery([string]$userName)
{
    return $userName.Trim().Replace("\", "/")
}

& {
    param(
        [string]$UserNames,
        [string]$GroupNames
    ) 

    Write-Host "Windows - Add Users to Local Groups"
    Write-Host "UserNames: $UserNames"
    Write-Host "GroupNames: $GroupNames"

    $UserNames.Split(";") | foreach {
        
        $userName = FormatUserNameForQuery $_
        $user = [ADSI]"WinNT://$userName"
        
        $userDoesNotExist = !(IsValidUser $user)
        
        if( $userDoesNotExist )
        {
            throw "User $userName was not found"
        }

        Write-Host "Current user $userName"

        $GroupNames.Split(";") | foreach {
            
            $groupName = $_.Trim()
            $group = [ADSI]"WinNT://$Env:COMPUTERNAME/$groupName"
           
            $groupDoesNotExist = !(IsValidGroup $group)
            
            if($groupDoesNotExist)
            {
                throw "Group $groupName was not found"
            }

            Write-Host "Current group $groupName"

            $isInGroup = IsUserInGroup $user $group

            if( $isInGroup ) {
                
                Write-Host "Skipping..."
                
                continue
            }

            Write-Host "Adding $userName to $groupName" -ForegroundColor Cyan
            
            $group.psbase.Invoke("Add",$user.Path)

            Write-Host "SUCCESS - added $userName to $groupName" -ForegroundColor Green
        }
    }

 } `
 (Get-Param 'UserNames' -Required) `
 (Get-Param 'GroupNames' -Required)

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "ed204305-3399-4ffa-8566-a62da4e36641",
  "Name": "Windows - Add Users to Local Groups",
  "Description": "Add a list of users to a list of Local Groups",
  "Version": 2,
  "ExportedAt": "2015-05-19T19:57:11.048+00:00",
  "ActionType": "Octopus.Script",
  "Author": "josh3ennett",
  "Parameters": [
    {
      "Name": "UserNames",
      "Label": "User Names",
      "HelpText": "List of user names separated by ;",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "MultiLineText"
      }
    },
    {
      "Name": "GroupNames",
      "Label": "Group Names",
      "HelpText": "list of group names separated by ;",
      "DefaultValue": null,
      "DisplaySettings": {
        "Octopus.ControlType": "MultiLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "# Running outside octopus\nparam(\n    [string]$UserNames,\n    [string]$GroupNames\n) \n\n$ErrorActionPreference = \"Stop\" \n\nfunction Get-Param($Name, [switch]$Required, $Default) {\n    $result = $null\n\n    if ($OctopusParameters -ne $null) {\n        $result = $OctopusParameters[$Name]\n    }\n\n    if ($result -eq $null) {\n        $variable = Get-Variable $Name -EA SilentlyContinue   \n        if ($variable -ne $null) {\n            $result = $variable.Value\n        }\n    }\n\n    if ($result -eq $null) {\n        if ($Required) {\n            throw \"Missing parameter value $Name\"\n        } else {\n            $result = $Default\n        }\n    }\n\n    return $result\n}\n\nfunction IsValidUser ( $user ) {\n    \n    if($user.Guid -and ($user.SchemaClassName -eq \"User\")){\n        return $true\n    }\n    \n    Write-Host \"ERROR - `\"WinNT://$($user.Name)`\" not found\"\n    return $false\n}\n\nfunction IsValidGroup ( $group ) {\n    \n    if( $group.Guid -and ($group.SchemaClassName -eq \"Group\") ) {\n        Write-Host \"the group $($group.Guid) was found\" -ForegroundColor green\n        return $true\n    }\n\n    Write-Host \"ERROR - `\"WinNT://$($Env:COMPUTERNAME)/$($group.Name)`\" not found\" -ForegroundColor red\n    return $false\n}\n\nfunction IsUserInGroup($user, $groupName){\n\n    Write-Host \"Checking to see if $($user.Name) is in $($group.Name)\"\n\n    if(!(isValidGroup $group)){\n        throw \"Could not find group $($group.Name)\"\n    }\n\n    $members = @($group.psbase.Invoke(\"Members\")) \n    \n    Write-Host \"There are $($members.Count) members in $($group.Name)\"\n    \n    $isInGroup = ($members | foreach {$_.GetType().InvokeMember(\"Name\", 'GetProperty', $null, $_, $null)}) -contains \"$($user.Name)\"\n        \n    if($isInGroup) {\n        Write-Host \"User $($user.Name) is already a part of `\"$($group.Name)`\"\" -ForegroundColor Yellow\n    } else {\n        Write-Host \"User $($user.Name) is not a part of `\"$($group.Name)`\"\" -ForegroundColor Green\n    }\n    \n    return $isInGroup\n}\n\nfunction FormatUserNameForQuery([string]$userName)\n{\n    return $userName.Trim().Replace(\"\\\", \"/\")\n}\n\n& {\n    param(\n        [string]$UserNames,\n        [string]$GroupNames\n    ) \n\n    Write-Host \"Windows - Add Users to Local Groups\"\n    Write-Host \"UserNames: $UserNames\"\n    Write-Host \"GroupNames: $GroupNames\"\n\n    $UserNames.Split(\";\") | foreach {\n        \n        $userName = FormatUserNameForQuery $_\n        $user = [ADSI]\"WinNT://$userName\"\n        \n        $userDoesNotExist = !(IsValidUser $user)\n        \n        if( $userDoesNotExist )\n        {\n            throw \"User $userName was not found\"\n        }\n\n        Write-Host \"Current user $userName\"\n\n        $GroupNames.Split(\";\") | foreach {\n            \n            $groupName = $_.Trim()\n            $group = [ADSI]\"WinNT://$Env:COMPUTERNAME/$groupName\"\n           \n            $groupDoesNotExist = !(IsValidGroup $group)\n            \n            if($groupDoesNotExist)\n            {\n                throw \"Group $groupName was not found\"\n            }\n\n            Write-Host \"Current group $groupName\"\n\n            $isInGroup = IsUserInGroup $user $group\n\n            if( $isInGroup ) {\n                \n                Write-Host \"Skipping...\"\n                \n                continue\n            }\n\n            Write-Host \"Adding $userName to $groupName\" -ForegroundColor Cyan\n            \n            $group.psbase.Invoke(\"Add\",$user.Path)\n\n            Write-Host \"SUCCESS - added $userName to $groupName\" -ForegroundColor Green\n        }\n    }\n\n } `\n (Get-Param 'UserNames' -Required) `\n (Get-Param 'GroupNames' -Required)",
    "Octopus.Action.Script.Syntax": "PowerShell"
  },
  "Category": "Windows",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/windows-add-users-to-local-groups.json",
  "Website": "/step-templates/ed204305-3399-4ffa-8566-a62da4e36641",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADNQTFRF////Da3qSsLvhtb0wur6O7zuWcfxldv2aMzyK7ftpOD3s+X48Pr+0fD7d9HzHLLr4fX8xD/OcwAAAaNJREFUeNrs3cFygjAUQFECWott1f//2sJoW6kIKEzNs+euXOmcmSSGDa8oJEmSJEmSJGmsj1W1K9cpsGD1Vr2WdToVEPC+2lYvZfpVrEW0qZpF1F+MRdRugzoNlvkiarfBPk0pT8GhWUSX2yASpDlLr2+DEJBmEY1ug6whx7N0n2b30G1QlmmxHsRYp6X76yvF9vg5RYQczq8UVURI35UiFmTgShED0p6lI1eKzCHTrxS5Qk6PZ9PLDtJ9PIsJmXWlyAky6/dAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQMJCyjltF/iO3gpJUpD8s4OAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgID8T8itwwKyhbTdMr4ha8hXUwZqhICcOgyNOIkE+V5wo4MSgr1u/fp7poO+AL8K/gL8yw0UeyRB34m9iQ/pVD8L5JYTO3NI58R+AsiEEzsW5OfE3sUe/zRwYkeGnG2g2CPS7rhjF4GKP0ZwyoldxK37kFqEL/7wU0mSJEmSJOmJ+xRgAHxZTCXGdZkfAAAAAElFTkSuQmCC",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Tuesday, May 19, 2015