使用提升的命令运行powershell脚本

时间:2015-09-28 18:38:15

标签: windows powershell

我有一个autologon Powershell脚本,当我双击它时,我想以管理员身份运行。我尝试使用不同的脚本,但我没有运气。

例如:

Start-Process PowerShell –Verb RunAs

将以管理员身份打开另一个Powershell屏幕,但没有我想要运行的原始脚本:

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

任何想法我怎样才能让它发挥作用?

3 个答案:

答案 0 :(得分:1)

你很幸运,因为我在这个问题上争论了一段时间,你需要做的就是让它记下它的位置以及何时开始备份shell作为管理员它需要执行脚本

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" 
}  
}

这只是把它放在你的脚本的顶部并调用该函数,你需要更改它检查的组,知道你是否是管理员,我正在使用AD组进行检查,因为它对我来说是一种更实用的方式。

答案 1 :(得分:1)

我之前使用过以下内容作为管理员重新启动脚本,但没有停止UAC提示:

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"
    }
}

答案 2 :(得分:0)

我实际上在我的上面使用了这个脚本,它运行得很好。

# ##########################################
# 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
}