PowerShell脚本通过创建两个同名的子文件夹将jpg文件从一个文件夹复制到另一个文件夹



我需要一些帮助,我是PowerShell的新手,我试图使用它来使我的一些工作更容易。我正在编写一个PowerShell脚本,从一个位置(C:PicturesPeoplePeople)复制JPG文件并将其移动到新位置。

问题是,在这个新位置,我需要创建一个与JPG相同名称的文件夹,然后再创建一个与JPG相同名称的子文件夹。

我需要将C:PicturesPeoplePeople的图片从JPG_Image移动到C:PicturesJPG_NameJPG_Name'JPG_Image'

到目前为止,我发现并一直在研究这个:

$SourceFolder = "C:PicturesPeoplePeople"
$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-ChildItemcmd,因此您也不会获得DirectoryInfo对象
  • 要获得没有扩展名的文件名,有一个属性.BaseName
  • Join-Path返回一个字符串,不需要将其强制转换为[System.IO.FileInfo]对象
  • 如果你添加-ForceNew-Itemcmd,没有必要检查文件夹是否已经存在,因为这将使cmdlet创建一个新的文件夹或返回现有的DirectoryInfo对象。
    因为我们不需要那个对象(以及它的控制台输出),我们可以使用$null = New-Item ...
  • 把它扔掉

把它们放在一起:

$SourceFolder = "C:PicturesPeoplePeople"
$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
}

最新更新