[.net] powershell - extract file name and extension

I need to extract file name and extension from e.g. my.file.xlsx. I don't know the name of file or extension and there may be more dots in the name, so I need to search the string from the right and when I find first dot (or last from the left), extract the part on the right side and the part on the left side from that dot.

Maybe there is better solution, but I did'n find anything here or anywhere else. Thank you

This question is related to .net powershell powershell-2.0

The answer is


This is an adaptation, if anyone is curious. I needed to test whether RoboCopy successfully copied one file to multiple servers for its integrity:

   $Comp = get-content c:\myfile.txt

ForEach ($PC in $Comp) {
    dir "\\$PC\Folder\Share\*.*" | Select-Object $_.BaseName
}

Nice and simple, and it shows the directory and the file inside it. If you want to specify one file name or extension, just replace the *'s with whatever you want.

    Directory: \\SERVER\Folder\Share

Mode                LastWriteTime     Length Name                                                                                                                                             
----                -------------     ------ ----                                                                                                                                             
-a---         2/27/2015   5:33 PM    1458935 Test.pptx                                                                                                             

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

Check the BaseName and Extension properties of the FileInfo object.


As of PowerShell 6.0, Split-Path has an -Extenstion parameter. This means you can do:

$path | Split-Path -Extension

or

Split-Path -Path $path -Extension

For $path = "test.txt" both versions will return .txt, inluding the full stop.


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];

PS C:\Users\joshua> $file = New-Object System.IO.FileInfo('file.type')
PS C:\Users\joshua> $file.BaseName, $file.Extension
file
.type

just do it:

$file=Get-Item "C:\temp\file.htm"
$file.Basename 
$file.Extension

If is from a text file and and presuming name file are surrounded by white spaces this is a way:

$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('.'))) }

If is a file you can use something like this based on your needs:

$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

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to powershell

Why powershell does not run Angular commands? How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line? How to print environment variables to the console in PowerShell? Check if a string is not NULL or EMPTY The term 'ng' is not recognized as the name of a cmdlet VSCode Change Default Terminal 'Connect-MsolService' is not recognized as the name of a cmdlet Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet Change directory in PowerShell

Examples related to powershell-2.0

Extract the filename from a path Out-File -append in Powershell does not produce a new line and breaks string into characters Using PowerShell to remove lines from a text file if it contains a string PowerShell The term is not recognized as cmdlet function script file or operable program Can't install nuget package because of "Failed to initialize the PowerShell host" Powershell script to see currently logged in users (domain and machine) + status (active, idle, away) How to export data to CSV in PowerShell? powershell is missing the terminator: " PowerShell script to check the status of a URL How to upgrade PowerShell version from 2.0 to 3.0