Powershell System.Array 到 CSV 文件

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

我在使用 Export-Csv 时遇到一些困难。 我正在创建一个像这样的数组...

[pscustomobject] @{
    Servername = $_.Servername
    Name = $_.Servername
    Blk = ""
    Blk2 = ""
    Method = "RDP"
    Port = "3389"
}

我遇到的问题是,当我尝试将其导出到 CSV 时,我得到的垃圾看起来像这样......

“9e210fe47d09416682b841769c78b8a3”,,,,,

我已经阅读了大量解决此问题的文章,但我只是不明白如何获得正确的数据。

powershell csv
4个回答
28
投票

为了测试,我构建了一个带有服务器名称的 CSV 文件,并将其读入,并且在 PS4 中进行了以下操作:

$serverList = import-csv "datafile.csv"

$AllObjects = @()

$serverList | ForEach-Object {
    $AllObjects += [pscustomobject]@{
        Servername = $_.Servername
        Name = $_.Servername
        Blk = ""
        Blk2 = ""
        Method = "RDP"
        Port = "3389"
    }
}

$AllObjects | Export-Csv -Path "outfile.csv" -NoTypeInformation

7
投票

使用

Select-Object
防止错误的 CSV 导出。

示例:

Get-Services | Select-Object * | export-csv -Path C:\log.csv

5
投票

当您尝试从任何

Format-*
命令进行管道传输时,会发生这种情况。

Format-List
Format-Table
Format-Wide
cmdlet 在 PowerShell 中很特殊,因为它们旨在使用管道,并将其转换为在控制台中显示。 因此,您无法从
FL
FT
FW
通过管道传输到
Export-csv
。 正如唐·琼斯所说的“格式在右边”。

不相信我?请注意,当我运行

Get-Process
时,将其通过
Format-Table
发送,然后转换为 Csv。

gps | ft | ConvertTo-Csv
#TYPE Microsoft.PowerShell.Commands.Internal.Format.FormatStartData
"ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo","shapeInfo","groupingEntry"
"033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Internal.Format.TableHeaderInfo",
"9e210fe47d09416682b841769c78b8a3",,,,,
"27c87ef9bbda4f709f6b4002fa4af63c",,,,,
"27c87ef9bbda4f709f6b4002fa4af63c",,,,,
"27c87ef9bbda4f709f6b4002fa4af63c",,,,,

甚至是同一条绳子! 为什么我们会得到这个字符串? 我真的希望我知道,但我认为这与

Format-*
命令将对象转换为文本指令以在控制台中显示的方式有关。

如果您真的喜欢

Format-Table
的外观,请将其发送到
Out-File
,这是重定向
Format-*
命令输出的唯一方法。

另一条消息是使用

Tee-Object
将管道的副本转储到变量,然后将其发送到 Export。

Get-Process | Tee-Object -Variable ExportMe | Format-Table
$exportMe | export-Csv .\Export.csv

我称之为“鱼与熊掌兼得”的方法。


0
投票
Better example of using HTMLemail formatting 

``################################################ ########################## ## PowerShell 脚本:# #################################################### #######################

#Global Variable Section
#########################################
#Email Variables
$emailTo = "test.org"
$emailFrom = "test.org"
$smtpServer = "Mail.test.org" 
$message = ""
$subject = "J-Summary"
$message = ""

#Default Summary Variables; Set to Zero/Blank
$totalDollar = 0
$totalAccptDollar = 0
$numTrans = 0
$numAccptTrans = 0
$batchNum = ""
$transDetail = ""

#HTML Header Variables
$Header1 = "J "
$Header2 = "EC OPERATIONS"
$Header3 = " ALIDATION STATUS REPORT"

#File Path Section
#########################################
# Specify the path to EDI 820/824/997 Files
$filePath820 = "C:\Users\test\Desktop\Chase-Summary_Files\JPM820.outb*"
$filePath824 = "C:\Users\test\Desktop\Chase-Summary_Files\Chase_SH_AP_824_*"
$filePath997 = "C:\Users\test\Desktop\Chase-Summary_Files\Chase_SH_AP_997_*"
$archiveFolder = "C:\Users\test\Desktop\Chase-Summary_Files\_Archive\"

# Read the content of the Summary file
$content820 = Get-Content -Path $filePath820 -Raw
$content824 = Get-Content -Path $filePath824 -Raw
$content997 = Get-Content -Path $filePath997 -Raw

