Windows PowerShell

背景

Win11 21H2(OS Build 22000.1880)

Windows PowerShell 5.1

简述

 

0x01 环境变量

# list
PS> ls env:
# set
PS> $env:_JAVA_LAUNCHER_DEBUG=1
# unset
PS> del env:_JAVA_LAUNCHER_DEBUG

0x02 Profile

~ $ $profile
C:\Users\xxx\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

~ $ type $profile

# Truncate homedir to ~
function limit-HomeDirectory($Path) {
  $Path.Replace("$home", "~")
}

# Must be called 'prompt' to be used by pwsh
function prompt {
  $realLASTEXITCODE = $LASTEXITCODE
  Write-Host $(limit-HomeDirectory("$pwd")) -ForegroundColor Yellow -NoNewline
  Write-Host " $" -NoNewline
  $global:LASTEXITCODE = $realLASTEXITCODE
  Return " "
}

0x03 Parsing

续行符 Line continuation,`

关于参数,有个要点,-之后为参数名,参数名不能有 .,会被断开传递,需要包引号。

command-parameter:
    dash first-parameter-char parameter-chars colon~opt~

parameter-chars:
    parameter-char
    parameter-chars parameter-char

parameter-char:
    Any Unicode character except
        { } ( ) ; , | & . [
        colon
        whitespace
        new-line-character

例:

$ .\TestExe.exe -echoargs -DA.D
Arg 0 is <-DA>
Arg 1 is <.D>

0x04 Character Encoding

In general, Windows PowerShell 5.1 uses the Unicode UTF-16LE encoding by default.

修改默认编码

  • $PSDefaultParameterValues
  • $OutputEncoding
    • The automatic variable $OutputEncoding affects the encoding PowerShell uses to communicate with external programs.
    • It has no effect on the encoding that the output redirection operators and PowerShell cmdlets use to save to files.

例:

  • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'

相关 Cmdlet

Beginning in PowerShell 5.1, the redirection operators (> and >>) call the Out-File cmdlet.

具体表现:

  • Out-File and the redirection operators > and >> create UTF-16LE.
  • Set-Content and Add-Content use Default encoding.
  • New-Item -Type File -Value creates a BOM-less UTF-8 file.
  • Get-Content uses the Default ANSI encoding, in the absence of a BOM.

更多

  1. 用新PowerShell 运行旧的CMD命令 - CSDN

参考

  1. microsoft.powershell.core > about_profiles
  2. microsoft.powershell.core > about_environment_variables
  3. microsoft.powershell.core > about_prompts
  4. microsoft.powershell.core > about_character_encoding
  5. lang-spec > chapter-15 Grammar

附录

BOM (byte-order-mark)[ref]

In Windows PowerShell, any Unicode encoding, except UTF7, always creates a BOM.

PowerShell (v6 and higher) defaults to utf8NoBOM for all text output.

posted @ 2023-04-26 23:20  UPeRVv  阅读(82)  评论(0编辑  收藏  举报