2013-08-27 35 views
0

我想自动化一个CSV文件,其中包含大量的数据行。这里是一个样本:PowerShell联合CSV列

========================== 
    = ID = Last Name =User ID= 
    = 22 = Smith = 0077 = 
    = 22 = Smith = 0078 = 
    = 22 = Smith = 0079 = 
    = 22 = Jones = 0081 = 

和名单继续。

我想要做的是将列ID与列姓氏合并,并使用Powershell将其放入新的CSV文件中。我试过如下:

@ {N =” ID”; E = {$ .ID +‘ - ’+ $。去年名称}}

没有太多的运气这虽然。

任何帮助,将不胜感激。

+0

是你能够解决你的问题? – Mitul

回答

0

您的列标题中有空格,这应该是您可以修复的第一件事。但除此之外,这是我的示例emp.csv文件,脚本,然后newemp.csv作为解决方案。

id loginid firstname lastname 
1 abc123 John patel 
2 zxy321 Kohn smith 
3 sdf120 Maun scott 
4 tiy123 Dham rye 
5 k2340 Naam mason 
6 lk10j5 Shaan kelso 
7 303sk Doug smith 

脚本

$objs [email protected](); 
$output = Import-csv -Path C:\Scripts\so\emp.csv | ForEach { 
$Object = New-Object PSObject -Property @{    
     Computed = [String]::Concat($_.id,$_.lastname) 
     Firstname = $_.firstname    
    } 
    $objs += $Object; 
} 
$objs 
$objs | Export-CSv C:\Scripts\so\newemp.csv 

Computed Firstname 
1patel John 
2smith Kohn 
3scott Maun 
4rye Dham 
5mason Naam 
6kelso Shaan 
7smith Doug 
1

我会先开始做内容CSV compatiable:

Get-Content file.txt | 
Where-Object {$_ -match '^\s+=\s.+\s+=$'} | 
ForEach-Object { $_ -replace '^\s+=\s*|\s+=$' -replace '\s+=\s+',','} | 
ConvertFrom-Csv -Header ID,LastName,UserID 

ID LastName UserID 
-- -------- ------ 
22 Smith 0077 
22 Smith 0078 
22 Smith 0079 
22 Jones 0081 

然后用Select-Object来创建新列:

... 
ConvertFrom-Csv -Header ID,LastName,UserID | 
Select @{n=’ID’;e={$_.ID + '-' + $_.LastName}},UserID 

ID  UserID 
--  ------ 
22-Smith 0077 
22-Smith 0078 
22-Smith 0079 
22-Jones 0081