Home > OS >  PowerShell not excluding folder
PowerShell not excluding folder

Time:11-03

I have a very simple script(or I thought) where I'm trying to use recurse to go through each folder and subfolder and check if that folder has "backup.log" in it, while excluding the OneDrive folder. I tried everything I can think of, searched online and tried the solutions provided but PowerShell just keeps going in to the OneDrive folder. Some of the common scripts I tried are below. Any help is much appreciated.

$exclude = @("$env:OneDrive")
get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse  -Exclude $exclude

get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse  | Where {$_.FullName -notmatch "$env:onedrive"}

get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse  | Where-Object { !($_.FullName).StartsWith($env:OneDrive) }

get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse  | Where {$_.FullName -notmatch "$env:onedrive\*"}

I tried some more things but it's pretty much along the same logic. I also tried changing the environmental variable with writing the path manually but had the same result. Also tried the DirectoryName instead of FullName.

Edit: Here is the error I'm getting:

Could not find a part of the path 'C:\Users\username\OneDrive - Company\Desktop\master\packages\System.Runtime.InteropServices.RuntimeInformation\runtimes\win\lib\netstandard1.1'. At line:1 char:1 get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse | ~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : ReadError: (C:\Users\username\netstandard1.1:String) [Get-ChildItem], DirectoryNotFoundException FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand –

CodePudding user response:

-exclude doesn't work with -recurse or -filter; excluding the full path doesn't work:

get-childitem -Path $env:USERPROFILE -Exclude 'OneDrive - Company' | 
  get-childitem -Filter backup.log -Recurse

In regex, backslashes in paths need to be escaped \\:

get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse  | 
  Where {$_.FullName -notmatch [regex]::escape("$env:onedrive")}

.StartsWith() is case sensitive:

get-childitem -Path $env:USERPROFILE -Filter 'backup.log' -Recurse  | 
  Where-Object { !($_.FullName.tolower()).StartsWith($env:OneDrive.tolower()) }

Or -notlike:

dir -r ~ backup.log | ? fullname -notlike $env:onedrive*

Enable long paths?

Set-ItemProperty HKLM:\System\CurrentControlSet\Control\FileSystem LongPathsEnabled 1 -type dword

# or
get-childitem -LiteralPath "\\?\$env:userprofile" -Recurse -filter backup.log

  • Related