获取名称中包含字符串的子文件夹的内容

时间:2017-03-23 21:20:43

标签: powershell path directory move

我想获取相同根文件夹的子文件夹中的所有文件,这些子文件夹在子文件夹的名称中都包含相同的字符串(" foo")。下面给我没有错误,没有输出。我不知道自己错过了什么。

Get-ChildItem $rootfolder | where {$_.Attributes -eq 'Directory' -and $_.BaseName -contains 'foo'}) | echo $file

最后,我不想只是回显他们的名字,而是将每个文件移动到目标文件夹。

谢谢。

3 个答案:

答案 0 :(得分:1)

这是一个解决方案,包括将每个文件夹的子文件移动到新的目标文件夹:

$RootFolder = '.'
$TargetFolder = '.\Test'

Get-ChildItem $RootFolder | Where-Object {$_.PSIsContainer -and $_.BaseName -match 'foo'} |
    ForEach-Object { Get-ChildItem $_.FullName |
    ForEach-Object { Move-Item $_.FullName $TargetFolder -WhatIf } }

当您感到满意时,请移除-WhatIf

如果您(例如)想要排除文件夹的子目录,或者想要在这些路径的所有子文件夹中包含子项而不是文件夹,则可能需要修改Get-ChildItem $_.FullName部分自己。

答案 1 :(得分:0)

替换

Get-ChildItem $rootfolder | where {$_.Attributes -match 'Directory' -and $_.basename -Match 'foo'}) | echo $file

Get-ChildItem $rootfolder | where {($_.Attributes -eq 'Directory') -and ($_.basename -like '*foo*')} | Move-Item $targetPath

您的要求:

  

所有包含相同的字符串(" foo")

您必须使用-like比较运算符。另外,对于完全匹配,我会使用-eq(区分大小写的版本为-ceq)而不是-match,因为它用于匹配子字符串和模式。

<强>的工作流程: 获取目录中的所有文件,通过管道将其发送到Where-Object cmdlet,您可以根据属性Attributes和Basename进行过滤。过滤完成后,将其发送到cmdlet Move-Item。

答案 2 :(得分:0)

将前两个变量适应您的环境。

$rootfolder = 'C:\Test'
$target = 'X:\path\to\whereever'
Get-ChildItem $rootfolder -Filter '*foo*' | 
  Where {$_.PSiscontainer} | 
    ForEach-Object {
      "Processing folder: {0} " -f $_
     Move $_\*  -Destination $target
   }