首页 > 解决方案 > In PowerShell, is it possible to create an alias whose name has a space in it?

问题描述

I want to make rm -rf an alias for Remove-Item, since I keep accidentally typing it when using PowerShell.

I had guessed maybe I could do something like this, but that doesn't work.

Set-Alias -name 'rm -rf' -value Remove-Item

标签: powershell

解决方案


You could also remove the default alias and then replace it with a custom function.

# remove default alias
if (Test-Path Alias:rm) {
    Remove-Item Alias:rm
}

# custom function for 'rm'
function rm {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [switch]$rf,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$Path
    )
    process {
        Remove-Item -Path $Path -Recurse:$rf -Force:$rf
    }
}

Then call it like this:

rm -rf "C:\Temp\dir"

If course, so far this function doesn't have the full functionality of Remove-Item, but you can extend it as you like.

Note: Even though this "solves" your problem in the short-run, you should not revert to these kinds of workarounds. Better get accustomed to the actual PowerShell commands and syntax, or you're bound to run into more problems sooner or later.


推荐阅读