【问题标题】:Delete multiple files or folders from a CSV file that contain more than one columns (Powershell)从包含多列的 CSV 文件中删除多个文件或文件夹 (Powershell)
【发布时间】:2013-07-25 07:35:16
【问题描述】:

我需要一些脚本帮助,该脚本将删除服务器 (DC) 上的 AD 禁用用户主文件夹和漫游配置文件文件夹。 我已经完成的步骤,我创建了一个 powershell 命令:

Import-Module ActiveDirectory
Get-ADUser -SearchBase "OU=Marked for Deletion,OU=Disable Users,DC=******,DC=com" -Filter * -Property * |
Select-Object -Property homeDirectory,profilePath | Export-CSV -Path .\Remove.csv

此命令导出禁用用户的主文件夹和漫游配置文件文件夹的属性。 现在' CSV 文件包含两个列,一个是“homeDirectory”,第二个是“profilePath”

问题是,当我执行这个脚本时,我得到了错误。

$folders = Get-Content "C:\lab\remove.csv"

foreach ($homeDirectory in $folders) {
    Remove-Item -Path $homeDirectory -force -Recurse
    }
foreach ($profilePath in $folders) {
    Remove-Item -Path $profilePath -force -Recurse
    }
write-host -foregroundcolor yellow "Delete action complete"

谁能帮帮我,我将不胜感激。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    首先,我会像这样从您的 CSV 中删除类型信息:

    Import-Module ActiveDirectory
    Get-ADUser -SearchBase "OU=Marked for Deletion,OU=Disable Users,DC=******,DC=com" -Filter * -Property * |
    Select-Object -Property homeDirectory,profilePath | 
    Export-CSV -Path .\Remove.csv -NoTypeInformation
    

    那么对于你的删除代码,我会使用这个:

    Import-Csv "C:\lab\remove.csv" | % {
      Remove-Item -Path $_.homeDirectory -force -Recurse
      Remove-Item -Path $_.profilePath -force -Recurse
    }
    
    write-host -foregroundcolor yellow "Delete action complete"
    

    您的代码的问题是您没有循环遍历列,而是逐行循环然后执行两次。要按照自己的方式进行操作,您需要在逗号处拆分行。

    【讨论】:

    • 为什么要去掉类型信息? Import-Csv 就是为了解决这个问题而设计的。
    • 感谢您的回复,还有一个问题,在配置文件文件夹中,我有名为 .V2 的文件夹,例如:\\lab\test\profilefolder.v2 \\lab\test\profilefolder 如何在脚本中包含他们也会被删除吗?
    猜你喜欢
    • 1970-01-01
    • 2015-09-14
    • 2021-09-29
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    相关资源
    最近更新 更多