简体   繁体   English

创建新进程或在Powershell中使用“启动cmdlet”

[英]Create new process or use Start cmdlet in Powershell

I was messing around with a script that I found on the internet that will check to see if you are running the current Powershell console under the Admin role and, if not, start a new instance of Powershell and close the former window. 我正在搞乱我在互联网上找到的脚本,它将检查你是否在Admin角色下运行当前的Powershell控制台,如果没有,启动一个新的Powershell实例并关闭前一个窗口。

The part that checks it isn't really the issue, I just have a question on how it starts a new instance of Powershell. 检查它的部分不是真正的问题,我只是对如何启动Powershell的新实例有疑问。

This is how it is performed in the script: 这是在脚本中执行的方式:

$newProcess = New-Object System.Diagnostics.ProcessStartInfo "Powershell";
$newProcess.Arguments = "& '" + $MyInvocation.MyCommand.Name + "'"
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
Exit;

This is a rather well-known and regularly used script (empirically, it is scattered all over the web in myriad websites). 这是一个相当着名且经常使用的脚本(根据经验,它遍布网络上的无数网站)。

As most Powershell-savvy folks know, you can bring up Powershell and have it run as Administrator from the command line (within a Run prompt, Command shell, & Powershell) by typing: 正如大多数知道Powershell的人都知道的那样,你可以打开Powershell并通过输入命令行(在Run提示符,Command shell和Powershell中)以管理员身份运行它:

Start Powershell -ArgumentList "& '$scriptpath'" -Verb runas

And anyone that is familiar with scripting can see that these will do the exact same thing--they even seem to resemble each other! 任何熟悉脚本的人都可以看到这些内容完全相同 - 它们甚至看起来彼此相似!

Between these two ways of starting a new instance of Powershell and running a called script, what are the differences? 在启动Powershell的新实例和运行调用脚本的这两种方式之间,有什么区别? Which is recommended and which is not? 哪个是推荐的,哪个不是? Is one more correct (appropriate) than the other? 一个比另一个更正确(适当)吗?

As I am self-taught and I generally learn as I go, best practices, advice, and what is deprecated\\superseded is often overlooked. 因为我是自学成才,而且我一般都会学习,最好的做法,建议,以及被弃用或被取代的内容经常被忽视。

I don't really have a background in the .NET framework or C#, so, if the answer is obvious from that standpoint, you'll have to forgive me. 我真的没有.NET框架或C#的背景知识,因此,如果答案从这个角度来看很明显,那么你必须原谅我。

Thanks. 谢谢。

Start is an alias for Start-Process , which is basically a wrapper around [System.Diagnostics.Process]::Start (it actually returns a System.Diagnostics.Process object). StartStart-Process的别名,它基本上是[System.Diagnostics.Process]::Start (它实际上返回一个System.Diagnostics.Process对象)的包装器。 You can use either of them, but the former is more PoSh since its syntax follows PowerShell conventions. 您可以使用它们中的任何一个,但前者更多是PoSh,因为它的语法遵循PowerShell约定。

See also this comprehensive Technet article for an overview of ways to run executables from PowerShell. 有关从PowerShell运行可执行文件的方法的概述,另请参阅此综合Technet文章

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

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