
Tengo problemas para extraer algunos datos de un nombre de archivo, ya que parece agregar un espacio al final del nombre extraído, incluso si intento usar el truco .trim() para eliminarlo, no funciona. También intenté contar la longitud del nombre de archivo -1 y deja el espacio, pero en su lugar eliminó el último carácter. Esto me hace muy difícil dirigir una ruta a una carpeta creada, ya que estoy poniendo el espacio en la ruta. ..
Nombres de archivos debajo de los cuales estoy intentando extraer datos
12 Monkeys S02E10 - Fatherland.txt
Colony S02E01 - Eleven Thirteen.txt
Prison Break S05E05 - Contingency.txt
Estoy intentando extraer el nombre del programa de televisión y crear una carpeta en un nuevo directorio y luego mover el archivo a la carpeta creada.
Aquí está el código que estoy usando.
$TRANSFER = 'C:\Users\BRACEGIRDLE\Favorites\Desktop\TRANSFER\'
$TVSHOWS = 'C:\Users\BRACEGIRDLE\Favorites\Desktop\TV_SHOW\'
$pattern = ‘\s+\S[0-9][0-9].*’
Get-ChildItem "$TRANSFER/*.txt" |
ForEach-Object{
$target = $_.BaseName -split $pattern
Write-Host $target@123
$jon = $TVSHOWS+$target
If( -not (test-path $jon))
{
New-Item -ItemType Directory -force -Path $jon
}
Copy-Item -path $_.FullName -Destination $jon
}
Y aquí está el error.
Quantico @123
Copy-Item : Could not find a part of the path
'C:\Users\BRACEGIRDLE\Favorites\Desktop\TV_SHOW\Quantico \Quantico S02E10 -
JMPALM.txt'.
At line:20 char:9
+ Copy-Item -path $_.FullName -Destination $jon
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundExcept
ion
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerSh
ell.Commands.CopyItemCommand
Como puede ver, para esta ilustración puse la variable (nombre del programa de televisión) en una 'oración' para que pueda ver el espacio agregado. He intentado agregar \s+, lo que elimina uno de los espacios, pero no puedo. deshazte del otro independientemente de si usas el truco de recorte o no.
¿Alguien puede ayudar? Gracias Connor Bracegirdle.
Respuesta1
Solo para mostrar una expresión regular adecuada, es muy posible obtener
no solo el nombre sino todos los elementos contenidos en el nombre del archivo
mediante el uso de grupos de captura que encierran las partes entre paréntesis.
**EDITAR ver RegEX en vivohttps://regex101.com/r/Vbhq7D/1**
## Q:\Test\2018\06\10\SU_1330038.ps1
$TRANSFER = 'C:\Users\BRACEGIRDLE\Favorites\Desktop\TRANSFER\'
$TVSHOWS = 'C:\Users\BRACEGIRDLE\Favorites\Desktop\TV_SHOW\'
$Pattern = '(.*)\s+S(\d{2})E(\d{2})[\- ]+(.*)'
Get-ChildItem $TVSHOWS *.txt| Where-Object BaseName -match $Pattern |
ForEach-Object{
$jon = Join-Path $TVSHOWS $Matches[1]
If( -not (Test-Path $jon)) {
New-Item -ItemType Directory -Force -Path $jon |Out-Null
}
$_ | Copy-Item -Destination $jon
[pscustomobject]@{
Name = $Matches[1]
Series = $Matches[2]
Episode= $Matches[3]
Title = $Matches[4]
}
}
El script crea el subdirectorio, lo copia y también muestra este resultado:
Name Series Episode Title
---- ------ ------- -----
12 Monkeys 02 10 Fatherland
Colony 02 01 Eleven Thirteen
Prison Break 05 05 Contingency
Árbol de muestra en mi Ramdrive a:
> tree A: /F
A:\
│ 12 Monkeys S02E10 - Fatherland.txt
│ Colony S02E01 - Eleven Thirteen.txt
│ Prison Break S05E05 - Contingency.txt
│
├───12 Monkeys
│ 12 Monkeys S02E10 - Fatherland.txt
│
├───Colony
│ Colony S02E01 - Eleven Thirteen.txt
│
└───Prison Break
Prison Break S05E05 - Contingency.txt
Respuesta2
Verifique el resultado de -split. Crea una matriz de 2 miembros.
10JUN2018:012955 /:> $txts = Get-ChildItem "$TRANSFER/*.txt"
10JUN2018:012955 /:> ($txts[0].basename -split $pattern).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
10JUN2018:012955 /:>"some random stuff" -split " stuff"
some random
10JUN2018:013239 /:>("some random stuff" -split " stuff")[0]
some random
El código modificado con ajuste:
$TRANSFER = "E:\Code\PS\myPS\2018\Jun\10"
$TVSHOWS = "E:\code\PS\myPS\2018\Jun\TV_SHOW\"
$pattern = ‘\s+\S[0-9][0-9].*’
Get-ChildItem "$TRANSFER/*.txt"| ForEach-Object {
$target = ($_.BaseName -split $pattern)[0]
Write-Host "$target@123"
$jon = $TVSHOWS+$target
}
Producción:
12 Monkeys@123
Colony@123
Prison Break@123