Json file arry to power shell array

Spunny 326 Reputation points
2022-04-01T18:38:55.597+00:00

Hi,
I have below code in powershell script
$ignore = @('.txt','.log','.dat','.ps1' ,'.bat','.zip')
Get-ChildItem -Path c:\temp -File | foreach {
""
$.Name
if ($ignore -contains $
.Extension ) {
# Leave it alone
} else {
$newname = $_.name + ".dat"
"rename to $newname"
}
}

I am trying to put $ignore variable in to Json file and import it into power shell script like this:
config.json
{
"ignoreExtensions":[".txt",".log",".xls"]
, "sourcePath":"reports\export"

}

powershell script. example.ps1
Tried multiple ways:
Try 1: (didn't work)
$configFile = 'C:\files\config.json'
$configJSON = Get-Content $configFile | Out-String | ConvertFrom-Json
$ignore = @($configJSON.ignoreExtensions)

Try 2: Didn't work
$configFile = 'C:\files\config.json'
$configJSON = Get-Content $configFile
$ignore = @($configJSON.ignoreExtensions)

None of this is working. I need to get those array of values and loop through all files in directory and check if file has extension. I am missing something in getting json array to powershell script array.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,433 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,416 Reputation points
    2022-04-01T19:24:36.233+00:00

    Like this:

    $json = @'
    {
        "ignoreExtensions":  [
                                 ".txt",
                                 ".log",
                                 ".xls"
                             ],
        "sourcePath":  "reports\\export"
    }
    '@
    
    $ignore = ($json | ConvertFrom-JSON).ignoreExtensions
    

0 additional answers

Sort by: Most helpful