【问题标题】:Foreach loop trouble while trying to edit a csv export file with powershell尝试使用 powershell 编辑 csv 导出文件时出现 Foreach 循环问题
【发布时间】:2022-01-12 19:25:20
【问题描述】:

我是 IT 界的新手,但有以下问题:我正在根据某些标准从 AD 中导出用户(代码很杂乱但有效)。当我在 foreach 部分之前导出 CSV 文件时,它一切正常,但是我需要在我的连接列中以 0 开头的所有行前面添加 9 作为扩展属性 1 和 2 的数字。我正在尝试导入CSV 文件,然后再次编辑导出。

代码:

$cost = @{Name="Cost";Expression={$_.extensionattribute1,$_.extensionattribute2 -join ''}}
$id = @{Name="SAP ID";Expression={$_.samaccountname}}



get-aduser -properties samaccountname,co,extensionattribute1,extensionattribute2 -filter {(co -eq "Dxxxx") -and (enabled -eq "true") -and (samaccountname -like "1*" -or samaccountname -like "2*" -or samaccountname -like "3*")} | select $id,$cost | export-csv C:\Users\xxxx\Favorites\CCDxxx.csv -notypeinformation -encoding UTF8



$csv = import-csv C:\Users\xxxx\Favorites\CCDxxx.csv



$var = foreach($line in $csv){


if($cost -like "0*"){
$newcost = "9"+$cost
write-host $sam ";" $newcost}




if($cost -notlike "0*"){
$newcost = $cost
write-host $sam ";" $cost}


}



$var | export-csv C:\Users\xxxx\Favorites\CCxxx1.csv -notypeinformation -encoding UTF8

脚本会运行,但我缺乏知识不会导出任何内容。任何帮助将不胜感激。

附:如果我是出于您在这里的高标准提出的问题,请原谅我,但我会学习的。谢谢, 问候。

【问题讨论】:

  • 请注意,对于 AD Cmdlet 使用基于 ScriptBlock 的过滤器,即使它可能工作也不是真正支持的。您应该按照 Microsoft 的建议使用 查询字符串。作为使用 ScriptBlock 时可能发生的情况的示例:stackoverflow.com/questions/70126195/…

标签: powershell csv


【解决方案1】:

您需要引用 foreach 循环中枚举的每个对象,以便检查和更新其 .cost 属性:

if($line.cost -like "0*"){ 
  # ...
  $line.cost = ...
}

你的循环不需要产生输出(不需要$var = ...),因为你可以简单地使用$csv作为第二个Export-Csv调用的输入,因为循环之后的$csv包含修改了个对象。[1]

但是,您可以通过仅使用 单个 管道来简化代码,在该管道中,您可以在 ForEach-Object 调用的帮助下根据需要转换 Get-ADUser 输出对象,在其脚本块 ( { ... }) 你可以使用automatic $_ variable 来引用手头的输入对象。代替具有计算属性的Select-Object,您可以使用[pscustomobject] 文字构造所需的输出对象。

get-aduser -properties samaccountname,co,extensionattribute1,extensionattribute2 -filter {(co -eq "Dxxxx") -and (enabled -eq "true") -and (samaccountname -like "1*" -or samaccountname -like "2*" -or samaccountname -like "3*")} | 
  ForEach-Object {
    $cost = $_.extensionattribute1, $_.extensionattribute2 -join ''
    if ($cost -notlike '0*') { $cost = '9' + $cost }
    # Create and output a custom object with the desired properties.
    [pscustomobject] @{
      Cost = $cost
      'SAP ID' = $_.samaccountname
    }
  } | 
    export-csv C:\Users\xxxx\Favorites\CCDxxx.csv -notypeinformation -encoding UTF8

[1] [pscustomobject] 是一个.NET 引用类型,这意味着$csv 数组包含对[pscustomobject] 实例的引用,所以以后对这些实例属性的修改也会反映在数组中。

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2015-11-04
    • 1970-01-01
    相关资源
    最近更新 更多