PowerShell을 사용하여 관리자 권한으로 명령을 실행 하시겠습니까? 입력하지 않고

시스템 관리자 인 경우 배치 스크립트를 마우스 오른쪽 버튼으로 클릭하고 관리자 암호를 입력하지 않고 관리자로 실행할 수 있습니까?

PowerShell 스크립트 로이 작업을 수행하는 방법이 궁금합니다. 비밀번호를 입력하고 싶지 않습니다. 마우스 오른쪽 버튼을 클릭하여 실행 관리자 방식 을 모방하고 싶습니다 .

지금까지 읽은 모든 내용은 관리자 암호를 제공해야합니다.



답변

현재 콘솔이 상승되어 있지 않고 수행하려는 작업에 상승 된 권한이 필요한 경우 다음 Run as administrator옵션을 사용하여 powershell을 시작할 수 있습니다 .

PS> Start-Process powershell -Verb runAs


답변

다음은 Shay Levi의 제안에 대한 추가 사항입니다 (스크립트 시작 부분에 다음 행을 추가하십시오).

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

{
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}

이로 인해 현재 스크립트가 관리자 모드에서 새 powershell 프로세스로 전달됩니다 (현재 사용자가 관리자 모드에 액세스 할 수 있고 스크립트가 관리자로 시작되지 않은 경우).


답변

자체 승격 PowerShell 스크립트

Windows 8.1 / PowerShell 4.0 이상

한 줄 🙂

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

# Your script here


답변

Benjamin Armstrong은 자체 상승 PowerShell 스크립트에 대한 훌륭한 기사를 게시했습니다 . 그의 코드에는 몇 가지 사소한 문제가 있습니다. 의견에 제안 된 수정 사항을 기반으로 수정 된 버전은 다음과 같습니다.

기본적으로 현재 프로세스와 관련된 ID를 가져 와서 관리자인지 확인하고, 그렇지 않은 경우 관리자 권한으로 새 PowerShell 프로세스를 만들고 이전 프로세스를 종료합니다.

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
    $newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

# Run your code that needs to be elevated here...

Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");


답변

*.bat두 번 클릭하면 관리자 권한으로 powershell 스크립트를 실행 하는 배치 파일 ( )을 만들 수 있습니다 . 이 방법으로 powershell 스크립트에서 아무것도 변경하지 않아도됩니다. 이렇게하려면 powershell 스크립트의 이름과 위치가 같은 배치 파일을 만든 후 다음 내용을 입력하십시오.

@echo off

set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1

powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%\`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

그게 다야!

설명은 다음과 같습니다.

powershell 스크립트가 경로에 있다고 가정하면 C:\Temp\ScriptTest.ps1배치 파일에 경로가 있어야합니다 C:\Temp\ScriptTest.bat. 누군가이 배치 파일을 실행하면 다음 단계가 수행됩니다.

  1. cmd는 명령을 실행합니다

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
  2. 새로운 powershell 세션이 열리고 다음 명령이 실행됩니다.

    Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
  3. 관리 권한이있는 다른 새 powershell 세션이 system32폴더 에서 열리고 다음 인수가 전달됩니다.

    -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
  4. 다음 명령은 관리자 권한으로 실행됩니다.

    cd "C:\Temp"; & ".\ScriptTest.ps1"

    스크립트 경로와 이름 인수가 큰 따옴표로 묶이면 공백이나 작은 따옴표 문자 ( ')를 포함 할 수 있습니다 .

  5. 현재 폴더가에서 system32로 변경되고 C:\Temp스크립트 ScriptTest.ps1가 실행됩니다. 매개 변수 -NoExit가 전달 되면 powershell 스크립트에서 예외가 발생하더라도 창은 닫히지 않습니다.


답변

다음 은 작업 디렉토리를 유지하는 Powershell 스크립트의 자체 상승 스 니펫입니다 .

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}

# Your script here

경로 관련 작업을 수행하는 스크립트의 경우 작업 디렉토리를 유지하는 것이 중요합니다. 다른 모든 답변은이 경로를 유지하지 않으므로 나머지 스크립트에서 예기치 않은 오류가 발생할 수 있습니다.

자체 상승 스크립트 / 스 니펫을 사용하지 않고 대신 관리자로 스크립트를 시작하는 쉬운 방법을 원한다면 (예 : Explorer 컨텍스트 메뉴에서) https : // stackoverflow .com / a / 57033941 / 2441655


답변

사용

#Requires -RunAsAdministrator

아직 언급되지 않았습니다. PowerShell 4.0 이후로만 존재하는 것 같습니다.

http://technet.microsoft.com/en-us/library/hh847765.aspx

이 스위치 매개 변수가 require 문에 추가되면 스크립트를 실행중인 Windows PowerShell 세션을 관리자 권한으로 시작해야합니다 (관리자 권한으로 실행).

나에게 이것은 이것에 관한 좋은 방법처럼 보이지만 아직 현장 경험이 확실하지 않습니다. PowerShell 3.0 런타임은이를 무시하거나 더 나쁜 경우 오류를 발생시킵니다.

스크립트가 비 관리자로 실행되면 다음 오류가 발생합니다.

‘StackOverflow.ps1’스크립트에는 관리자로 실행하기위한 “#requires”문이 포함되어 있으므로 실행할 수 없습니다. 현재 Windows PowerShell 세션이 관리자로 실행되고 있지 않습니다. 관리자 권한으로 실행 옵션을 사용하여 Windows PowerShell을 시작한 다음 스크립트를 다시 실행하십시오.

+ CategoryInfo          : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ScriptRequiresElevation