1

i found an old question on this topic. However, i am not clear. I have a script that checks, if PS has been run using "run as administrator" and if yes it does the job, otherweise it prompts that the script must be run as administrator.

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CheckforAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

it gives true or false. I have if-else statement that does the rest.

    If($CheckforAdmin -eq 'True'){
        $MSG = ""
        If(($EventLogCheck -ne $EventLog) -or ($EventLogsourceCheck -ne 'True')){
            New-EventLog -LogName $EventLog -Source $EventLogSource -ErrorAction Stop
            $MSG = "$env:USERNAME has successfully created a new eventlog named $EventLog with the source $EventLogSource."
            Write-EventLog -logname $PiEventLog -source  $PiEventLogSource -eventID 1021 -entrytype Information -message $MSG
        }
        else{
            $MSG = "$env:USERNAME tried to create an EventLog named $EventLog with the source $EventLogSource. `nSince the EventLog and the source already exist, this step was aborted."
            Write-EventLog -logname $EventLog -source  $EventLogSource -eventID 1021 -entrytype Information -message $MSG
        }

#           Wenn der Parameter Silent auf true gesetzt ist, wird das Skript nach der Erstellung des EventLogs unmittelbar beendet.
        if($install -eq $true){
            Write-Host $MSG
            Read-Host 'Press any key to continue...'
        }
        exit
    }
    else{
        Write-Host "The Script must be executed as admin"
     [System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
        [System.Windows.Forms.MessageBox]::Show('Installation: The script must be run as administrator in order to create the event log', 'Run as admin')
        exit
    }

It works well, if i am logged in with a normal user. But on my server where i want to run the script, i log in as domain administrator. Even if if run the script just double clicking on it, it runs instead of prompting that the script must be run using "run as administrator".

I red the articles about UAC (User Account control) and as far as i understood: running a script using "run as administor" is actually the same as logging in as domain administrator and double clicking on the script.

Is there any other way to check, if the script was run using "run as administrator" option that shows up if u right click on powershell (doesn't matter, whether you are logged in as admin or not) ?

Keeran
  • 302
  • 1
  • 15
  • How did you implement the prompt? Because obviously, this part only returns $true or $false. I suppose a way to work around this would be something like PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""PS_Script_Path&Name.ps1""' -Verb RunAs}"; To call the script as admin again, if it wasnt before. – Bowshock Feb 09 '22 at 14:14
  • Whether you're running 'elevated' it more complex than looking wether you're in an admin role or logged on as a builtin administrator account. The proper c# code can be found in this answer: https://stackoverflow.com/a/17492949/736079 – jessehouwing Feb 09 '22 at 14:18
  • @Bowshock You are right, it only gives true or false. I have an if else statement that check the value and does the trick. I don't want to start another powershell console by using start powershell -verb runas. i edited my question also, pls take a look. – Keeran Feb 09 '22 at 14:26
  • If I understand you correctly, you're saying that running as a domain admin *implicitly* runs elevated. But shouldn't your check detect that condition, given that domain administrators are part of the bulit-in Administrators group too? (Or is that not always the case?) – mklement0 Feb 09 '22 at 15:01

3 Answers3

2

At the top of your script add the line:

 #Requires -RunAsAdministrator

then remove all your code to check for an administrator.

If the user running the script is not an elevated administrator, a message will be displayed and the execution of the scripts stops.

Peter Hahndorf
  • 10,767
  • 4
  • 42
  • 58
  • Nicely done; here's the relevant help topic: [about_Requires](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Requires#-runasadministrator) – mklement0 Feb 09 '22 at 16:43
0

Original comment:

How did you implement the prompt? Because obviously, this part only returns $true or $false. I suppose a way to work around this would be something like

PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""PS_Script_Path&Name.ps1""' -Verb RunAs}"

To call the script as admin again, if it wasnt before.


Newly added:

Additionally, you have an error in your if-statement. To compare to boolean, you want to have your if-statement like following:

 If($CheckforAdmin -eq $true){

Comparing against strings can lead to problems. Otherwise I cannot locate any other errors.

Bowshock
  • 190
  • 5
  • 1
    As an aside: There's no reason to use `"& { ... }"` in order to invoke code passed to PowerShell's CLI via the `-command` (`-c`) parameter - just use `"..."` directly. Older versions of the [CLI documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pwsh) erroneously suggested that `& { ... }` is required, but this has since been corrected. – mklement0 Feb 09 '22 at 14:46
  • 1
    True, I had that in one of my script-depositories which has some very old pieces of history. I will actually go ahead and change that for the future, I havn't needed to call another script since ages. Thanks mklement0! – Bowshock Feb 09 '22 at 14:49
  • thank you two. I think UAC delivers a token that considers "run as admin" and being logged in as an admin to have the same privileges. I think unfortunately it is going to be the end of this post. – Keeran Feb 09 '22 at 14:56
  • @keeran I just tried a simple ps1 file with the two lines you had initially, and called the variable. When I started the ps1 via "run script" as administrator, it returned false (didnt run as admin), when I called the file from another posh as admin, it returned true. So it does seem to work, but its just a question how you want to use that. – Bowshock Feb 09 '22 at 14:58
0

Tested on Win11 22H2:

([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

Admin PowerShell: Returns True

Non Admin PowerShell: Returns False

Tested on WinSer22 21H2:

Admin PowerShell always runs for me by default: Returns True

RoelDS
  • 997
  • 7
  • 10