SOLVED

Use an arraylist in a comparison operation

Occasional Contributor

Hello,

 

here is a short code.

 

 

 

 

$infos = $null
$infos = @{}
$infos = @{ 
"toto" = "tutu" ; 
"hello" = "hellu"
<#...#>
 }

$extensions = $null
$extensions = New-Object -TypeName 'System.Collections.ArrayList';
$extensions = ("txt", "cmd","ps1" <#...#>)


foreach
($key in $infos.keys)
{
$key
    Get-ChildItem ".\Desktop\test" -Recurse | Where-Object {-not $_.PSIsContainer -and ($_.Extension -eq ".frm" -or $_.Extension -eq ".ps1" -or $_.Extension -eq ".txt")} | 
    ForEach-Object {(Get-Content $_.FullName) | 
    ForEach-Object { 
    $_ -replace [regex]::Escape($key), $($infos[$key]) } | Set-Content $_.FullName
    }
}

 

 

 

 

I want to use an arraylist containing a list of file extensions when I do my extensions checks in there:

 

 

 

-and ($_.Extension -eq ".frm" -or $_.Extension -eq ".ps1" -or $_.Extension -eq ".txt")

 

 

 

 

I'd like to replace it with something similar to:

 

 

 

-and ($_.Extension -eq $extensions)

 

 

 

 

Is there anyway clean way to writting this?

 

Thank you! 

2 Replies
best response confirmed by John_Dodo (Occasional Contributor)
Solution

@John_Dodo 

 

Hey, @John_Dodo .

 

Yep, there sure is: it's the -in operator.

 

For example:

 

($_.Extension -in @(".frm", ".ps1", ".txt"))

 

 

Edited:

In the context of your script (I answered a bit too hastily), you can drop lines 9 and 10, then change 11 to:

$extensions = @(".txt", "cmd",".ps1", ".txt");

 

And then line 18 to:

Get-ChildItem -File -Path ".\Desktop\test" -Recurse | Where-Object { $_.Extension -in $extensions } |

 

-File means you won't need the PSIsContainer test in the Where clause.

 

Cheers,

Lain

Thank you Lain !!