2017-07-07 80 views
1

我想复制一堆jpg/gif文件与起始名称到另一个位置。它不符合预期。它会创建添加文件夹,保持静态并且不会复制所有子文件夹。然后我再次运行整个路径并删除所有空文件夹。powershell - 复制项目创建空文件夹

如何防止Copy-Item创建添加空文件夹?我想用新的根目录保留当前路径,并用文件名的起始字母添加一个新的子目录,并将所有文件放在那里。

当前文件夹结构

F:\pics\2016\071310 
| 
-----> K001 
    | 
    ------> 0494434-002394 
    ------> 0494434-002394 
. 
. 
------> K0073 

想要的文件夹结构

C:\test\2016\071310 
| 
-----> K001 
    | 
    ------> 0494434-002394 
    | 
    ----> K-G 
    ----> K-F 
    . 
    . 
    ------> 0494434-002394 
    | 
    ----> K-G 
    ----> K-F 
    . 
    . 
. 
. 
------> K0073 

这里是我的代码

$source = "F:\pics\2016\071310" 
$destination = "C:\test" 
$folder = "K-G\" 
$filterKG = [regex] "^K-G.*\.(jpg|gif)" 

$bin = Get-ChildItem -Exclude $folder -Path $source -Recurse | Where-Object {($_.Name -match $filterKG) -or ($_.PSIsContainer)} 

foreach ($item in $bin){ 
$new_folder = $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,$folder) 

if(-not (Test-Path $new_folder)){ 
    New-Item -Type dir $new_folder 
    Write-Host $new_folder 
} 
Copy-Item $item.FullName -Destination $item.FullName.ToString().Replace($source,$destination).Replace($item.Name,$folder+$item.Name) 
} 

#remove empty folders which where added 
$tdc="C:\test" 
do { 
    $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName 
    $dirs | Foreach-Object { Remove-Item $_ } 
} while ($dirs.count -gt 0) 
+1

我不是你想要什么明确的。你说你想要_“保留当前路径和一个新的根目录,并添加一个新的子目录与文件名的起始字母,并把所有的文件”._。但想要的文件夹结构看起来像复制的文件在目的地'K001'的根目录,并且有空的子目录'K-G'等? – gms0ulman

+1

在核心中,我想只复制以最深的子文件夹中最深的文件夹中最深的子文件夹中以K-G开头的所有文件,该子文件夹以该文件的前3个字母命名。 –

回答

1

当前脚本

  • $_.PSIsContainer - 我想你会得到这些保留文件夹结构,但最好忽略,因为你不直接感兴趣。 AFAICS这就是为什么你会得到空文件夹。
  • -Exclude $folder - 这没有做任何事;名称为K-G的文件夹仍将包含在内。

  • $item.FullName.ToString() - 由于$item.FullName已经是字符串,所以ToString()没有任何作用。运行$item.Fullname.GetType().Name即可查看。


建议脚本

  • Split-path可以让你获得目录的文件在使用-Parent

  • .Replace($source,$destination)与您的原始脚本相同。

  • 您无需硬编码$folder即可将其置于您的目的地。只需使用$item.Name.SubString(0,3)即可获取文件名的前3个字母。
    string manipulation demo


$bin = Get-ChildItem -Path $source -Recurse | Where-Object {($_.Name -match $filterKG)} 

foreach ($item in $bin){ 

    $new_folder = (Split-path $item.Fullname -Parent).Replace($source,$destination) + "\" + $item.Name.SubString(0,3) + "\" 

    if(-not (Test-Path $new_folder)){ 
     New-Item -Type dir $new_folder 
     Write-Host $new_folder 
    } 

    Copy-Item $item.FullName -Destination $new_folder 

} 
相关问题