gpt4 book ai didi

powershell - 根据文件名的子字符串创建文件夹

转载 作者:行者123 更新时间:2023-12-02 23:37:44 25 4
gpt4 key购买 nike

尝试从包含1000多个MP3文件的目录中的文件名中获取歌手姓名。我正在尝试使用该子字符串创建目录以将文件复制到其中。

文件名格式为“artistname-songtitle.mp3”,艺术家和标题始终以“-”分隔,并且它们都位于同一目录中。

例:

Vic Damone - You And The Night And The Music.mp3Sarah Vaughan - They Can't Take That Away From Me.mp3...

I want to extract the artist name as a substring, which I can do with Split("-"), but do not know how to do this for 1,000+ files (all in the same directory).

I want to create new folders based on the name of the artist, then move all the files for that artist into correct folder.

So "Sarah Vaughan - They Can't Take That Away From Me.mp3" would be copied into a folder named "Sarah Vaughan".

Here is what I have had success with, 1 file at a time:

Set-Location -Path L:\   # This is where I have all the files

$file = (Get-ChildItem).BaseName # get rid of the mp3 extension --- this works

$artist = $file.Split("-")[15].Trim # trim will remove the trailing space --- this works (for the 15th element as an example)

对于该目录中的每个文件,我都需要某种循环,并且需要某种方式来获取提取的艺术家名称,以使其成为新目录的名称。

最佳答案

Get-ChildItem L:\ -Filter *.mp3 | ForEach-Object {
# Extract the artist name from the file's base name.
$artist = ($_.BaseName -split '-')[0].Trim()
# Ensure that a subdirectory named for the artist exists
# (creates it on demand; -Force ensures that the command is a no-op if
# the subdir. already exists)
$null = New-Item -Type Directory -Force $artist
# Move the file at hand to the artist folder.
Move-Item -LiteralPath $_.FullName -Destination $artist
}

关于powershell - 根据文件名的子字符串创建文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com