PowerShell - 如何以管理员身份打开 PowerShell 并以管理员身份启动脚本

问题描述 投票:0回答:1

我正在努力解决一个非常复杂的问题。我的脚本必须安装的应用程序需要提升管理员权限。附加到此应用程序也仅适用于管理员。 首先,我设置执行策略:

try
{
  Set-ExecutionPolicy -Scope CurrentUser Unrestricted
  Write-Output "Completed"
}
catch
{
 throw $PSItem
}

我的下一个 PowerShell 脚本将创建一个包含域\用户组合和密码的 PSCredential 对象。之后,它使用以下命令打开 .exe 安装文件:

Start-Process powershell -Credential $credential -ArgumentList ('-noprofile -command &{Start-Process "' + $filePathSetup + '" -wait -verb runas}')

并继续执行安装代码。

当我使用提供的管理员凭据手动打开 PowerShell ISE 并粘贴我的脚本时,它会起作用。然而,实际上,我是从外部软件(Blue Prism)运行脚本,我既不能使用 GUI,也不能执行手动活动。应用程序需要在没有任何人为干扰的情况下完全以编程方式安装,因此我无法自行以管理员身份打开 PowerShell。

我在做什么?我创建一个 Runspace 和一个 PowerShell 对象,添加将应用程序安装到此 PowerShell 对象的脚本,并以这种方式调用它:

Runspace runspace;

try {

  runspace = RunspaceFactory.CreateRunspace();
  if(STA == true) {
    runspace.ApartmentState = System.Threading.ApartmentState.STA;
  } else {
    runspace.ApartmentState = System.Threading.ApartmentState.MTA;
  }
  runspace.ThreadOptions = PSThreadOptions.ReuseThread;
  runspace.Open();

} catch(System.Exception ex) {
  ErrorMessage = ex.Message;
  return;
}

//-Create PowerShell----------------------------------------------------
System.Management.Automation.PowerShell PS;

try {

  PS = System.Management.Automation.PowerShell.Create();
  PS.Runspace = runspace;
  PS.AddScript(PSCode);

} catch(System.Exception ex) {
  runspace.Close();
  ErrorMessage = ex.Message;
  return;
}

//-Add parameters to PowerShell-----------------------------------------
    foreach(DataRow ThisRow in Parameters.Rows) {
        PS.AddParameter(ThisRow["Name"].ToString().Trim(), ThisRow["Value"].ToString().Trim());
  }

//-Invoke PowerShell----------------------------------------------------
try {

  Collection<PSObject> Ret = PS.Invoke();
  runspace.Close();

我的问题是什么?我无法在此代码中切换到管理员,但我需要以管理员身份运行 PowerShell 和应用程序,而现在我仅通过 PowerShell 以管理员身份运行应用程序。我听说过一个旧的 Impersonate 类,它会很有帮助,但不再受支持。你建议我做什么?

PS 请不要手动操作。我知道如何按鼠标右键打开上下文菜单并选择以管理员身份运行;)

powershell admin uac runas runspace
1个回答
0
投票

不确定这里的问题是什么,但我们在启动时在所有 BP 机器上执行了一些需要管理员权限的操作。为此,我们在任务计划程序中将一个任务设置为“以最高权限运行”,无论“用户是否登录”,然后该任务将触发一个指向我们的 powershell 文件的 cmd 脚本,并且它们都可以在没有管理员提示的情况下正常运行。任务计划程序在任务配置期间请求计算机上的管理员凭据,但我认为这可以解决您在这里尝试的问题。

© www.soinside.com 2019 - 2024. All rights reserved.