2016-06-07 68 views
0

文本和文件复制到的位置我有我们的工作秩序程序转储XML文件到一个目录。我需要搜索这些文件中的特定字符串,然后根据该字符串将它们复制到另一个位置。我从另一篇文章修改了下面的代码,虽然我没有得到任何错误,但它也不起作用。我是一个脚本新手,所以任何帮助将不胜感激。搜索基于文本的PowerShell

[string] $FileDirectory = "D:\Temp"; 
[string] $OutputPath = "D:\Temp\Temp_NY"; 
[string] $OutputPath2 = "D:\Temp\TEMP_FL"; 


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

if ($Header -match 'PARTNER |TEST_NY') { 
    Copy-Item $FilePath $OutputPath 
} 
elseif ($Header -match 'PARTNER |TEST_FL*') { 
    Copy-Item $FilePath $OutputPath2 
} 
} 

回答

0

标题将为-First 1(仅限第一行)。 -First 0什么都不返回。请尝试:

$FileDirectory = "D:\Temp"; 
$OutputPath = "D:\Temp\Temp_NY"; 
$OutputPath2 = "D:\Temp\TEMP_FL"; 

Get-ChildItem $FileDirectory | ? { !$_.PSIsContainer } | ForEach-Object { 

    $FilePath = $_.FullName 
    $Header = Get-Content $FilePath -First 1 

    if ($Header -match 'PARTNER |TEST_NY') { 
     Copy-Item $FilePath $OutputPath 
    } 
    elseif ($Header -match 'PARTNER |TEST_FL*') { 
     Copy-Item $FilePath $OutputPath2 
    } 

} 
+0

我现在收到访问错误。获取内容:对路径“d:\ TEMP \ TEMP_FL”被拒绝。 在行:8字符:15 + $部首=获取内容文件路径$ 1 - 第一 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~ + CategoryInfo:PermissionDenied:(d:\ TEMP \ TEMP_FL:字符串)获取内容],UnauthorizedAccessException + FullyQualifiedErrorId:GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand 获取内容:访问路径' D:\ Temp \ TEMP_NY'被拒绝。 在行:8字符:15 + $头=获取内容$文件路径 - 首先1 –

+0

刚才检查我的输出目录和它移动的所有文件到Temp_NY目录,即使它扔了访问被拒绝的消息。所以它不会根据搜索字符串复制文件。找出访问被拒绝的问题。由于这些子目录Temp_FL和Temp_NY的是同一个目录中的文件是试图运行对他们的脚本为好。给Get-ChildItem命令添加了-af,并解决了它。现在我只需要弄清楚为什么它将所有文件复制到一个目录中。 –

+0

尝试更新的答案。它只搜索文件..最后一个可能(出于某种原因)决定复制一个目录等...另外,如果答案解决了您的问题,您可以通过使用答案旁边的复选标记来接受它,而不是通过提供一个新的答案(这是一个评论):) –