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