2025年12月4日 星期四

PowerShell 產生隨機密碼

經常用到每次都要查有點煩了,乾脆弄個函式寫到系統中,呼叫的時候比較方便

在 PowerShell 中輸入 $PROFILE 會顯示出每次 PowerShell 載入時讀取的腳本,可以把以下函式寫到裡面去,這樣打開 PowerShell 只要輸入 nrp 就可以產出密碼了

(第一次創建的時候需要設定權限不然會錯,那個複製錯誤信息Google或問AI就可以解了)

以下是產密碼的函式

# Generate a random password
function New-RandomPassword {
    [Alias('nrp')]
    param (
        [Parameter(Position = 0)]
        [ValidateRange(1, 512)]
        [int]$Length = 15,
        [switch]$Symbols,
        [switch]$Ambiguous,
        [string]$IncludeCharacters,
        [string]$ExcludeCharacters
    ) $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    if (-not $Ambiguous) { $chars = $chars -replace '[lIO01]', '' }
    if ($Symbols) { $chars += '!@#$%^&*()-_=+' }
    if ($IncludeCharacters) { $chars += $IncludeCharacters }
    if ($ExcludeCharacters) { $chars = -join $chars.ToCharArray().Where{ $ExcludeCharacters.IndexOf($_) -lt 0 } }
    if ($chars.Length -eq 0) { Write-Error "Character set is empty after exclusions"; return }
    $rng = [Security.Cryptography.RandomNumberGenerator]::Create()
    try {
        $rng.GetBytes(($bytes = [byte[]]::new($Length * 8)))
        -join (0..($Length - 1)).ForEach({ $chars[[BitConverter]::ToUInt64($bytes, $_ * 8) % $chars.Length] })
    } finally { $rng.Dispose() }
} # New-RandomPassword

預設使用 New-RandomPassword 或是 ‘nrp’ 會產出 15 碼的隨機密碼 (預設不包含易造成混亂的 lIO01 字元)

如果需要複雜包含符號,可以使用 -Symbols 與 -Ambiguous 參數
要定義字元可以使用 -IncludeCharacters -ExcludeCharacters 參數
顯式指定與 Symbols / Ambiguous 有衝突時顯式優先級更高