0

This is a PowerShell question, sorry if it wound up in the wrong place.

I have a data file which I will call PS_Upgrade_Data. It has 6 items in it listed like this:

item1=item-2=item.3=item 4=item5=item6

Please note that items 2 through 4 are written that way due to the data coming in over which I have no control. There is a dash in item2, a period in intem3 and a space in item4 just to be clear. Items 1, 5, and 6 have nothing between the word item and the number.

I am using the follow PS line to read the data in from the file:

Get-Content "P:\PS_Upgrade_Data.txt" | Where-Object {$_.length -gt 0} | Where-Object {!$_.StartsWith("#")} | Foreach-Object -begin {$count1=0} -process {$var = $_.Split('=',6).Trim()}

This does read the data from the file in ok.

I want to take that data and drop it into six (6) different variables and I tried a foreach loop like the one below:

        $count1 = 0
    ForEach ($item in $var) {
        Write-Host "`n"
        Write-Host "count = " , $count1
        if($count1 = 0) {
            Write-Host "UserInit"
            $UserInit = $item
        }
        elseif ($count1 = 1) {
            Write-Host "UserInit"
            $TicketNumber = $item
        }
        elseif ($count1 = 2) {
            Write-Host "UserInit"
            $UpgradeVersion = $item
        }
        elseif ($count1 = 3) {
            Write-Host "UserInit"
            $ClientName = $item
        }
        elseif ($count1 = 4) {
            Write-Host "UserInit"
            $InstName = $item
        }
        elseif ($count1 = 5) {
            Write-Host "UserInit"
            $Coffee = $item
        }
        $count1 +=1
        }

The problem is that the counter is jumping from 0 (zero) to two (2) and then wont increase and I have no idea why.

What stupid thing am I doing or missing?

Thanks for any help.

2
  • 2
    = is the assignment operator in PowerShell. Whereas -eq is the equality/comparison operator. Commented Feb 8, 2023 at 16:37
  • 1
    You don't need a loop for this: $UserInit,$TicketNumber,$UpgradeVersion,$ClientName,$InstName,$Coffee = $var Commented Feb 8, 2023 at 16:40

1 Answer 1

1

PowerShell's assignment operator = supports multiple assignment targets per operation, so you can skip the counter and foreach loop and instead, simply do:

Get-Content "P:\PS_Upgrade_Data.txt" | Where-Object {$_.length -gt 0} | Where-Object {!$_.StartsWith("#")} | Foreach-Object {
  $UserInit,$TicketNumber,$UpgradeVersion,$ClientName,$InstName,$Coffee = $_.Split('=',6).Trim()

  # do with your variables what you want here
}
Sign up to request clarification or add additional context in comments.

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.