简体   繁体   English

如何将混合字符串的定界列表转换为Powershell脚本的数组

[英]How to convert a Delimited List of Mixed Strings to an array for powershell script

I'm looking to solve a problem where I have a long file of comma-delimitted ordered 8-digit numbers and ranges (with leading zeros), as below: 我正在解决一个长文件,用逗号分隔的有序8位数字和范围(带前导零),如下所示:

00001253,00001257-00001268,00001288,...,02154320,02154321,02154323-02154327,...

I want to (a) store any values that aren't ranges as tokens in a PowerShell array while retaining leading zeros and (b) expand ranges to all of their corresponding values and store the tokens in the same array. 我想(a)将不属于范围的任何值存储为PowerShell数组中的标记,同时保留前导零,并且(b)将范围扩展到所有其对应的值,并将标记存储在同一数组中。 Here's the PowerShell "script" I threw together for my purpose so far: 到目前为止,这是我出于目的拼凑的PowerShell“脚本”:

$refids = @(ARRAY_DERIVED_FROM_ABOVE_LIST)

foreach ($refid in $refids) {
New-Item c:\scripts\$refid.txt -type file -force -value "KEY:$refid"
}

Any ideas on how to proceed? 关于如何进行的任何想法? Thanks in advance for any assistance 在此先感谢您的协助

You can start with this, maybe: 您可以从此开始,也许:

$string = '00001253,00001257-00001268,00001288,02154320,02154321,02154323-02154327'

$string.split(',') |
foreach {
  if ($_.Contains('-'))
    {
     invoke-expression ($_.replace('-','..')) |
     foreach {'{0:D8}' -f $_}
    }

  else {$_}
 }

00001253
00001257
00001258
00001259
00001260
00001261
00001262
00001263
00001264
00001265
00001266
00001267
00001268
00001288
02154320
02154321
02154323
02154324
02154325
02154326
02154327

Mjolinor's answer is very good. Mjolinor的回答很好。 Some people refrain from using Invoke-Expression . 有些人不使用Invoke-Expression Here is another example that accomplishes the same thing while showing a slightly different approach. 这是另一个示例,它在显示稍有不同的方法的同时完成了同一件事。

$string = '00001253,00001257-00001268,00001288,02154320,02154321,02154323-02154327'

$string.split(',') | ForEach-Object {
    If($_.Contains('-')){
        $_.Split("-")[0]..$_.Split("-")[1]
    } Else {
        $_
    } 
} | ForEach-Object{ Write-Output ([string]$_).PadLeft(8,"0")}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM