开发者

Error with powershell script

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 performa开发者_运维问答nce. 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 }


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