I’m doing analysis on servers in our environment, where the data is retrieve via PowerShell and a JSON file is created for each server. It turns out that some of the JSON is not formatted correctly and I need to loop through all the files, find the ones not formatted correctly, and remove the parts that are not correct. Here is an example of a malformed file:
{
"value": [
{
"Server": "SERVERNAME",
"Name": "SHARE",
"ScopeName": "*",
"Path": "",
"Description": "",
"ShareState": 1,
"AvailabilityType": 0,
"ShareRights": [
],
"ShareSddl": "",
"ShareRoot": [
],
"TotalFileCount": 35,
"TotalDirectoryCount": 47,
"TotalFolderSizeBytes": "",
"TotalFolderSizeInMB": "",
"TotalFolderSizeInGB": "",
"TreeSizeDirFailed": null,
"TreeSizeFileFailed": null,
"TreeErrorHistory": null
}
],
"Count": 10 (This number varies)
}
What I need to do is remove the following parts:
{
"value": [
AND
,
"Count": 10 (This number varies)
}
I’ve tried to use -replace
and String.Replace()
with no luck… the parts above are still present. Below is an example of what I’ve done, but for testing only, it only focuses on removing the end portion. How can I go about fixing this so the replace works? Thanks!
$Files = Get-ChildItem -path ""
$StartMatch = @"
{
"value":
"@
$EndMatch = @"
,
!!!ROW!!!
}
"@
ForEach ($File in $Files){
Write-Host "■ Checking file: $File"
$Contents = (Get-Content -Path "$File")
if ($Contents.StartsWith($StartMatch)){
Write-Host "Match" -ForegroundColor Green #test print
Write-Host "-Checking EOF... " -NoNewline
if (($Contents | Select-Object -Last 3) -like "*Count*"){
Write-Host "Match" -ForegroundColor Green
$EOFMatch = $EndMatch -replace "!!!ROW!!!", $Contents[$Contents.length - 2]
Write-Host $EOFMatch -ForegroundColor Yellow
$Contents = $Contents -replace $EOFMatch, ""
$Contents #test print
Break #testing only
}
}else{
Write-Host "No match"#test print
}
}
2
Answers
Since you’re interested in the objects inside
.value
property, this might be as easy as reading the file -> parsing withConvertFrom-Json
-> getting the value of the.value
property -> converting that value back to Json:This should work