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