Running a command as Administrator using PowerShell?

后端 未结 26 2911
粉色の甜心
粉色の甜心 2020-11-22 09:41

You know how if you\'re the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator p

26条回答
  •  感情败类
    2020-11-22 10:04

    You need to rerun the script with administrative privileges and check if the script was launched in that mode. Below I have written a script that has two functions: DoElevatedOperations and DoStandardOperations. You should place your code that requires admin rights into the first one and standard operations into the second. The IsRunAsAdmin variable is used to identify the admin mode.

    My code is an simplified extract from the Microsoft script that is automatically generated when you create an app package for Windows Store apps.

    param(
        [switch]$IsRunAsAdmin = $false
    )
    
    # Get our script path
    $ScriptPath = (Get-Variable MyInvocation).Value.MyCommand.Path
    
    #
    # Launches an elevated process running the current script to perform tasks
    # that require administrative privileges.  This function waits until the
    # elevated process terminates.
    #
    function LaunchElevated
    {
        # Set up command line arguments to the elevated process
        $RelaunchArgs = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" -IsRunAsAdmin'
    
        # Launch the process and wait for it to finish
        try
        {
            $AdminProcess = Start-Process "$PsHome\PowerShell.exe" -Verb RunAs -ArgumentList $RelaunchArgs -PassThru
        }
        catch
        {
            $Error[0] # Dump details about the last error
            exit 1
        }
    
        # Wait until the elevated process terminates
        while (!($AdminProcess.HasExited))
        {
            Start-Sleep -Seconds 2
        }
    }
    
    function DoElevatedOperations
    {
        Write-Host "Do elevated operations"
    }
    
    function DoStandardOperations
    {
        Write-Host "Do standard operations"
    
        LaunchElevated
    }
    
    
    #
    # Main script entry point
    #
    
    if ($IsRunAsAdmin)
    {
        DoElevatedOperations
    }
    else
    {
        DoStandardOperations
    }
    

提交回复
热议问题