powershell -- 慢慢学习

Tips

  • powershell对大小写不敏感,但是命令都是动词+名词的形式,比如Set-Alias, 写作set-alias也是没有问题的。

设置别名永久生效

场景: 初次从linux控制台切换到powershell,可以设置一些常用的命令比如ll(ls -l)等

  1. 输入$profile查看配置文件会从哪个位置读取,如果文件不存在则创建
  2. 将要设置的别名输入,重启即可。 比如设置ll
Set-Alias -Name ll -Value Get-ChildItem

参考: https://blog.vvzero.com/2019/07/22/set-user-alias-for-windows-PowerShell/

递归遍历目录下所有文件,去掉末尾的空格

  • 场景: 用于整改代码编程规范,不允许行尾有空格,虽然IDE通常有这样的功能,但是整体对一个工程做转换或者通过jenkins检查的话可能不如写个脚本
  • Note: 识别文件编码并不完善,本地尝试的时候gb2312编码且代码中有中文的话会转换的有问题,如果是UTF-8的话可以放心使用。
function Get-FileEncoding {
    param ( [string] $FilePath )

    [byte[]] $byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $FilePath

    if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
        { $encoding = 'UTF8' }  
    elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
        { $encoding = 'BigEndianUnicode' }
    elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe)
         { $encoding = 'Unicode' }
    elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
        { $encoding = 'UTF32' }
    elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
        { $encoding = 'UTF7'}
    else
        { $encoding = 'ASCII' }
    return $encoding
}

$files = Get-ChildItem -Recurse -File -include "*.cpp","*.h" | foreach {write-output $_.FullName}
foreach($file in $files) {
    $encoding = Get-FileEncoding $file
    write-output "$file 's encoding is $encoding"
    (Get-Content -Encoding $encoding $file) | foreach {write-host "before: $_"; $_.TrimEnd(); write-host "after: $_"} | set-content -Encoding $encoding -Path $file
}

获取脚本自身的文件名、完整路径、所在的文件夹路径

自身文件名: $MyInvocation.MyCommand.Name
参考: http://www.bathome.net/viewthread.php?tid=36253

根据某个进程id, 获取它启动时的命令行参数

场景:想研究某些参数很长的cmd命令或者想在脚本中通过命令行启动一个进程等

Get-WmiObject -Query "SELECT CommandLine FROM Win32_Process WHERE ProcessID = [process_id]"

整理的常用命令

命令 功能 示例 linux对应命令
Get-Command 获取一个命令的真正位置 get-command vim where
Set-Alias 设置别名 Set-Alias -Name ll -Value Get-ChildItem alias ll='ls -l'

非powershell但是也可以在powershell命令行运行的命令

命令 功能 示例 linux对应命令
getmac 获取机器物理地址 getmac ifconfig
posted @ 2020-10-29 14:54  mooooonlight  阅读(148)  评论(0编辑  收藏  举报