Powershell 以具有提升权限的另一个用户身份运行

标签 powershell powershell-2.0 powershell-3.0

我有两个脚本位于 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 

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

最佳答案

看来您可能需要调整 powershell.exe 的参数。您应该使用 -File 参数,而不是使用我认为无效的 -ArgumentList。此外,您还需要使用 -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 提示,并且目标脚本成功执行。

关于Powershell 以具有提升权限的另一个用户身份运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837130/

相关文章:

arrays - 空值 powershell 数组

powershell - Powershell-哈希表转义引号

powershell - 如何让我的 parent 轻松运行此 Powershell 命令?

sorting - 格式列表 : sort properties by name

c# - 提供 .NET 方法作为委托(delegate)回调

Powershell v2 函数返回 System.Object[] 而不是 PSCustomObject

regex - 替换不适用于正则表达式

PowerShell 启 Action 业增量

Powershell try catch

windows - 用于更改服务帐户的 Powershell 脚本