Powershell Tips

  • New-Object 创建一个新对象
> New-Object System.String '~',20
~~~~~~~~~~~~~~~~~~~~
  • 设置命令行的提示符
function prompt
{
    $title = "`n[" + $(Get-Content("Env:Username")) + "@" + $(Get-Content("Env:ComputerName")) + "] " + $(Get-Location).Path
    Write-Host($title) -foregroundcolor DarkGreen
    $Host.UI.RawUI.WindowTitle = $title
    return "> "
}
[admin@localhost] D:\Home\
> 
  • 获取 PATH 列表
function path_list
{
    $items = $Env:Path.Split(@(';'))
    return $items | Get-Unique
}
> path_list
C:\Windows\system32
C:\Windows
C:\Windows\System32\Wbem
C:\Windows\System32\WindowsPowerShell\v1.0\
C:\Windows\System32\OpenSSH\
...
  • 获取环境变量
function env
{
    gci env:* | Sort-Object name
}
> env

Name                           Value
----                           -----
ALLUSERSPROFILE                C:\ProgramData
CommonProgramFiles             C:\Program Files\Common Files
CommonProgramFiles(x86)        C:\Program Files (x86)\Common Files
CommonProgramW6432             C:\Program Files\Common Files
ComSpec                        C:\WINDOWS\system32\cmd.exe
CUDA_PATH_V9_0                 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9.0
DriverData                     C:\Windows\System32\Drivers\DriverData
  • Which 命令,在当前环境路径中搜索匹配的文件
function which($pattern)
{
    $arraylist = new-Object System.Collections.ArrayList
    if (![String]::IsNullOrEmpty($pattern)) {
        foreach ($path in path_list) {
            if ([System.IO.Directory]::Exists($path)) {
                foreach ($file in [System.IO.Directory]::EnumerateFiles($path)) {
                    $name = [System.IO.Path]::GetFileName($file)
                    if ($name -match $pattern) {
                        $file
                    }
                }
            }
        }
    }
}
> which 'notepad'
C:\Windows\system32\notepad.exe
C:\Windows\notepad.exe
  • 查看函数的定义
function decl($fn)
{
    $cmd = "Get-Command $fn"
    (iex $cmd).Definition
}
> decl wget
Invoke-WebRequest
  • 查看对象的内容
function inspect($obj)
{
    $type = $obj.GetType()
    $props = $type.GetProperties()
    $list = New-Object System.Collections.Generic.List[System.String]
    foreach ($p in $props) {
        $name = $p.Name
        try {
            $value = $p.GetValue($obj)
        }
        catch [System.Reflection.TargetParameterCountException] {
            $value = "[]"
        }
        $list.Add([System.String]::Format("{0}={1}", $name, $value))
    }
    return "{ " + [System.String]::Join(", ", $list) + " }"
}
> inspect "Hello"
{ Length=5, Chars=[] }
  • 执行命令
> iex "& cmd /c ver"

Microsoft Windows [Version 10.0.18362.418]
  • Where 是 Where-Object 的缩写
> alias where
CommandType     Name
-----------     ----
Alias           where -> Where-Object
  • where 用于过滤对象
> ps | where ProcessName -like win*

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    169      11     1716       6400              1000   0 wininit
    245      10     2348       8620             22824   7 winlogon
   1081      75    54048      71092       1.27   8916   7 WinStore.App
  • Where 除了过滤对象之外,也可以过滤纯文本
> cmd /c dir | where { $_ -like "*Program*" }
2018-09-03  05:23 PM    >DIR<          Program Files
2018-08-23  07:10 PM    >DIR<          Program Files (x86)
  • 过滤文本也可以用 Select-String
> cmd /c dir | select-string -pattern "B[a-r]"
2018-09-07  11:27 AM    >DIR<          Bin
2018-06-08  03:37 PM    >DIR<          Library
  • 执行一个命令并 Source 其环境变量
function source()
{
    if ($args.Length -gt 0) {
        $cmd = $args[0]
        $arg = [String]::join(" ", $args[1..$args.length])
        $cmd = "`"$cmd`" $arg && set" 
        $lines = CMD.exe /c $cmd
    
        foreach ($line in $lines) {
            if ($line -match '^([^=]+)=(.*)') {
                $key = $matches[1]
                $val = $matches[2].Replace('"', '`"')
                $x = "`${Env:$key} = `"$val`""
                iex $x
            }
        }
    }
}
> source "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Auxiliary\Build\vcvarsall.bat" "x64"
> msbuild /version
Microsoft (R) Build Engine version 15.9.21+g9802d43bc3 for .NET Framework
Copyright (C) Microsoft Corporation. All rights reserved.

15.9.21.664