지금까지 관리자 암호를 다 읽었어요 제공해야 합니다.
다음은 추가 셰이 Levi& # 39 의 제안 (추가하기만 이러한 선의 맨 앞에 스크랩트):
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 프로세스 관리자 모드로 경우 현재 사용자가 관리자 모드 및 스크립트는 실행되지 액세스하려면 관리자로).
윈도우 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
벤햐민 암스트롱 게시하기를 ui_policytable_java_spe_policy 뛰어난 관한 기사를 자체 높이는 powershell 스크립트에만. 몇 가지 사소한 문제가 있을 수 있는 그의 코드입니다. 수정된 버전을 바탕으로 수정 제안됩니다 논평에서 아래에 있다.
기본적으로 it gets identity 연관됨 인스턴스인지 관리자임을 현재 공정, 검사, 만일 이 isn& # 39, t 는 프로세스 관리자 권한 및 프로세스를 통해 새로운 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 script.T , 변경하지 않아도 이렇게 배치 파일 생성 및 위치 그리곤요 동일팔레트에 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 '길' '길' 이 있어야 합니다. 누군가 이 배치 파일을 실행할 때, 다음 단계는 발생합니다.
powershell - - - -;; - 에스쿠션폴리시 우회 시작 프로세스 powershell \" " 명령을 명령 '\', '), cd \" 노프로피레 노이스트 \" c:\temp\ \"; &. \ ',', '\" \" .\ScriptTest.ps1\ \" \"; - 동사 RunAs".
cd " C:\Temp";; &. " .\ScriptTest.ps1";
일단 스크립트입니다 연산뿐 인수가 경로와 이름을 인용, 그들은 포함할 수 있는 공간 또는 작은따옴표 문자 ('& # 39;').
일부 레지스트리로 얻을 수 있다, 실행하십시오 administrator" " 엔트리입니다 쉽게 추가할 수 있습니다. 컨텍스트로 .ps1 '메뉴' 파일:
New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" `
-Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"'
(업데이트되도록 맞추기바인딩 간단해진다는 스크립트입니다 @Shay 에서)
기본적으로 '세트' 를 사용하여 스크립트입니다 emc. HKCR:\Microsoft.PowershellScript.1\Shell\runas\command 기본값입니다 호출하십시오 Powershell.
사용
아직 적이 없다고 밝혔다. 디렉토리에만 PowerShell 4.0 이후 있을 것으로 보인다.
http://technet.microsoft.com/en-us/library/hh847765.aspx
이 스위치에서는 > 파라메트가 기술서임을 单捞磐啊 추가할 경우, windows PowerShell 세션용으로 틀렸다니까 있는 it 지정합니다. 스크립트를 실행하는 사용자 권한 높은 함께 시작되어야 합니다. (관리자 권한으로 실행).
이에 대해 좋은 길을 갈 다는일은, 이 같다, 그러나 I& # 39 m not 잘 현장 경험 하지 않았다. 아마도 이, 심지어 더 무시하시겠습니까 powershell 3.0gb 런타임을 제공할 오류:.
다음 실행될 때 스크립트입니다 비관리자로 오류: 주어진:
>. # 39, & # 39 스크립트입니다 StackOverflow.ps1&. 때문에 실행할 수 없는 있습니다. >. # requires" "; 관리자 권한으로 실행을 위한 기술서임을. 현재 >. 윈도우 파워셸 세션 관리자 권한으로 실행되고 있지 않습니다. 시작 >. 관리자 권한으로 실행 후 옵션을 사용하여 windows PowerShell >. 다시 스크립트입니다 실행하십시오.
>. + 카테고리앵포: 페르미시오수리드: [], 파렌터 콩탱세로레코드렉세페시옹 (StackOverflow.ps1:String) >. + 파울리퀄리피데로리드: 스크리프트레키레세르베이션
조너선 및 코드 올린 내 업무에 셰이 레비 않았다.
부탁일세 작업 코드 (아래 참조).
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user for Admin rights"
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
필요한 경우 관리자 권한을 가진 실행하십시오 스크립트입니다 출범한 것은 확인할 수 있는 모드. 나는 기록되었으므로 아래에 있는 스크립트입니다 두 가지 기능을 가집니다. 및 도스탄다르도프라티온스 도리바이도프라티온스. 첫 번째 및 표준 코드 관리 권한이 꽂으십시오 배치하십시오 합니다 필요로 하는 사업을 두 번째. 아뤼나사드민 가변입니다 식별하는 데 대한 관리 모드.
내 코드를 작성할 때 자동으로 생성됩니다 Microsoft 에서 푸십시오 백업이었습니다 간편화된 스크립트입니다 app 패키지의 윈도우 스토어 앱.
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
}
내 추가 2 센트. 항상 내 간단한 기반한 확장본을 네트워크없음 세션이고 작동하는 중 현재까지 Windows 7 / 윈도우 10. 왜 어렵게 통해 it?
if (!(net session)) {$path = "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}
맨 위로 추가하기만 스크립트입니다 관리자 권한으로 실행 예정이다.
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
보존 작업을 수행하는 작업 디렉토리에 스크립트입니다 상대 경로를 중요합니다. 거의 모든 다른 답을 이 경로를 유지하지 않음, 예상치 못한 오류를 유발할 수 있는 나머지 스크립트입니다.
또한 응용 프로그램을 인력용 열 수 있는 경우, 물론이겠지 관리자 계정 (administrator,
파일, right >) 을 찾습니다. 속성 >. 짧은보기 >. Advanced Administrator_ _Run 확인할 수 있다
확인을 누릅니다.
이 중 ',' C:\Users\" username" \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows 대화상자에서는 짧은보기 , PowerShell PowerShell 합니다. 실제 & # 39, 여전히 너무 다른 위치로 댁이라면 호출하십시오 exe& # 39. ('%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe').
이후 PowerShell 은 사용자 프로파일 제어됨을 권한만으로 때 우려하고 있다. 뭔가 할 수 있는 권한이 있습니다 / 프로파일할 sername 경우, 그렇게 할 수 있는 것과 그 밑에다 프로파일할 PowerShell 일반적으로 잘 알려져 있다. 말하였노라 쉽게 이해할 수 있다는 것이 바로 아래에 위치한 변경하십시오 만한 예를 들어, ',' 사용자 프로파일을 C:\Users\", username" \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell.
마우스 오른쪽 단추로 클릭하고 속성을 클릭합니다. Advanced" 선택하시려면 "; 아래 버튼를 " Shortcut"; 탭 바로 아래에 있는 이 " Comments"; 텍스트 필드는 오른쪽에 버튼, " 인접해야 다른 두 파일 열기 Location"; , 변경 및 " Icon" 것으로 조사됐다.
,) 로 읽는 " 실행하십시오 administrator" 확인란 확인합니다. ,,, 그럼 < 선택하시려면 < kbd> OK< /kbd> kbd> Apply< /kbd>; 그리고,, < kbd> OK< /kbd>. # 39, & # 39, Windows PowerShell& 아이콘을 마우스 오른쪽 단추로 클릭합니다 다시 한 번 ',' 를 선택하고, \AppData\Roaming\Microsoft\Windows\Start 위치한 C:\Users\" username" Menu\Programs\Windows PowerShell ", 핀 시작 Menu/Taskbar".
이제 이 아이콘을 클릭할 때마다 호출하십시오 에스컬레이션을 UAC 를 위한 것으로 보인다. # 39, & # 39 를 선택한 후, YES& PowerShell 콘솔입니다 될 것이며, Administrator" 레이블된 " 오픈 되어 있습니다. 화면 상단에.
가서 한 단계 더. 바로 가기 아이콘을 마우스 오른쪽 단추를 클릭할 수 있다면 같은 위치를 지정할 수 있는 Windows PowerShell 프로필에 있는 키보드 단축키 못하며창조된 똑같이 따라 최근 추가되든지 클릭했으면 더블클릭하십시오. 그렇다면 썻냐면 " 짧은보기 Key"; 넣어 키보드 키 / 버튼 조합 다음과 같습니다. < kbd> Ctrl< /kbd>;;; + < kbd> Alt< /kbd>;;; + P< kbd> P< /kbd>;;; (예를 PowerShell) . 선택하시려면 < kbd> Apply< /kbd>;;; 그리고,, < kbd> OK< /kbd>.
이제 네가 해야 할 일은 그 버튼을 누르지 조합으로의 UAC 가 지정한 뒤, & # 39, 그대가 보게 호출되었을 확보하십시오 선택한 YES& # 39. powershell 콘솔입니다 나타나고, Administrator" " 보실 수 있습니다. 제목 표시줄에 표시됩니다.
이 비헤이비어는 by design. # 39, 이후 여러 가지 계층의 Microsoft 상행담관염이라고 didn& .ps1 t want to be 파일을 최신 전자 메일 바이러스. 어떤 사람들은 이 개념을 찾을 수 있는 업무 자동화, 이는 매우 엇회전식 공정한인가요. 이 것이 Vista+ 보안 모델을 " de-automate"; 따라서 사용자가 그땅은 저들이요 셨으며 있다.
하지만, 제가 용의자요 시작하면 반드시 배치 파일을 실행할 수 없는 높은 powershell 자신을 요청하는 닫으십시오 암호란이 때까지 다시 powershell.
다음은 가깝냐고, 하지만 조금 더 작동합니까 필요 이상으로 많은 있습니다.
스크립트는 실행됩니다 Administrator" " 가기를 만들고, 이를 구성하고,:
문제의 @pgk 및 @Andrew 오드리 답변 & # 39 의 경우, 특별히 스크립트입니다 매개변수입니다 때 필수입니다. 다음 방법을 사용하여 이 문제를 해결할 수 있습니다.
이 경우 어떻게 포트 ComputerName 경식도 스크립트입니다 약간만이라도 코드 및 필수 매개변수입니다:
[CmdletBinding(DefaultParametersetName='RunWithPowerShellContextMenu')]
param (
[parameter(ParameterSetName='CallFromCommandLine')]
[switch] $CallFromCommandLine,
[parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
[parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
[string] $ComputerName,
[parameter(Mandatory=$false, ParameterSetName='RunWithPowerShellContextMenu')]
[parameter(Mandatory=$true, ParameterSetName='CallFromCommandLine')]
[UInt16] $Port
)
function Assert-AdministrativePrivileges([bool] $CalledFromRunWithPowerShellMenu)
{
$isAdministrator = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if ($isAdministrator)
{
if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
{
# Must call itself asking for obligatory parameters
& "$PSCommandPath" @script:PSBoundParameters -CallFromCommandLine
Exit
}
}
else
{
if (!$CalledFromRunWithPowerShellMenu -and !$CallFromCommandLine)
{
$serializedParams = [Management.Automation.PSSerializer]::Serialize($script:PSBoundParameters)
$scriptStr = @"
`$serializedParams = '$($serializedParams -replace "'", "''")'
`$params = [Management.Automation.PSSerializer]::Deserialize(`$serializedParams)
& "$PSCommandPath" @params -CallFromCommandLine
"@
$scriptBytes = [System.Text.Encoding]::Unicode.GetBytes($scriptStr)
$encodedCommand = [Convert]::ToBase64String($scriptBytes)
# If this script is called from another one, the execution flow must wait for this script to finish.
Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -EncodedCommand $encodedCommand" -Verb 'RunAs' -Wait
}
else
{
# When you use the "Run with PowerShell" feature, the Windows PowerShell console window appears only briefly.
# The NoExit option makes the window stay visible, so the user can see the script result.
Start-Process -FilePath 'powershell' -ArgumentList "-ExecutionPolicy Bypass -NoProfile -NoExit -File ""$PSCommandPath""" -Verb 'RunAs'
}
Exit
}
}
function Get-UserParameters()
{
[string] $script:ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a computer name:', 'Testing Network Connection')
if ($script:ComputerName -eq '')
{
throw 'The computer name is required.'
}
[string] $inputPort = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a TCP port:', 'Testing Network Connection')
if ($inputPort -ne '')
{
if (-not [UInt16]::TryParse($inputPort, [ref]$script:Port))
{
throw "The value '$inputPort' is invalid for a port number."
}
}
else
{
throw 'The TCP port is required.'
}
}
# $MyInvocation.Line is empty in the second script execution, when a new powershell session
# is started for this script via Start-Process with the -File option.
$calledFromRunWithPowerShellMenu = $MyInvocation.Line -eq '' -or $MyInvocation.Line.StartsWith('if((Get-ExecutionPolicy')
Assert-AdministrativePrivileges $calledFromRunWithPowerShellMenu
# Necessary for InputBox
[System.Reflection.Assembly]::Load('Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a') | Out-Null
if ($calledFromRunWithPowerShellMenu)
{
Get-UserParameters
}
# ... script code
Test-NetConnection -ComputerName $ComputerName -Port $Port
나는 이 솔루션을 활용하면 다음과 같습니다. 기록을 통해 stdout / 표준에러출력 피쳐이고 종료하십시오 올바르게 부모 프로세스가 코드를 가공 처리한다. 경로 / 파일_이름 내용을 조정할 필요가 있습니다.
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "powershell"
$pinfo.Arguments = "& '" + $myinvocation.mycommand.definition + "'"
$pinfo.Verb = "RunAs"
$pinfo.RedirectStandardError = $false
$pinfo.RedirectStandardOutput = $false
$pinfo.UseShellExecute = $true
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript.txt"
Remove-Item "C:/jenkins/transcript.txt"
Exit $p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript.txt"
}
# Rest of your script goes here, it will be executed with elevated privileges
나는 할 수 있는 방법이 있습니다.
Open your 스크립트입니다 배치 파일을 만듭니다.
@echo off
START "" "C:\Scripts\ScriptName.ps1"
그 후, 바탕 화면에 바로 가기를 만들 말하도다 ( - 새로운 >, 마우스 오른쪽 단추로 클릭합니다. 짧은보기 ).
이 후 붙여넣습니다 꽂으십시오 위치:
C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat
첫 번째 오프닝 때 한 번 암호를 입력할 수 있습니다. 이렇게 하면 다음 저장하면 Windows 자격증명이 감독이다.
그 후 이 관리자 권한으로 실행 수 있어야 합니다 입력할 필요 없이 아이디나 비밀번호 관리자.
그 방법은 다음과 같습니다 실행하십시오 명령 및 windows powershell 수집하십시오 높은 출력 형식을 배치 파일 내에서 단일 명령 (이리에 ps1 powershell 스크립트입니다 쓰는 것이 아니다). "' & # 39 powershell - -;; - " 아르구멍리스트 powershell 시작 프로세스 명령을 명령 (프레젠테이션이든 프로세스 postgres 객체 선택 삼중평균 객체 선택 - 인덱스화할 0) - $ env:temp\camp-postgres.tmp" ascii 인코딩을 스파스 아웃해야 파일. - 동사 RunAs& # 39. "' 내가 처음 출시 후 그 위에 높은 프롬프트합니다 powershell 볼 수 있는 다른 powershell (서브노드 쉘로) 를 시작할 함장님이요 실행하십시오 하나님께용서를