Kyl*_*Mit 7 windows powershell
我想查找并复制某个目录中的所有文件及其所有具有特定名称的子目录。
我Copy-Item在 Powershell 中使用(technet | ss64)
这是我所拥有的:
Copy-Item `
-Path \\Server\Apps\* `
-Destination C:\ReadMeFiles\ `
-Include *ReadMe.txt `
-Recurse `
-WhatIf
Run Code Online (Sandbox Code Playgroud)
它将抓取以下文件:
\\Server\Apps\ReadMe.txt
Run Code Online (Sandbox Code Playgroud)
但不是:
\\Server\Apps\AppName\ReadMe.txt
Run Code Online (Sandbox Code Playgroud)
即使我已经指定 -recurse
我怎样才能让它在每个目录中向下移动?
这是 Copy-Item 的一个已知问题,您无法在源中指定通配符,并使用 Recurse(并使其按预期工作)。
如果您不介意也复制文件夹结构(但只复制自述文件),请尝试使用“过滤器”选项。就像是:
Copy-Item \\Server\Apps\ C:\ReadMeFiles\ -Filter *ReadMe.txt -Recurse
Run Code Online (Sandbox Code Playgroud)
或者,您可以将 Get-Child-Item 与 Recurse 一起使用,并使用 For 循环一次为 Copy-Item 提供一个文件。
我对这个问题的稍微修改的答案:批处理文件:列出一种类型的所有文件,重命名文件,展平目录
它做你想做的事:使用通配符复制文件,扁平化目录结构,处理文件名冲突。它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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29469 次 |
| 最近记录: |