2016-03-01 42 views
0

我已经在那里我每天都会收到2个CSV文件所在的文件命名是一样的东西CMCS_ {}时间戳,例如CMCS_02012016100101和CMCS_02012016100102情景differrent位置。这2个文件是不同的文件,并且具有不同的结构,但是因为这两个文件将进入同一个文件夹,在那里我的ETL工具将检索并处理它们。所以我写了一个脚本,脚本将根据文件的结构来区分它是文件A还是文件B.Powershell的文件复制到基于文件内容

对于文件A,我告诉脚本查看文件的第一行,如果以'Name,Emp(Date)'开头。 '然后将文件复制到folderA否则如果行以'名称,组'开头。'然后将文件复制到folderB,否则将文件复制到文件夹C

这里是我编写的代码,powershell不会生成任何错误,但它也不会产生任何结果。我想知道我的剧本有什么问题。

$fileDirectory = "D:\Data"; 
$output_path = "D:\Output\FileA"; 
$output_path2 = "D:\Output\FileB"; 
$output_path2 = "D:\Output\FileC"; 

foreach($file in Get-ChildItem $fileDirectory) 
{ 
# the full file path. 
$filePath = $fileDirectory + "\" + $file; 
$getdata = Get-Content -path $filePath 
$searchresults = $getdata | Select -Index 1 | Where-Object { $_ -like 'Name,Emp(Date).*' } 
$searchresults2 = $getdata | Select -Index 1 | Where-Object { $_ -like 'Name,Group.*' } 

if ($searchresults -ne $null) { 
Copy-Item $filePath $output_path 
} 
if ($searchresults2 -ne $null) { 
Copy-Item $filePath $output_path2 
} 
} 

回答

1

您的问题可能由Select -Index 1引起的,因为PowerShell使用基于0的索引这实际上会选择该文件的第二行。如果将其更改为0,则应正确获取标题行。

在另一个笔记上,您可以使用$file.FullName来取代文件路径,而不是使用$filePath = $fileDirectory + "\" + $file;

编辑:

[string] $FileDirectory = "D:\Data"; 
[string] $OutputPath = "D:\Output\FileA"; 
[string] $OutputPath2 = "D:\Output\FileB"; 
[string] $OutputPath3 = "D:\Output\FileC"; 

foreach ($FilePath in Get-ChildItem $FileDirectory | Select-Object -ExpandProperty FullName) 
{ 
    [string] $Header = Get-Content $FilePath -First 1 

    if ($Header -match 'Name,Emp.*') { 
     Copy-Item $FilePath $OutputPath 
    } 
    elseif ($Header -match 'Name,Group.*') { 
     Copy-Item $FilePath $OutputPath2 
    } 
    else { 
     Copy-Item $FilePath $OutputPath3 
    } 
} 
+0

此外,声明“,然后将文件复制到folderA,如果符合启动:

我想这应该做你以后‘名称,集团’。然后将文件复制到folderB,否则将文件复制到文件夹C“似乎不是真的。文件只会被复制到“D:\ Output \ FileA”和“D:\ Output \ FileC”。 –

+0

修改为else,而不是和 – user664481

+0

我已经将索引更正为0,但它仍然不起作用。 – user664481