Jun 22 2022 05:59 AM
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!
Jun 22 2022 07:03 AM - edited Jun 22 2022 07:09 AM
Solution
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
Jun 22 2022 07:15 AM - edited Jun 22 2022 07:15 AM
Thank you Lain !!