【问题标题】:Powershell running as a another user with elevated privilegesPowershell 作为具有提升权限的另一个用户运行
【发布时间】:2014-04-03 12:03:05
【问题描述】:

我在 C:\setup 中有两个脚本:script.ps1 和 script1.ps1。

我希望能够以另一个用户身份并以提升的权限从 withing script.ps1 运行 script1.ps1,但我无法使其工作。新的 powershell 窗口打开但立即关闭...

这是脚本:

 $cspath = $MyInvocation.MyCommand.Path
 $sfolder = Split-Path $cspath
 $spath = Join-Path $sfolder "\Script1.ps1"

 $sa = "domain\user"
 $sap = "userpassword"
 $sasp = ConvertTo-SecureString -String $sap -AsPlainText -Force
 $sac = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sa, $sasp 


 Start-Process $PSHOME\powershell.exe `
            -Credential $sac `
            -ArgumentList "-Command Start-Process $PSHOME\powershell.exe -ArgumentList `"'$spath'`" -Verb Runas" -Wait 

任何帮助将不胜感激...

【问题讨论】:

  • 您通过Start-Process 调用的脚本有什么作用?

标签: powershell powershell-2.0 powershell-3.0


【解决方案1】:

您可能需要调整powershell.exe 的参数。而不是使用我认为无效的-ArgumentList,您应该使用-File 参数。此外,您还需要使用-ExecutionPolicy Bypass 参数来确保脚本执行策略不会受到干扰。

最后,我建议从脚本路径中删除单引号,因为 Windows 命令解释器不理解单引号包围参数。

试试这个:

$ArgumentList = '-Command Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-ExecutionPolicy Bypass -File \"{0}\"" -Verb Runas' -f $sPath;
Start-Process $PSHOME\powershell.exe `
    -Credential $sac `
    -ArgumentList $ArgumentList -Wait 

更新

似乎有些引用规则也在这里起作用,因为我们将一个命令嵌入到另一个命令中。我在 PowerShell v4.0 上编写并测试了一个功能齐全的脚本。

以下是内容:

# Create test directory and script file
[void](New-Item -Path c:\test -ItemType Directory -Force);
Set-Content -Path c:\test\test1.ps1 -Value 'Add-Content -Path $PSScriptRoot\blah.txt -Value (Get-Date);';

# Get credential and define script path
$Credential = Get-Credential;
$ScriptPath = 'c:\test\test1.ps1';

# Define the command line arguments
$ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $ScriptPath;

Start-Process -FilePath powershell.exe `
    -Credential $Credential `
    -ArgumentList $ArgumentList -Wait -NoNewWindow;

我可以确认我得到了一个 UAC 提示,并且目标脚本成功执行。

【讨论】:

  • -ArgumentListStart-Process 的有效参数,这是他用来调用powershell.exe 的参数。
  • 哦,我对包装的命令感到困惑。让我纠正一下。
【解决方案2】:

由于您担心新会话窗口关闭,我猜您需要命令行输出。

Start-Process 正在按预期工作。它将运行通过-ArgumentList 传入的脚本并退出会话。这意味着它不会保持显示命令行输出 - 会话将在进程完成后立即终止。

如果您想要持久会话,请使用New-PSSession。否则,您可以将正在收集的数据导出到文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2021-01-09
    • 2018-08-03
    • 2013-05-31
    • 2016-06-05
    • 2019-10-05
    • 2013-01-19
    相关资源
    最近更新 更多