【问题标题】:Formatting output from PowerShell to a csv file将 PowerShell 的输出格式化为 csv 文件
【发布时间】:2019-06-28 18:27:14
【问题描述】:

尝试将两个变量结果从 Active Directory 输出到 PowerShell,并在 .csv 文件的一行中进行格式化,每个返回的变量位于单独的单元格中。输入文件包含四个 AD 组的名称。任务是统计每个组中的用户并返回用户总数。

目标是写入 .csv 文件,将输出格式化为一个单元格中的广告组名称,右侧下一个单元格中的用户计数。

这是一个简单的脚本,从读取文件开始并将结果返回到屏幕。尝试使用 Export-Csv 写入文件,但没有成功。 Add-Content 是最成功的技术。

以下代码可以部分工作,但广告组名称和用户数会写入 .csv 文件中的同一单元格。较早的尝试将 AD 组名称写在一行上,将用户总数写在下一行。

foreach($object in $groupfile){
    $groupName = $object.adgroupname
    $groupName = $groupName.Trim()
    $users = Get-ADGroupMember -Identity $groupName
    $usercount = $users.Count
    $groupinfo = ($groupName + " " + $usercount)

    # both of the lines below return the information to the screen on on line
    Write-Host $groupname, $usercount
    Write-Host $groupinfo

    # this line returns the information as shown below in the First result
    Add-Content -Path $filepath $groupname, $usercount

    # this line writes to the file as shown below in the Second result
    Add-Content -Path $filepath $groupinfo
}

第一个结果(对于少数组是可以接受的,但对于大量组来说,需要更稳健的解决方案。): 广告组名称一 357 广告组名称二 223 广告组名称三 155 广告组名称四 71

第二个结果(返回变量的两个值都在一个单元格中): 广告组名称一 357 广告组名称二 223 广告组名称三 155 广告组名称四 71

目标是写入 .csv 文件,将输出格式化为一个单元格中的广告组名称,右侧下一个单元格中的用户计数。

【问题讨论】:

  • 下面这行我犯了一个明显的错误; # 下面的两行都在一行中将信息返回到屏幕
  • 执行此操作的常用方法是构建一个自定义对象,该对象具有来自 ONE 对象 [a CSV 行] 中各种来源的所需道具。然后使用Export-CSV 自动构建合适的 CSV 文件。

标签: powershell active-directory


【解决方案1】:

我假设您的变量 $groupfile 是 Import-Csv 命令的结果。

如果我正确理解了这个问题,您可以这样做:

# loop through the $groupfile rows and collect the results as objects
$result = $groupfile | ForEach-Object {
    $groupName = $_.adgroupname.Trim()
    [PSCustomObject]@{
        'GroupName' = $groupName
        'UserCount' = @(Get-ADGroupMember -Identity $groupName).Count
    }
}

# display on screen
$result | Format-Table -AutoSize

# export to csv
$result | Export-Csv -Path $filepath -NoTypeInformation -Force

应该输出一个csv,比如

"GroupName","UserCount"
"ad group name one","357"
"ad group name two","223"
"ad group name three","155"
"ad group name four","71"

注意:Get-ADGroupMember 可以返回user、group 和computer 类型的对象,因此要么将第二列命名为ObjectCount,要么在Get-ADGroupMember 中添加Where-Object {$_.objectClass -eq 'user'} 子句仅过滤用户对象的函数

希望有帮助

【讨论】:

  • 在= @(Get-ADGroupMember ... 中使用AT SIGN 有什么作用?使用@() 表示一个数组。
  • @lit 是的,这样我们可以确保我们得到一个数组(即使是空的)以便能够使用.Count
  • 使用.Count 适用于基本(非数组)类型;总是返回一 (1)。如果需要一个数组,我会认为需要@(, (Get-ADGroupMember -Identity $groupName)).Count。我弄错了吗?
  • @lit.这仅适用于 PowerShell 3.0 及更高版本(除非您已打开严格模式)。 This answer 解释得比我想象的要好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 2022-07-20
  • 2018-11-29
  • 2017-08-20
  • 1970-01-01
相关资源
最近更新 更多