LoginSignup
0
0

More than 5 years have passed since last update.

Powershellでファイルの拡張子をドット抜きで取得する方法 get extensionname without dot /Period

Posted at

Poweshellは拡張子を取得すると.txtになる

拡張子を取得する方法はいろいろありますが、知る限りピリオドというかドットが付きます。
PowerShell/ファイルのフルパス,basename,拡張子を取得する方法

SubstringとLength

ものすごく悩んでいたのですが、最初置換を使うおうかと思って遠回りをしていたようです。
Substringで1文字目から取得します。0からカウントしているので0が必ずピリオドになるためです。
しかし、この方法では字数を取得する必要があります。それがLengthです。
しかし、Lengthをそのまま使うと1文字目のピリオドを除外するので足りず、エラーになります。
そこでマイナス1をします。

拡張子がない場合は$nullではない

拡張子がないと''つまり文字なしが返ります。$nullではありません。


$ofile = Get-Childitem('C:\hoge\hoge.txt')
Write-host  $ofile.extension.Substring(1,$ofile.extension.Length-1)

エラーを除外したサブルーチン用


$strFileName ="C:\hoge\hoge.txt" 
if((Test-Path $strFileName) -eq $true){$ofile = Get-childItem -Path $strFileName #ファイルの存在をテスト
if($ofile.PSIsContainer-eq $false){ #ファイルかフォルダか確認
if([string]::IsNullOrEmpty($ofile.extension)){Write-Host "no extention";$strExtension='' #拡張子がなければNullStringを返す
}Else{
$strExtension = ( $ofile.extension.Substring(1,$ofile.extension.Length-1)) ;
Write-Host $strExtension
}
}
}

参考

ファイルとフォルダのどちらかを判定する方法-バヤシタ
それにしてもPsicontainerがfalseがファイルになるなんて・・・

PowerShellで文字列などの変数のNullまたは空文字を確認するには - 2014-11-20  - YOMON8.NET

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0