2010-12-09 106 views
2

我有一個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 } 

回答

2

Select-String可以在文件中找到多個匹配項。我懷疑它是在同一個文件中找到更多的匹配,但是你已經移動了文件,所以源碼不再存在。使用Select-String上的-List參數可以使每個文件只有一個匹配項。

$list = gci $startdir -r *.imap | select-string $pattern -List 
+0

這正是問題!它總是有意義的 - 我只是不知道爲什麼我沒有想到它。非常感謝!! – Brad 2010-12-10 02:42:43

0

嘗試改變產生$名單像這樣的行:

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

您可能還需要將最後一行更改爲:

$list | mv $newdir