Home > Software design >  Powershell Get-ChildItem extract username from profile folder
Powershell Get-ChildItem extract username from profile folder

Time:03-31

I have drive where roaming user profiles are stored:

U:\Users\john.doe
U:\Users\john.wick
U:\Users\john.smith

I need to check if users have files with *.pdf extensions stored in their profiles

$a = Get-ChildItem "U:\users\" -Include *.pdf -Recurse | select FullName
foreach ($b in $a){

Write-Output $b



}

Output

U:\Users\john.wick\desktop\file.pdf
U:\Users\john.wick\documents\a.pdf
U:\Users\john.doe\desktop\1.pdf
..................................

I need to write column to extract username from path, and one column with full file path. How to do it ?

john.doe
john.wick
--------

CodePudding user response:

Call Get-ChildItem without -Recurse to discover the profile folders, then use Where-Object Get-ChildItem to find the ones containing pdfs:

$profilesWithPDFs = Get-ChildItem U:\Users\ -Directory |Where-Object { $_ |Get-ChildItem -File -Recurse -Filter *.pdf |Select -First 1 }

Once you've discovered the relevant folders, you can grab the name only:

$profilesWithPDFs |ForEach-Object -MemberName Name
  • Related