如何在PowerShell中将JSON中的字符串数组转为字符串数组?代码故障排查
Let's fix your code and get that JSON array into a proper PowerShell string array. First, let's break down what's going wrong with your current approach, then walk through the correct solution.
Issues in Your Current Code
- Incorrect
xyzproperty access: Your$json.abcis an array of objects (each withdef,ghi, orxyzrespectively). You can't directly use$json.abc.xyzbecause that tries to fetch thexyzproperty from every element in theabcarray—this property only exists on the third element. - Unnecessary global variable: Using
$global:arrayis poor practice here. Functions should return values instead of modifying global state. - Redundant
Out-String:Get-Contentwith the-Rawparameter reads the entire file as a single string, which works directly withConvertFrom-Jsonwithout needing extra string conversion.
Correct Solution
Let's walk through a clean, robust way to extract the string array:
Step 1: Parse the JSON File
Simplify the JSON reading process:
# Read and parse the JSON in one concise step $json = Get-Content "path to json file" -Raw | ConvertFrom-Json
Step 2: Extract the xyz String Array
Since $json.abc is an array, we need to target the specific object that holds the xyz property. Here are two reliable methods:
Option 1: Target by Index (for fixed positions)
If you know the xyz object is always the third element (PowerShell uses zero-based indexing, so index 2):
$stringArray = $json.abc[2].xyz
Option 2: Dynamic Lookup (for variable positions)
If the position of the xyz object might change, use Where-Object to find it dynamically:
$xyzObject = $json.abc | Where-Object { $_.PSObject.Properties.Name -contains 'xyz' } $stringArray = $xyzObject.xyz
Step 3: Rewrite Your Function (Best Practice)
If you want to wrap this logic in a function, make it return the array instead of relying on global variables:
function Get-XyzStringArray { param( [Parameter(Mandatory=$true)] $JsonInput ) # Locate the object with the xyz property $xyzObject = $JsonInput.abc | Where-Object { $_.PSObject.Properties.Name -contains 'xyz' } # Return the string array return $xyzObject.xyz } # Usage example: $json = Get-Content "path to json file" -Raw | ConvertFrom-Json $stringArray = Get-XyzStringArray -JsonInput $json # Verify the result $stringArray # Check the type to confirm it's a string array $stringArray.GetType()
Test the Result
When you run this code, $stringArray will be a proper PowerShell string array containing:
[dbo].[abc1] [dbo].[def1]
You can confirm it's an array by checking $stringArray.Count (it will return 2) or looping through it with a foreach statement.
内容的提问来源于stack exchange,提问作者Ronnie Kapoor

