简体   繁体   中英

Powershell Running as Administrator not working?

I need some way to be able to run the below script as Administrator .

Script to get the Security Event log:

$DateAfter = (Get-Date).AddDays(-1)
$DateBefore = (Get-Date)
$EventLogTest = Get-EventLog -LogName Security -InstanceId 4625 -Before $DateBefore -After $DateAfter -Newest 5
$WinEventTest = Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4625; StartTime = $DateAfter; EndTime = $DateBefore } -MaxEvents 5

Write-Host "$EventLogTest result is: "
$EventLogTest

Write-Host "$WinEventTest result is: "
$WinEventTest

I have compiled the below snippets, but somehow, the result is not displayed or nothing? Combined Script:

$Role = "Domain Admins"
$CurrentLoginPrincipal = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent())
$IsDomainAdminGroupMember = $CurrentLoginPrincipal.IsInRole($Role)
$IsLocalComputerAdminMember = $CurrentLoginPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

If( -not ($IsDomainAdminGroupMember -and $IsLocalComputerAdminMember) ) {
    Write-Warning "You are not running this as $($Role) and Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN). The script will be re-executed as Local Administrator"
    Try {
        Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"" -Verbose
    }
    Catch {
       Write-Warning -Message "[PROCESS] Something wrong happened"
       Write-Warning -Message $Error[0].Exception.Message
        $out.Details = $_.Exception.Message
        Write-Host " ERROR: $($out.Details)" -ForegroundColor Red
    }
}
Else {
    #a user running the script has the Domain Admins and Local PC Admin rights
    Write-Host " $($CurrentLoginPrincipal.Identity.Name.ToString()) is currently member of $($Role) and Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN) " -ForegroundColor Green
}

$DateAfter = (Get-Date).AddDays(-1)
$DateBefore = (Get-Date)
$EventLogTest = Get-EventLog -LogName Security -InstanceId 4625 -Before $DateBefore -After $DateAfter -Newest 5
$WinEventTest = Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4625; StartTime = $DateAfter; EndTime = $DateBefore } -MaxEvents 5

Write-Host "$EventLogTest result is: "
$EventLogTest

Write-Host "$WinEventTest result is: "
$WinEventTest

However, it is still not executing as Administrator to get the result displayed. How can I fix this?

First thing I noticed is that your if condition is wrong. It uses -and where that should be or (because either a Domain admin OR a local Administrator can run this)

Next, the arguments for Start-Process are incorrect. Personally, I like using the -ArgumentList as array.

Finally, in the catch block you use an undefined variable $out with an equally undefined property $out.Details . In the code below I have changed that to simply re-throw the exception.

Starting from where the if..else is:

if( -not ($IsDomainAdminGroupMember -or $IsLocalComputerAdminMember) ) {
    Write-Warning "You are not running this as $($Role) or Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN). The script will be re-executed as Local Administrator"
    # give the user some time to see this message
    Start-Sleep 4

    # Build base arguments for powershell.exe as string array
    $argList = '-NoLogo', '-NoProfile', '-NoExit', '-ExecutionPolicy Bypass', '-File', ('"{0}"' -f $PSCommandPath)
    # Add script arguments if any
    $argList += $MyInvocation.BoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key)", "$($_.Value)"}

    try {
        Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList -Verbose -ErrorAction Stop
        # exit the current script. 
        exit  # Use return if you want to keep this instance open aswell
    }
    catch {
        throw
    }
}
else {
    #a user running the script has the Domain Admins and Local PC Admin rights
    Write-Host " $($CurrentLoginPrincipal.Identity.Name.ToString()) is currently member of $($Role) and Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN) " -ForegroundColor Green
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM