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

问题描述 投票:0回答:2

我正在使用以下脚本生成磁盘空间利用率报告,但输出的 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 protected]>"                        
                To = "Email name1 <[email protected]>"
                CC = "Email name2 <[email protected]>"
                Attachments = (Get-ChildItem C:\StorageReport\*.* | sort LastWriteTime | select -last 1)                   
                SmtpServer = "SMTPServerName.com"                        
            }   
Send-MailMessage @messageParameters -BodyAsHtml
powershell csv server diskspace
2个回答
1
投票

虽然我的 Excel 版本(2016)接受(并显示)输入 csv 中的空白行,但我不能保证其他版本中也会出现这种情况,所以我认为最好在csv,有效地添加一行所有字段为空的。

为此,您可以在循环中输出 Csv 文件 inside,在循环中添加

-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 = '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)"
        }
    }
} 

0
投票

在您的脚本中添加一个变量 $空白行=“” 然后使用 Export-Csv 在您想要的位置附加一个空行,如下所示

Export-Csv -Path $path$file1 -InputObject $blankline -Append -Force

© www.soinside.com 2019 - 2024. All rights reserved.