递归将文件添加到文件夹并创建文件夹(如果不存在)

时间:2018-06-28 22:27:14

标签: powershell recursion windows-installer directory

我试图将配置文件递归添加到以下路径:C:\ Users * \ AppData \ Roaming \

到目前为止,这里有我的代码:

#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}

我希望Powershell脚本为每个用户添加路径(如果他们没有的话),然后添加.cfg文件。我曾尝试搜索问题,但没有运气。

1 个答案:

答案 0 :(得分:2)

我认为这里的一个好的解决方案是迭代所有用户文件夹,确保目标路径存在,然后执行复制。

#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}

使用New-Item创建文件夹,并且-Force开关将使其创建文件夹(如果该文件夹不存在),并传递该文件夹对象,或者仅存在该文件夹对象传递文件夹对象而不做其他任何事情。