【问题标题】:powershell to copy files and append foldername to copied filespowershell复制文件并将文件夹名称附加到复制的文件
【发布时间】:2021-03-31 03:33:09
【问题描述】:

我正在尝试从根文件夹下的日常文件夹中复制文件“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 文件夹中,则它有可能存在于“Details”文件夹中。如果 父文件夹 上存在“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"}

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

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    我认为您在某种程度上混淆了 Source 和 Destination。 为此,您需要递归获取abc.txt 文件,并且仅当直接父文件夹的名称类似于日期时,才使用新名称复制文件:

    $Source      = 'C:\Source\rootdir'       # rootfolder where the subfolders with files are
    $Destination = "\\Server01\Destination"  # path to where the files need to be copied
    
    if (!(Test-Path -Path $Destination -PathType Container)) {
        $null = New-Item -Path $Destination -ItemType Directory
    }
    
    Get-ChildItem -Path $Source -Recurse -Filter 'abc.txt' -File | 
        Where-Object {$_.DirectoryName -match '\\\d{2}-\d{2}-\d{2}$'} | 
        ForEach-Object {
            $newName = '{0}_{1}{2}' -f $_.BaseName, ($_.DirectoryName -split '\\')[-1], $_.Extension
            $target  = Join-Path -Path $Destination -ChildPath $newName
            try {
                $_ | Copy-Item -Destination $target -Force -Confirm:$false -ErrorAction Stop
                Write-Host "File '$($_.Name)' copied to '$target'"
            }
            catch {
                Write-Warning "Error: $($_.Exception.Message)"
            }
        }
    

    【讨论】:

    • 感谢您的回复。你能看看修改后的问题吗?希望它能消除所有的困惑。
    • 非常感谢您花费的时间。它工作得很好
    【解决方案2】:

    我没有对此进行测试,但我认为您的代码存在一些问题。您似乎混淆了来源和目的地。此外,您正在将文件收集到变量 $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!"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多