Youssef Karami
Youssef Karami

Reputation: 75

Run powershell script with elevated command

I have an autologon Powershell script that I'd like to run as admin when I double click on it. I tried to use different scripts but I'm out of luck.

For example:

Start-Process PowerShell –Verb RunAs

Would open another Powershell screen as administrator but without the original script that I wanna run which is:

net accounts /minpwlen:0
net user TPUser /add
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name AutoAdminLogon -Value 1
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultUserName -Value "TPUser"
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefaultPassword -Value ""
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name DefautDomainName -Value ""
copy c:\temp\OP.rdp c:\Users\Public\Desktop
pause

Any idea how can I get this to work ?

Upvotes: 0

Views: 1833

Answers (3)

Youssef Karami
Youssef Karami

Reputation: 75

I actually used this script on top of mine and it worked perfectly.

# ##########################################
# Determine if we have Administrator rights
Write-Host 'Checking user permissions... '
$windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsSecurityPrincipal = New-Object System.Security.Principal.WindowsPrincipal($windowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator

If (!($windowsSecurityPrincipal.IsInRole($adminRole))) {
    Write-Warning 'Current user does not have Administrator rights'
    Write-Host 'Attempting to copy files to temporary location and restarting script'

    # Get random file name
    Do {
        $temp = [System.IO.Path]::GetTempPath() + [System.IO.Path]::GetRandomFileName()
    } Until (!(Test-Path -LiteralPath "$temp"))

    # Create directory
    Write-Host 'Creating temp directory... ' -NoNewLine
    New-Item -Path "$temp" -ItemType 'Directory' | Out-Null
    Write-Host 'done.'

    # Copy script to directory
    Write-Host 'Copying script to temp directory... ' -NoNewLine
    Copy-Item -LiteralPath "$($myInvocation.MyCommand.Path)" "$temp" | Out-Null
    Write-Host 'done.'
    $newScript = "$($temp)\$($myInvocation.MyCommand.Name)"

    # Start new script elevated
    Write-Host 'Starting script as administrator... ' -NoNewLine
    $adminProcess = New-Object System.Diagnostics.ProcessStartInfo
    $adminProcess.Filename = ([System.Diagnostics.Process]::GetCurrentProcess()).Path
    $adminProcess.Arguments = " -File `"$newScript`""
    $adminProcess.Verb = 'runas'

    Try {
        [System.Diagnostics.Process]::Start($adminProcess) | Out-Null
    }
    Catch {
        Write-Error 'Could not start process'
        Exit 1
    }
    Write-Host 'done.'

    Exit 0
}

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201652

I have used the following before to re-launch as script as admin but there is not stopping the UAC prompt:

function IsAdministrator
{
    $Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
    $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

function IsUacEnabled
{
    (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

#
# Main script
#
if (!(IsAdministrator))
{
    if (IsUacEnabled)
    {
        [string[]]$argList = @('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
        $argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
        $argList += $MyInvocation.UnboundArguments
        Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList 
        return
    }
    else
    {
        throw "You must be administrator to run this script"
    }
}

Upvotes: 1

Luke
Luke

Reputation: 667

You are in luck because I was fighting with this issue for some time, what you need to do is make it take note of where it is at and when it starts back up the shell as an admin it needs to execute the script.

Function Test-IsAdmin   {    
[cmdletbinding()]  
Param()  

Write-Verbose "Checking to see if current user context is Administrator"  
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.NTAccount] "[WriteGroupHere]"))  
{  
    Write-Warning "You are not currently running this under an Administrator account! `nThere is potential that this command could fail if not running under an Administrator account."  
    Write-Verbose "Presenting option for user to pick whether to continue as current user or use alternate credentials"  
    #Determine Values for Choice  
    $choice = [System.Management.Automation.Host.ChoiceDescription[]] @("Use &Alternate Credentials","&Continue with current Credentials")  

    #Determine Default Selection  
    [int]$default = 0  

    #Present choice option to user  
    $userchoice = $host.ui.PromptforChoice("Warning","Please select to use Alternate Credentials or current credentials to run command",$choice,$default)  

    #$workingDir = $PSCommandPath
    #$PSCommandPath

    Write-Debug "Selection: $userchoice"  

    #Determine action to take  
    Switch ($Userchoice)  
    {  
        0  
        {  
            #Prompt for alternate credentials  
            Write-Verbose "Prompting for Alternate Credentials"  
            $Credential = Get-Credential  
            #Write-Output $Credential 
           #We are not running "as Administrator" - so relaunch as administrator
            Start-Process powershell.exe -ArgumentList "$PSCommandPath" -Credential $Credential
            #-WorkingDirectory $workingDir
            exit   

        }  
        1  
        {  
            #Continue using current credentials  
            Write-Verbose "Using current credentials"  
            Write-Output "CurrentUser" 

        }  
    }          

}  
Else   
{  
            Write-Verbose "Passed Administrator check" 
            #$Host.UI.RawUI.WindowTitle = "Custom Powershell Environment" +
            #$Host.UI.RawUI.BackgroundColor = "DarkBlue" 
}  
}

with this just put it in the top of your script and call the function, and you will need to change the group that it checks to know if you are an admin or not, I was using an AD group to check since it was a more functional way for me.

Upvotes: 1

Related Questions