Powershell仅在包含特定字符串的文件夹名称中移动子目录中的项目

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Powershell仅在包含特定字符串的文件夹名称中移动子目录中的项目相关的知识,希望对你有一定的参考价值。

因此,假设有一堆包含不同子文件夹的文件夹。下面的示例包含用户1的根文件夹和该文件夹下的3个子目录。如何创建循环脚本以仅将包含字符串“upload”的子目录中的项目向上移动到用户文件夹。

->user1
--->user1upload
--->randomfolder1
--->randomfolder2
->user2
--->user2upload
--->randomfolder1
--->randomfolder2

到目前为止,我有以下代码将子目录中的所有文件移动到root用户文件夹。

$files = Get-ChildItem '*\*\*'
Get-ChildItem $files | Move-Item -Destination  $_.Directory.Parent.FullName 
$files | Remove-Item -Recurse

我想从中删除其他文件夹,以便只有名称中带有“upload”的文件夹才能将文件内容移动到root用户文件夹。我怎样才能做到这一点?

编辑:也尝试了这没有运气

$files = Get-ChildItem '*\*\*' | Select-String -Pattern "upload"
Get-ChildItem $files | Move-Item -Destination  $_.Directory.Parent.FullName 

EDIT2(3/21/201)为了清楚起见,他是一个SFTP计划。在C:/ usrs中有一个用户文件夹列表,我想将文件从c:/ usrs / user1 / user1upload移动到C:/ usrs / user1

答案

这使用PowerShell 5来指定-Directory。如果您尚未使用PowerShell 5,可以采用不同的方式完成。

搜索目录,然后搜索目录中的文件。

如果您确信文件将被正确移动,请从-WhatIf cmdlet中删除Move-Item

Get-ChildItem -Directory -Path $Env:USERPROFILE -Filter '*upload*' |
    ForEach-Object 
        Get-ChildItem -File -Path $_.FullName |
            ForEach-Object 
                Move-Item -Path $_.FullName -Destination $_.PSParentPath -WhatIf
            
    

我以为你在“用户”目录中,你通常无法访问所有目录。一个目录搜索级别。

Get-ChildItem -Directory -Path 'C:\Users\*\*upload*' |
    ForEach-Object 
        Get-ChildItem -File -Path $_.FullName |
            ForEach-Object 
                Move-Item -Path $_.FullName -Destination $(Split-Path -Parent $_.PSParentPath) -WhatIf
            
    

以上是关于Powershell仅在包含特定字符串的文件夹名称中移动子目录中的项目的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 PowerShell 递归删除具有特定名称的文件夹?

Lotus Notes Xpage - view.postScript("window.open()") 在替换包含的页面名称后不会打开新窗口(仅在特定文档中)

遍历文件夹内的特定子文件夹并删除包含特定名称的文件 - AIX

如何使用 PowerShell 处理数组以查找特定字符串?

AIX:查找名称包含特定字符串的文件并将其添加到列表中

在过去 1 分钟创建的文件中查找特定单词的 Powershell 脚本