我正在尝试从另一个$ Table2更新$ Table1中的多个值。
说我有$ Table1(在这种情况下是导入的CSV文件):
Model ModelID Blah
abc 0 Blah
ghi 0 Blah
mno 0 Blah
,我有$ Table2(在这种情况下,是从数据源获得的):
name id
abc 11
def 12
ghi 13
jkl 14
mno 15
pqr 16
etc.
我正在尝试从$ Table2。“ id”更新$ Table1。“ ModelID”中的值
WHERE $Table1."Model" = $Table2."name"
在SQL中,我会做类似的事情:
UPDATE $Table1
SET ModelID = $Table2."id"
WHERE $Table1."Model" = $Table2."name"
如何基于PowerShell中变量中各列的联接进行条件更新?
我在看:
-replace... (I can't seem to do conditional replaces based on joins)
Add-Member -MemberType NoteProperty "modelID" -Value ... (again, I can't seem to set the value based on joins)
foreach($item in $Table1)
{
$Table1."ModelID" = $Table2."id"
where ?????
}.. (again, I can't seem to set the value based on joins)
我在这里超吃布丁吗?
答案 0 :(得分:1)
这非常混乱,但似乎可以完成工作。
$Table2 = import-csv C:\temp\test.csv
$Table1 = import-csv C:\temp\Test55.csv
Foreach($item in $Table1){
Foreach($tab2 in $Table2){
If($tab2.name -match $item.model){
$item.ModelID = $tab2.id
}
}
}
答案 1 :(得分:1)
这是我认为可以提供帮助的代码。
foreach($i in $t1)
{
foreach($j in $t2)
{
if($i.'model' -eq $j.'id')
{
$i.'modelid' = $j.'name'
break
}
}
}
对于表1中的每个项目,在表2中查找模式,如果找到匹配项,则更改表1中的值。
答案 2 :(得分:1)
使用哈希表从模型中查找ID的 dirty 变体。
使用此处的字符串作为源。
## Q:\Test\2018\11\23\SO_53440594.ps1
$table1 = @"
Model,ModelID,Blah
abc,0,Blah
ghi,0,Blah
mno,0,Blah
"@ | ConvertFrom-Csv
$Hashtable2 = @{}
@"
Name,Id
abc,11
def,12
ghi,13
jkl,14
mno,15
pqr,16
"@ | ConvertFrom-Csv | ForEach-Object {$Hashtable2.Add($_.Name,$_.Id)}
ForEach ($Row in $table1){
if($Hashtable2.Containskey($Row.Model)){
$Row.ModelID = $Hashtable2[$Row.Model]
} else {
"Model {0} not present in `$table2" -f $Row.Model
}
}
$table1
示例输出:
Model ModelID Blah
----- ------- ----
abc 11 Blah
ghi 13 Blah
mno 15 Blah
答案 3 :(得分:1)
这是另一种方法。它使用了“针对集合操作”技术[我认为是在v4中引入的]。当查找列表很大时,哈希表仍然是最快的方法。 [咧嘴]
$OneTable = @'
Model, ModelID, Blah
abc, 0, Blah
ghi, 0, Blah
mno, 0, Blah
'@ | ConvertFrom-Csv
# removed one line [ghi, 13] to allow for "no match" error test
$TwoTable = @'
Name, ID
abc, 11
def, 12
jkl, 14
mno, 15
pqr, 16
'@ | ConvertFrom-Csv
foreach ($OT_Item in $OneTable)
{
$Lookup = $TwoTable -match $OT_Item.Model
if ($Lookup)
{
$OT_Item.ModelID = $Lookup.ID
}
else
{
Write-Warning ('No matching Model was found for [ {0} ].' -f $OT_Item.Model)
}
}
$OneTable
输出...
WARNING: No matching Model was found for [ ghi ].
Model ModelID Blah
----- ------- ----
abc 11 Blah
ghi 0 Blah
mno 15 Blah
答案 4 :(得分:1)
这种方式...
$Data = @"
Model,ModelID,Blah
abc,0,Blah
ghi,0,Blah
mno,0,Blah
"@ | ConvertFrom-Csv
$Reference = @"
Name,Id
abc,11
def,12
ghi,13
jkl,14
mno,15
pqr,16
"@ | ConvertFrom-Csv
$Data | ForEach-Object {
$Local:ThisModelKey = $_.Model
if ($Reference.Name -contains $ThisModelKey) {
$_.ModelID = (@($Reference | Where-Object { $_.Name -like $ThisModelKey } ))[0].ID
}
}
结果是...
$Data
Model ModelID Blah
----- ------- ----
abc 11 Blah
ghi 13 Blah
mno 15 Blah