首页 > 解决方案 > 导出到 Excel 会导致字符串长度而不是数据长度

问题描述

在 PowerShell 中,我有一个简单的 AD 搜索例程,用于查询 netbios 名称并返回用户名。它正在读取 netbios 名称的文本文件并添加到最后导出到 Excel 的数组中。Excel 文件中只有整数,例如字符串的长度,而不是netbios 和用户名。这是 Excel 输出的屏幕截图: Excel 文件输出

这是代码:

$de = New-Object System.DirectoryServices.DirectoryEntry
$ds = New-Object System.DirectoryServices.DirectorySearcher
$ds.SearchRoot = $de

Function GetInfo($argSearchCriteria) {
    $ds.Filter = "(&(objectCategory=computer)(objectClass=computer)(samAccountName=$($argSearchCriteria)$))"
    $ds.SearchScope = "SubTree"

    $r = $ds.FindOne()

    if ($r.Count -ne 0) {
        
        $ReturningData = $argSearchCriteria.Trim()  + ",    " + $r.Properties.description.Trim()
        return $ReturningData

    } # end if

} # end function

$filename = "H:\Working\tags.txt"               # input text file, one netbios name on each line. i.e. ctb123456win10
$FilePath = $env:TEMP + '\' + 'AD_Report.csv'   # output CSV file containing netbios and username i.e. ctb123456win10, Smith Regan

# initialize new array for results
$FinalArray = @()

# open tag file and read each tag and get the user's name returned
$(foreach ($line in Get-Content $filename) {

    $Results = GetInfo ($line.trim())
    $FinalArray += $Results
    
    write-host $Results
 })

######   Export results to CSV file to be opened by Excel  #######
$FinalArray | Export-Csv -notype -Path $FilePath
            
# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
                
# Display Excel and Maximized it
$objExcel.Visible = $false

# Open the Excel file and save it in $WorkBook
$wb = $objExcel.Workbooks.Open($FilePath)
$ws = $wb.Worksheets.Item(1) 
$range = $ws.UsedRange                  # select all values in workbook
$range.EntireColumn.Autofit()           # autosize all columns in selection
$ws.Rows("1:1").Font.Bold=$true         # bold the top header row
$ws.Rows("1:1").Interior.ColorIndex =48 # dark gray the top header row
$objExcel.Visible = $true               # display Excel
$objExcel.WindowState= "xlMaximized"    # max Excel

标签: excelpowershellexport

解决方案


问题是您将字符串数组传递给Export-Csv. 你最终得到的是看起来像这样的字符串:

 Server1,     Web Server
 Server2,     SQL Server
 Server3,     File Server

虽然您想要的是具有两个属性(NetBiosName 和描述)的对象,例如:

NetBiosName  Description
-----------  -----------
Server1      Web Server
Server2      SQL Server
Server3      File Server

您可以通过管道传输到的那些对象Export-Csv,它会按预期工作。

因此,您可以使用Set-Content您目前拥有的内容(尽管您不会像您期望的那样有一个标题行,并且您的所有描述都会在开头有几个空格),或者您可以创建对象以发送到Export-Csv. 我建议后者。

更改您的函数以创建对象:

Function GetInfo($argSearchCriteria) {
    $ds.Filter = "(&(objectCategory=computer)(objectClass=computer)(samAccountName=$($argSearchCriteria)$))"
    $ds.SearchScope = "SubTree"

    $r = $ds.FindOne()

    if ($r.Count -ne 0) {
        
        [PSCustomObject]@{
          NetBiosName = $argSearchCriteria.Trim()
          Description = $r.Properties.description.Trim()
        }

    } # end if

} # end function

函数返回所有未明确重定向的内容(例如在变量中捕获的内容,或通过管道传输到类似Write-Host的内容),因此不需要该return行。


推荐阅读