Foreach到CSV PowerShell

时间:2018-09-04 16:37:53

标签: powershell iis

今天在愤怒中第一次使用Exportto-CSV,使其在其他地方也起作用,但是当我执行以下操作时,它会得出一些随机数。

有人可以告诉我我在做什么错吗?

cast(lastseen AS date) = cast(lastseen as date) - interval '1' day 

2 个答案:

答案 0 :(得分:1)

看看get-help Export-Csv的描述。它说-

DESCRIPTION
    The Export-CSV cmdlet creates a CSV file of the objects that you submit. Each object is represented as a line or
    row of the CSV. The row consists of a comma-separated list of the values of object properties. You can use this
    cmdlet to create spreadsheets and share data with programs that take CSV files as input.

    Do not format objects before sending them to the Export-CSV cmdlet. If you do, the format properties are
    represented in the CSV file, instead of the properties of the original objects. To export only selected properties
    of an object, use the Select-Object cmdlet.

阅读一行-该行包含对象属性值的逗号分隔列表。您看到的随机数就是您导出到CSV的属性的长度。

要克服这一点,您可以使用PSCustomObject-

$array= @()
dir IIS:\AppPools | ForEach-Object {
    $obj = New-Object PSObject

    $Name = Add-Member -MemberType NoteProperty -Name "Name" $_.Name
    $managedRuntimeVersion = Add-Member -MemberType NoteProperty -Name "managedRuntimeVersion" $_.managedRuntimeVersion
    .
    .
    #Rest of your properties
    $array += $obj
    }
$array | Export-Csv C:\bob.csv -NoTypeInformation

再次问您,您在做什么错-

  1. 不了解Export-Csv cmdlet的正确输入类型。
  2. 使用Exportto-Csv代替Export-Csv。我非常怀疑Exportto-Csv名称的cmdlet是否存在。想知道如何得到结果。
  3. 生气时编码!

答案 1 :(得分:1)

Export-CSV希望将结构化数据作为对象属性。但是,您当前的代码会将值的数组传递给Export-CSV

尝试使用Select-Object即时创建对象,其中包含您想要的csv属性,然后将其通过管道传输到Export-CSV

这样的事情应该可以完成工作:

Get-ChildItem -path 'IIS:\AppPools' | 
    Select-Object -Property Name, `
        managedRuntimeVersion, `
        enabled32BitAppOnWin64, `
        managedPipelineMode, `
        @{label='processModel_username';     expression={$_.processModel.username}}, `
        @{label='processModel_password';     expression={$_.processModel.password}}, `
        @{label='processModel_identityType'; expression={$_.processModel.identityType}} | 
    Export-CSV -path 'C:\bob.csv'