承接前文,这里是另一些可能有点用的 pwsh 脚本。

命令行代理

让命令行应用走代理,用法是 socks app command。也可以把 Set-CliProxyClear-CliProxy 单独拿出来用。

function socks {
    $Command = "$args"

    Set-CliProxy
    Invoke-Expression $Command 2>&1 | out-default
    Clear-CliProxy
}

function Set-CliProxy {
    $proxy = 'http://127.0.0.1:43333'

    $env:HTTP_PROXY = $proxy
    $env:HTTPS_PROXY = $proxy
}

function Clear-CliProxy {
    Remove-Item env:HTTP_PROXY
    Remove-Item env:HTTPS_PROXY
}

time

为命令行应用计时,大概类似于 *nix 中的 time。用法是 time app command

仅仅计时的话可以用 Measure-Command 命令,但它没有输出,只有时间信息,所以写了个 function 封装一下。

function time {
    $Command = "$args"

    $time = Measure-Command { Invoke-Expression $Command 2>&1 | out-default }

    $info = "{0:d2}:{1:d2}:{2:d2}.{3}" -f $time.Hours, $time.Minutes, $time.Seconds, $time.Milliseconds

    Write-Output $info
}

Get-Size

命令行里查看文件夹、文件的大小,按 M 显示。用法是 Get-Size folder/file

function Get-Size {
    param([string]$pth)
    "{0:n2}" -f ((Get-ChildItem -path $pth -recurse | measure-object -property length -sum).sum / 1mb) + " M"
}

翻译

命令行里的翻译程序,其实之前是想用 go 写一个的,但不如直接写个 pwsh 脚本简便。由于 api key 是扒的别人的,所以就在源码里删去了。

function fy {
    if ($args.Length -eq 0 ) {
        Write-Output 'this is a cli translator, try `fy hello world`.'
    }
    else {
        $query = ""
        for ($i = 0; $i -lt $args.Count; $i++) {
            $query += " "
            $query += $args[$i]
        }

        $ApiUrl = "redacted"

        $info = (Invoke-WebRequest $ApiUrl).Content | ConvertFrom-Json

        Write-Host "@" $query  "[" $info.basic.phonetic "]"
        Write-Host "翻译:`t" $info.translation
        Write-Host "词典:"
        for ($i = 0; $i -lt $info.basic.explains.Count; $i++) {
            Write-Host "`t" $info.basic.explains[$i]
        }
        Write-Host "网络:"
        for ($i = 0; $i -lt $info.web.Count; $i++) {
            Write-Host "`t" $info.web[$i].key ": " -NoNewline
            for ($j = 0; $j -lt $info.web[$i].value.Count; $j++) {
                Write-Host $info.web[$i].value[$j] "; " -NoNewline
            }
            Write-Host ""
        }
    }
}