2013-07-16 116 views
0

我有一个.txt文件中没有扩展名约500个文件名。我有另一个.txt文件,全文件名超过1000个。Powershell搜索和替换

我需要遍历较小的.txt文件并搜索当前在较大的.txt文件中读取的行。如果找到它,则将该名称复制到新的found.txt文件中,如果没有,则移动到较小的.txt文件中的下一行。

我是新来的脚本,不知道从这里开始。

Get-childitem -path "C:\Users\U0146121\Desktop\Example" -recurse -name | out-file C:\Users\U0146121\Desktop\Output.txt #send filenames to text file 
(Get-Content C:\Users\U0146121\Desktop\Output.txt) | 
ForEach-Object {$_ 1 

让我知道如果这没有意义。

+0

你可以添加一些示例输入和你想要的输出?这将有助于我们更好地理解这个问题。 – Eris

+0

请退后一步,描述您尝试解决的实际问题,而不是您认为的解决方案。你想通过这样做来达到什么目的? –

回答

1

您的示例显示您通过递归通过文件夹桌面创建文本文件,您不需要文本文件循环,您可以使用该文件,但可以说,您生成短名称的文本文件像你说的那样。

$short_file_names = Get-Content C:\Path\To\500_Short_File_Names_No_Extensions.txt 

现在,你可以通过该数组有两种方式循环:

使用foreach关键字:

foreach ($file_name in $short_file_names) { 
    # ... 
} 

或者使用ForEach-Object的cmdlet:

$short_file_names | ForEach-Object { 
    # ... 
} 

最大的区别是当前项目将是一个命名变量$file_name中的第一个和第二个中的非命名内置变量$_

假设你使用第一个。您需要查看$file_name是否在第二个文件中,如果是,请记录您是否找到它。可以这样做。我已在代码中解释每个部分的注释。

# Read the 1000 names into an array variable 
$full_file_names = Get-Content C:\Path\To\1000_Full_File_Names.txt 

# Loop through the short file names and test each 
foreach ($file_name in $short_file_names) { 

    # Use the -match operator to check if the array contains the string 
    # The -contains operator won't work since its a partial string match due to the extension 
    # Need to escape the file name since the -match operator uses regular expressions 

    if ($full_file_names -match [regex]::Escape($file_name)) { 

     # Record the discovered item 
     $file_name | Out-File C:\Path\To\Found.txt -Encoding ASCII -Append 
    } 
}