Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive adding file to folder and create folder if it doesn't exist

I'm trying to add a config file recursively to following path: C:\Users*\AppData\Roaming\

Heres my code so far:

#Sets config file as source.
$Source = "$dirFiles\NewAgentAP\AgentAP.cfg"

#Recursive copying of a file to specific folder destination.
$Destination = 'C:\Users\*\AppData\Roaming\Trio\Trio Enterprise'
Get-ChildItem $Destination | ForEach-Object {Copy-Item -Path $Source -Destination $_ -Force}

I would want the powershell script to add the path for each user if they don't have it already and afterwards add the .cfg file. I have tried searching about the problem but without luck.

like image 979
Rainoa Avatar asked Feb 13 '26 18:02

Rainoa


1 Answers

I think a good solution here would be to iterate all user folders, make sure the destination path exists, and then perform your copy.

#Sets config file as source.
$Source = "$dirFiles\NewAgentAP\AgentAP.cfg"

#Recursive copying of a file to specific folder destination.
$Destination = 'AppData\Roaming\Trio\Trio Enterprise'
Get-ChildItem C:\Users\* -Directory | ForEach-Object {New-Item -Path (Join-Path $_.FullName $Destination) -ItemType "directory" -Force | Copy-Item -Path $Source -Destination $_ -Force}

Using New-Item to create the folder, and the -Force switch will cause it to create the folder if it doesn't exist, and pass on the folder object, or if it does exist it just passes on the folder object without doing anything else.

like image 140
TheMadTechnician Avatar answered Feb 15 '26 11:02

TheMadTechnician



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!