如何在输出csv中添加空行?

问题描述

我正在使用以下脚本来生成磁盘空间利用情况的报告,但是输出的csv文件在不同服务器之间没有任何空格/空白行,那么如何添加空格/空白行以提高可读性?

$LogDate = get-date -f yyyyMMddhhmm
$File = Get-Content -Path C:\StorageReport\Servers.txt

$diskReport = ForEach ($Servernames in ($File)) 

{Get-WmiObject win32_logicaldisk <#-Credential $RunAccount#> `
-ComputerName $Servernames -Filter "Drivetype=3" `
-ErrorAction SilentlyContinue 
} 

$diskReport | 

Select-Object @{Label = "Server Name";Expression = {$_.SystemName}},@{Label = "Drive Letter";Expression = {$_.deviceid}},@{Label = "Total Capacity (GB)";Expression = {"{0:N1}" -f( $_.Size / 1gb)}},@{Label = "Free Space (GB)";Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) }},@{Label = 'Free Space (%)'; Expression = {"{0:P0}" -f ($_.freespace/$_.size)}} |

Export-Csv -path "C:\StorageReport\diskReport_$logDate.csv" -NoTypeinformation

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; 

$messageParameters = @{                        
                Subject = "Weekly Server Storage Report"                        
                Body = "Attached is Weekly Server Storage Report.All reports are located in C:\StorageReport\,but the                

          most recent  is sent weekly"                   
                From = "Email name1 <Email.name1@domainname.com>"                        
                To = "Email name1 <Email.name1@domainname.com>"
                CC = "Email name2 <Email.name2@domainname.com>"
                Attachments = (Get-ChildItem C:\StorageReport\*.* | sort LastWriteTime | select -last 1)                   
                SmtpServer = "SMTPServerName.com"                        
            }   
Send-MailMessage @messageParameters -BodyAsHtml

解决方法

尽管我的Excel(2016)版本在输入的CSV中接受(并显示)空白行,但我不能保证在其他版本中也会出现这种情况,因此我认为最好只包含逗号的行在csv中,有效地添加了一个所有字段为空的行。

为此,您可以在循环中的内部中输出Csv文件,在该循环中,您可以在添加了-Append开关的不同服务器上进行迭代。

$LogDate = Get-Date -Format 'yyyyMMddHHmm'
$File    = Get-Content -Path C:\StorageReport\Servers.txt
$OutFile = Join-Path -Path 'C:\StorageReport' -ChildPath "DiskReport_$LogDate.csv"

# because we now are Appending to the csv,we must make sure we start off with a new file
if (Test-Path -Path $OutFile -PathType Leaf) { 
    Remove-Item -Path $OutFile -Force
}

foreach ($Server in $File) {
    Get-WmiObject Win32_LogicalDisk -ComputerName $Server -Credential $RunAccount -Filter "Drivetype=3" -ErrorAction SilentlyContinue |
    Select-Object @{Label = 'Server Name';Expression = {$_.SystemName}},@{Label = 'Drive Letter';Expression = {$_.DeviceID}},@{Label = 'Total Capacity (GB)';Expression = {'{0:N1}' -f ( $_.Size / 1gb)}},@{Label = 'Free Space (GB)';Expression = {'{0:N1}' -f ( $_.Freespace / 1gb ) }},@{Label = 'Free Space (%)'; Expression = {'{0:P0}' -f ($_.freespace/$_.size)}} |
    Export-Csv -Path $OutFile -NoTypeInformation -Append

    # add a line with just commas (empty fields) below this server info to the file
    Add-Content -Path $OutFile -Value (',' * 4)
} 

接下来,继续发送电子邮件。我对此的评论只是做

Attachments = $OutFile

编辑

看您在注释中显示的错误,我怀疑您在其中读取服务器名称的输入文件以空行开头或服务器名称周围有空格,这导致Get-WmiObject命令失败

当返回$null时,将没有任何属性可以写入CSV文件,并且由于-ErrorAction SilentlyContinue,没有什么可以阻止脚本将zilch写入文件的。

下面的代码对此进行了广泛的错误检查,包括读取文件,剥离空行和空格,预先测试服务器是否在线以及现在使用try{..} catch{..}块。

>
$LogDate = Get-Date -Format 'yyyyMMddHHmm'
# make sure you skip empty or whitespaace only lines and trime the values
$File    = (Get-Content -Path 'C:\StorageReport\Servers.txt' | Where-Object { $_ -match '\S' }).Trim()
$OutFile = Join-Path -Path 'C:\StorageReport' -ChildPath "DiskReport_$LogDate.csv"

# because we now are Appending to the csv,we must make sure we start off with a new file
if (Test-Path -Path $OutFile -PathType Leaf) { 
    Remove-Item -Path $OutFile -Force
}

foreach ($Server in $File) {
    if (!(Test-Connection -ComputerName $Server -Count 1 -Quiet)) {
        Write-Warning "Could not connect to server '$Server'"
    }
    else {
        try {
            Get-WmiObject Win32_LogicalDisk -ComputerName $Server -Credential $RunAccount -Filter "Drivetype=3" -ErrorAction Stop |
            Select-Object @{Label = 'Server Name';Expression = {$_.SystemName}},@{Label = 'Free Space (%)'; Expression = {'{0:P0}' -f ($_.freespace/$_.size)}} |
            Export-Csv -Path $OutFile -NoTypeInformation -Append

            # add a line with just commas (empty fields) below this server info to the file
            Add-Content -Path $OutFile -Value (',' * 4)
        }
        catch {
            Write-Warning "Error getting drive information for server '$Server'`r`n$($_.Exception.Message)"
        }
    }
}