【问题标题】:Recursive adding file to folder and create folder if it doesn't exist递归将文件添加到文件夹并在文件夹不存在时创建文件夹
【发布时间】:2018-12-08 01:44:40
【问题描述】:

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

【问题讨论】:

  • 将单引号改为双引号,看看是否有帮助。使用您当前的代码,Powershell 假定文件夹名称为 * 并且不将其用作通配符。
  • 没有改变结果。尝试'C:\Users\*\' 作为似乎工作正常的路径。问题似乎是一些用户有一个 AppData 文件夹,而其他用户没有,因此脚本无法继续。如果我给它提供一条已经存在的路径,它就像一个魅力。谢谢你。
  • 这是通过 MSI 包中的自定义操作完成的吗?还是通过 Active Directory 或其他机制运行?如果这是一个包,它是安装一个带有自己的 EXE 并启动的应用程序,还是一个插件安装连接到其他东西?

标签: powershell recursion windows-installer directory


【解决方案1】:

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

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

【讨论】:

  • 这种方法很有趣!差不多了。现在它在C:\Users\*\AppData\Roaming\Trio` instead of creating C:\Users*\AppData\Roaming\Trio\Trio Enterprise\AgentAP.cfg 处创建了一个名为“Trio Enterprise”的文件,尝试在 $Destination 末尾添加一个额外的反斜杠,但没有工作。
  • 我会使用 New-Item -ItemType "directory" 而不是 New-Item -Force 别名 MD 似乎暗示了这一点。
  • 已更新以包含项目类型,感谢您的建议。
猜你喜欢
  • 2014-04-09
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多