简体   繁体   English

以本地管理员身份从另一个 powershell 脚本调用 powershell 脚本

[英]Call a powershell script from another powershell script as local admin

not sure if I'm overcomplicating this, I just want to call another script as local admin and have it run.不确定我是否过于复杂,我只想以本地管理员身份调用另一个脚本并运行它。

The command below opens powershell, and in the new window I get an error and then the window closes too fast for me to be able to see it.下面的命令打开powershell,在新窗口中我收到一个错误,然后窗口关闭得太快,我无法看到它。

start powershell -verb runas -ArgumentList {Invoke-Expression -Command "C:\Script.ps1"}

If you want to stay native powershell use the start-process cmdlet and you can specify the filepath (process to run) as powershell.exe and the -ArgumentList parameters as conditions for your new session.如果您想保留本机 powershell,请使用 start-process cmdlet,您可以将文件路径(要运行的进程)指定为 powershell.exe,并将 -ArgumentList 参数指定为新会话的条件。 In my example below i'm setting ExecutionPolicy so you don't have to rely on the system level policy, NoProfile will make your script a bit more resiilent by not loading any customized profile on a system.在下面的示例中,我设置了 ExecutionPolicy,因此您不必依赖系统级策略,NoProfile 将通过不在系统上加载任何自定义配置文件来使您的脚本更具弹性。

$Cred = (Get-Credential)
$ScriptLocation = "C:\Temp\TestScript.ps1"
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File $ScriptLocation" -Credential $Cred

You can see in the script getting a credential object (which you'll probably want to provide so the script will just run) then specifying the script location and executing.您可以在脚本中看到获取凭证对象(您可能希望提供该对象以便脚本运行),然后指定脚本位置并执行。

As vonPryz mentioned, you can always troubleshoot by adding -NoExit to your Argument list so the window stays open after executing the script but keep in mind if that if the script location doesn't exist you'll still see the powershell host appear and close right away.正如 vonPryz 提到的,您始终可以通过将 -NoExit 添加到您的参数列表来进行故障排除,以便在执行脚本后窗口保持打开状态,但请记住,如果脚本位置不存在,您仍然会看到 powershell 主机出现并关闭马上。

You can also add -WindowStyle Hidden to your argument list to hide any window from appearing at all.您还可以将 -WindowStyle Hidden 添加到您的参数列表以隐藏任何窗口。

Turned out to be an execution policy issue.原来是执行策略问题。 This was a device that was non-standard in our environment and didn't have that GPO pushed.这是我们环境中的非标准设备,没有推送 GPO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM