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

How to add empty rows in output csv?

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

$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 命令失败。

当此 returns $null 时,将没有属性可写入 CSV 文件,并且由于 -ErrorAction SilentlyContinue 无论如何都无法阻止脚本将 zilch 写入文件.

下面的代码在这方面做了大量的 error-checking,包括读取文件和去除空行和空格,预先测试服务器是否 on-line 现在它使用 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 = '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)
        }
        catch {
            Write-Warning "Error getting drive information for server '$Server'`r`n$($_.Exception.Message)"
        }
    }
}