【问题标题】:PowerShell find number of files in users homedirectoryPowerShell 查找用户主目录中的文件数
【发布时间】:2018-03-21 13:26:05
【问题描述】:

我正在尝试编写一个 PowerShell 脚本来提取 Active Directory 中每个用户主目录的文件数。我想出了以下脚本,但实际上并没有获取文件数,每个用户的文件数为 0。我在表达中错过了什么?我试过 % 代替 ?我尝试添加! $_ 前面的结果不正确。

Get-ADUser -Filter * -properties * -SearchBase "OU=Information Technology,`
OU=User Accounts,DC=net,DC=local" | ft name, homedirectory, homedrive,`
@{Name='Files'; Expression={(Get-ChildItem -Recurse -Force -ErrorAction Ignore`
| ?{$_.HomeDirectory}).count}} -A

【问题讨论】:

  • Active Directory 只包含主目录的路径,文件在文件系统上。您需要在 $_.HomeDirectory 文件夹中使用 Get-Child 项,并计算这些项。
  • OP 正在尝试这样做。尝试使用 Select-Object 而不是 Format-Table。拇指规则是向左过滤并向右格式化。一旦您从 Select-Object 获得正确的信息,您就可以随心所欲地格式化表格。
  • 很好的捕获@randoms,除了那些在他们的个人资料中没有主目录的人之外,它为我提供了我运行脚本时碰巧所在的文件和文件夹。否则它会起作用。

标签: powershell active-directory expression home-directory


【解决方案1】:

作为randoms points out,您需要提供$_.HomeDirectory 作为Get-ChildItem 的参数。

为避免在HomeDirectory 属性为空或不存在时运行Get-ChildItem,您可以在表达式中放入if 语句(为了便于阅读,此处拆分为多个语句):

$ITUsers = Get-ADUser -Filter * -properties homedirectory,homedrive -SearchBase "OU=Information Technology,OU=User Accounts,DC=net,DC=local" 
$ITUsers |Format-Table name, homedirectory, homedrive,@{Name='Files'; Expression={
  if(Test-Path $_.homedirectory){
    @(Get-ChildItem $_.homedirectory -Recurse -Force -ErrorAction Ignore).Count
  } 
  else {
    0
  }
} -AutoSize

【讨论】:

  • 谢谢,它奏效了。您的 IF 语句有助于消除没有主目录的用户。谢谢!
猜你喜欢
  • 2021-03-23
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多