0

我在没有扩展名的 .txt 文件中有大约 500 个文件名。我有另一个带有完整文件名的 .txt 文件,扩展名总数超过 1,000。

我需要遍历较小的 .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
4

1 回答 1

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-Objectcmdlet:

$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
    }
}
于 2013-07-17T03:49:31.073 回答