简体   繁体   English

PowerShell:以长数组的形式编写Export-csv属性

[英]PowerShell: Export-csv writing properties in long array

Following is an example of my code: 以下是我的代码示例:


$logpath = @(gci -path "c:\logs")
foreach ($i in $logpath)    
        {
        [array]$n += ($i.tostring()).trimend(".log")
    [array]$t += ($i.tostring()).lastwritetime
    }
$obj = new-object psobject
$obj | Add-Member -MemberType NoteProperty -Name Logname -Value $n
$obj | Add-Member -MemberType NoteProperty -Name LastWriteTime -Value $t
$i | export-csv c:\temp\logs.csv

Following is what the output looks like: 以下是输出结果:

Name,LastWriteTime  
----,-------------
Value1...,Value1

Following is what I want it to look like: 以下是我希望它看起来像:

Name,LastWriteTime  
Value1,Value1
Value2,Value2

Just to use your code can you try this : 只是为了使用你的代码,你可以试试这个:

$logpath = @(gci -path "c:\logs")
$objects = @() # Empty array
foreach ($i in $logpath)    
{
  $n = ($i.tostring()).trimend(".log")
  $t = ($i.tostring()).lastwritetime

  $obj = new-object psobject
  $obj | Add-Member -MemberType NoteProperty -Name Logname -Value $n
  $obj | Add-Member -MemberType NoteProperty -Name LastWriteTime -Value $t
  $objects += $obj
}

$objects | export-csv c:\temp\logs.csv

I just use an array of objects inside the loop. 我只是在循环中使用一个对象数组。

There's a basename property you can use in lieu of trimming off the file extensions: 您可以使用basename属性来代替修剪文件扩展名:

gci -path "c:\logs" |
select @{l='Name';e={$_.basename}},Lastwritetime |
export-csv c:\temp\logs.csv

You're trying too hard. 你太努力了。 Simply use a pipeline, select the desired properties, then export the result to a CSV: 只需使用管道, select所需的属性,然后将结果导出为CSV:

$logFolders = 'C:\logs', 'D:\more\logs', 'H:\some\other\logs'
gci -Path $logFolders `
  | select @{n='Logname';e={$_.Name.TrimEnd(".log")}}, LastWriteTime `
  | Export-Csv 'C:\temp\logs.csv'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM