Exclude folders with special characters when using Get-Childitem

I have folders with %, _ and () in the names, how can I exclude these chars?
Get-ChildItem c:\ -Name -Directory

What do you mean by exclude them? Do you mean ignore?

Yes, I would like to ignore them.

My questions aren’t the best, I’m still lacking context. What is the issue? Are you getting errors? Are you wanting to list all except those with special characters?

[quote quote=236572]My questions aren’t the best, I’m still lacking context. What is the issue? Are you getting errors? Are you wanting to list all except those with special characters? - Yes

[/quote]
I finally managed to get the command: Get-ChildItem C:\ | Where-Object Name -notmatch “^%” but now I’m battling to add the other characters

This will return objects that contain numbers and letters only. i.e. no special characters :slight_smile:

Get-ChildItem c:\ | Where-Object Name -match "^[a-zA-Z0-9]+$"

 

To exclude just those characters, use the line below. Separate multiple characters with ‘|’

Get-ChildItem -Directory | Where-Object {$_.Name -notmatch '%|_|\(|\)'}

I also initially thought “wouldn’t it be easier to include than exclude?” but then I recalled just how many special characters there are. This regex pattern matches the characters you listed.

'(?:([%,_()]*))',''

Here is a test you can run to confirm it will match all.

@'
test1%
test2,
test3_
test4(
test5)
test6%,_()
%t,e_s(t)7
'@ -replace '(?:([%,_()]*))',''

It can be simplified to this so long as you leave it as an object with a name property. You can let it be extracted as part of the where-object process instead of -name in get-childitem or deal with it later on.

Get-ChildItem c:\ -Directory | where name -NotMatch '[%|,|_|(|)]'

Then you still have your object and if you need to get down to just the name you have the many normal powershell ways.

Get-ChildItem c:\ -Directory | where name -NotMatch '[%|,|_|(|)]' | select -exp name

(Get-ChildItem c:\-Directory | where name -NotMatch '[%|,|_|(|)]').name

$dirs = Get-ChildItem c:\ -Directory | where name -NotMatch '[%|,|_|(|)]'
$dirs.name

Take care.

[quote quote=236587]This will return objects that contain numbers and letters only. i.e. no special characters :slightly_smiling_face:

<textarea class="ace_text-input" style="opacity: 0; height: 17.6px; width: 6.59775px; left: 44px; top: 0px;" spellcheck="false" wrap="off"></textarea>
1
Get-ChildItem c:\ | Where-Object Name -match "^[a-zA-Z0-9]+$"
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
[/quote] This returns exactly what i'm looking for. thanks for the assist