chr*_*ips 246 powershell administrator
您知道如果您是系统的管理用户,您可以右键单击"说",批处理脚本并以管理员身份运行它而不输入管理员密码吗?
我想知道如何使用PowerShell脚本执行此操作.我不想输入密码; 我只是想模仿右键单击Run As Administrator方法.
到目前为止我读到的所有内容都要求您提供管理员密码.
Sha*_*evy 272
如果当前控制台未升级并且您尝试执行的操作需要提升权限,则可以使用"以管理员身份运行"选项启动PowerShell
PS> Start-Process powershell -Verb runAs
Run Code Online (Sandbox Code Playgroud)
小智 105
这是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
}
Run Code Online (Sandbox Code Playgroud)
这会导致当前脚本以管理员模式传递给新的PowerShell进程(如果当前用户可以访问管理员模式,并且脚本未以管理员身份启动).
Jay*_*end 92
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
Run Code Online (Sandbox Code Playgroud)
And*_*dri 43
Benjamin Armstrong发表了一篇关于自我提升PowerShell脚本的优秀文章.他的代码有一些小问题; 基于修订建议的修改版本如下所示.
基本上,它获取与当前进程关联的标识,检查它是否是管理员,如果不是,则创建具有管理员权限的新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");
Run Code Online (Sandbox Code Playgroud)
Ros*_*res 18
您可以创建一个批处理文件(*.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"
Run Code Online (Sandbox Code Playgroud)
而已!
这是解释:
假设您的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"
Run Code Online (Sandbox Code Playgroud)将打开一个新的PowerShell会话,并执行以下命令:
Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
Run Code Online (Sandbox Code Playgroud)另一个具有管理权限的新PowerShell会话将在system32文件夹中打开,并且以下参数将传递给它:
-ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
Run Code Online (Sandbox Code Playgroud)将使用管理权限执行以下命令:
cd "C:\Temp"; & ".\ScriptTest.ps1"
Run Code Online (Sandbox Code Playgroud)
一旦脚本路径和名称参数被双引号,它们可以包含空格或单引号字符(').
当前文件夹将从更改system32为C:\Temp,脚本ScriptTest.ps1将被执行.一旦参数-NoExit传递,即使你的powershell脚本抛出一些异常,窗口也不会被关闭.
man*_*lds 14
您可以轻松添加一些注册表项以获取文件的"以管理员身份运行"上下文菜单.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"'
Run Code Online (Sandbox Code Playgroud)
(从@Shay更新为更简单的脚本)
基本上在HKCR:\Microsoft.PowershellScript.1\Shell\runas\command设置默认值时使用Powershell调用脚本.
aka*_*ppi 13
运用
#Requires -RunAsAdministrator
尚未说明.它似乎只有自PowerShell 4.0以来.
http://technet.microsoft.com/en-us/library/hh847765.aspx
将此switch参数添加到requires语句时,它指定必须使用提升的用户权限(以管理员身份运行)启动运行该脚本的Windows PowerShell会话.
对我而言,这似乎是一个很好的方法,但我不确定现场经验.PowerShell 3.0运行时可能会忽略这一点,甚至更糟糕的是,会出错.
当脚本以非管理员身份运行时,会出现以下错误:
无法运行脚本'StackOverflow.ps1',因为它包含以管理员身份运行的"#requires"语句.当前的Windows PowerShell会话未以管理员身份运行.使用"以管理员身份运行"选项启动Windows PowerShell,然后再次尝试运行该脚本.
Run Code Online (Sandbox Code Playgroud)+ CategoryInfo : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ScriptRequiresElevation
Joh*_*ohn 10
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"
Run Code Online (Sandbox Code Playgroud)
您需要使用管理权限重新运行脚本,并检查脚本是否以该模式启动.下面我编写了一个脚本,它有两个函数:DoElevatedOperations和DoStandardOperations.您应该将需要管理员权限的代码放入第一个,将标准操作放入第二个.所述IsRunAsAdmin变量用来识别管理模式.
我的代码是Microsoft脚本的简化摘录,在您为Windows应用商店应用创建应用包时自动生成.
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
}
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
对于执行相对路径操作的脚本,保留工作目录很重要。几乎所有其他答案都不会保留此路径,这可能会导致脚本其余部分出现意外错误。
如果您不想使用自动提升的脚本/代码段,而只想以一种简单的方式以管理员身份启动脚本(例如,从资源管理器上下文菜单中),请在此处查看我的其他答案:https:// stackoverflow .com / a / 57033941/2441655
再加上我的2美分。我基于网络会话的简单版本至今在Windows 7 / Windows 10中一直有效。为什么过于复杂?
if (!(net session)) {$path = "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}
Run Code Online (Sandbox Code Playgroud)
只需添加到脚本顶部,它将以管理员身份运行。
当然,如果您有管理员帐户,也可以强制应用程序以管理员身份打开。
找到文件,右键单击>属性>快捷方式>高级,然后选中以管理员身份运行
然后单击“确定”。
这里的许多答案都很接近,但比需要的工作多了一点。
创建脚本的快捷方式并将其配置为“以管理员身份运行”:
Properties...Target从<script-path>到powershell <script-path>Run as administrator此行为是设计使然。由于 Microsoft 确实不希望 .ps1 文件成为最新的电子邮件病毒,因此存在多层安全性。有些人发现这与任务自动化的概念背道而驰,这是公平的。Vista+ 安全模型是“去自动化”事物,从而让用户接受它们。
但是,我怀疑如果您以提升的身份启动 powershell,它应该能够运行批处理文件而无需再次请求密码,直到您关闭 powershell。
以下是如何运行提升的 powershell 命令并在单个命令中收集 Windows 批处理文件中的输出形式(即不编写 ps1 powershell 脚本)。
powershell -Command 'Start-Process powershell -ArgumentList "-Command (Get-Process postgres | Select-Object Path | Select-Object -Index 0).Path | Out-File -encoding ASCII $env:TEMP\camp-postgres.tmp" -Verb RunAs'
Run Code Online (Sandbox Code Playgroud)
在上面您可以看到我首先使用提升的提示符启动一个 powershell,然后要求启动另一个 powershell(子 shell)来运行该命令。
| 归档时间: |
|
| 查看次数: |
829150 次 |
| 最近记录: |