Search code examples
powershellforeachoctopus-deploy

Verify if user exists in Octopus Deploy


I want to add a user in Octopus Deploy with Powershell script which works fine. I want to verify if the user exists already then don't add the user. Can someone please point out what I am doing wrong. It says that the user exists even though the user does not exist. It searches through the list of users to see if the user exists. I am using Invoke RestMethod to add the user and that works fine. I am getting confused with the verification if the user exists before I add it. Is there an easier way to do this?

function AddNewUser{
Param(
[string]$OctopusURL,
[string]$APIKey,
[string]$UserName = "New User"
)
$header = @{ "X-Octopus-apiKey" = $APIKey }

Write-Host "Adding user $UserName"
$userList = Invoke-RestMethod "$OctopusURL/api/users?skip=0&take=100000" -Headers $header

foreach ($user in $userList.Items){
    if ($user.UserName -eq $UserName){
        $userId = $user.Id
        return $userId          
    }
}

if ($userId -eq '') {
    Write-Host "No user called `'$UserName`' was found"
        try{
            $newUserResp = Invoke-RestMethod "$OctopusURL/api/users" -Headers $header -Method Post -Body $newUserAsJson -ContentType "application/json"
            return $newUserResp
        } catch {
             Write-Error $_
        }
    } 
else {
    Write-Host "User `'$UserName`' exists"
}

}


Solution

  • if ($userId -eq '') {
    

    $userId is $null if an existing user hasn't been found so this evaluates to false.

    Your foreach loop also returns if the user is found, so this if statement doesn't look like it's necessary. If it's made it to this point, you can assume the user doesn't exist (as long as you have less than 100,000 users).