Home > other >  I search how to match with my last character
I search how to match with my last character

Time:03-02

I'm on PowerShell and i need to match my last character of my variable:

My example is not to get user

$Myobject = Get-Something -Filter 'Name -like "T*"'

When I write $Myobject I have this:

Ta
Taaa
Tb
Tbaa
Tc
Tcaa

I'm trying to match to have only:

Ta
Tb
Tc

So I have try this:

$MyObject | Where-Object{ ($_.Name -match '^T[a-c]$')} | Select-Object Name

The only result i have with different type of command is the first result and it's impossible to find on the web "How to match the last character".

Thank you for your help.

Best regards

CodePudding user response:

If you're only trying to do the wildcard for the one character following the string you've specified, the easiest option (which sticks with your existing code format) is to use ? rather than *.

Using a * catches everything after the specified string, while ? only catches a single string. As a very rough example :

$foo = @("Ta","Taaaa","Tbaaa","Tb")
$foo | where-object {$_ -like "T?"}

you'll see it only returns Ta and Tb like you're after.

So in your example above it would be :

$Myobject = Get-Something -Filter 'Name -like "T?"'
  • Related