简体   繁体   English

从脚本打开 Powershell 后将命令传递给管理员 Powershell

[英]Passing command to Admin Powershell after opening Powershell from script

Through the Command Prompt, I am looking to open Powershell as Admin and pass a command for it to execute.通过命令提示符,我希望以管理员身份打开 Powershell 并传递命令以使其执行。 The command is simple: remove all.txt files in a directory.命令很简单:删除目录中的所有.txt 文件。 I am having a difficult time passing this command into the Admin Powershell. Here's what I'm trying:我很难将此命令传递给管理员 Powershell。这是我正在尝试的:

powershell -Command "Start-Process powershell -Verb runAs | Remove-Item -Path C:\MyFolder\*.txt"

So far, the Powershell window opens but nothing is executed.到目前为止, Powershell window 打开但没有执行任何操作。

Problem问题

You are just piping the $null output of Start-Process to Remove-Item , which makes no sense.您只是将Start-Process$null output 传递给Remove-Item ,这是没有意义的。

Solution解决方案

Your 2nd Powershell invocation should use -Command parameter:您的第二次 Powershell 调用应使用-Command参数:

powershell -command Start-Process powershell -Verb runAs -ArgumentList @('-Command', 'Remove-Item', \"'C:\MyFolder\*.txt'\")

The command-line that follows -command doesn't need to be quoted, which simplifies nested quoting. -command后面的命令行不需要引用,简化了嵌套引用。

The somewhat strange looking quoting for the Remove-Item argument is required to support path with spaces. Remove-Item参数的引号看起来有点奇怪,以支持带空格的路径。 First the backslash-escaped double quotes will be resolved by the cmd parser, finally the Remove-Item call will look like this:首先反斜杠转义的双引号将由 cmd 解析器解析,最后Remove-Item调用将如下所示:

Remove-Item 'C:\MyFolder\*.txt'
powershell -Command  "start-process powershell -Verb RunAs -Args 'Remove-Item -Path C:\MyFolder\*.txt'"

you can also pass remove-item as args in string format您还可以将 remove-item 作为字符串格式的 args 传递

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

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