简体   繁体   English

Powershell中的子字符串

[英]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? 但是,假设输入是字符串,是否有更好/更漂亮的方法呢?

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

One way is as per BenH's comment. 一种方法是根据BenH的评论。 Another is to use Split-Path to get only the filename first: 另一个方法是使用Split-Path首先获取文件名:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM