根据部分文件名创建文件夹名称

时间:2021-04-13 18:04:58

标签: powershell

我有文件名中带有“-”(连字符)的文件名。我正在尝试为每个文件名创建一个文件夹并将文件移动到该文件夹​​中。

这是我想要使用的:

dir | %{ 
    $id = $_.Name.SubString(0,5); 
    if(-not (Test-Path $id)) {mkdir $id}; 
    mv $_ "$id\$_";}

问题是,某些文件名的连字符前少于 5 个字符,因此对于这些文件夹,会将连字符添加到文件夹名称中。我曾尝试使用 Split 语言,但我坚持使用语法。

下面是几个文件名示例:

  • A1909-6628.txt
  • A963-6634.txt

预先感谢您的帮助

3 个答案:

答案 0 :(得分:1)

试试这个

#split return an array
$id = ($_.Name -split '-')[0];

答案 1 :(得分:0)

您几乎走在正确的轨道上,并且您提到了 -split 运算符,这正是您真正需要的。

Get-ChildItem | ForEach-Object -Process {
    $id = $_.BaseName.split('-')[0];
        if((Test-Path $id) -eq $false){Mkdir $id}
            Move-Item -Path $_.FullName -Destination $id 
                }

在没有过多修改代码的情况下,我在连字符处添加了拆分,然后在拆分后选择了第一个值。

答案 2 :(得分:0)

试试这个:

Get-ChildItem -file -filter "*-*" | %{

#extract first part of file
$Part1=($_.BaseName -split '-')[0].Trim()

#create directory if exist
$NewFolderName="{0}\{1}" -f $_.DirectoryName, $Part1 
New-Item -ItemType Directory -Path $NewFolderName -Force -ErrorAction SilentlyContinue

#prepare new filename
$NewPathFile="{0}\{1}" -f $NewFolderName, $_.Name

#move file into new directory
Move-Item $_.FullName $NewPathFile

}
相关问题