PowerShell数组数据替换:基于映射规则重构ID字段
Solution for Transforming User IDs in PowerShell
Got it, let's sort out this ID transformation task cleanly. The key here is to process each user entry individually so we don't run into mismatches between the first/second parts, and using hashtables for mappings makes the code way easier to maintain than chaining multiple replace() calls.
Step-by-Step Solution Code
# Define clear mapping rules for the first and second 4-digit segments $firstSegmentMap = @{ "0" = "A" "1" = "B" "3" = "C" # Add any other digit-to-character mappings you need here } $secondSegmentMap = @{ "0" = "Z" "1" = "X" "3" = "Y" # Add any other digit-to-character mappings you need here } # Fetch your user data (replace with your actual data source) $Users = Get-some-content() # Process each user to update their ID $updatedUserList = $Users | ForEach-Object { # Grab the original ID (Description field) $originalId = $_.Description # Validate we have an 8-digit ID first if ($originalId.Length -ne 8) { Write-Warning "Skipping user $($_.User) - Invalid ID length: $originalId" $_ # Keep the original entry if invalid return } # Split the ID into first and second 4-character segments $firstSegment = $originalId.Substring(0, 4) $secondSegment = $originalId.Substring(4, 4) # Convert the first segment using its mapping $convertedFirst = -join ($firstSegment.ToCharArray() | ForEach-Object { # Use mapped value if available, otherwise keep the original digit $firstSegmentMap[$_] ?? $_ }) # Convert the second segment using its mapping $convertedSecond = -join ($secondSegment.ToCharArray() | ForEach-Object { $secondSegmentMap[$_] ?? $_ }) # Build the new ID with dot separator $newId = "$convertedFirst.$convertedSecond" # Return a new object with the updated ID [PSCustomObject]@{ User = $_.User ID = $newId } } # Output the final result $updatedUserList
Why This Works Better
- Per-User Processing: By looping through each user with
ForEach-Object, we ensure the first and second segments always belong to the same user (no index mismatches like you might get with separate arrays). - Maintainable Mappings: Hashtables let you add/remove mappings in one place instead of editing a long chain of
replace()calls. - Error Handling: We check for invalid 8-digit IDs and warn you instead of breaking the script.
- Clean Output: The final object matches exactly the format you requested (User and ID columns).
Example Output
For your sample input:
User ID (Description)
User1 12345678
User2 87654321
With the mappings you provided, the output would be:
User ID
User1 B2C4.5678
User2 876Y.X21
(Note: Adjust the mappings in the hashtables to get your exact desired AB.CD/DE.FG output by adding the remaining digit rules.)
内容的提问来源于stack exchange,提问作者Markus
相关产品推荐
相关产品推荐

