使用Move-Item

时间:2018-03-01 20:40:29

标签: powershell scripting powershell-v2.0

我想做以下事情:

  1. 列出目录

  2. 中的所有项目
  3. 根据文件名称将文件移动到不同的位置

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

    $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 Ñ
      • 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 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~     + CategoryInfo:ObjectNotFound:(C:\ users \ admini ... re3_revised.txt:String)[Move-Item],ItemNotFoundExceptio    ñ     + FullyQualifiedErrorId:PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand

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

    提供以下参数的值:

    路径[0]:

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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(在字面意义上)。看看上面是否适合你。

相关问题