PowerShell - 查找任何和所有子目录并移动它们

时间:2016-03-28 14:56:28

标签: powershell

这有点被问到,但我发现的问题都没有完全回答我想要做的事情。我正在使用PowerShell(全新的)编写一个脚本,用于搜索目录中的子目录,并将其移动到指定目录(如果找到)。

我的问题在于以下代码:

$Folders = C:\Users\temp

$MoveFolders = Test-Path $Folders -PathType Container

Write-Host $MoveFolders 
#I'm writing this with ISE, so I'm using write-host to view output for testing.

我遇到的问题是,每次运行此代码时,即使temp目录中没有文件夹,它也会返回true。我已经尝试了几乎所有可以想象的方式,并使用带有where-object的get-childitem进行测试,但我想只在存在子目录时才执行移动。

背后的想法是,如果用户以某种方式将文件或文件夹添加到该特定文件或文件夹,则在任务调度程序运行脚本时它将被移动。

修改的 重定向我的问题;它总是返回true,有几个人指出我写的东西会测试temp文件夹本身;那么有没有办法测试任何子文件夹并将其存储为布尔值,然后我可以将其传递给将完成移动过程的if语句?

2 个答案:

答案 0 :(得分:1)

我相信这就是你想要做的。

  #get the folders/subfolders from the directory
  $folders = Get-ChildItem C:\Users\temp -Recurse -Directory
    #loop through the folders
    foreach($folder in $folders) {    
        #copy the the folder(s) and item(s) within to the destination   
        Copy-Item -Path $folder.FullName -Destination C:\test -Recurse
    }

以下是您编辑问题后的更新答案。

$items = Get-ChildItem -Path C:\Users\mkrouse\Desktop\test -Directory -Recurse
#if items is equal to null, then there are no subfolders so assign the boolean to true
if($items -eq $null) {
    [bool]$NoSubfolders = $true;
    } else {
    [bool] $NoSubfolders = $false;
    }        

答案 1 :(得分:0)

您的代码测试“c:\ users \ temp”是否为文件夹 - 始终为true。您需要在“c:\ users \ temp”中查找文件夹。一种方法:

$Folders = "C:\temp"
$MoveFolders = Get-ChildItem -Path $folders -Directory
Write-Host $MoveFolders.Count 

$ MoveFolders现在包含“c:\ users \ temp”中所有文件夹的列表。现在您有一个要移动的文件夹列表。