使用Move-Item时找不到路径

问题描述 投票:-1回答:2

我想做以下事情:

  1. 列出目录中的所有项目
  2. 将文件根据其名称移动到不同的位置

示例:在我的文档文件夹中,我有各种文件。根据文件名,我将它们移动到不同的目录。我使用以下脚本。但它没有用。

$allfiles = Get-ChildItem $home\documents
$count = 0
foreach($file in $allfiles)
{
    if ($file.name -like "*Mama*") 
    {
        move-item $file.name -Destination $home\documents\mom
        $count++
    }
    elseif ($file.name -like "*Papa*")
    {
        move-item -destination $home\documents\Dad
        $count++
    }
    elseif ($file.name -like "*bro")
    {
        Move-Item -Destination $home\documents\Brother
        $count++
    }
}
write-host "$count files been moved"

我在这做错了什么?

我的错误输出是

move-item:找不到路径'C:\ users \ administrator \ documents \ Lecture3.txt',因为它不存在。

在行:6 char:10

  • {move-item $ file.name -Destination $ home \ documents \ Win213SGG \ lectures
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ CategoryInfo:ObjectNotFound:(C:\ users \ admini ... ts \ Lecture3.txt:String)[Move-Item],ItemNotFoundExceptio n FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand

move-item:找不到路径'C:\ users \ administrator \ documents \ Lecture3_revised.txt',因为它不存在。在行:6 char:10 + {move-item $ file.name -Destination $ home \ documents \ Win213SGG \ lectures + ~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (C:\ users \ admini ... re3_revised.txt:String)[Move-Item],ItemNotFoundExceptio n + FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand

cmdlet Move-Item位于命令管道位置1

提供以下参数的值:

路径[0]:

powershell scripting powershell-v2.0
2个回答
1
投票

或者你可以通过使用powershell中的管道功能使它更整洁。像这样,您不必使用'-path'指定要移动的文件,但是您可以直接从Get-ChildItem的结果传递它:

Get-ChildItem $home\documents | Foreach-Object {
    $count = 0
    if ($_.Name -like "*Mama*") 
    {
        $_ | Move-Item -Destination $home\documents\mom
        $count++
    }
    elseif ($_.Name -like "*Papa*")
    {
        $_ | Move-Item -Destination $home\documents\Dad
        $count++
    }
    elseif ($_.Name -like "*bro")
    {
        $_ | Move-Item -Destination $home\documents\Brother
        $count++
    }
}

write-host "$count files been moved"

0
投票

试试这个 -

$allfiles = Get-ChildItem $home\documents
$count = 0
foreach($file in $allfiles)
{
    if ($file.name -like "*Mama*") 
    {
        move-item -path $file -Destination $home\documents\mom
        $count++
    }
    elseif ($file.name -like "*Papa*")
    {
        move-item -path $file -destination $home\documents\Dad
        $count++
    }
    elseif ($file.name -like "*bro")
    {
        Move-Item -path $file -Destination $home\documents\Brother
        $count++
    }
}
write-host "$count files been moved"

您没有两次指定文件名,这是move-item的必需参数。在一个地方,你试图使用Name参数移动文件,该参数不是item(字面意思上)。看看上面是否适合你。

© www.soinside.com 2019 - 2024. All rights reserved.