【问题标题】:Powershell script to copy a file into all given subfolders?Powershell脚本将文件复制到所有给定的子文件夹中?
【发布时间】:2015-08-17 18:54:48
【问题描述】:

请注意,这是我的第一个 powershell 脚本项目。我正在尝试编写一个脚本,提示用户输入源文件和将其复制到的目录。该脚本运行没有错误,但实际上并没有复制文件。任何帮助将不胜感激。一个使用示例是:将 C:\Users\User\Desktop\info.txt 复制到 C:\Users\User\Documents\*

$source = Get-ChildItem -Path (Read-Host -Prompt 'Enter the full name of the file you want to copy')
$dirs = Get-ChildItem -Path (Read-Host -Prompt 'Enter the full name of the directory you want to copy to')  

foreach ($dir in $dirs){
   copy $source $dir
}

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    我对您的脚本进行了一些更改以使其正常工作,您可能需要对其进行一些调整以实现您的目标:

    $source = Get-Item -Path (Read-Host -Prompt 'Enter the full name of the file you want to copy')
    $dirs = Get-ChildItem -Path (Read-Host -Prompt 'Enter the full name of the directory you want to copy to')  
    foreach ($dir in $dirs){
    Copy-Item $source $dir.FullName
    }
    

    首先,我将 $source 从 Get-ChildItem 更改为 Get-Item,因为您指定它应该查找单个文件。

    从那里开始,当我运行脚本时,我注意到不是在目录中创建文件,而是创建了一堆与目录名称相同的文件。

    为了调查这种行为,我在 Copy-Item 命令行开关的末尾添加了 -whatif。

    Copy-Item $source $dir -whatif
    

    这给了我以下输出:

    如果:对目标“项目:H:\test\source\test.txt 目标:H:\test\Folder1”执行“复制文件”操作。

    如果:对目标“项目:H:\test\source\test.txt 目标:H:\test\Folder2”执行“复制文件”操作。

    如果:对目标“项目:H:\test\source\test.txt 目标:H:\test\Folder3”执行“复制文件”操作。

    如果:对目标“项目:H:\test\source\test.txt 目标:H:\test\Folder4”执行“复制文件”操作。

    这解释了脚本的奇怪输出,这是对目的地的误解。有时 Powershell 无法理解您要执行的操作,因此您必须更加明确。

    然后我运行了以下命令:

    $dir | select *
    

    这提供了很多属性,但重要的是:

    全名:H:\test\Destination\Folder4

    所以我把脚本改成了这样:

    Copy-Item $source $dir.FullName
    

    进行这些更改后,运行脚本将我指定的 test.txt 文件复制到目标文件夹的每个子目录中。

    【讨论】:

    • 太棒了!感谢您的解释。我唯一注意到的是,当复制到包含快捷方式的目的地时,这些快捷方式被破坏了。不过,这些文件的例外情况可以解决,对吗?
    • 递归复制到目录而不复制到非目录使用$dirs = Get-ChildItem -Path . -Directory -Recurse