【问题标题】:Add Text at top of exported CSV in powershell在 powershell 中导出的 CSV 顶部添加文本
【发布时间】:2022-01-01 03:15:03
【问题描述】:

我正在尝试在 AzureAD 中创建一个包含计算机 objectid 的 csv 文件,以便能够导入到组中。 csv的格式需要是:

version:v1.0
[memberObjectIdOrUpn]

然后是计算机的objectid列表

$devices = Get-AzureADDevice -SearchString COMPUTERS
$devices = $devices.objectid | Select-Object @{n = '[memberObjectIdOrUpn]'; e = { $_ } }
$devices | Export-Csv -Path C:\temp\computers.csv -NoTypeInformation 

这将为我提供一个列表,其中包含需要在文件顶部添加“版本:v1.0”的唯一问题。

在导出 csv 之前有什么方法可以添加它还是我需要这样做:

@("version:v1.0") +  (Get-Content "C:\temp\computers.csv") | Set-Content "c:\temp\computers.csv"

我只是觉得有更好的方法:)

【问题讨论】:

  • 您的解决方案非常好(无论您感觉如何):)
  • 这种方法确实没有什么问题。
  • 有一个 ConvertTo-Csv cmdlet 可以为您提供导出到 csv 文件中的所有文本。因此您可以构建它,将其与您的自定义前缀行 [s] 连接,然后将其发送到文件。 [咧嘴]
  • 我忘记了 ConvertTo-Csv !

标签: powershell csv


【解决方案1】:

我认为Convert-Csv 可能更简单,因为它返回一个字符串数组而不是写入文件。

# get the system line separator for convenientce
$newline = [Environment]::NewLine

# set up the file header
$header = ("version:v1.0{0}" -f $newline) 

# get the device list (returns an array of strings)
$devices = Get-AzureADDevice -SearchString COMPUTERS
$devices = $devices.objectid | Select-Object @{n = '[memberObjectIdOrUpn]'; e = { $_ } } | ConvertTo-Csv -NoTypeInformation 

# write the header and your content
Set-Content -Value ($headers + ($devices -join $newline)) -Path C:\temp\computers.csv 

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多