PowerShell alias syntax for running a cmd.exe builtin function?

百般思念 提交于 2019-12-07 23:59:38

问题


As I have only recently switched to PowerShell from cmd.exe, I often find it convenient to do little things in a familiar way by calling cmd to do them. For instance, to do a 'bare' file listing this works great:

PS> cmd /c dir /b
dir1
dir2
file1.txt

I'd like to make an alias for this but I can't figure out the right syntax. So far I've tried:

PS> Set-Alias dirb cmd /c dir /b        # error (alias not created)
PS> Set-Alias dirb "cmd /c dir /b"      # fail (alias doesn't work)
PS> Set-Alias dirb "cmd `"/c dir /b`""  # fail (alias doesn't work)

Any suggestions? I'm looking for a general solution to calling builtin cmd.exe commands (such as dir). I'd also like to know how to produce bare output the right way using PowerShell cmdlets, but that's a secondary concern at the moment. This question is about the proper syntax for calling cmd.exe from an alias.


回答1:


I believe what you want is a function, not an alias. For instance:

  function dirb {
    cmd /c dir $args[0] /b
     }

From a PS prompt, run notepad $profile, paste that into your profile and then it will load automatically when you open a PS console and you can do this:

dirb c:\somedir

See get-help about_functions for more information about functions.




回答2:


Aliases are not designed for this kind of tasks. An alias is just another name of a command. Use the function instead.

function dirb { cmd /c dir /b }



回答3:


Aliases in powershell don't take parameters unfortunately - you need to define a function for this. For more info,

get-help aliases



回答4:


Why on earth would you use powershell to open the command prompt? That seems to be defeating the purpose.

The Alias I prefer to list out files is simply ls



来源:https://stackoverflow.com/questions/4753919/powershell-alias-syntax-for-running-a-cmd-exe-builtin-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!