Start CMD.exe from powershell with arguments in a script block?

Question:

Is this possible?

I’ve just been trying something simple:

CMD starts in admin, but nothing happens after that.

The long story is, when I want to use “Remove-Item” I do not want to use the -Recurse argument because it will throw access denied errors for various reasons. The only way I know how to do it without any prompts is using rmdir inside a command prompt window.

Does anyone know a way to either suppress the prompt without -recurse or how I could start CMD and call rmdir with all its parameters?

Answer:

Paul G’s answer solves your immediate problem based on the sample command in your question and helpfully points out that /c must precede any command to pass to cmd.exe (or /k, if you want to keep the session open).

While using a script block with Start-Process‘s -ArgumentList parameter can be convenient, you should know its limitations:

  • The script block’s literal contents becomes a single string argument that is passed to -ArgumentList.
  • Therefore, use of a script block prevents use of PowerShell variables and expressions as (parts of) the arguments to pass.

Therefore, more work is needed if you want to pass the target directory path by way of a variable:

Note that I’ve added echo so as to preview the rmdir command – remove it to perform actual deletion.

Note the use of embedded double-quoting around $targetDir, which, unfortunately, is necessary to pass arguments with embedded spaces properly, due to a
a known bug.

Also note the -Wait switch, which ensures that the command doesn’t return until the elevated process has exited – though that in itself doesn’t guarantee successful completion, which you’d have to check for afterwards.

You could add -WindowStyle Hidden to run the elevated console window itself invisibly, but note that the UAC dialog (to confirm elevation) will obviously still show – unless your PowerShell session already is elevated.


As for:

When I want to use Remove-Item I do not want to use the -Recurse argument because it will throw access denied errors for various reasons.

In order to remove an entire directory with Remove-Item – including all its contents, including subdirectories – you must use -Recurse.

You can force certain deletions to occur without complaint with -Force (such as files marked as read-only), but deletion attempts that lack the required permissions will never succeed.

While you can suppress the associated error messages with -ErrorAction SilentlyContinue, the items in questions won’t be deleted, and running the code elevated may again be your only choice.

Source:

Start CMD.exe from powershell with arguments in a script block? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply