Powershell作为另一个具有提升权限的用户运行
我在C:\setup中有两个脚本:script.ps1和script1.ps1 我希望能够以另一个用户的身份使用script.ps1以提升的权限运行script1.ps1,但我无法让它工作。新的powershell窗口将打开,但会立即关闭 以下是脚本:Powershell作为另一个具有提升权限的用户运行,powershell,powershell-2.0,powershell-3.0,Powershell,Powershell 2.0,Powershell 3.0,我在C:\setup中有两个脚本:script.ps1和script1.ps1 我希望能够以另一个用户的身份使用script.ps1以提升的权限运行script1.ps1,但我无法让它工作。新的powershell窗口将打开,但会立即关闭 以下是脚本: $cspath = $MyInvocation.MyCommand.Path $sfolder = Split-Path $cspath $spath = Join-Path $sfolder "\Script1.ps1" $sa =
$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提示,并且目标脚本成功执行。由于您担心新会话窗口关闭,我猜您需要命令行输出
启动过程
正在按预期工作。它将运行通过-ArgumentList
传入的脚本并退出会话。这意味着它不会保持显示命令行输出-会话将在进程完成后立即终止
如果需要持久会话,请使用。否则,您可以将正在收集的数据导出到一个文件。您通过
启动流程
调用的脚本有什么作用?-ArgumentList
是启动流程
的有效参数,这是他用来调用powershell.exe
的。噢,我对包装的命令感到困惑。让我纠正一下。