首页 > 解决方案 > 递归将文件添加到文件夹并在文件夹不存在时创建文件夹

问题描述

我正在尝试将配置文件递归地添加到以下路径: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 文件。我试过搜索这个问题,但没有运气。

标签: powershellrecursionwindows-installerdirectory

解决方案


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

#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导致它创建文件夹,并传递文件夹对象,或者如果它确实存在,它只是传递文件夹对象而不做任何其他事情。


推荐阅读