PowerShell创建PSCustomObject及生成指定格式JSON Payload技术求助
PowerShell: Generate Target JSON Payload from ID File
Hey there! Let's tackle this PowerShell JSON payload problem together. Here's a straightforward, reliable way to build exactly the JSON structure you need from your ID file.
Step-by-Step Solution
First, let's assume your ID file has one ID per line (the most common format for this scenario). If your file uses a different delimiter, I'll add a quick tweak for that too.
1. Full Working Code
# 1. Read the ID file, filter out empty lines to avoid invalid entries in the array $assetIds = Get-Content -Path "C:\your\file\path\ids.txt" | Where-Object { $_ -match '\S' } # 2. Build the custom object matching your target JSON structure $jsonPayload = [PSCustomObject]@{ assetIds = $assetIds sendNotification = $true } # 3. Convert to properly formatted JSON (use -Compress if you want minified output) $jsonPayload | ConvertTo-Json -Depth 10 # Optional: Save directly to a JSON file # $jsonPayload | ConvertTo-Json -Depth 10 | Set-Content -Path "C:\your\output\payload.json"
2. Key Details Explained
- Filtering Empty Lines: The
Where-Object { $_ -match '\S' }ensures we skip any blank lines in your ID file, so yourassetIdsarray won't have empty strings. - PSCustomObject Structure: Using
[PSCustomObject]creates an object with exactly the keys your target JSON requires (assetIdsandsendNotification), which translates perfectly when converted to JSON. - Depth Parameter:
-Depth 10ensures PowerShell properly serializes the array (the default depth is 2, which works here, but setting a higher value prevents issues if you ever expand the structure later). - Minified vs. Pretty-Print: Remove
-Depth 10and add-Compressif you need minified JSON instead of human-readable format.
3. If Your IDs Are Comma-Separated (Not Per Line)
If your ID file has all IDs in a single line separated by commas (e.g., id1, id2, id3), adjust the first line to split and clean the values:
$assetIds = (Get-Content -Path "C:\your\file\path\ids.txt" -Raw).Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }
That should give you exactly the JSON payload you're targeting! Let me know if you run into any edge cases with your specific ID file format.
内容的提问来源于stack exchange,提问作者Hein
相关产品推荐
相关产品推荐

