如何阅读多台计算机说明?



我想创建一个脚本,从CSV文件中读取所有计算机名。从所有这些中,我想要描述。此外,它应该以单个 CSV 导出。

这是我尝试过的,但是...

$path = Split-Path -Parent $MyInvocation.MyCommand.Definition 
$path_import_csv = $path + "" + "Computernamen.csv"
$path_export_csv = $path + "" + "Alessio.csv"
$computernames = Import-Csv $path_import_csv
foreach ($computername in $computernames) {
    Get-ADComputer -SearchBase "OU=1,OU=2,OU=3,DC=my,DC=domain" -Properties * |
        Select -Expand description |
        Export-Csv -Path $path_export_csv -Append -Delimiter ";" -NoTypeInformation -Force
}

从您的评论中,我收集到该文件Computernamen.csv根本不是CSV文件,而只是一个文本文件,每个文件的计算机名称都在单独的行上。 在这种情况下,不使用 Import-Csv ,而是Get-Content检索计算机名称数组。

此外(其他人已经明确表示(您根本没有在 foreach 循环中使用 $computername 变量,并且通过将-ExpandProperty开关添加到 Select-Object cmdlet,您不会收到具有属性 Description 的对象,而只是将描述作为字符串。 要输出带有Export-Csv的 CSV,您需要有一个(一系列(对象。

此外,我建议使用 Join-Path cmdlet 创建文件路径,而不是用 + 来污染字符串,这样你就不必担心可能缺少反斜杠。

除了$MyInvocation.MyCommand.Definition,您还可以使用 $PSScriptRoot 变量来获取当前脚本路径。 在 Windows PowerShell 2.0 中,此变量仅在脚本模块 (.psm1( 中有效。 从 Windows PowerShell 3.0 开始,它在所有脚本中都有效。

$path            = Split-Path -Parent $MyInvocation.MyCommand.Definition   # or use $PSScriptRoot
$path_import_csv = Join-Path -Path $path -ChildPath 'Computernamen.csv'
$path_export_csv = Join-Path -Path $path -ChildPath 'Alessio.csv'
$computernames   = Get-Content $path_import_csv
$searchBase      = 'OU=1,OU=2,OU=3,DC=my,DC=domain'
$result = foreach ($computername in $computernames) {
    # it is bad practice to use -Properties * if all you need is a small set of properties
    $computer = Get-ADComputer -Filter "Name -eq '$computername'" -SearchBase $searchBase -Properties Name, Description -ErrorAction SilentlyContinue
    # did we find a computer by that name?
    if ($computer) {
        # output an object with the two selected properties to get collected in the $result variable
        $computer | Select-Object Name, Description
    }
    else {
        Write-Host "A computer with name '$computername' does not exist."
    }
}
# output the result on console
$result | Format-Table -AutoSize
# save the result as proper CSV file
$result | Export-Csv -Path $path_export_csv -Delimiter ';' -NoTypeInformation -Force

最新更新