Home > front end >  How to have a script check for admin privileges', and rerun itself as admin if it doesn't
How to have a script check for admin privileges', and rerun itself as admin if it doesn't

Time:09-21

So I am trying to create a solution for an issue I am having in powershell.

I need to come up with a way to have my script check if it was ran with Administrative Rights. If it wasn't it needs to rerun itself with admin rights.

My situation is special from the other times this has been asked (From all the posts I have checked) as our normal user accounts doesn't have the rights, so I need to enter alternative credentials.

If this helps, Our Administrative Accounts do have an ending identifier in the name if we can filter off this. EX. "John.Doe.A" and the .A indicates this is an Admin account.

CodePudding user response:

Continuing from my comment.

Your case is not unique. It gets asked a lot here and in many other spots.

'powershell SecretManagement module' auto elevate

Sample hit:

https://petri.com/powershell-secrets-management-how-to-securely-elevate-privileges-in-powershell-scripts

You store needed credentials in the 'Windows Credential Manager', and call from the as needed. MS even provides a new Secrets Module for this kind of use case. See more details via MS Docs on the topic.

Like this:

SecretManagement and SecretStore are Generally Available

https://devblogs.microsoft.com/powershell/secretmanagement-and-secretstore-are-generally-available

and this:

Microsoft.PowerShell.SecretManagement

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.secretmanagement/?view=ps-modules

Get-Secret
Get-SecretInfo
Get-SecretVault
Register-SecretVault
Remove-Secret
Set-Secret
Set-SecretInfo
Set-SecretVaultDefault
Test-SecretVault
Unregister-SecretVault

CodePudding user response:

Use this.

$adminrole = ([Security.Principal.WindowsBuiltInRole] "Administrator")
$wid = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent())
If (-not $wid.IsInRole($adminrole)) {        
    $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
    $newProcess.Arguments = $myInvocation.MyCommand.Definition
    $newProcess.Verb = "runas";
    [System.Diagnostics.Process]::Start($newProcess);
    exit
}
  • Related