3

I have a powershell script (below) which seems to work but prints an error every time it runs which I believe may be impacting its performance. Why am I getting this error?

The error:

Move-Item : Cannot find path 'C:\Program Files (x86)\mailserver\mail\domain.com\user\inbox\201012090411577967.imap' because it does not exist.

At C:\scripts\findfiles.ps1:27 char:21
+ $list | foreach { mv <<<<  $_.Path $newdir }
    + CategoryInfo          : ObjectNotFound: (C:\Program File...0411577967.imap:String) [Move-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand

The powershell script:

# Prompt the user for a start directory
$startdir=Read-Host "Enter a directory to search (without trailing slash)"

# Define a variable for the new directory
$newdir="$startdir\temp"

# Make the temp directory
if (!(Test-Path -path $newdir))
{
  New-Item $newdir -type directory
}

# Tell them we will write to the start director\temp
write-host "Files will be moved to $newdir"

# Prompt to a pattern to search for
$pattern=Read-Host "Enter a pattern to search for"

# Tell the user we are doing something
write-host "Searching $startdir for `"$pattern`" then moving. Please wait...."

# Generate a list of files containing a pattern
$list = gci $startdir\* -include "*.imap" -recurse | select-string -pattern $pattern


# Move files matching the pattern to temp
$list | foreach { mv $_.Path $newdir }

2 Answers 2

2

Select-String can find more than one match within a file. I suspect it is finding more matches within the same file but you've already moved the file so the source doesn't exist anymore. Use the -List parameter on Select-String to get just one match per file.

$list = gci $startdir -r *.imap | select-string $pattern -List
Sign up to request clarification or add additional context in comments.

1 Comment

That was precisely the problem! It makes total sense - I just don't know why I didn't think of it. Thank you so much!!
0

Try changing the line that generates $list to something like this:

$list = gci $startdir* -include "*.imap" -recurse | where { select-string -Path $_ -Pattern $pattern -Quiet }

You might also want to change the last line to:

$list | mv $newdir

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.