Remove-Item cmdlet无法正常工作

时间:2017-03-18 03:45:05

标签: powershell powershell-v2.0

所以我有一个脚本可以梳理大约1200首歌曲的目录,用户选择一首歌曲(然后将其放入$Selected变量中),然后通过“#34;脚本魔法”#34; (我可以在必要时提供代码,但我认为这不是出于我们的目的)将电子邮件发送到我需要将其发送到的电子邮件帐户。然后我想删除aaaannnnndddd目录中的歌曲,当时我遇到问题。这是我最初尝试删除歌曲的代码:

Remove-Item C:\Users\woafr\Desktop\Songs\$Selected -recurse -force

使用该代码我收到了这条错误消息:

Remove-Item : Cannot remove item C:\Users\woafr\Desktop\Songs\song.mp3: The process cannot access the file C:\Users\woafr\Desktop\Songs\song.mp3' because it is being used by another process

然后我读了this articethis Stack Overflow thread以及this Server Fault thread并修改了我的代码:

Get-ChildItem C:\Users\woafr\Desktop\Songs\$Selected -recurse -force | Remove-Item

仍然遇到了同样的错误。我可以在这里做些什么让我删除这些歌曲,或者我必须手动完成(恐怖!)

以下是整个脚本供参考:

# Search Engine part
$SearchInput = Read-Host "Enter song name here:"
$Items = Get-ChildItem C:\Users\woafr\Desktop\Songs -Recurse -Filter *$SearchInput*
IF (-Not $Items)
{Write-Host 'Nothing returned...
The search engine does not care about capitilization (so "That" and "that" are read the exact same by the search engine) 
But it does care about punctuation (so "That''s" and "Thats" are not read the same by the search engine). Try Again' -ForegroundColor Red}

# Choose you this day what song you want
IF (-Not $Items)
{cmd /c pause}
$Index = 1
$Count = $Items.Count
foreach ($Item in $Items) {
    $Item | Add-Member -MemberType NoteProperty -Name "Index" -Value $Index
    $Index++
}
$Items | Select-Object Index, Attributes, LastWriteTime, Name | Out-Host
$Input = Read-Host "Select an item by index number, then press enter (1 to $Count)"
$Selected = $Items[$Input - 1]
Write-Host "You have selected $Selected"


# Email account the script is sending from
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "myemail@gmail.com"
$Password = "mypassword"

# Email the script is sending
$to = "emailtoingest@gmail.com"
$subject = "Songs To Ingest"
$body = "Ingest attachment into WideOrbit"
$attachment = New-Object System.Net.Mail.Attachment("C:\Users\woafr\Desktop\Songs\$Selected")

$attachment.ContentDisposition.FileName = "$Selected"

# Act of sending the email
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($attachment)

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent" -ForegroundColor Green

cmd /c pause

# Trying to delete the damn thing
Get-ChildItem C:\Users\woafr\Desktop\Songs\$Selected -recurse -force | Remove-Item

cmd /c pause

1 个答案:

答案 0 :(得分:1)

所以问题是发送邮件对象正在锁定文件,请尝试在remove-item命令行开关之前使用此代码片段:

$smtp = $null

foreach ($attachment in $message.attachments){
$attachment.dispose();

} 
$message.dispose();