PowerShell脚本的错误
问题描述:
我有一个PowerShell脚本(下面)似乎工作,但每次运行时打印一个错误,我相信可能会影响其性能。为什么我得到这个错误?PowerShell脚本的错误
错误:
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
PowerShell脚本:
# 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
可以在文件中找到多个匹配项。我怀疑它是在同一个文件中找到更多的匹配,但是你已经移动了文件,所以源码不再存在。使用Select-String上的-List
参数可以使每个文件只有一个匹配项。
$list = gci $startdir -r *.imap | select-string $pattern -List
答
尝试改变产生$名单像这样的行:
$list = gci $startdir* -include "*.imap" -recurse | where { select-string -Path $_ -Pattern $pattern -Quiet }
您可能还需要将最后一行更改为:
$list | mv $newdir
这正是问题!它总是有意义的 - 我只是不知道为什么我没有想到它。非常感谢!! – Brad 2010-12-10 02:42:43