#Remove Line Feeds from EDI File Used For Easier Processing/Parsing Logic
$content820 = [string]::join("",($content820.split("`n")))
$content824 = [string]::join("",($content824.split("`n")))
$content997 = [string]::join("",($content997.split("`n")))

#HTML Compiler Section
#########################################
#Build Header HTML Section
$rptHeader = @"
<html>
<body>
<center><strong>$($Header1)</strong></center>
<center><strong>$($Header2)</strong></center>
<center><strong>$($Header3)</strong></center>
<br>
"@

#Build Footer HTML Section
$rptFooter = @"
</table>
<br>
<br>
STATUS(ST): TA=ACCEPTED TC=ACCEPTED W/CHANGE TE=ACCEPTED W/ERROR TR=REJECTED
<br>
<br>
<br>
IF YOU HAVE ANY QUESTIONS, PLEASE OPEN A SERVICENOW INCIDENT
ASSIGNED TO <strong>APP-BUSINESS-MATERIALS MANAGEMENT</strong>
<br>
<center>*****END OF REPORT*****</center>
</body>
</html>
"@

#EDI Reader Section to Finalize HTML Compiler
#########################################
#Read EDI 820 File (Used to Gather Total Received Number of Transactions and Dollar Amount)
$ediSegments = $content820 -split "\\"
##Parse Through Fields of Section and Get Total Dollar Amount Sent For All Transactions Regardless of Status For Summary Line
for ($s = 0; $s -lt $ediSegments.Count; $s++) {
    $ediSummarySegment = $ediSegments[$s] -split "\*"
    
    #Calculate Total Dollar Amount By Collecting Amount From Each Read BPR Section
    if ($ediSummarySegment[0] -eq "BPR") {
        $totalDollar = $totalDollar + $ediSummarySegment[2]
    }
    #Collect Total Number of Transactions From the GE Section
    elseif ($ediSummarySegment[0] -eq "GE") {
        $numTrans = $ediSummarySegment[1]
    }
}

#Read EDI 824 File (Used to Gather Total Processed Number of Transactions and Dollar Amount)
$ediSegments = $content824 -split "\\"
##Parse Through Fields of Section and Get Total Number of Accepted Dollar Amount and Accepted Transactions
for ($e = 0; $e -lt $ediSegments.Count; $e++) {
    $ediSummarySegment = $ediSegments[$e] -split "\*"

    #Calculate Total Dollar Amount By Collecting Amount From Each Read AMT Section
    if ($ediSummarySegment[0] -eq "AMT") {
        $totalAccptDollar = $totalAccptDollar + $ediSummarySegment[2]
    }
    #Collect Total Number of Transactions From the GE Section
    elseif ($ediSummarySegment[0] -eq "GE") {
        $numAccptTrans = $ediSummarySegment[1]
    }
}

