1

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

only downside of this script is it does not work for every file. It touches them all but only saves the final one. Just an FYI for future users
2

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 
    }
}

2 Comments

How would I set each part to a variable, like the post above?
Add $custId, $invID, $prodID, $Boolvalue = $file as the first line inside the if-loop. Try and fail, that's how you learn.
1

Seems to me that you're doing it the hard way. Why not:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.