Running CMD commands in PowerShell

by | August 13,2018

Table of Contents

PowerShell by default does not support the native cmd.exe command such as „dir“. Instead, it uses historic aliases called “dir” to point you to the closest PowerShell cmdlet:

 

PS C:\> Get-Command -Name dir | ft -AutoSize

CommandType Name                 Version Source
----------- ----                 ------- ------
Alias       dir -> Get-ChildItem 

This explains why “dir” in PowerShell won’t support the switches and arguments it used to in cmd.exe and batch files, like “cmd.exe /w”.

Running Traditional CMD Commands from PowerShell

If you must use the old cmd-style commands, launch an original cmd.exe with parameter /c (for “command”), issue the command, and process the results inside PowerShell. This example runs cmd.exe /c, and then runs the old cmd command “dir” with its argument /w:

 
PS C:\> cmd.exe /c dir /w

An even safer way is to use the „–%“ operator:

 
PS C:\> cmd.exe --% /c dir /w 

Limitations and Behavior of cmd.exe Arguments

When it is specified at the beginning of arguments, then the PowerShell parser leaves the argument untouched, and you can even use environment variable notations like in cmd.exe. The backdraw: you can no longer use PowerShell techniques inside the arguments, like variables:

 
PS C:\> cmd.exe --% /c dir %WINDIR% /w 

Twitter This Tip! ReTweet this Tip!