C
C
CrazyKing2019-05-17 14:55:05
PowerShell
CrazyKing, 2019-05-17 14:55:05

How to substitute values ​​from a JSON file in PowerShell?

Good afternoon everyone!
There is a JSON file:

{
  "id": "22",
  "name": "Server",
  "components":
  [
    {
      "name": "Web",
      "update": true,
      "package": [
        {
          "source": "D:\\products\\*",
          "target": "D:\\test\\"
        },
        {
          "source": "%inetpub_path%\\web1\\*",
          "target": "\\Web\\web1\\"
        },
        {
          "source": "%inetpub_path%\\web2\\*",
          "target": "\\Web\\web2\\"
        },
        {
          "source": "%inetpub_path%\\web3\\*",
          "target": "\\Web\\web3\\"
        }
      ]
    }
  ]
}

It is necessary to get all the values ​​for which "update" = true from the JSON file, then select the values ​​"source" and "target" from there and substitute the paths into the formula "xcopy $foreachp /e /y". Ideally, to complete the task, it should turn out like this: "xcopy D:\products\* D:\test\ /e /y". The number of paths may increase over time.
Here is what I have:
#Парсим JSON
$JSON = Get-Content "D:\file.json" -Raw -Encoding UTF8 | ConvertFrom-Json

#Сортируем по update = true
$componentSelect = $JSON.components | select name, update, package | Where-Object {$_.update -like "True"}
$nextCompon = [string[]]
$nextCompon = $componentSelect.package | Select-Object source,target

$nextCompon.count

#Загоняем в цикл полученные значения

foreach ($foreach in $nextCompon)
     {
    
        $foreachp = $foreach -replace '@{source=', '' -replace ';', '' -replace 'target=','' -replace '}',''
        $d = xcopy $foreachp /e /y
     }

In the $foreachp variable, if I output, I get "D:\products\* D:\test\", but when substituting into the $d variable, I get the error:
xcopy : Invalid path
D:\Unnamed1.ps1:22 sign:14
+ $ d = xcopy $foreachp /e /y
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Invalid Path:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Please tell me how to overcome.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2019-05-17
@CrazyKing

I suspect that the matter is in two things:
1. using the environment variable %inetpub_path% in the powershell script. I never wondered if this would work, but in Posh environment variables are used like this: $ENV:HOMEPATH instead of %HOMEPATH%
In cmd scripts, I remind you that you also need to double the signs %
2. using variables in the launch of a console program directly
Here, try using start- process "xcopy.exe" -argumentlist "all the variable arguments you need"
Or Invoke-Expression -command "xcopy.exe all the variable arguments you need"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question