powershell - 验证用户是否存在于 Octopus Deploy 中
问题描述
我想使用 Powershell 脚本在 Octopus Deploy 中添加一个用户,该脚本运行良好。我想验证用户是否已经存在然后不要添加用户。有人可以指出我做错了什么。它说即使用户不存在,用户也存在。它搜索用户列表以查看用户是否存在。我正在使用 Invoke RestMethod 添加用户并且效果很好。如果用户在我添加之前存在,我会对验证感到困惑。有没有更简单的方法来做到这一点?
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 语句看起来没有必要。如果到此为止,您可以假设该用户不存在(只要您的用户少于 100,000 个)。
推荐阅读
- r - 使用应用函数制作多个图表并在标题中显示变量名称
- react-native - 在没有道具的情况下访问 React-Native 导航
- c - 在 n 个符号后放置 ' ' 的函数
- php - 如何存储和检索数据类型的图像:image/jpeg;base64?
- regex - 区分 .htaccess 中的两个重定向
- thingsboard - 来自时间戳打包的远程信息处理元素的解析错误
- c# - VS2017 WinForms Designer 在更改时创建第二个构造函数
- android - 如何在 Kotlin 中将一个 MutableLiveData 列表附加到另一个列表
- split - 如何通过 python-pptx 将多张幻灯片 pptx 文件拆分为单独的文件?
- php - 在 laravel 中创建插入表单