powershell - Powershell:如何请求用户身份验证以继续
问题描述
我的 Powershell 脚本实现了一些特性/功能,但是我想限制某些用户使用一些特性。
为了允许当前用户或其他用户从菜单中选择此类受限功能,我正在寻找一种方法来要求 Windows 进行用户身份验证才能继续。我怎么能那样做?下面的UserAuthentication
功能应该如何?
代码:
$feature = Read-Host 'Select the feature by typing the number [1 - 2]'
switch ($feature)
{
1
{
write-output "This feature any user can reach"
}
2
{
$user = Read-Host "This feature only some user can reach and requires authentication. Entry your username to proceed"
$allowedUsers = "user1", "user2"
if($allowedUsers.contains($user))
{
write-output "This feature the user $user can reach. Please authenticate to continue"
if((UserAuthentication $user) -eq $true)
{
write-output "$user successfully authenticated"
}
else
{
write-output "$user unsuccessful authenticated"
}
}
else
{
write-output "This feature the user $user cannot reach"
}
}
}
function UserAuthentication($user)
{
return $true #May return 'True' if successfully authenticated or 'False' if not.
}
解决方案
此答案适用于您的用户是 AD 域的成员时
我已更改函数名称UserAuthentication
以Get-Authentication
符合 PowerShell 中的动词-名词函数命名约定。
# helper function test if a username/password combination is valid.
# if valid, the username entered in the box is returned.
function Get-Authentication {
$Credentials = Get-Credential "$env:USERDOMAIN\$env:USERNAME" -Message "Please authenticate to continue" -ErrorAction SilentlyContinue
if ($Credentials) {
$UserName = $Credentials.UserName
$Password = $Credentials.GetNetworkCredential().Password # --> plain-text password
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$ds = New-Object System.DirectoryServices.AccountManagement.PrincipalContext Domain
if ($ds.ValidateCredentials($UserName, $Password)) {
# return the username entered
$UserName
}
}
}
# your code here
# fill in the SamAccountNames of allowed users for this feature
$allowedUsers = 'samaccountname','of', 'users', 'that', 'are', 'allowed', 'to', 'use', 'feature 2'
$feature = Read-Host 'Select the feature by typing the number [1 - 2]'
switch ($feature) {
'1' { Write-Output "This feature any user can reach" }
'2' {
$user = Get-Authentication
if ($null -ne $user -and $allowedUsers -contains $user) {
Write-Output "User $user is allowed for this feature"
}
else {
Write-Output "This feature the user cannot reach"
}
}
}
推荐阅读
- javascript - 无法在 React 组件中访问 Javascript 对象
- python - 我应该如何处理python中的不可下标问题?
- laravel - Laravel 通过表单建立一对多关系关联
- html - 将子 div 扩展到一侧
- ios - Swift 4 相机视图,为什么这会在 iPad 而不是 iPhone 上崩溃?
- typescript - 我如何表达一个参数可以扩展打字稿中的字符串列表?
- c# - 如何验证集合的类型?
- python - 我的程序在打印输出之前循环了两次
- mysql - Oracle - 选择语句引发错误
- html - 如何使我的聊天容器的标题对于其中的每个元素都是可滚动的并且不重叠