首页 > 解决方案 > powershell复制文件并将文件夹名称附加到复制的文件

问题描述

我正在尝试从根文件夹下的日常文件夹中复制文件“abc.txt”。假设源文件夹路径和文件看起来像..

\\Server01\rootdir->01-01-20->abc.txt
\\Server01\rootdir->01-01-20->abc.txt
\\Server01\rootdir->01-01-20->Details->abc.txt
..
..
\\Server01\rootdir->10-25-20->Details->abc.txt
\\Server01\rootdir->11-15-20->abc.txt
\\Server01\rootdir->12-30-20->abc.txt           ---File existed in parent folder
\\Server01\rootdir->12-31-20->Details->abc.txt  ---File not in parent but in child

我想将所有这些文件夹中的 abc.txt 文件复制到一个位置。但是在复制时,我需要将文件夹名称附加到 abc_01-01-20.txt 之类的文件中。但是有可能里面 root->01-01-20 可能包含子文件夹(Details)并且它可能在里面有相同的文件名。因此,如果文件在 01-01-20 文件夹中不存在,则它有可能存在于“详细信息”文件夹中。如果父文件夹中存在“abc.txt”,则脚本不应查看子(详细信息)文件夹。

TargetDir->abc_01-01-20.txt
TargetDir->abc_01-02-20.txt
..
..
TargetDir->abc_12-31-20.txt

这是我构建的脚本

$Source = "\\Server01\root"
$SrcFile="abc.txt"
$GetSrcFile = Get-ChildItem $Source | Where-Object {$_.name -like "$SrcFile"}
$Destination = "C:\Target"
Copy-Item "$Source\$GetFile" "$Destination" -Force -
Confirm:$False -ErrorAction silentlyContinue
if(-not $?) {write-warning "Copy Failed"}
else {write-host "Successfully moved $Source\$SrcFile to $Destination"}

问题是此脚本无法将文件夹名称提取并附加到文件中。

标签: powershellpowershell-4.0

解决方案


我没有对此进行测试,但我认为您的代码存在一些问题。您似乎混淆了来源和目的地。此外,您正在将文件收集到变量 $ScrFile 中,但您没有以可以确定新名称的方式对其进行迭代......

我很快就完成了这项工作,并没有对其进行测试,但作为你如何完成这项工作的一个示例,它可能是一个起点。

$Source      = "\\Server01\Destination"
$SrcFile     = "abc.txt"
$Destination = "C:\Source\rootdir"

# Note: this can be done with other ForEach permutations as well.

Get-ChildItem $Source -File | 
Where-Object{ $_.Name -match $SrcFile } |
ForEach-Object{
    # Get the name of the dir you found the file in:
    $ParentDirectory = Split-Path $_.DirectoryName -Leaf 
    
    #calculate a new file name including the directory it was found in:
    $NewFileName     = + $_.BaseName + $ParentDirectory + $_.Extension
    
    #Join the new name with the directory path you want top copy the file to
    $NewFileName     = Join-Path $Destination $NewFileName 
    
    # Finally try and copy the file.  Use try catch for more robust error handling
    Try{
        Copy-Item $_.FullName $NewFileName -ErrorAction Stop
        Write-Host -ForegroundColor Green "Successfully copied the file..."
    }
    Catch{
        # You can do a better job here...
        Write-Host -ForegroundColor Red "There was an error copying the file!"
    }
}

推荐阅读