powershellpasswordsuacwindows-11powershell-7.0

How to prompt for UAC in PowerShell 7 and save the entered password as variable?


I have a simple script to create a scheduled task like this:

$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument '-file "File.ps1"'
$trigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -Action $action -Trigger $trigger -TaskPath "Tasks" -TaskName "Name" -Description "Description" -User Admin -Password $password -RunLevel Highest 

how can I prompt for UAC and capture the password that user enters in the UAC prompt as $password variable to be used in the script?


Solution

  • Note:

    # Prompt for an administrator's credentials and verify that they are valid.
    do {
        $cred = Get-Credential -Message 'Please specify an administrator''s credentials: '
        if (-not $cred) { Write-Warning 'Aborted by user request.'; exit 2 }
        if (-not (Test-WinCredential $cred)) {
            Write-Warning "The specified username-password combination isn't valid. Please try again."
        }
        elseif (-not (Get-LocalGroupMember -ErrorAction Ignore Administrators $cred.UserName)) {
            Write-Warning "User $($cred.UserName) is not a member of the local Administrators group. Please try again."
        } else {
            break # OK
        }
    } while ($true)
    
    # $cred.UserName now contains the username.
    # Obtain the password as plain text.
    # Note: This should generally be avoided.
    $plainTextPassword = $cred.GetNetworkCredential().Password