用于从文件夹中读取和拆分文件名的 Powershell 脚本

Powershell script to read and split filename from a folder

我是 Powershell 的新手。我想读取文件夹中每个文件的名称,例如。 900_CA_2022.pdf,从文件名中删除 _ 并创建一个名为 900CA2022900_CA_2022.txt

的新文本文件

基本上,我想从无扩展名的文件名中删除 _,按原样附加后者,并使用新的扩展名 .txt

重要:以下所有解决方案都会在 current 目录中创建新文件。如果需要,使用 Join-Path 使用显式目录路径构造目标文件路径,例如:
Join-Path C:\target (($_.BaseName -replace '_') + $_.BaseName + '.txt')


创建新的空文件,其名称应从输入文件派生, 使用 New-Item:

Get-ChildItem -Filter *.pdf | 
  New-Item -Path { ($_.BaseName -replace '_') + $_.BaseName + '.txt' } -WhatIf

注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf

注意:如果目标文件存在,会报错。如果添加 -Force,现有文件将被 截断 - 请谨慎使用。

  • $_.BaseName 是输入文件的名称 没有扩展名 .
  • -replace '_' 删除所有 _ 个字符。来自它。

创建新文件,其名称应从输入文件派生并填充,使用ForEach-Object:

Get-ChildItem -Filter *.pdf | 
  ForEach-Object { 
    # Construct the new file path.
    $newFilePath = ($_.BaseName -replace '_') + $_.BaseName + '.txt'
    # Create and fill the new file.
    # `>` acts like Out-File. To control the encoding, use 
    # something like `| Out-File -Encoding utf8 $newFilePath` instead.
    "content for $newFilePath" > $newFilePath
  }

请注意,> / Out-File and Set-Content(对于字符串数据)都悄悄地替换了现有目标文件的内容。

最简单的方法是使用相同的源文件名称 + .txt 来创建文本文件而不会对源代码造成太大损害文件名。

例如 900_CA_2022.pdf -----> 900_CA_2022.pdf.txt

我的替代解决方案

初始文件

脚本代码

$files = Get-ChildItem "./*.pdf" -Recurse -Force
$files | ForEach-Object{
    New-Item -Path "$($_ | Split-Path)/$($_ | Split-Path -Leaf).txt" -Force
}

结果文件