powershell-extraer el nombre y la extensión del archivo
Necesito extraer el nombre del archivo y la extensión de, por ejemplo, my.file.xlsx. No conozco el nombre del archivo o extensión y puede haber más puntos en el nombre, así que necesito buscar la cadena desde la derecha y cuando encuentre el primer punto (o el último desde la izquierda), extraiga la parte del lado derecho y la parte del lado izquierdo de ese punto.
Tal vez haya una mejor solución, pero no encontré nada aquí ni en ningún otro lugar. Gracias
8 answers
Si el archivo está saliendo del disco y como otros han indicado, use las propiedades BaseName
y Extension
:
PS C:\> dir *.xlsx | select BaseName,Extension
BaseName Extension
-------- ---------
StackOverflow.com Test Config .xlsx
Si se le da el nombre del archivo como parte de una cadena (digamos que viene de un archivo de texto), usaría los métodos GetFileNameWithoutExtension
y GetExtension
estáticos de la clase System.IO.Path :
PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-20 14:45:53
PS C:\Windows\System32\WindowsPowerShell\v1.0>split-path "H:\Documents\devops\tp-mkt-SPD-38.4.10.msi" -leaf
tp-mkt-SPD-38.4.10.msi
PS C:\Windows\System32\WindowsPowerShell\v1.0> $psversiontable
Name Value
---- -----
CLRVersion 2.0.50727.5477
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-26 23:26:22
Si es de un archivo de texto y y presumiendo archivo de nombre están rodeados por espacios en blanco esta es una manera:
$a = get-content c:\myfile.txt
$b = $a | select-string -pattern "\s.+\..{3,4}\s" | select -ExpandProperty matches | select -ExpandProperty value
$b | % {"File name:{0} - Extension:{1}" -f $_.substring(0, $_.lastindexof('.')) , $_.substring($_.lastindexof('.'), ($_.length - $_.lastindexof('.'))) }
Si es un archivo, puede usar algo como esto en función de sus necesidades:
$a = dir .\my.file.xlsx # or $a = get-item c:\my.file.xlsx
$a
Directory: Microsoft.PowerShell.Core\FileSystem::C:\ps
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 25/01/10 11.51 624 my.file.xlsx
$a.BaseName
my.file
$a.Extension
.xlsx
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-20 14:50:16
Compruebe las propiedades de nombre base y Extensión del objeto FileInfo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-20 14:25:11
PS C:\Users\joshua> $file = New-Object System.IO.FileInfo('file.type')
PS C:\Users\joshua> $file.BaseName, $file.Extension
file
.type
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-25 17:23:09
Use Split-Path
$filePath = "C:\PS\Test.Documents\myTestFile.txt";
$fileName = (Split-Path -Path $filePath -Leaf).Split(".")[0];
$extension = (Split-Path -Path $filePath -Leaf).Split(".")[1];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-28 15:31:59
Esta es una adaptación, si alguien tiene curiosidad. Necesitaba probar si RoboCopy copió correctamente un archivo a varios servidores para su integridad:
$Comp = get-content c:\myfile.txt
ForEach ($PC in $Comp) {
dir "\\$PC\Folder\Share\*.*" | Select-Object $_.BaseName
}
Agradable y simple, y muestra el directorio y el archivo dentro de él. Si desea especificar un nombre de archivo o extensión, simplemente reemplace los *'s con lo que desee.
Directory: \\SERVER\Folder\Share
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2/27/2015 5:33 PM 1458935 Test.pptx
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-03 23:01:07
Simplemente hazlo:
$file=Get-Item "C:\temp\file.htm"
$file.Name
$file.Extension
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-29 10:12:43