【问题标题】:Run powershell script with elevated command使用提升的命令运行 powershell 脚本
【发布时间】:2015-09-28 18:38:15
【问题描述】:

我有一个自动登录 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

知道如何让它工作吗?

【问题讨论】:

    标签: windows powershell


    【解决方案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 组进行检查,因为它对我来说是一种更实用的方式。

    【讨论】:

    • 如何用这个脚本调用函数?
    • 您只需在脚本的第一行调用test-isadmin
    【解决方案2】:

    我之前使用以下命令以管理员身份重新启动脚本,但没有停止 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"
        }
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        • 2021-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多