I want to write code that run on all PowerShell platforms. The following code generates output with \
path separators on Windows and /
path separators on Linux.
Get-ChildItem -File -Recurse | ForEach-Object { $_.FullName }
I want to exclude files that are anywhere under an obj
directory. The number and depth of obj
directories is not known. One way to do this would be to filter out those using something like the following. However, this will not work on Linux because the path separator is different.
Get-ChildItem -File -Recurse |
Where-Object { -not ($_.FullName -like '*\obj\*' |
ForEach-Object { $_.FullName }
Using a regex pattern appears to work, but I would like to know if there is a more clear way to do this. I see this as awkward. Not only that, the \\
character is valid as part of a Linux file name which could present a failure vulnerability to this code.
Get-ChildItem -Recurse |
Where-Object { -not ( $_.FullName -like "*[/\]obj[/\]*") } |
ForEach-Object { $_.FullName }
I would suggest to shift responsibility for handling directory separator character to the underlying .Net platform. Something like this:
Get-ChildItem -Recurse |
Where-Object { $_.FullName.Split([IO.Path]::DirectorySeparatorChar) -notcontains "obj" } |
ForEach-Object { $_.FullName }