PowerShell은 관리자로 PowerShell을 시작하는 것과 다릅니다.

PowerShell은 관리자로 PowerShell을 시작하는 것과 다릅니다.

관리자 권한 PowerShell 콘솔에서 아래 명령을 실행하면 가상 드라이브가 생성되고 생성됩니다.

New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB

그러나 권한이 상승되지 않은 쉘에서 아래 명령을 실행하십시오.

runas /user:$env:userdomain\$env:username "New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB"

비밀번호를 묻는 메시지를 표시하고 명령 실행을 시도합니다.

Enter the password for dom1\user1:  
Attempting to start New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB as user "dom1\user1" ...

하지만 오류가 발생합니다.

RUNAS ERROR: Unable to run - New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB
2: The system cannot find the file specified.

권한이 상승되지 않은 쉘에서 이 명령을 실행하려면 어떻게 해야 합니까?

답변1

처럼PetSerAl제안, 사용하면 runas /user:$env:userdomain\$env:username "powershell -NoExit", "Get-VM"효과가 있습니다.

그러나 장기적으로 내용을 덜 장황하게 유지하기 위해 다음을 수행했습니다.

관리자 권한 PowerShell 세션에서 명령을 실행하는 기능입니다.

psudo.ps1:
function psudo ([string]$cmd = "echo Hello!") {
    Start-Process -FilePath "powershell" -Verb RunAs -ArgumentList "-NoExit", $cmd
}

if ($args[0] -eq $null) {
    $cmd = "echo 'please provide powershell command to execute in elevated shell as a quoted string'"
} else {
    $cmd = $args[0]    
}

psudo $cmd

psudo승격되지 않은 쉘에서 실행 :

psudo "echo 'This is a test using psudo'"

열린 상태로 높은 콘솔이 생성됩니다.

This is a test using psudo

권한 상승이 필요한 psudoPowerShell cmdlet을 실행하기 위해 실행 중 :Get-VM

psudo Get-VM

열린 상태로 높은 콘솔이 생성됩니다.

Name    State CPUUsage(%) MemoryAssigned(M) Uptime   Status             Version
----    ----- ----------- ----------------- ------   ------             -------
test_vm Off   0           0                 00:00:00 Operating normally 9.0

Invoke-Command이 기능을 사용하여 동일한 콘솔에서 결과를 볼 수 있고 관리자로서 명령을 실행할 때마다 별도의 창을 열 필요가 없었으면 좋겠습니다 .

그러나 다음과 유사한 버전이 작동하지 못했습니다.

자격 증명 가져오기 및 저장

getcreds.ps1내 변수에도 있는 사용자 폴더의 디렉터리에 저장된 스크립트 파일입니다 $env:PATH. 이렇게 하면 비밀번호를 한 번만 입력하고 보안 정책을 위해 비밀번호를 변경할 때마다 한 번만 입력합니다.

getcreds.ps1:
function getcurcreds {
    $pwd = Get-Content "$HOME\ExportedPassword.txt" | ConvertTo-SecureString
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList "$env:USERDOMAIN\$env:username", $pwd

    Add-Type -AssemblyName System.DirectoryServices.AccountManagement -ErrorAction Stop
    $Domain = $env:USERDOMAIN
    $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
    $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct, $Domain
    $validated = $pc.ValidateCredentials($cred.UserName, $cred.GetNetworkCredential().password)

    if (-Not $validated) {
        $cred = Get-Credential -UserName "$env:USERDOMAIN\$env:username" -Message "WK NA password"
        Set-Content "$HOME\ExportedPassword.txt" ($cred.Password | ConvertFrom-SecureString)
    }
    $cred
}

getcurcreds

승격된 PowerShell 세션에서 명령을 실행하고 현재 승격되지 않은 PowerShell 세션에 결과를 반환하는 함수 수정.

psudo.ps1:
$cred = getcreds

function psudo ([string]$cmd = "echo Hello!") {
    $cmdBlk = [scriptblock]::Create(
        "Start-Process -FilePath 'powershell' -Verb RunAs -ArgumentList '-NoExit', $cmd"
    )
    Invoke-Command -ComputerName $env:computername $cmdBlk -RunAsAdministrator -Credential $cred
}

다음과 같은 오류가 계속 발생합니다.

Invoke-Command : Parameter set cannot be resolved using the specified named parameters.

또는

cmdlet Invoke-Command at command pipeline position 1
Supply values for the following parameters:
ContainerId[0]:

관련 정보