【问题标题】:Copy filenames with matching foldernames in powershell在powershell中复制具有匹配文件夹名的文件名
【发布时间】:2020-12-22 13:08:34
【问题描述】:

我在源驱动器中有一堆文件名,即 G:\Langpacks,我需要将它们复制到目标驱动器,即 G:\OSLANGS

源驱动器包含目标目录名称的一部分,即

  1. G:\Langpacks\Microsoft-Windows-Client-Language-Pack_x64_de-de.cab

  2. G:\Langpacks\Microsoft-Windows-Client-Language-Pack_x64_en-US.cab

目标云端硬盘文件夹名称包含文件名的一部分,即

  1. G:\OSLANGS\de-de
  2. G:\OSLANGS\zh-CN

如何将匹配的文件名从源复制到目标? 到目前为止,我已经尝试了以下代码,但无法为每个文件夹名称硬编码变量,请帮助

$filename = '*de-de*.*' 
$searchinfolder = "G:\langpacks" Get-ChildItem -Path $searchinfolder -Filter $filename -Recurse | %{$_.FullName}  ```




【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以通过遍历源文件夹并查找所有扩展名为 .cab 的文件来完成此操作。 然后,添加 Where-Object 子句以使用正则表达式将该列表细化为基本名称以“两个字母破折号两个字母”序列结尾的文件。

    然后将其与“G:\OSLANGS”目标路径结合起来。

    $sourcePath  = 'G:\langpacks'
    $destination = 'G:\OSLANGS'
    
    # get a list of FileInfo objects from files with extension .cab
    (Get-ChildItem -Path $sourcePath -Filter '*.cab' -Recurse) | 
        Where-Object { $_.BaseName -match '.*_([a-z]{2}-[a-z]{2})$' } |  # refine the result using regex
        ForEach-Object {
            # create the target path combining the $destination and the match from the Where-Object clause 
            $targetPath = Join-Path -Path $destination -ChildPath $matches[1]
            # create that path is it does not already exist
            if (!(Test-Path -Path $targetPath -PathType Container)) {
                $null = New-Item -Path $targetPath -ItemType Directory
            }
            $_ | Copy-Item -Destination $targetPath -Force
        }
    

    正则表达式详细信息:

    .              Match any single character
       *           Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    _              Match the character “_” literally
    (              Match the regex below and capture its match into backreference number 1
       [a-z]       Match a single character in the range between “a” and “z” (case insensitive)
          {2}      Exactly 2 times
       -           Match the character “-” literally
       [a-z]       Match a single character in the range between “a” and “z” (case insensitive)
          {2}      Exactly 2 times
    )             
    $              Assert position at the end of the string, or before the line break at the end of the string, if any (line feed)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多