您將如何生成從 000 到 9ZZ 的唯一序列。最后,我的 export-csv 不作業。請參閱下面的資料和匯出輸出。
字母數字序列從 0 到 9 開始,然后是 A 到 Z。
請注意,我的 PowerShell 技能有點新。:)
$i = @()
$a = 0..9
$b = 65..90 | Foreach{[Char]$_}
$i = $a $b
For($d = 0; $d -le $i.count; $d ){
$g = $i[$d]
For($e = 0; $e -le $i.count; $e ){
$h = $i[$e]
For($f = 0; $f -le $i.count; $f ){
$j = $i[$f]
$k = "{0}{1}{2}" -f $g, $h, $j
$k #| Export-Csv -Path .\List.csv -NoTypeInformation -Append
If($k -eq '9ZZ'){
Break
}
}
}
}
Data Output:
000
001
.
.
|
V
009
00A
.
.
00Z
00 <-- I don't get this.
010
Export:
Length
3 <-- I don't get this either.
.
.
|
v
3
任何和所有的幫助表示贊賞。謝謝你的高級。;)
uj5u.com熱心網友回復:
這是一個經典的 off-by-1 錯誤 - 您的回圈從 0 運行到$i.count(包括),它正好比$i.
在所有 3 個回圈條件中更改-le $i.count為-lt $i.count,它將起作用。
您可以通過稍微不同地預先生成完整范圍的數字/字符來簡化代碼,然后改用 3 個嵌套foreach回圈:
$digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.ToCharArray()
$ranges =
:outerLoop
foreach($a in $digits){
foreach($b in $digits){
foreach($c in $digits){
# save and output new value
($label = "${a}${b}${c}")
# exit the label generation completely if we've reached the desired upper boundary
if($label -eq '9ZZ'){ break outerLoop }
}
}
}
$ranges000現在包含正確的標簽范圍9ZZ
uj5u.com熱心網友回復:
我會這樣做,有 3 個foreach回圈和一個標記的 break:
$digits = 0..9
$chars = (65..90).ForEach([char])
$dict = $digits $chars
$result = :outer foreach($i in $dict)
{
foreach($x in $dict)
{
foreach($z in $dict)
{
'{0}{1}{2}' -f $i,$x,$z
if($i -eq 9 -and $x -eq 'Z' -and $z -eq 'Z')
{
break outer
}
}
}
}
$result | Export-Csv ...
uj5u.com熱心網友回復:
為了使用遞回輔助函式生成具有給定位置數的字符排列的通用解決方案來補充有用的現有答案Get-Permutations:
function Get-Permutations {
param(
[Parameter(Mandatory)]
[string] $Chars, # e.g. '0123456789'
[Parameter(Mandatory)]
[uint] $NumPlaces # e.g. 2, to produce '00', '01', ..., '99'
)
switch ($NumPlaces) {
0 { return }
1 { [string[]] $Chars.ToCharArray() }
default {
Get-Permutations -Chars $Chars -NumPlaces ($NumPlaces-1) | ForEach-Object {
foreach ($c in $chars.ToCharArray()) { $_ $c }
}
}
}
}
您可以按如下方式呼叫它(獲取'000', '001', ...,但一直到'ZZZ'- 您可以使用 進行后過濾... | Where-Object { $_ -le '9ZZ' })
Get-Permutations '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' 3
筆記:
- 在PowerShell (Core) 7 中,您可以使用
-join ('0'..'9' 'A'..'Z') - 在Windows PowerShell中,您不能將
[char]實體與范圍運算子,一起..使用,您可以使用以下更簡潔的替代方法:
-join ([char[]] (48..57) [char[]] (65..90))基于字符。獲得的代碼點,例如[int] [char] 'A'
uj5u.com熱心網友回復:
同樣,您可以作弊,因為 '009' -le '00A'
function inc([string]$s){
[byte[]]$v = [char[]]$s
$radix = $v.Count-1
$carry = $true
while($carry -and $radix -ge 0){
switch( $v[$radix]){
91{$v[$radix] = 48}
58{$v[$radix] = 65; $carry = $false}
default{$carry = $false}
}
$radix--
}
$out = [char[]]$v -join ''
$c = if($carry){'1'}else{''}
return ($c $out)
}
&{for($i = '000'; $i -le '9ZZ'; $i = inc $i){
write-output $i
}} | set-content -Path .\List.csv
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/412545.html
標籤:
上一篇:XML按子節點值洗掉節點
