Powershell:多次解析和复制

时间:2018-02-13 20:22:13

标签: powershell parsing copy

此命令

$("#modalButton").click(function(){
      $("#buttonAlert").addClass('show') 
})

给了我这个结果:

Get-ChildItem -Filter "*$s*"

我想将单个文件复制到多个文件中,例如:

    Mode                LastWriteTime         Length Name                                                  
----                -------------         ------ ----                                                  
-a----        1/21/2018  12:18 PM         337562 001938 H-22 and Note.pdf                   
-a----        1/24/2018   8:48 AM         319382 002104 H-22 and Note.pdf                   
-a----        1/21/2018  12:27 PM         339307 002351 H-22 and Note.pdf                   
-a----        1/24/2018   8:41 AM         338962 002454 H-22 and Note.pdf   

同一档案的3份副本 - 原件和2份重复件。

问题:如何简洁地获取每个文件的编号(例如001938),然后将该文件复制到多个文件中(例如001938 H-22 and Note.pdf 001938 H-22.pdf 001938 Note.pdf 001938 22.pdf)?

我似乎无法找到一个很好的起点来获取数字,然后使用它复制多次。

3 个答案:

答案 0 :(得分:1)

使用正则表达式的示例:

$fn = "001938 H-22 and Note.pdf"
$fn | Select-String '^([0-9]+) (\S+) and (\S+)(\.pdf)' | ForEach-Object {
  "Copy $fn to {0} {1}{2}" -f
    $_.Matches[0].Groups[1].Value,
    $_.Matches[0].Groups[2].Value,
    $_.Matches[0].Groups[4].Value
  # Outputs 'Copy 001938 H-22 and Note.pdf to 001938 H-22.pdf'
  "Copy $fn to {0} {1}{2}" -f
    $_.Matches[0].Groups[1].Value,
    $_.Matches[0].Groups[3].Value,
    $_.Matches[0].Groups[4].Value
  # Outputs 'Copy 001938 H-22 and Note.pdf to 001938 Note.pdf'
}

答案 1 :(得分:1)

这可能很明显,但如果文件名的各个部分是固定长度的,那么你可以采用直接的解决方案:

$a = "001938 H-22 and Note.pdf"
$a
$a.substring(0,7) + $a.substring(7,4) + ".pdf" 
$a.substring(0,7) + $a.substring(16)

答案 2 :(得分:1)

以下使用-split运算符的一元形式将基本名称(文件名根)拆分为以空格分隔的标记,然后从这些标记构造输出文件名数组:

Get-ChildItem -Filter "*$s*" | % {
  # Split the base name (filename root) into whitespace-separated tokens.
  # (For separators other than whitespace, use the binary form of -split;
  # e.g., `$_.BaseName -split '_'`)
  $tokens = -split $_.BaseName
  $ext = $_.Extension # save the input extemsion
  # Construct the array of output filenames from the tokens:
  $destNames = 
    $_.Name,                                        # e.g.: 001938 H-22 and Note.pdf
    ('{0} {1}{2}' -f $tokens[0], $tokens[1], $ext), # e.g.: 001938 H-22.pdf
    ('{0} {1}{2}' -f $tokens[0], $tokens[-1], $ext) # e.g.: 001938 Note.pdf
  # Use $destNames to copy the source file to multiple destinations...
  $destNames # for diagnostic purposes, simply output the destination filenames
}