#Parse Through Fields of Section
for ($i = 0; $i -lt $ediSegments.Count; $i++) {
    $ediSegment = $ediSegments[$i] -split "\*"

    #Collect and Format Date Value From the ISA Section
    if ($ediSegment[0] -eq "ISA") {
        $Customer = $ediSegment[8].TrimEnd()
        $Date = $ediSegment[9]
        $FormatDate = "$($Date.Substring(2,2))/$($Date.Substring(4,2))/$($Date.Substring(0,2))"
        $Time = $ediSegment[10]
        $FormatTime = "$($Time.Substring(0,2)):$($Time.Substring(2,2))"

        #Create Report Info Table
        $rptInfo = @"
<table border="0">
<tr><td>Customer ID: $($Customer)</td><td>&nbsp;</td><td>$($FormatDate) $($FormatTime) PT</td></tr>
</table>
<br>
"@
    }
    elseif ($ediSegment[0] -eq "ST") {
        $ediType = $ediSegment[0] -split "\*"    
    }
    elseif ($ediSegment[0] -eq "BGN") {
        #Collect Batch Number and Build Summary Table Section Based on First Collected Occurrence; Ignore All Other Values As They Would Be Duplicating This Section
        if ($batchNum -eq "") {
            $batchNum = $ediSegment[2]
                
            #Create Summary Table For First Time - Include Table Header
            $rptSummary = @"
<table border="1">
<tr><th>FILE# / BATCH#</th><th>AMOUNT</th><th># TRANS</th><th>STATUS</th></tr>
<tr><td>$($batchNum)</td><td>$($totalDollar)</td><td>$($numTrans)</td><td>TRANS RECEIVED</td></tr>
<tr><td>$($batchNum)</td><td>$($totalAccptDollar)</td><td>$($numAccptTrans)</td><td>TRANS ACCEPTED</td></tr>
</table>
<br>
"@
        }
    }
    elseif ($ediSegment[0] -eq "OTI") {
        #Collect and Format Date Value
        $effDate = $ediSegment[6]
        $effFormatDate = "$($effDate.Substring(4,2))/$($effDate.Substring(6,2))/$($effDate.Substring(0,4))"

        #Collect Transaction Detail and Build Detail Table and Rows Based on Each OTI Section Found in EDI File
        if ($transDetail -eq "") {
            #Create Transaction Detail Table For First Time - Include Table Header
            $transDetail = @"
<table border="1">
<tr><th>ST</th><th>TRANS #</th><th>TRACE #</th><th>EFF DATE</th><th>AMOUNT</th><th>MESSAGE</th></tr>
<tr><td>$($ediSegment[1])</td><td>$($ediSegment[9])</td><td>$($ediSegment[3])</td><td>$($effFormatDate)</td>
"@
        }
        #Build Additional Table Rows
        else {
        $transDetail = $transDetail + 
 @"
<tr><td>$($ediSegment[1])</td><td>$($ediSegment[9])</td><td>$($ediSegment[3])</td><td>$($effFormatDate)</td>
"@
        }
    }
    #Append Amount Value as Last Column in Row
    elseif ($ediSegment[0] -eq "AMT") {
        if ($transDetail -ne "") {
            $transDetail = $transDetail + "<td>$($ediSegment[2])</td><td></td></tr>" + "`r`n"
        }
    }
}

#Reset Variables to Avoid Duplication of Displayed Data
$errDetail = ""
$errReport = ""

#Read 997 EDI File (Used to Gather Total Number of Errored Transactions and Dollar Amounts)
$ediSegments = $content997 -split "\\"

#Parse Through Fields of Section
for ($i = 0; $i -lt $ediSegments.Count; $i++) {
    $ediSegment = $ediSegments[$i] -split "\*"
    
    #Collect Transaction Error Detail and Build Detail Table and Rows Based on Each AK2 Section Found in EDI File
    if ($ediSegment[0] -eq "AK2") {
        if ($errDetail -eq "") {
            #Create Transaction Error Detail Table For First Time - Include Table Header
            $errDetail = @"
<table border="1">
<tr><th>TRANS #</th><th>MESSAGE</th></tr>
<tr><td style="color:red"><strong>$($ediSegment[2])</strong></td><td style="color:red"><strong>TRANSACTION NOT ACCEPTED</strong></td></tr> `r`n
"@
        }
        #Build Additional Table Rows
        else {
            $errDetail = $errDetail + 
 @"
<tr><td style="color:red"><strong>$($ediSegment[2])</strong></td><td style="color:red"><strong>TRANSACTION NOT ACCEPTED</strong></td></tr> `r`n
"@
        }
    }
}

#Check If Error Detail Data Exists
if ($errDetail -eq "") {
    #Display Default Message to Customer Alerting No Errors Exist
    $errReport = @"
<br>
No Errors Exist.
<br>
"@
}
else {
    #Append Built Transaction Error Table to End Table Tag
    $errReport = @"
$($errDetail)
</table>
<br>
"@
}

#Build Email Message Body Section
#########################################
#Compile HTML Code
$body = @"
$($rptHeader)
$($rptInfo)
$($rptSummary)
$($errReport)
$($transDetail)
$($rptFooter)
"@

#Build Email Notification Section
#########################################
$message = $body
$anonUsername = "anonymous"
$anonPassword = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
$anonCredentials = New-Object System.Management.Automation.PSCredential($anonUsername,$anonPassword)
Send-MailMessage -smtpserver "$smtpServer" -from "$emailFrom" -to "$emailTo" -subject "$subject" -body "$message" -BodyAsHtml -credential $anonCredentials 

#Cleanup EDI File Section
#########################################
#Move Files to Archive Directory
Move-Item -Path $filePath820 -Destination $archiveFolder
Move-Item -Path $filePath824 -Destination $archiveFolder
Move-Item -Path $filePath997 -Destination $archiveFolder
© www.soinside.com 2019 - 2024. All rights reserved.