简体   繁体   中英

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. 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. How can I use $total inside my if statement to do different operations based upon the number of "_" found?

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.

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.

You need to get the count-property value, like $total.count in your if test. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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