简体   繁体   English

Powershell在每个新行中添加文件名(添加内容)

[英]Powershell adding name of file to each new line (add-content)

I am trying to export Groupmembers list from azuread, my whole script works fairly well, but I need each new line in the final file to have the name of the file it is importing from (as well as the content it is importing) 我正在尝试从azuread导出Groupmembers列表,我的整个脚本运行得很好,但是我需要最终文件中的每个新行都具有要导入的文件的名称(以及要导入的内容)

the part of the script i am using to do this is as follows 我用来执行此操作的脚本部分如下

(found this code here (在此处找到此代码

Merging multiple CSV files into one using PowerShell ) 使用PowerShell将多个CSV文件合并为一个

get-childItem "C:\Users\user\Documents\Azure\Intune\management\*.csv" | foreach {

    $filePath = $_

    $lines =  $lines = Get-Content $filePath | Select -Skip 1
    $linesToWrite = switch($getFirstLine) {
           $true  {$lines}
           $false {$lines | Select -Skip 1}

    }

    $getFirstLine = $false
       Add-Content "C:\Users\user\Documents\Azure\Intune\management\master_list.csv" $linesToWrite
    }

I would probably do something like this: 我可能会做这样的事情:

$files = Get-ChildItem -Path "C:\Users\user\Documents\Azure\Intune\management\*.csv"

ForEach ($file in $files) {
    Import-Csv -Path $File.FullName | 
        Select-Object -Property *, @{n='FileName';e={$file.Name}} | 
        Export-Csv -Path "C:\Users\user\Documents\Azure\Intune\management\master_list.csv" -NoTypeInformation -Append

}

Note that you need v3 or later of PowerShell to get the -Append flag for Export-Csv . 请注意,您需要PowerShell的v3或更高版本才能获取Export-Csv-Append标志。

Another way to do it. 另一种方法。 This way would be potentially memory intensive if the files are large but I like the method and it fits well with the way my brain works. 如果文件很大,则这种方式可能会占用大量内存,但我喜欢这种方法,它非常适合我的大脑工作方式。

$result = New-Object System.Collections.ArrayList
foreach($file in Get-ChildItem 'C:\Users\User\Documents\Azure\InTune\Management\*.csv'){
  $result.AddRange((Import-CSV $file | Add-Member -InputObject $_ -Name 'File' -MemberType NoteProperty -Value $file.Name))
}
$result | Export-CSV 'C:\Users\user\Documents\Azure\Intune\management\master_list.csv' -NoTypeInformation

I think that would be version agnostic but I always lose track of which features happen in which version. 我认为这与版本无关,但我始终无法跟踪哪个功能在哪个版本中发生。 Actually I think Add-Member would put it at v3+. 实际上,我认为Add-Member会将其设置为v3 +。

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

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