简体   繁体   English

PowerShell将每个字符串部分设置为变量以供重用

[英]PowerShell set each string part as a variable for reuse

I have a list of files in a folder each are in this format: custID_invID_prodID or custID_invID_prodID_Boolvalue. 我在一个文件夹中有一个文件列表,每个文件都采用以下格式:custID_invID_prodID或custID_invID_prodID_Boolvalue。 For every file I need to break it into sections based on '_'. 对于每个文件,我都需要根据“ _”将其分成多个部分。 Currently I have this code: 目前,我有以下代码:

$files = Get-ChildItem test *.txt
foreach($f in $files){
    $file = @()
    $file += ([String]$f).Split("_")
    $total = ([String]$f).Split("_") | Measure-Object | select count
    Write-Host  "${total}"
    if($total -eq 2) {
    for($i = 2; $i -lt $file.length; $i+=3) {
        $file[$i] = $file[$i].trimend(".txt")
        Write-Host  "${file}"
    }
    }
}

The problem is that Write-Host "${total}" equals @{Count=#} where # is real number of times "_" is found in file. 问题是写主机“ $ {total}”等于@ {Count =#},其中#是在文件中找到"_"真实次数。 How can I use $total inside my if statement to do different operations based upon the number of "_" found? 我如何在if语句中使用$total来基于找到的"_"数执行不同的操作?

Would it not be simpler just to assign the parts you want directly to named variables rather than working with an array? 将所需的部分直接分配给命名变量而不是使用数组会不会更简单?

foreach($f in (Get-ChildItem test *.txt)) {
    $custId, $invID, $prodID, $Boolvalue = $f.BaseName -split "_"
    Write-Host $custId, $invID, $prodID, $Boolvalue
}

If the name only has 3 parts this will simply set $Boolvalue to an empty string. 如果名称只有3个部分,则只需将$Boolvalue设置$Boolvalue空字符串。

Also note that you don't have to trim the extension off the last element after splitting, just use the BaseName property to get the name without extension. 还要注意,拆分后不必将扩展名从最后一个元素上BaseName ,只需使用BaseName属性即可获取不带扩展名的名称。

You need to get the count-property value, like $total.count in your if test. 您需要获取计数属性值,例如if测试中的$total.count You could also clean it up like this. 您也可以像这样清理它。

$files = Get-ChildItem test *.txt
foreach($f in $files){
    $file = @(([String]$f).Split("_"))
    Write-Host "$($file.Count)"
    if($file.Count -eq 2) {
        for($i = 2; $i -lt $file.length; $i+=3) {
            $file[$i] = $file[$i].trimend(".txt")
            Write-Host  "${file}"
        }
    }
}

If you had included more information about what you were trying to do, we could clean it up alot more. 如果您提供了有关您要执行的操作的更多信息,我们可以进行更多清理。 Ex. 例如 It's seems like you want to do something like this: 似乎您想执行以下操作:

Get-ChildItem test *.txt | ForEach-Object {
    $file = @($_.BaseName.Split("_"))
    Write-Host "$($file.Count)"
    if($file.Count -eq 2) {
        Write-Host $file 
    }
}

Seems to me that you're doing it the hard way. 在我看来,您正在艰难地做这件事。 Why not: 为什么不:

$x = "aaa_bbb_ccc"
$cnt = $x.Split("_").count

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

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