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

Powershell 如何在输出csv中添加空行?,powershell,csv,server,diskspace,Powershell,Csv,Server,Diskspace,我使用以下脚本生成磁盘空间利用率报告,但输出csv文件在不同服务器之间没有任何空格/空行,因此如何添加空格/空行以提高可读性 $LogDate = get-date -f yyyyMMddhhmm $File = Get-Content -Path C:\StorageReport\Servers.txt $DiskReport = ForEach ($Servernames in ($File)) {Get-WmiObject win32_logicaldisk <#-Creden

我使用以下脚本生成磁盘空间利用率报告,但输出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
$LogDate=获取日期-f yyyyMMddhhmm
$File=获取内容-路径C:\StorageReport\Servers.txt
$DiskReport=ForEach($File中的服务器名))
{获取WmiObject win32_logicaldisk`
-ComputerName$Servernames-筛选器“Drivetype=3”`
-错误动作持续不断
} 
$DiskReport|
选择对象@{Label=“Server Name”表达式={$\系统名},
@{Label=“Drive Letter”表达式={$\设备ID},
@{Label=“总容量(GB)”;表达式={{0:N1}”-f($\大小/1gb)},
@{Label=“空闲空间(GB)”;表达式={{0:N1}“-f($\ Freespace/1gb)},
@{Label='Free Space(%)';Expression={{0:P0}“-f($\.freespace/$\.size)}|
导出Csv-路径“C:\StorageReport\DiskReport\uU$logDate.Csv”-NoTypeInformation
在Microsoft.Exchange.Management.PowerShell.SnapIn中添加PSSnapin;
$messageParameters=@{
主题=“每周服务器存储报告”
Body=“附件是每周服务器存储报告。所有报告都位于C:\StorageReport\中,但
最近一次每周发送”
From=“电子邮件名称1”
To=“电子邮件名称1”
CC=“电子邮件名称2”
附件=(获取子项C:\StorageReport\*.|排序LastWriteTime |选择-last 1)
SmtpServer=“SMTPServerName.com”
}   
发送邮件@messageParameters-BodyAsHtml

虽然我的Excel(2016)版本接受(并显示)输入csv中的空行,但我不能保证其他版本也会如此,因此我认为最好在csv中包含一行,只包含逗号,这样可以有效地添加一行,所有字段都为空

为此,您可以在添加了
-Append
开关的循环中输出Csv文件

$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
的原因,无法停止脚本将Zlich写入文件

下面的代码对此进行了广泛的错误检查,包括读取文件和剥离空行和空白,预先测试服务器是否联机,现在它使用
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)"
        }
    }
} 

你是说只有逗号的ro?如果你想要一个完全空白的行,为什么还要使用csv?@DougMaurer是的,我不介意在excel中使用一行逗号…csv…一个txt文件会在excel中像csv文件一样打开吗…我的意思是在单独的单元格中??除此之外,为什么需要
(Get ChildItem C:\StorageReport\*.| sort LastWriteTime | select-last 1)
当您已经拥有先前创建的csv文件的完整路径时
“C:\StorageReport\DiskReport\uu$logDate.csv”因为每个文件的日志日期将不同,我不能显式地提供它。在任务调度器中运行这个命令,每次需要运行脚本时,都需要更改脚本。为什么不在阅读时添加空白行到报表中?这样您就不会修改原始数据。“最好在csv中包含一行逗号,有效地添加一行,所有字段都为空”-是的,这是我想要的…非常感谢…我还没有尝试过…我会很快回复您。您认为“mm”应该从日期格式中删除吗,因为如果分钟发生变化,加入路径可能有问题吗?@DavidKent加入路径不会有任何问题。此计划任务需要多长时间运行一次?我会保留会议记录,否则您很可能会覆盖在同一小时内创建的文件。这应该没问题,但我不知道你要保留多少文件。这应该每三个运行一次days@DavidKent那就没有问题了。由于
Join Path
在脚本中很早就被用来定义您正在创建的csv文件,因此我们一直使用该变量
$OutFile
,无论分钟、小时、天甚至年份是否发生变化都无关紧要。这是我们创建的文件,因此这是我们在电子邮件中作为附件发送的文件。