I'm trying to work on a Powershell function which will copy a few files from a source directory and paste them to the destination. The source directory, destination path and the name of the file to be copied is being read from a JSON file. The JSON file looks like this:
{
"sourceFolder": "C:\\LaptopFiles\\SourceFiles\\",
"Alienware": {
"files": [
{
"source": "AlienwareLatest",
"destination": "D:\\AlienwareLaptop\\AlienwareFiles",
"forceOverwrite": "true",
"copying": {
"files": [
"appsettings.json",
"web.config"
]
}
}
]
},
"Lenovo": {
"files": [
{
"source": "LenovoLatest",
"destination": "D:\\LenovoLaptop\\LenovoFiles",
"forceOverwrite": "true",
"copying": {
"files": [
"appsettings.json",
"web.config",
"version.txt"
]
}
}
]
}
}
NOTE: I have a RegEx in place that ignore the double slashes in the json file so when it's loaded in Powershell, it gets the correct path and not one with 2 slashes.
The script that I am trying to work on should do the following:
- Note the
sourceFolder. - Add the
sourceFolderto thesourceand then the name of the file incopyingof each object in JSON to make a full path. (C:\LaptopFiles\SourceFiles\AlienwareLatest\appsettings.json). - Copy the file from the above source path to the
destinationpath written. So copy the file from for exampleC:\LaptopFiles\SourceFiles\AlienwareLatest\appsettings.jsontoD:\AlienwareLaptop\AlienwareFiles\appsettings.json.
But I can't seem to make it work and I'm failing to come up with a proper structure so that each file is placed where it belongs.
I've done this so far:
$jsonConfigs = (Get-Content -Path LaptopInfo.json -raw) | ConvertFrom-Json
foreach ($item in $jsonConfigs.psobject.properties) {
$configs = $item.Value
$config = $configs.files
foreach ($_file in $config.copying.files) {
$_destination = $config.destination + "\" + $_file
$_source = $sample_configs + $config.source + "\" + $_file
$Check_Sample_Files = Test-Path $_source
if ($Check_Sample_Files -eq 'True'){
### Do the copyig operation here and overwrite the file if it already exists ####
}
}
}