0
votes

I am running invoke-command on 50 servers and I need to write multiple files to the local machine. I have tried using a combination of UNC paths out-file and write-output, but cant get it to write the files to the local machine.

$data = Invoke-Command -ComputerName $servers -ScriptBlock { 
    $Server = $env:COMPUTERNAME
    $services = Get-Service | Where-Object { $_.Status -ne "Running" } | Select-Object name
    $services | Write-Output "\\local\monitor\Services\$Server.html"
    $EventLogs = Get-WinEvent -FilterHashtable @{Logname = 'Application'; Level = 1; StartTime = [datetime]::Now.AddMinutes(-15) }
    $EventLogs | Out-File "\\local\monitor\Events\$server.html" 
}

Edit: If I run this on the remote server, It will write the file to the local server

$services | Write-Output "\\local\monitor\Services\file.txt"

However, I get access denied running this - I am running PS as admin. Why Access Denied when running invoke-command, but not directly from remote server?

Invoke-Command -ComputerName $remote -ScriptBlock { 

"this is a test" | Out-File -FilePath "\\local\monitor\Services\file.txt" -force

$Error

}
Out-File : Access to the path '\\local\monitor\Services\file.txt' is denied.
At line:3 char:20
+ ... s a test" | Out-File -FilePath "\\local\monitor\Services\file.txt" ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Out-File], UnauthorizedAccessException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
1
Why are you sending the results of your remote call to a variable? [$data = Invoke-Command -ComputerName $servers...]postanote
It collects other metrics that is processed latermattnicola
ended up using a hash table similar to this answer stackoverflow.com/a/62542092/4022830mattnicola

1 Answers

0
votes

Try this...

Invoke-Command -ComputerName $Servers -ScriptBlock { 
    $Server = $env:COMPUTERNAME

    $services = Get-Service | 
    Where-Object { $PSItem.Status -ne 'Running' } | 
    Select-Object name |
    Out-File -LiteralPath "\\local\monitor\Services\$Server.html" -Append

    $EventLogs = Get-WinEvent -FilterHashtable @{
        Logname   = 'Application'
        Level     = 1
        StartTime = [datetime]::Now.AddMinutes(-15) 
    } | 
    Out-File -LiteralPath "\\local\monitor\Events\$server.html" -Append
}