You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中匹配列表用户名并提取对应行生成新列表的方法

PowerShell脚本完善:根据用户名列表筛选匹配行

需求

基于$secondlist中的用户名清单,在$list中筛选出用户名匹配的条目,生成包含这些条目的$newlist。

原始数据

$list

姓名经理用户名
KumarPollyKumar.A
GinnyBerthaGinny.P
AdamSamAdam.r
OliviaJohnOliv.e
RiaEdwinRia.k
WayneSidWayne.g
GregJoelGreg.s
FionBestonFion.w
SandyMattSandy.k

$secondlist

用户名
Kumar.A
Ginny.P
Oliv.e
Wayne.g
Sandy.k

预期结果 $newlist

姓名经理用户名
KumarPollyKumar.A
GinnyBerthaGinny.P
OliviaJohnOliv.e
WayneSidWayne.g
SandyMattSandy.k

初始脚本

script: |     
  [CmdletBinding()]
  param (
       [array]
       $list,
       [array]
       $secondlist
   )


   foreach ($item in $list) {     
       $username = $item.Username     
       $manager = $item.Manager  
       $name = $item.Name  
   } 
   foreach ($item in $secondlist) {     
       $newusername = $item.Username 
   }

 parameters:
   list: "{{ list }}" 
   secondlist: "{{ secondlist }}"         

完善后的脚本

script: |     
  [CmdletBinding()]
  param (
       [array]
       $list,
       [array]
       $secondlist
   )

   # 提取目标用户名集合,提升匹配效率
   $targetUsernames = $secondlist.Username

   # 筛选出用户名匹配的条目
   $newlist = $list | Where-Object { $targetUsernames -contains $_.Username }

   # 输出结果
   $newlist

 parameters:
   list: "{{ list }}" 
   secondlist: "{{ secondlist }}"         

关键修改点

  • 提取$secondlist中的所有用户名到$targetUsernames数组,避免重复遍历目标列表
  • 使用Where-Object结合-contains运算符,高效筛选$list中符合条件的条目
  • 直接将筛选结果赋值给$newlist,完成核心需求
  • 保留原有参数结构,确保脚本兼容外部传入的数据源

内容的提问来源于stack exchange,提问作者865296

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:45:09