SQL_Deadwood
SQL_Deadwood

Reputation: 521

Powershell: Trying to locate file in multiple drives from list of servers

I'm trying (and failing) to:

  1. Connect to the server by iterating through a list.
  2. Confirm location where file exists (1 of 3 locations).
  3. Replace a string in that file.

I've tried to do this multiple ways. There are two that I have which do part of what I want.

Can someone please help me understand if there's something I'm doing inefficiently or how to put all this together?

This one can loop through the servers and find the file

$ErrorActionPreference = 'SilentlyContinue'
$nope=$null
$servers= Get-Content C:\Servers.txt

foreach ($server in $servers)
    {
    If (Test-Connection -ComputerName $server -Quiet)
        {Invoke-Command -ComputerName $server -ScriptBlock {$file=(Get-Childitem -Path C:\DiskSpace.ps1, D:\DiskSpace.ps1, Y:\DiskSpace.ps1); Write-Host "Found $file on $env:computername."}}
    Else {
        Write-Host ">> Could not connect to $server."; $nope += $server}
         }
Write-Host $nope

...and this one can at least find a local file

$valid=@('')
$paths = @("C:\Users\user_name\Desktop\DiskSpace.ps1","C:\DiskSpace.ps1","D:\DiskSpace.ps1","Y:\DiskSpace.ps1")

Foreach ($path in $paths) 
{ 
if (Test-Path $path)
    {$valid += $path}
}

write-host $valid

Here's how I intend to to replace the string:

$ErrorActionPreference = 'SilentlyContinue'

$find=(Get-Childitem -Path C:\, D:\, Y:\ -include DiskSpace.ps1 -Recurse)
Write-Host $find

$ErrorActionPreference = 'Stop'

try {

    (Get-Content $find).replace('[email protected]', '[email protected]') | Set-Content $find
}
catch {

}

Get-Content $find

Upvotes: 0

Views: 400

Answers (1)

BenH
BenH

Reputation: 10044

You had all the pieces already. Simply loop over your Get-Content command for each file in the Invoke-Command.

$ErrorActionPreference = 'SilentlyContinue'
$servers = Get-Content C:\Servers.txt
$files = @('C:\DiskSpace.ps1', 'D:\DiskSpace.ps1', 'Y:\DiskSpace.ps1')

$report = foreach ($server in $servers) {
    if (Test-Connection -ComputerName $server -Quiet) {
        $response = Invoke-Command -ComputerName $server -ScriptBlock {
            Get-Childitem -Path $using:files  | ForEach-Object {
                (Get-Content $_).replace('[email protected]', '[email protected]') | Set-Content $_
                [PSCustomObject]@{
                    Name = $env:COMPUTERNAME
                    Message = "$($_.fullname) updated."
                }
            }
        }
        if ($response -eq $null) {
            [PSCustomObject]@{
                Name = $env:COMPUTERNAME
                Message = "No files found"
            }
        } else {
            $response
        }
    } else {
        [PSCustomObject]@{
            Name = $env:COMPUTERNAME
            Message = "Unreachable"
        }
    }
}
$report

Upvotes: 1

Related Questions