2016-04-11 79 views
0

我正在尝试搜索某个文本的文本文件,然后只有匹配时才将该文本输出到不同的文本文件。我有麻烦创造这个。我附上了我有的代码,但问题不在于它创建results.txt文件,而且该文件是空白的。如果multiplatform_201604110718.txt中包含CCTK STATUS CODE:SUCCESS,我只想创建results.txt文件。Powershell问题输出文件

$Path = "C:\multiplatform_201604110718.txt" 
$Text = "CCTK STATUS CODE : SUCCESS" 
$PathArray = @() 
$Results = "C:\results.txt" 

# This code snippet gets all the files in $Path that end in “.txt”. 
Get-ChildItem $Path -Filter “*.txt” | 
Where-Object { $_.Attributes -ne “Directory”} | 
ForEach-Object { 
If (Get-Content $_.FullName | Select-String -Pattern $Text) { 
$PathArray += $_.FullName 
$PathArray += $_.FullName 
} 
} 
Write-Host “Contents of ArrayPath:” 
$PathArray | ForEach-Object {$_} 
$PathArray | % {$_} | Out-File "C:\Resuts.txt" 
+1

你的'$ PathArray'输出到控制台正常吗?你只需要输入'$ PathArray' – Matt

+0

这是输出,如果文本文件包含文本:“ArrayPath的内容: C:\ multiplatform_201604110718.txt”如果文本文件不包含文本,输出是:“ArrayPath的内容:” – James

回答

1

如果你真的只需要检查一个文件,你可以用少得多的代码做到这一点:

$Text = "CCTK STATUS CODE : SUCCESS" 
$p = "C:\Users\kzbx\Desktop\test.txt" 

if($ln = Select-String -pattern $text -path $p){ 
$ln.Line | Out-File C:\result.txt 
} 

这写在文字出现在您的结果文件行(如果我理解你正确,这就是你所需要的,如果不是,请澄清;))

+2

不错,但呃...为什么不只是'$ ln.Line'而不是再读整个文件呢? :-) –

+1

只需将选择的字符串直接传递给路径即可。无论如何,当你不想查找除一个文件以外的任何内容时,无需调用gci。 – Matt

+0

确实如此,如果你没有想到它会做什么:D – Paul