PowerShell: Copy $Profile to every Windows Server

A system administrator PowerShell script to get your profile set up on every server on the domain

'D:\PowerShell\Copy-Profile.ps1'
# Set the path of your PowerShell profile file  
$profilePath = "C:\Users\$env:USERNAME\Documents\WindowsPowerShell\Microsoft.PowerShell*_profile.ps1"  
  
# Get a list of servers to copy the file to  
$servers = Get-ADComputer -Filter {OperatingSystem -like "Windows Server*"} -SearchBase "DC=Burwell,DC=tech" -Properties OperatingSystem | Select-Object -ExpandProperty Name  
  
# Initialize a variable to keep track of the successful servers  
$successes = @()  
  
# Loop through each server and copy the file  
foreach ($server in $servers) {  
    # Test if the server is reachable  
    if (!(Test-Connection -ComputerName $server -Quiet)) {  
        Write-Host "Skipping $server - server is not reachable" -ForegroundColor Yellow  
        continue  
    }  
      
    # Test if WinRM is configured and running on the server  
    if (!(Test-WSMan -ComputerName $server -ErrorAction SilentlyContinue)) {  
        Write-Host "Skipping $server - WinRM is not configured or running" -ForegroundColor Yellow  
        continue  
    }  
      
    # Set the path on the remote server  
    $remotePath = "\\$server\C$\Users\$env:USERNAME\Documents\WindowsPowerShell\"  
      
    # Copy the file to the remote server  
    try {  
        Invoke-Command -ComputerName $server -ScriptBlock {  
            param($sourcePath, $destinationPath)  
            Copy-Item -Path $sourcePath -Destination $destinationPath -Force -Verbose:$false|Out-Null   
            ls $destinationPath  
        } -ArgumentList $profilePath, $remotePath -ErrorAction Stop  
          
        # Add the server to the list of successful servers  
        $successes += $server  
    }  
    catch {  
        $errorMessage = "Failed to copy file to $server. Error message: $($Error[0].Exception.Message)"  
        Write-Host $errorMessage -ForegroundColor Red  
    }  
}  
  
# Display the list of successful servers  
Write-Host "Successfully copied file to the following servers:"  
$successes

Just remember to put your domain in for the ‘-SearchBase’


Posted

in

by

Tags: