PowerShell 自定义 cd 命令

学习系统脚本纯粹是为了提高编程效率,因为平时写的代码都在 E:/develop 目录下的各个子目录。不想敲全路径,于是想到自定义命令。

1.开启允许命令行执行脚本的权限

右键 PowerShell 选择以管理员身份运行,输入命令:  set-executionpolicy -executionpolicy unrestricted 

2.创建 prefile 文件,输入命令: New-Item -Type file -Force $profile ,这时会创建一个 C:\Users\zbseoag\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 的 PowerShell  脚本文件。

3. PowerShell 中可以执行与 linux shell 同名的命令,是通过定义命令的别名实现的。 输入 alias 命令,结果可见 cd 实际上是 Set-Location 命令的别名。

4.我们可以脚本格式导出这些命令,输入: Export-Alias -Path "d:\alias.ps1" -As Script  这命令一看就懂的,哈哈。导出为 d:\alias.ps1 文件之后,打开它。找到 其中 cd 的定义行

5. 下面就可以开始写我们自己的代码了。脚本写完后,重新打开 PowerShell  运行命令试试吧。脚本最后有一条添加别名 命令。

 1 <#
 2 切换目录
 3 
 4 location [父级目录别名] [目录]
 5 切换目录
 6 location d:/aaa
 7 
 8 切换到桌面目录
 9 location -desktop
10 
11 切换到桌面目录下的 javafx 目录
12 location -desktop javafx
13 #>
14 function location {
15 
16     param(
17         [switch]$dev,
18         [switch]$desktop,
19         [switch]$test,
20         [switch]$bat,
21         [switch]$demo,
22 
23         [string]$path
24     )
25     
26     $mapping = @(
27         @{ is = $dev.ToBool();        path = "E:\develop\" },
28         @{ is = $desktop.ToBool();    path = "C:\Users\zbseoag\Desktop\" },
29         @{ is = $test.ToBool() ;      path = "E:\develop\test" },
30         @{ is = $bat.ToBool();        path = "E:\develop\windows\bat" },
31         @{ is = $demo.ToBool();       path = "D:\demo\" }
32     )
33 
34     $mapping = $mapping.where({$_.is -eq $true})
35     if($mapping){
36         $mapping = $mapping.path
37         #若有二级目录,则加上二级目录结成完整目录
38         if($path){ $mapping += $path }
39     }else{
40         $mapping = $path
41     }
42     
43     if(Test-Path $mapping){ 
44         Set-Location -Path $mapping
45     }else{
46         Write-Error "Directory is not exist: $mapping"
47     }
48 
49 }
50 
51 set-alias -Name:"cd" -Value:"location" -Description:"" -Option:"AllScope"

猜你喜欢

转载自www.cnblogs.com/zbseoag/p/13379076.html