u123
u123

Reputation: 16267

Substring in powershell

I usually use:

 $ext = [IO.Path]::GetExtension($file)

to get extensions from files. But there are cases where that will thrown an exception and I don't really care about that. So I am trying to do the same assuming input is just a string:

$a = $str.LastIndexOf('.')
$b = $str.length
$c = $b - $a
$ext = $str.Substring($str.LastIndexOf('.'), $c)

But is there a better/prettier way to do this, assuming input is string?

Upvotes: 0

Views: 129

Answers (2)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

You can simplify this:

(Get-Item -Path $File).Extension

Alternatively:

PS C:\> $File = 'C:\Temp\Fold\File.exe'
PS C:\> $File -match '(?<Extension>\.\w+$)'
True
PS C:\> $Matches.Extension
.exe

or

PS C:\> ($File -split '\.')[-1]
exe

Upvotes: 2

G42
G42

Reputation: 10019

One way is as per BenH's comment. Another is to use Split-Path to get only the filename first:

[string]$Path = "c:\path\to\somefile.withdots.csv"
$extension    = (Split-Path $path -Leaf).Split(".")[-1]

Upvotes: 0

Related Questions