powershell - PowerShell 脚本通过创建两个同名的子文件夹将 jpg 文件从一个文件夹复制到另一个文件夹
问题描述
我需要一些帮助,我是 PowerShell 的新手,我正在尝试使用它来简化我的一些工作。我正在编写一个 PowerShell 脚本来从一个位置(C:\Pictures\People\People)复制 JPG 文件并将它们移动到一个新位置。
问题是,在这个新位置,我需要创建一个与 JPG 同名的文件夹,然后再创建一个与 JPG 同名的子文件夹。
所以我需要移动C:\Pictures\People\People
我将调用 JPG_Image 的图像C:\Pictures\JPG_Name\JPG_Name\'JPG_Image'
到目前为止,我发现并一直在处理这个问题:
$SourceFolder = "C:\Pictures\People\People"
$TargetFolder = "C:\Pictures\"
# Find all files matching *.JPG in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.jpg |
ForEach-Object {
$ChildPath = Join-Path -Path $_.Name.Replace('.jpg','') -ChildPath $_.Name
[System.IO.FileInfo]$Destination = Join-Path -Path $TargetFolder -ChildPath $ChildPath
# Create the directory if it doesn't already exits
if( -not ( Test-Path -Path $Destination.Directory.FullName ) ){
New-Item -ItemType Directory -Path $Destination.Directory.FullName
}
Copy-Item -Path $_.FullName -Destination $Destination.FullName
}
解决方案
你让自己变得比需要的更难。
对您的代码的一些增强:
- 将开关添加
-File
到Get-ChildItem
cmd,这样您就不会获得 DirectoryInfo 对象 - 要获取没有扩展名的文件名,有一个属性
.BaseName
Join-Path
返回一个字符串,无需将其转换为[System.IO.FileInfo]
对象- 如果添加
-Force
到New-Item
cmd,则无需检查文件夹是否已存在,因为这将使 cmdlet 要么创建一个新文件夹,要么返回现有的 DirectoryInfo 对象。
因为我们不需要那个对象(以及它的控制台输出),我们可以使用$null = New-Item ...
把它们放在一起:
$SourceFolder = "C:\Pictures\People\People"
$TargetFolder = "C:\Pictures"
# Find all files matching *.JPG in the folder specified
Get-ChildItem -Path $SourceFolder -Filter '*.jpg' -File |
ForEach-Object {
# Join-Path simply returns a string containing the combined path
# The BaseName property is the filename without extension
$ChildPath = Join-Path -Path $_.BaseName -ChildPath $_.BaseName
$Destination = Join-Path -Path $TargetFolder -ChildPath $ChildPath
# Create the directory if it doesn't already exits
# Using -Force will not give an error if the folder already exists
$null = New-Item -Path $Destination -ItemType Directory -Force
$_ | Copy-Item -Destination $Destination
}
推荐阅读
- python-3.x - BeautifulSoup4 - 在批处理 url 的两个不同标签之间连接多个 html 元素
- ruby - Redis 信号量锁无法释放
- javascript - 我如何在 Javascript(最好)中编写 eclipse 命令脚本:Import/Check out Maven Projects from SCM using eclipse ease
- android - 通知未显示 android API 29
- javascript - 如何从对象数组中删除重复项
- python - Python读取文本文件
- javascript - 如何使用 Vue CLI 创建带有选项卡的 Vue 项目
- python-3.x - python-fortran integration: callback comparison between f2py and ctypes
- python - 如何从保存的 HTLM 页面解析表?
- angular - ANGULAR - 服务尚未完成加载 Observable
在被方法使用之前