2015-09-28 5 views
0

У меня есть сценарий autologon Powershell, который я бы хотел запустить как admin, когда я дважды нажимаю на него. Я пытался использовать разные сценарии, но мне не повезло.Сценарий сценария запуска с повышенной командой

Например:

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 

Любая идея, как я могу получить эту работу?

ответ

1

Вам повезло, потому что я долгое время боролся с этой проблемой, и вам нужно сделать все, чтобы она запомнила, где она находится, и когда она начинает резервное копирование оболочки в качестве администратора, ей необходимо выполнить скрипт.

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 группы чтобы проверить, так как это был более функциональный способ для меня.

+0

Как я могу назвать функцию с помощью этого скрипта? –

+0

Вы просто называете 'test-isadmin' в первой строке вашего скрипта – Luke

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