trying to write a PowerShell script to use a list of servers to gather user profiles and bring back to local server running the script

Michael Rowand 0 Reputation points
2023-06-12T10:40:47.33+00:00

I am trying to write a PowerShell script to use a list of servers to gather user profiles and bring the list of users back to the local server running the script. I am not very good at this and am hoping someone can assist me, please. The below is what I have so far however it throws a "missing for each statement" error when I try to run it.

$computers = Get-Content "C:\scripts\Servers1.txt" 
$hostname = get-content $computers
$sPath = "$hostname + .csv"
foreach ($computer in {
    gwmi win32_userprofile | select localpath, sid
    Get-Alias gwmi, select, ft
    write-host $sPath
#Export-Csv -Path $sPath -NoTypeInformation

} )
robocopy $sPath '\\powerserver\C$\Temp\ServerUsers'
Windows for business Windows Server User experience PowerShell
Windows for business Windows Client for IT Pros User experience Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2023-06-12T12:16:32.3533333+00:00

    Your script has multiple problems. Download this PDF and use it as a reference.

    https://www.sapien.com/books_training/Windows-PowerShell-4

    Try this.

    $computers = Get-Content "C:\scripts\Servers1.txt"
    $Report = @()              
    foreach ($computer in $computers) {
        "Processing $computer"
        Get-CimInstance -ComputerName $computer win32_userprofile | select localpath, sid | foreach {
            $Report +=  [PSCustomObject]@{
                Computer = $computer;
                LocalPath = $_.localpath;
                SID = $_.sid
            }
        }
    }
    "Here is the report."
    $Report 
    
    $Report | Export-Csv -Path '\\powerserver\C$\Temp\ServerUsers\Report.csv' -NoTypeInformation
    
    

  2. Rich Matheisen 47,901 Reputation points
    2023-06-12T15:15:36.7166667+00:00

    Here's another version of your script that doesn't report the profiles like these:

    • C:\WINDOWS\ServiceProfiles\NetworkService
    • C:\WINDOWS\ServiceProfiles\LocalService
    • C:\WINDOWS\system32\config\systemprofile
    Get-CimInstance -ComputerName (Get-Content "C:\scripts\Servers1.txt") win32_userprofile |
        ForEach-Object {
            if ($_.localpath -like "?:\users\*"){
                [PSCustomObject]@{
                    Computer = $_.PSComputerName
                    LocalPath = $_.localpath
                    SID = $_.sid
                }
            }
        } | Export-Csv -Path '\\powerserver\C$\Temp\ServerUsers\Report.csv' -NoTypeInformation
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.