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

时间:2018-06-30 23:28:55

标签: powershell loops substring directory

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

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

示例:

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

我想提取艺术家姓名作为子字符串,可以用Split("-")提取,但是不知道如何处理1,000多个文件(都在同一目录中)。

我想基于艺术家的名字创建新文件夹,然后将该艺术家的所有文件移到正确的文件夹中。

因此,“莎拉·沃恩-他们不能从Me.mp3拿走它”将被复制到名为“莎拉·沃恩”的文件夹中。

这是我成功的原因,一次只有1个文件:

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)

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

1 个答案:

答案 0 :(得分:1)

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
}