使用Powershell复制具有特定名称的所有文件


3

我想查找并复制特定目录中的所有文件以及具有特定名称的所有子目录。

Copy-Item在Powershell中使用(technet | ss64

这是我所拥有的:

Copy-Item `
    -Path \\Server\Apps\* `
    -Destination C:\ReadMeFiles\ `
    -Include *ReadMe.txt `
    -Recurse `
    -WhatIf

它将获取以下文件:

\\Server\Apps\ReadMe.txt

但不是:

\\Server\Apps\AppName\ReadMe.txt

即使我已经指定 -recurse

我怎样才能使它在每个目录中向下传播?


为什么\\Server\Apps\*\\Server\Apps呢?
2015年

您没有为其提供文件扩展名(即Path \\ Server \ Apps *。*)。 存在的问题
Ramhound

@Ramhound和@Dan,这两个更改都未在“ Apps”内部找到子目录
KyleMit 2015年

@KyleMit-希望您纠正了我的错字。
Ramhound

Answers:


3

我对这个问题的回答略有修改:批处理文件:列出所有类型的文件,重命名文件,展平目录

它可以满足您的要求:使用通配符复制文件,展平目录结构,处理文件名冲突。它使用Get-ChildItem,如Tᴇcʜιᴇ007建议。

# Setup source and destination paths
$Src = '\\Server\Apps'
$Dst = 'C:\ReadMeFiles'

# Wildcard for filter
$Extension = '*ReadMe.txt'

# Get file objects recursively
Get-ChildItem -Path $Src -Filter $Extension -Recurse |
    # Skip directories, because XXXReadMe.txt is a valid directory name
    Where-Object {!$_.PsIsContainer} |
        # For each file
        ForEach-Object {

            # If file exist in destination folder, rename it with directory tag
            if(Test-Path -Path (Join-Path -Path $Dst -ChildPath $_.Name))
            {
                # Get full path to the file without drive letter and replace `\` with '-'
                # [regex]::Escape is needed because -replace uses regex, so we should escape '\'
                $NameWithDirTag = (Split-Path -Path $_.FullName -NoQualifier)  -replace [regex]::Escape('\'), '-'

                # Join new file name with destination directory
                $NewPath = Join-Path -Path $Dst -ChildPath $NameWithDirTag
            }
            # Don't modify new file path, if file doesn't exist in target dir
            else
            {
                $NewPath = $Dst
            }

            # Copy file
            Copy-Item -Path $_.FullName -Destination $NewPath
        }

4

这是Copy-Item的一个已知问题,您不能在源代码中指定通配符,而要使用Recurse(并使它按预期工作)。

如果您不介意也复制文件夹结构(但仅复制自述文件),请尝试使用“过滤器”选项。就像是:

Copy-Item \\Server\Apps\ C:\ReadMeFiles\ -Filter *ReadMe.txt -Recurse

另外,您也可以将Get-Child-Item与Recurse一起使用,并使用For循环一次将Copy-Item文件提供给一个。


谢谢!是的,我这样做是为了将所有文件从目录结构中拉平,所以我可能不得不使用Get-Childitem并通过管道将其插入Copy-Item
KyleMit
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.