首页 > 解决方案 > 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.
}

标签: powershellauthentication

解决方案


此答案适用于您的用户是 AD 域的成员时

我已更改函数名称UserAuthenticationGet-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"
        }
    }
}

推荐阅读