powershell: 生成随机字符串

ASCII范围内的

获取6个随机字符(字母和数字)

4857是数字0-9,powershell的范围操作符是..,和Perl 5的一样, 所以 48..57就是指(48 49 50 51 52 53 54 55 56 57)的列表。 6590是大写字符A到Z,97122是小写字母。如果需要获取多有的可打印字符(包括空格)的话,范围是32..127

[char]把对应数字转换成字符,例如 [char](66)就是B(大写字母B),C语言使用的小括号来进行类型强制转换。

# 1
-join((48..57 + 65..90 + 97..122) | get-random -count 6 | %{[char]$_})
# 如果不指定-count参数,则前面的list有多少个字符
# get-random就会获取多少个字符,只是顺序打乱了
# 2
-join(0..1024|%{[char][int]((48..57 + 65..90 + 97..122)| Get-Random)})
# 这里的0..1024相当于循环控制,每循环一次后面的%{[char][int]((48..57 + 65..90 + 97..122)| Get-Random)}执行一次,其中在数字字母中随机选一个字符
# 0..1024, like Perl, loop controller
#-join是
字符连接操作符
# 3
-join ([char[]](65..90+97..122) | Get-Random -Count 6)
function Get-RandomString() {
    param(
    [int]$length=10,
    # 这里的[int]是类型指定
    [char[]]$sourcedata
    )

    for($loop=1; $loop –le $length; $loop++) {
            $TempPassword+=($sourcedata | GET-RANDOM | %{[char]$_})
    }
    return $TempPassword
}

Get-RandomString -length 14 -sourcedata (48..127)

Unicode

引用

1. Powershell Reference 3.0: Get-Random
[2. Generating A New Password With Windows Powershell](from https://blogs.technet.microsoft.com/heyscriptingguy/2013/06/03/generating-a-new-password-with-windows-powershell/)
3. Generate Random Letters With Powershell
4. How do I encode Unicode character codes in a PowerShell string literal?

原文地址:https://www.cnblogs.com/raybiolee/p/6261928.html