mkrouse
mkrouse

Reputation: 277

PowerShell search and replace

I have about 500 filenames in a .txt file without the extensions. I have another .txt file with full filenames with extensions that total over 1,000.

I need to loop through the smaller .txt file and search for the current line being read in the bigger .txt file. If it's found then copy the name to a new file, found.txt, and if it's not then move on to the next line in the smaller .txt file.

I am new to scripting and don't really know here to start.

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

Upvotes: 0

Views: 350

Answers (1)

Andy Arismendi
Andy Arismendi

Reputation: 52699

Your example shows you creating the text file by recursing through a folder on the desktop. You don't need a text file to loop through; you could just use that, but let’s say you do generate the text file of a short name like you state.

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

Now you can loop through that array in two ways:

Using the foreach keyword:

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

Or using the ForEach-Object cmdlet:

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

The big difference is that the current item will be a named variable $file_name in the first and a non-named built-in $_ variable in the second.

Let's say you use the first. You need to see if $file_name is in the second file and if so record that you found it. It can be done this way. I've put comments in the code explaining each part.

# 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
    }
}

Upvotes: 1

Related Questions