powershell - 如何使用变量导出Csv?

标签 powershell csv

我正在尝试使用PowerShell将8个变量写到CSV文件中,但是它最终只是,,,,,,,而不是var1,var2,var3,var4,var5,var6,var7,var8
我的代码如下:

$newRow = "{0},{1},{2},{3},{4},{5},{6},{7}" -f $var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8
$newRow = $newRow -Replace "`t|`n|`r",""
$newRow = $newRow -Replace " ;|; ",";"
$newRow += "`n"
$newRow | Export-Csv -Path $file -Append -noType -Force

没有-Force我得到以下错误消息:
Export-Csv : Cannot append CSV content to the following file: C:\result.txt. The
appended object does not have a property that corresponds to the following column:
var1. To continue with mismatched properties, add the -Force parameter, and then
retry the command.
At C:\Test.ps1:72 char:12
+     $newRow | Export-Csv -Path $file -Append -noType
+               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : InvalidData: (var1:String) [Export-Csv], InvalidOperationException
     + FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell.Commands.ExportCsvCommand

EDIT:

Script:

$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = 'C:\zabbix\script\zabbix_vbr_job.ps1 "Discovery"'

$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
#$startInfo.Username = "DOMAIN\Username"
#$startInfo.Password = $password

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$discoveryJson = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
cls

$discovery = $discoveryJson | ConvertFrom-Json
$file = "C:\zabbix\script\result.txt"

function RunScript ($param, $id)
{
    $startInfo = New-Object System.Diagnostics.ProcessStartInfo
    $startInfo.FileName = "powershell.exe"
    $startInfo.Arguments = "C:\zabbix\script\zabbix_vbr_job.ps1 '$param' '$id'"

    $startInfo.RedirectStandardOutput = $true
    $startInfo.UseShellExecute = $false
    $startInfo.CreateNoWindow = $false

    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $startInfo
    $process.Start() | Out-Null
    $output = $process.StandardOutput.ReadToEnd()
    $process.WaitForExit()

    return $output
}

$fileContent = Import-csv $file

$NewCSVObject = @()
foreach($obj in $discovery.data)
{
    $index = [array]::indexof($discovery.data, $obj)
    Write-Host $index "/" $discovery.data.count
    #Write-Host (RunScript "Result" $obj.JOBID )
    $Result = RunScript "Result" $obj.JOBID
    #Write-Host $Result
    $RunStatus = RunScript "RunStatus" $obj.JOBID
    #Write-Host $RunStatus
    $IncludedSize = RunScript "IncludedSize" $obj.JOBID
    #Write-Host $IncludedSize
    $ExcludedSize = RunScript "ExcludedSize" $obj.JOBID
    #Write-Host $ExcludedSize
    $VmCount = RunScript "VmCount" $obj.JOBID
    #Write-Host $VmCount
    $Type = RunScript "Type" $obj.JOBID
    #Write-Host $Type
    $RunningJob = "RunningJob"#RunScript "RunningJob" $obj.JOBID
    #Write-Host $RunningJob

    #$newRow = New-Object PsObject -Property @{ JobID = $obj.JOBID ; Result = $Result ; RunStatus = $RunStatus ; IncludedSize = $IncludedSize ; ExcludedSize = $ExcludedSize ; VmCount = $VmCount ; Type = $Type ; RunningJob = $RunningJob }
    $newRow = "{0},{1},{2},{3},{4},{5},{6},{7}" -f $obj.JOBID,$Result,$RunStatus,$IncludedSize,$ExcludedSize,$VmCount,$Type,$RunningJob
    $newRow = $newRow -Replace "`t|`n|`r",""
    $newRow = $newRow -Replace " ;|; ",";"
    $newRow += "`n"
    #$newRow | Out-File $file
    #[io.file]::WriteAllText("C:\zabbix\script\test.txt",$newRow)
    Write-Host $newRow
    $newRow | Export-Csv -Path $file -Append -noType
    break
}
#cls
Write-Host $fileContent

CSV header :

JobID,结果,RunStatus,IncludedSize,ExcludedSize,VmCount,Type,RunningJob

最佳答案

如果您还是手动构建CSV行,则没有必要使用Export-Csv

要么改变

$newRow | Export-Csv -Path $file -Append -noType -Force

进入
$newRow | Add-Content $file

或像这样构建$newRow:
$newRow = New-Object -Type PSObject -Property @{
  'JobID'        = $var1
  'Result'       = $var2
  'RunStatus'    = $var3
  'IncludedSize' = $var4
  'ExcludedSize' = $var5
  'VmCount'      = $var6
  'Type'         = $var7
  'RunningJob'   = $var8
}

问题就会消失。

此行为的原因是Export-Csv用于将对象转换为其属性的表格字符串表示形式。本质上是一个对象
@{
  propertyA: 'foo'
  propertyB: 23
}

变成

属性(property)A,属性(property)B
“foo”,“23”

如果您已经在构建字符串,则生成的(字符串)对象只有一个属性(Length),该属性与现有CSV中的任何属性都不匹配。因此,您在没有-Force的情况下遇到的错误。即使使用-Force,写入CSV的属性也是从现有CSV中的第一项确定的。该集合中不存在的属性将从输出中省略,并且该对象中不存在的该集合中的属性将填充为空值。

关于powershell - 如何使用变量导出Csv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42647624/

相关文章:

powershell - 神秘主义:Invoke-WebRequest仅通过ISE工作

powershell - 防止胁迫

windows - 在 Windows 2012 R2 中使用 Powershell 导入计划任务

python - dataframe和csv文件的日期格式可以相同吗?

java - 是否有任何库可以将 XLSX 文件转换为 CSV?

python - 在 python 中打开 .csv 文件时语法无效

powershell - Powershell-错误检查以查找和替换(ForEach对象)

azure - 如何通过powershell在azure ad中创建动态组?

Python脚本读取一个目录中的多个excel文件并将它们转换为另一个目录中的.csv文件

file - 如何在 Spark 中写入 CSV