在powershell中确定第4个管道分隔符出现后的字符并移动文件

时间:2016-11-07 20:02:30

标签: powershell

我有一个文件夹,其中包含一些管道分隔的一行文本文件。我需要查找并将与模式匹配的文件移动到一个文件夹,并将不匹配移动到另一个文件夹。

示例:

file1.txt包含State | Ohio | Zip | 43001 | 1 | Fred | Smith

file2.txt包含州|肯塔基州|邮编| 40006 | 3 |亨利|希金斯 等

使用PowerShell,我需要找到并移动所有文件,其中第5个字段(发生在第4个管道分隔符之后)等于特定值,例如1.然后我需要移动第5个字段不存在的所有文件等于1到不同的文件夹。我无法修改任何文本文件的内容。

我无法找出Powershell和RegEx的组合来查找和移动文件。

感谢。

[编辑] 添加了额外的代码......它确实在第5个字段中找到了所需的值,我还没有完成移动语句,我知道我的代码效率不高。由于嵌入在文件中的非打印回车/换行,在Get-Content行中添加了“-Raw”。似乎解决了我遇到的无法识别的管道字符的问题。

$sourcepath = "D:\Infiles"  
$destpath1 = "D:\Outfiles1"  
$destpath2 = "D:\Outfiles2"  
Set-Location $sourcepath  
$files = Get-ChildItem -Path $sourcepath -Recurse 
foreach ($file in $files)  
{
    $testtext = Get-Content $file -Raw  
    $fields = $testtext.Split('|')  
    $Field5=$fields[4]
    # write the output to test the code
    Write-Output $Field5
    # insert code here to move file to destination path based on the value of $Field5
}

1 个答案:

答案 0 :(得分:0)

除非您需要保留源目录的结构,否则请将其添加到循环的末尾:

if ($Field5 -eq 1) {
    Move-Item -Path $file.FullName -Destination $destpath1;
} else {
    Move-Item -Path $file.FullName -Destination $destpath2;
}