0

for hours I've been struggling to get powershell to do the following:

Use the base directory C:\Users and go recursively through all folders excluding the AppData folder of each user dir and also excluding the users named:

$exclude = @('Administrator', 'All Users', 'Default', 'Default User', 'Public', 'TEMP')

The output should then list me all files with certain extensions.

UPDATE

How can I add these additional statements to the output?

 Get-Childitem $Path -Include $extensions -Recurse -Force  -ErrorAction SilentlyContinue |
  Select Name,Directory,@{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}},CreationTime,LastAccessTime,  Length

2. Update

what is the right way to set a pattern in order to match with remote hosts of the network?

$exclude_pattern = "\\hostname\\c$\\Users\\(" + ($exclude -join '|') + ")";

If I replace hostname with my computer name it doesn't match. I don't see where the line is wrong compared to the local pattern:

C:\\Users\\(Administrator|All Users|Default|Default User|Public|TEMP|Saargummi|dvop|leasingadmin|cenit|cadop|[^\\]+\\AppData)
\\hostname\\c$\\Users\\(Administrator|All Users|Default|Default User|Public|TEMP|Saargummi|dvop|leasingadmin|cenit|cadop|[^\\]+\\AppData) 

3. Update

Is there a smart way to include extensions which are written in upper case? Or do I need to write '.wav', '.WAV' for example?

Tony Clifton
  • 703
  • 3
  • 14
  • 27

1 Answers1

2
$exclude = @("Administrator",
             "All Users",
             "Default",
             "Default User",
             "Public",
             "TEMP",
             "[^\\]+\\AppData")

$extensions = "*.ini" # replace this with your extension
$hostname = "hostname" # replace this with your hostname

$exclude_pattern = "\\\\{0}\\C[$]\\Users\\({1})" `
    -f $hostname, ($exclude -join '|')
$path = "\\{0}\C$\Users" -f $hostname

Get-ChildItem -Path $path -Force -Recurse -Include $extensions `
    -ErrorAction "SilentlyContinue" `
    | Where-Object { $_.PSIsContainer -eq $false } `
    | Where-Object { $_.FullName -notmatch $exclude_pattern } `
    | ForEach-Object {
        $_ | Select-Object -Property @(
            "Name",
            "Directory",
            @{Label="Owner";Expression={(Get-ACL $_.Fullname).Owner}},                      
            "CreationTime",
            "LastAccessTime",
            "Length"
        )
    }

[Update 1]: Added output formatting as per your updated question. Shortened by merging all excludes in one regex pattern.

[Update 2]: Changed to UNC path. Note that owner may be displayed as a SID. Look here for SID to username translation.

[Update 3]: PowerShell is case-insensitive by default so you don't need to add the same extension more than once.

Alexander Obersht
  • 3,215
  • 2
  • 22
  • 26