验证用户是否存在于Octopus Deploy中



我想在Octopus Deploy中添加一个使用Powershell脚本的用户,该脚本运行良好。我想验证该用户是否已经存在,然后不要添加该用户。有人能指出我做错了什么吗。它说用户存在,即使用户不存在。它在用户列表中进行搜索,以查看该用户是否存在。我正在使用InvokeRestMethod来添加用户,这很好。如果用户在我添加之前存在,我会对验证感到困惑。有更简单的方法吗?

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"
}

}

if ($userId -eq '') {

如果没有找到现有用户,$userId为$null,因此计算结果为false。

如果找到用户,foreach循环也会返回,所以这个if语句看起来并没有必要。如果它做到了这一点,你可以假设用户不存在(只要你的用户少于100000(。

最新更新