首页 文章

使用Move-Item时找不到路径

提问于
浏览
-1

我想做以下事情:

  • 列出目录中的所有项目

  • 根据文件名将文件移动到不同的位置

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

$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 ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~分类信息:ObjectNotFound :( C: \ users \ admini ... re3_revised.txt:String)[Move-Item],ItemNotFoundExceptio n FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand

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

提供以下参数的值:

路径[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 (从字面意义上说) . 看看上面是否适合您 .

相关问题