我需要按特定名称删除文件夹(如果存在)

时间:2015-01-08 09:19:11

标签: powershell

我有一个文件服务器,用户拥有自己的磁盘空间。我需要删除每个用户磁盘空间上的某个文件夹,但并非所有用户都有此文件夹。用户也分为部门,因此文件夹的布局如下所示:

d:\用户\ departmentA \ usernameA \ foldertodelete

d:\用户\ departmentA \ usernameB \ foldertodelete

d:\用户\ departmentB \ usernameC \ foldertodelete

d:\用户\ departmentC \ usernameD \ foldertodelete

...

我怎样才能实现这一目标?我正在考虑使用Poweshell,我一直在阅读有关Test-Path的内容,但我不知道如何使用它然后所有用户的路径都不同。

4 个答案:

答案 0 :(得分:0)

使用PowerShell,这非常简单:

$TargetName = "foldertodelete"
$BaseDir    = "D:\Users"

# Iterate over each department directory
foreach($Department in @(Get-ChildItem $BaseDir -Directory)){
  # Within each department, iterate over each user directory
  foreach($User in @(Get-ChildItem $Department -Directory)){
    # Check if the undesirable folder exists
    if([System.IO.Directory]::Exists(($TargetPath = Join-Path -Path $User -ChildPath $TargetName))){
      # If so, remove the directory and all child items
      Remove-Item $TargetPath -Recurse
    }
  }
}

PowerShell 3.0及更高版本中提供-Directory上的Get-ChildItem参数。对于PowerShell 2.0,您可以使用:

Get-ChildItem $BaseDir |Where {$_.PSIsContainer}

答案 1 :(得分:0)

感谢您的回答。我确实有一些问题使脚本工作。看起来脚本不了解BaseDir部分。用户拥有其文件夹的部门文件夹位于D:\ Users上。我将脚本复制到C:\ skript。并且错误消息显示它正在我的C驱动器上查找用户文件夹。它应该在D:\ users \ AAL-users \ username

上查看

以下是错误消息:

PS C:\ skript> \ RemoveFolder.ps1 Get-ChildItem:找不到路径' C:\ skript \ AAL-users'因为它不存在 在C:\ skript \ RemoveFolder.ps1:7 char:22 + foreach(@(Get-ChildItem $ Department -Directory)中的$用户){ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo:ObjectNotFound:(C:\ skript \ AAL-users:String)[Get-ChildItem],ItemNotFoundException     + FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.GetChildItemComman d

我确实尝试将脚本复制到我的D:\ users文件夹中。这次我没有收到任何错误消息,但脚本没有删除任何文件夹,因为它被调用。

答案 2 :(得分:0)

尝试下面的内容......

Remove-Item -path D:\Users\* -Filter *specificnameof the folder* -WhatIf --(Whatif allows you to   test a command before you run)


Remove whatif and execute the delete

Remove-Item -path C:\users\* -Filter *specificnameof the folder*

答案 3 :(得分:0)

以下是我现在运行的确切代码:

PS D:> Remove-Item -path“D:\ DU Users *” - 过滤器注释85 PS D:>

没有错误消息,但也没有删除相关文件夹。