Quantcast
Channel: Active questions tagged windows - Super User
Viewing all articles
Browse latest Browse all 9273

Powershell $idValue doesn't write the extracted ID, but writes "TRUE" instead -- why?

$
0
0

I am writing a Windows PowerShell script to split a text file based on a delimiter, and create output filenames with an incrementing number and a captured identifier string.

I've checked for syntax errors and the script runs without errors. The splitting, the output file formation and filename numbering all works ok, but the script is not populating the captured identifier value into the filename as expected. Instead of using the extracted string, it's using 'True'.

I've been using $idValue to extract the character strings I want, but all I get from it is "True", as in, it sees the regex match I've used, and agrees the logic condition is true (there's a match).

But before I go on, here's a simplified version of the input file, so you can see the structure:

\id EUCAL\v Text\v more text\z Endsect\id LEUCO\v Text\v more text\z Endsect

The strings I want to see in the filename are in the "\id" field. So here, it's EUCAL and LEUCO. All these "id" strings are exactly 5 characters in length. So I've taken advantage of that in the regular expression I've used to extract them. The regex definitely works. But instead of getting output filenames 01-EUCAL.txt and 02-LEUCO.txt (etc.), I get 01-True.txt and 02-True.txt, which are puzzling.

I've verified that the regular expression works correctly. I suspect the issue might be with how I'm accessing the captured group value in $idValue. Any help in resolving this would be appreciated.

Here's the PowerShell script:

$Text = Get-Content -Path "D:\Test_input.txt" -raw  # Read the file content$SplitText = $Text -split "z Endsect\r?\n?"  # Split with empty lines included$SplitText = $SplitText -notmatch '^$'    # Filter out empty lines$i = 1foreach ($File in $SplitText) {  # Append "z Endsect" to every entry  $File += "z Endsect"     # Extract the identifier (assuming 5 characters after \id ) using regex  $idValue = $File -match "\\id\s(.{5})" -replace '(?<=\\id\s)', ''  # Capture 5 characters after \id and space/tab  # Pad the incrementing number with a leading zero if necessary  $paddedNumber = "{0:00}" -f $i  # Construct the new filename with separator and padded number  $NewFilename = "D:\$paddedNumber-$idValue.txt"  # Write the content to the new files  $File | Out-File -FilePath $NewFilename  $i++}

Viewing all articles
Browse latest Browse all 9273

Trending Articles