Classify file extension and applying logic

时光怂恿深爱的人放手 提交于 2019-12-11 17:37:44

问题


Need to execute logic depending on the file extension.

Input: $FileName = "ABC.tar.gz.manifest" or "ABC.tar.gz" or "ABC.zip"

$EXTZ = ".zip"
$EXTGZ = "tar.gz"
$EXT = $FileName -match "$EXTZ"

$EXT
if ($EXT = 'True') {
    Write-Host "$EXTZ"
} elseif ($EXT = 'False') {
   Write-Host "$EXTGZ"
}

But the problem is some files are having the double extension. How we can solve this?

If the extension is .zip need to print "ABC".

If the file extension is .tar.gz or .tar.gz.manifest need to print "XYZ".


回答1:


You can check if the $fileInfo contains the extension (you have a problem in the if, in PowerShell you can't do =, you do -eq):

$Filename = "ABC.tar.gz.manifest"
$EXTGZ = "tar.gz"
$EXT = $Filename.Contains($EXTGZ)
if($EXT -eq $true)
{
   # Do Something
}



回答2:


I'd use a Regular Expression and a switch instead of multiple if commands

## Q:\Test\2019\05\27\SO_56322763.ps1

foreach ($FileName in ("ABC.tar.gz.manifest","ABC.tar.gz","ABC.zip","foo.bar")){
    "`$FileName is: {0}" -f $FileName

    switch -regex ($FileName){
        "\.tar\.gz(\.manifest)?$" {"XYZ";Break}
        "\.zip$"                  {"ABC";Break}
        default                   {"anything"}
    }
}

Sample output:

> Q:\Test\2019\05\27\SO_56322763.ps1
$FileName is: ABC.tar.gz.manifest
XYZ
$FileName is: ABC.tar.gz
XYZ
$FileName is: ABC.zip
ABC
$FileName is: foo.bar
anything


来源:https://stackoverflow.com/questions/56322763/classify-file-extension-and-applying-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!