问题
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