function - 在同一脚本中同时运行提升和非提升代码的问题
问题描述
我需要在 powershell 中运行一些提升的代码以及一些非提升的代码(以进行一些用户特定的更改)。我已经能够使提升工作,但是一旦代码被提升,我就不能在未提升的状态下运行代码。
使用下面的示例代码块(我从链接的网站劫持),我尝试将其转换为一个函数并将另一个函数的名称传递给 RunAs-Admin 函数,以便它只执行该块然后返回。我无法让代码只执行一个提升的功能!没有 break/exit/etc 会让你回到用户级别的原始代码!
#### ========================
#### Self Elevate
#### ------------------------
function RunAs-Admin
{
Param($elevate)
#### ========================
#### Code credit of Ben Armstrong’s Virtualization Blog
#### https://blogs.msdn.microsoft.com/virtual_pc_guy/
#### ========================
# 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 Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
#### $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
# We are not running "as 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
####$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$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
}
#### ========================
#### Elevated Function
#### ========================
$(& $elevate)
Write-Host -NoNewLine "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
#### ========================
#### Elevated Function
#### ========================
}
function SomeElevatedCode1
{
#### things happen elevated
}
funtion SomeUserLevelCode1
{
#### things happen under the user account at user level
}
RunAs-Admin SomeElevatedCode1
SomeUserLevelCode1
RunAs-Admin SomeElevatedCode1
理想的情况是让 RunAs-Admin 调用一个需要提升的函数,然后返回以运行下面的其余代码。在我的场景中,提升和非提升任务的顺序是相关的,因此我希望能够控制以管理员身份运行的内容以及在用户级别运行的内容。
前任。创建系统还原点(提升),返回,对配置文件进行一些更改(以用户身份运行),添加计划任务(提升)等。
解决方案
推荐阅读
- python - 广义骰子损失问题
- sql - SQLite:按每个日期分组的两个日期之间的差异总和
- c# - 负前瞻行为不符合预期
- java - 三元运算符中不需要的 NullPointerException - 为什么?
- java - 通信链路故障(MYSQL SERVER 8 + JAVA)
- python - 需要从下拉菜单中单击一个文本来更改下拉菜单中的默认选项
- django - Django 对象唯一性地狱与 M2M 字段
- angular - *ngFor keyvalue descOrder 不适用于日期
- python - 未找到非 root 用户命令
- string - 为什么在获取和显示字符串中的字符时会得到意外结果?