我试图找出最好的方法来做到这一点,我不知道如何Import-Csv
通过同一个管道使用2个不同的文件并导出找到的值...
所以,让我们开始与CSV文件1:我只想为价值观LoginNumber
哪里Type = H and (ContractorDomain -ne $null -or ContractorDomain -ne "")
.例如,这应该只是拉值0031482
和2167312
从下面.
注意:我只添加了空格和箭头,以便在此处更容易阅读.csv文件的列值或箭头之间没有空格.
"LoginNumber","Type","ContractorDomain"
"0031482" ,"H" ,"P12345" <<
"1251632" ,"P" ,"A52671"
"2167312" ,"H" ,"425126" <<
"0598217" ,"L" ,""
"1405735" ,"H" ,""
"2058194" ,"A" ,"L21514"
当找到LoginNumber
(基于上述条件)的值编号时,在CSV文件2中搜索它.然后获取AccountStatus
和SamAccountName
的相应值的值UserIDNumber
.
"SamAccountName","UserIDNumber","AccountDescriptionDetails","AccountStatus"
"jd12395" ,"0052142" ,"Company CEO" ,"Enabled"
"jwet" ,"2167312" ,"Software Developer" ,"Disabled" <<
"1b3gas5" ,"1385293" ,"Project Manager" ,"Disabled"
"632g1fsa" ,"0031482" ,"QA Tester" ,"Enabled" <<
"4126hs" ,"0000418" ,"Program Manager" ,"Disabled"
"axv" ,"1840237" ,"Accountant Administrator" ,"Disabled"
对于第3个CSV文件,我们有以下内容:
"domainName","SameAccountName","DateExpired"
"TempDomain","jwet" ,"20151230" <<
"PermDomain","p21942" ,""
"PermDomain","qz231034" ,""
"TempDomain","632g1fsa" ,"20151231" <<
"TempDomain","ru20da2bb22" ,"20160425"
接下来,对于第3个文件,我想添加列以插入Disabled
和Enabled
值(或User Match Not Found
值):
"domainName","SameAccountName","DateExpired","UserStatus"
"TempDomain","jwet" ,"20151230" ,"Disabled" <<
"PermDomain","p21942" ,"" ,"User Match Not Found"
"PermDomain","qz231034" ,"" ,"User Match Not Found"
"TempDomain","632g1fsa" ,"20151231" ,"Enabled" <<
"TempDomain","ru20da2bb22" ,"20160425" ,"User Match Not Found"
我学会了如何导入-csv并使用类似的东西创建新列...
Import-Csv $file | Select-Object -Property *, @{Name="UserStatus";Expression={ if ($true) {"fill value in here"} }} | Export-Csv $newFile -NoType
所以我在想这样的事情.我只是不确定如何通过管道搜索/查找/传递多个CSV文件值.
注意:其中一些CSV文件在我们搜索的列之前和之后有15列.另外,一些列值有逗号,所以我不能真正依赖它-Delimiter ,
.此外,某些列值没有"
(如果您要以txt格式打开CSV).
如果值被正确引用(即CSV有效),则包含逗号的列不应成为问题.Import-Csv
将正确导入记录42,"a,b",c
为三个值42
,a,b
和c
.如果您的CSV格式不正确:先修复它.
从第一个CSV文件中获取登录ID:
$logins = Import-Csv 'C:\path\to\file1.csv' | Where-Object { $_.Type -eq 'H' -and $_.ContractorDomain } | Select-Object -Expand LoginNumber
您可以简化ContractorDomain
属性检查$_.ContractorDomain
,因为PowerShell将空字符串解释为该上下文中$null
的布尔值$false
.对于其他零或空值(0,0.0,空数组等)也会发生相同的情况,但这不应该是您的方案中的问题.
接下来,将哈希表映射帐户名称创建为各自的状态.按您之前创建的ID列表过滤导入的第二个CSV,因此哈希表仅包含相关的映射.
$accountStatus = @{} Import-Csv 'C:\path\to\file2.csv' | Where-Object { $logins -contains $_.UserIDNumber } | ForEach-Object { $accountStatus[$_.SamAccountName] = $_.AccountStatus }
使用该哈希表,您现在可以将UserStatus
列添加到第三个CSV:
(Import-Csv 'C:\path\to\file3.csv') | Select-Object -Property *, @{n='UserStatus';e={ if ($accountStatus.ContainsKey($_.SameAccountName)) { $accountStatus[$_.SameAccountName] } else { 'User Match Not Found' } }} | Export-Csv 'C:\path\to\file3.csv' -NoType
Import-Csv
语句周围的括号确保在Export-Csv
开始写入文件之前完全读取和关闭该文件.只有在将修改后的数据写回同一文件时才需要它们,否则可以省略.星号选择所有导入的列,其他计算属性将添加要包括的新列.