首页 > 解决方案 > 使用 Move-Item 时文件已存在时,Powershell 无法创建文件

问题描述

我正在尝试将子文件夹中的 png 图像移动到它们所在文件夹中的子文件夹中。

主文件夹称为“stuff”,图像位于“stuff”主文件夹中不同名称的子文件夹中,每个子文件夹中都有一个文件夹名称“Oneshot”,我正在尝试移动 M 中的这些图像: /Stuff/FolderExample/ 到 M:/Stuff/FolderExample/Oneshot/。我正在使用的当前代码

Get-ChildItem -Path C:\Users\a\Desktop\stuff\*.png -Recurse | Move-Item -Destination "$($_.FullName)\Oneshot\"

我怎样才能使这项工作?我只是想学习powershell,这样我就可以自动化这个过程,否则我需要手动重复这个过程数千次

标签: powershell

解决方案


使用脚本块 ( {...}) 作为参数- 这将允许您在参数绑定期间-Destination访问当前管道项:$_

Get-ChildItem -Path C:\Users\a\Desktop\stuff\*.png -Recurse |Where-Object Directory -notlike *\OneShot | Move-Item -Destination {"$($_.Directory.FullName)\Oneshot\"}

管道中间的Where-Object命令将确保我们不会尝试移动已经其中一个OneShot文件夹中的图片。


推荐阅读