あなたがシステムの管理者ユーザーで、たとえばバッチ スクリプトを右クリックして、管理者パスワードを入力せずに管理者として実行できるとしたら、どうすればよいでしょうか。
PowerShell スクリプトでこれを行う方法を考えています。パスワードを入力する必要はありません。右クリックの [管理者として実行]メソッドを模倣したいだけです。
これまでに読んだものはすべて、管理者パスワードを入力する必要があります。
あなたがシステムの管理者ユーザーで、たとえばバッチ スクリプトを右クリックして、管理者パスワードを入力せずに管理者として実行できるとしたら、どうすればよいでしょうか。
PowerShell スクリプトでこれを行う方法を考えています。パスワードを入力する必要はありません。右クリックの [管理者として実行]メソッドを模倣したいだけです。
これまでに読んだものはすべて、管理者パスワードを入力する必要があります。
現在のコンソールが昇格されておらず、実行しようとしている操作に昇格された特権が必要な場合は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 プロセスに渡されます (現在のユーザーが管理者モードにアクセスでき、スクリプトが管理者として起動されていない場合)。
Windows 8.1 / PowerShell 4.0 +
1行:)
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");
作業ディレクトリを保持する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
作業ディレクトリを保持することは、パス相対操作を実行するスクリプトにとって重要です。他のほとんどすべての回答ではこのパスが保持されないため、スクリプトの残りの部分で予期しないエラーが発生する可能性があります。
自己昇格スクリプト/スニペットを使用せず、代わりに管理者としてスクリプトを起動する簡単な方法が必要な場合 (たとえば、エクスプローラーのコンテキストメニューから)、ここで私の他の回答を参照してください: https://stackoverflow .com/a/57033941/2441655
ダブルクリックすると管理者権限で PowerShell スクリプトを実行するバッチ ファイル (*.bat) を作成できます。この方法では、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が必要です。誰かがこのバッチ ファイルを実行すると、次の手順が実行されます。
cmdはコマンドを実行します
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
新しい PowerShell セッションが開き、次のコマンドが実行されます。
Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
管理者権限を持つ別の新しい PowerShell セッションがsystem32フォルダーで開き、次の引数がそれに渡されます。
-ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
次のコマンドは、管理者権限で実行されます。
cd "C:\Temp"; & ".\ScriptTest.ps1"
スクリプト パスと名前の引数を二重引用符で囲むと、スペースまたは単一引用符文字 (') を含めることができます。
現在のフォルダーがsystem32からC:\Tempに変更され、スクリプトScriptTest.ps1
が実行されます。パラメータ-NoExit
が渡されると、PowerShell スクリプトが何らかの例外をスローしたとしても、ウィンドウは閉じられません。
使用する
#Requires -RunAsAdministrator
まだ明言されていません。PowerShell 4.0以降にのみ存在するようです。
http://technet.microsoft.com/en-us/library/hh847765.aspx
このスイッチ パラメーターを requires ステートメントに追加すると、スクリプトを実行している Windows PowerShell セッションを昇格されたユーザー権限 (管理者として実行) で開始する必要があることが指定されます。
私には、これは良い方法のように思えますが、現場での経験についてはまだ確信が持てません。PowerShell 3.0 ランタイムはおそらくこれを無視するか、さらに悪いことにエラーを出します。
スクリプトを非管理者として実行すると、次のエラーが表示されます。
スクリプト 'StackOverflow.ps1' は、管理者として実行するための "#requires" ステートメントが含まれているため、実行できません。現在の Windows PowerShell セッションは管理者として実行されていません。[管理者として実行] オプションを使用して Windows PowerShell を起動し、スクリプトを再度実行してみてください。
+ CategoryInfo : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ScriptRequiresElevation
いくつかのレジストリエントリを簡単に追加して、ファイルの「管理者として実行」コンテキストメニューを取得.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からより単純なスクリプトに更新されました)
基本的に、HKCR:\Microsoft.PowershellScript.1\Shell\runas\command
Powershellを使用してスクリプトを呼び出すためのデフォルト値を設定します。
Jonathan と Shay Levy が投稿したコードはうまくいきませんでした。
以下の作業コードを見つけてください。
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"
管理者権限でスクリプトを再実行し、スクリプトがそのモードで起動されたかどうかを確認する必要があります。以下に、 DoElevatedOperationsとDoStandardOperationsの 2 つの関数を持つスクリプトを記述しました。管理者権限を必要とするコードを最初のコードに配置し、標準操作を 2 番目のコードに配置する必要があります。IsRunAsAdmin変数は、管理モードを識別するために使用されます。
私のコードは、Windows ストア アプリのアプリ パッケージを作成するときに自動的に生成される Microsoft スクリプトからの簡略化された抜粋です。
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
}
この動作は仕様です。Microsoft は .ps1 ファイルを最新の電子メール ウイルスにすることを本当に望んでいなかったため、複数のセキュリティ層があります。一部の人々は、これがタスク自動化の概念そのものに反していると感じていますが、これは公正なことです。Vista+ のセキュリティ モデルは、物事を「非自動化」することであり、ユーザーがそれらを受け入れるようにします。
ただし、powershell 自体を昇格して起動すると、powershell を閉じるまで、パスワードを再度要求することなくバッチ ファイルを実行できるはずです。
ここでの多くの答えは近いですが、必要以上の作業が必要です。
スクリプトへのショートカットを作成し、「管理者として実行」に構成します。
Properties...
Target
から編集<script-path>
powershell <script-path>
Run as administrator
私はこれを行う方法を見つけました...
スクリプトを開くバッチ ファイルを作成します。
@echo off
START "" "C:\Scripts\ScriptName.ps1"
次に、デスクトップにショートカットを作成します(右クリックNew -> Shortcut)。
次に、これを次の場所に貼り付けます。
C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat
初めて開くときは、パスワードを一度入力する必要があります。これにより、Windows 資格情報マネージャーに保存されます。
この後、管理者のユーザー名またはパスワードを入力しなくても、管理者として実行できるようになります。
C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell
PowerShellのショートカットが存在する場所です。それも、実際の「exe」を呼び出すために別の場所に移動します ( %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
)。
アクセス許可が関係する場合、PowerShell はユーザー プロファイルによって駆動されるためです。ユーザー名/プロファイルに何かを実行する権限がある場合、そのプロファイルの下で、通常、PowerShell でも同様に実行できます。そうは言っても、ユーザープロファイルの下にあるショートカットを変更することは理にかなっていますC:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell
。
右クリックしてプロパティをクリックします。「ショートカット」タブの下にある「詳細」ボタンをクリックします。「コメント」テキスト フィールドのすぐ下にあり、「ファイルの場所を開く」と「アイコンを変更」という 2 つのボタンの右側にそれぞれ隣接しています。
「管理者として実行」というチェックボックスをオンにします。をクリックしOKてから、 をクリックApplyしOKます。にある [Windows PowerShell] というラベルの付いたアイコンをもう一度右クリックし、C:\Users\"username"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell
[スタート メニュー/タスク バーにピン留めする] を選択します。
そのアイコンをクリックするたびに、エスカレーションのためにUACが呼び出されます。[はい] を選択すると、PowerShell コンソールが開き、画面の上部に [管理者] というラベルが表示されます。
さらに一歩進んで、Windows PowerShell のプロファイルの場所にある同じアイコン ショートカットを右クリックし、最近追加したアイコンをクリックした場合とまったく同じことを行うキーボード ショートカットを割り当てることができます。したがって、「ショートカット キー」と表示されている箇所には、Ctrl+ Alt+ P P(PowerShell の場合) のようなキーボード キー/ボタンの組み合わせを入力します。と をクリックApplyしOKます。
割り当てたボタンの組み合わせを押すだけで、UAC が呼び出されます。[はい] を選択すると、PowerShell コンソールが表示され、タイトル バーに「管理者」と表示されます。
私が見つけた最も信頼できる方法は、自己昇格 .bat ファイルにラップすることです。
@echo off
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
CD %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
EXIT
:ADMINTASKS
powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"
EXIT
.bat は、既に管理者であるかどうかを確認し、必要に応じてスクリプトを管理者として再起動します。また、 の 4 番目のパラメーターを にShellExecute()
設定して無関係な「cmd」ウィンドウが開くのを防ぎます0
。
簡単すぎることがわかりました。管理者として cmd を実行するだけです。次にexplorer.exe
、入力してEnterキーを押します。Windows Explorerが開きます。実行する PowerShell スクリプトを右クリックし、[PowerShell で実行] を選択します。これにより、PowerShell が管理者モードで起動されます。
ポリシーの実行を有効にするよう求められる場合があります。Y と入力して Enter キーを押します。これで、スクリプトは PowerShell で管理者として実行されます。すべて赤で表示される場合は、ポリシーがまだ有効になっていないことを意味します。その後、もう一度やり直してください。正常に動作するはずです。