个人在windows下习惯用PowerShell替代CMD作为命令行工具。如何自定义命令来提高生产力呢?
linux中有alias工具,如
alias grep='grep --color'
alias tailf='tail -f'
alias duh='du -lah --max-depth=1'
或者在profile中定义函数
function duf(){
du -lah --max-depth==1
}
PowerShell中同样支持alias工具。使用参考PowerShell设置命令别名Alias这篇文章。个人推荐永久别名方式,简单来说分两步:
(1) PowerShell中执行,创建profile文件,创建完成会打出文件位置。当然可以先执行$profile命令查看profile文件位置并检查是否已存在
New-Item -Type file -Force $profile
(2) 在profile文件中定义Alias
以下是几个示例:
(1) 打开程序sublime text
function openSublimeText{
& 'D:\tools\Sublime Text\sublime_text.exe' $args
}
Set-Alias subl openSublimeText
定义好后可以在PowerShell中使用
subl .\README.md #使用sublime text打开当前目录下README.md文件
subl . #使用sublime text打开当前目录
(2) java带固定参数运行
function runJavaWithGCLog{
java '-verbose:gc -Xloggc:gc.log -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCApplicationStoppedTime -XX:+PrintReferenceGC' $args
}
Set-Alias java-with-gclog runJavaWithGCLog
(3)实现tailf
function getContentLikeTailf{
get-content $args -ReadCount 0 -Tail 5 -Wait
}
Set-Alias tailf getContentLikeTailf
使用tailf xxx.log监听xxx.log文件尾部内容
(4)实现tail
function getContentLikeTail{
$count = $($args[0] -replace "-","")
get-content $args[1] -ReadCount 0 -Tail $count
}
Set-Alias tail getContentLikeTail
使用tail -100 xxx.log 或 tail 100 xxx.log查看xxx.log文件尾部100行内容。
(5)切换Maven的settings.xml文件
约定使用Maven安装位置下conf目录下的settings.xml
当需要在不同环境下切换settings.xml配置时,提前给每个环境的settings.xml准备好,并以settings-${name}.xml这样得格式命名,如settings-com.xml、settings-home.xml等,当需要切换到com时,就把settings-com.xml复制为settings.xml。
function changeMavenSettingFile{
$mvn_home = "$env:MAVEN_HOME"
$mvn_conf = "$mvn_home\conf"
if(Test-Path "$mvn_conf\settings.xml.bak"){
Write-Output "remove file: $mvn_conf\settings.xml.bak"
Remove-Item "$mvn_conf\settings.xml.bak"
}
if(Test-Path "$mvn_conf\settings.xml"){
Write-Output "move file: $mvn_conf\settings.xml to $mvn_conf\settings.xml.bak"
Move-Item "$mvn_conf\settings.xml" "$mvn_conf\settings.xml.bak"
}
Write-Output "copy file $mvn_conf\settings-$args.xml to $mvn_conf\settings.xml"
Copy-Item "$mvn_conf\settings-$args.xml" "$mvn_conf\settings.xml"
}
Set-Alias mu changeMavenSettingFile
其中$env:MAVEN_HOME是获取环境变量MAVEN_HOME的值,是安装Maven后配置在环境变量中
Test-Path是检测文件或路径是否存在
按需使用,如mu com就切换到settings-com.xml配置
(6)切换Git用户名字
在多个项目下使用不同的Git用户名字提交时,不适合全局的配置如git config --global user.name xxx这样使用,可以到项目目录下使用git config user.name xxx、git config user.email xxx这样给项目单独配置
function changeGitUser{
$arg_cnt = $($args.Count)
if($arg_cnt -gt 0){
git config user.name $args[0]
Write-Output "config git user.name $($args[0])"
}
if($arg_cnt -gt 1){
git config user.email $args[1]
Write-Output "config git user.email $($args[1])"
}
}
Set-Alias gcu changeGitUser
按需使用,如gcu xyz xyz 就设置当前项目的git用户的name=xyz、email=xyz
实现原理都比较简单,核心还是PowerShell自身的支持,可自行研究。