Out-File within Script Block Access Denied?

Ok, so I’m an elementary PS coder. I try… I’m trying to write a script that will query through a whole bunch of servers for some text in files within a few different directories.

Right now, I cannot get the foreach to work past the first server. The first server defined in the array is the server I’m running the PS script from. Once it finishes that server, when it tries to run the commands on the next server in the array, I get access denied when it tries to write the output back to the server I’m running the script from.

 

Sounds like a permissions issue not necessarily a script issue. Can you try to run a remote command “Invoke-Command” using your $credential variable to one of the problem servers? This will help determine if it is the script or permissions. The next thing I would look at is the logic. Its hard to tell with the server names redacted, but appears you are running commands on a remote machine then writing the results to a file from the remote machine back to your machine. This could also cause issues. I would recommend a couple changes that will make this much cleaner if that is indeed what you are doing.

  1. No loop is needed. The computername parameter of Invoke-Command will accept an array of server names. It will add a PSComputername property to the objects returned so you will know where they came from.
  2. Just return the objects in the Invoke-Command scriptblock
  3. You can either assign the results of Invoke-Command to a variable or export to a file or both..
Here is a simplified example of this logic:
$servers = "sv1", "sv2", "sv3"
$credential = Get-Credential

$results = Invoke-Command -ComputerName $servers -Credential $credential -ScriptBlock {
$return = @{} #empty hashtable
$return.stuff1 = Get-ChildItem “C:\Program Files\Microsoft”
$return.stuff2 = Get-ChildItem “C:\Users”
[pscustomobject]$return #returns object to $results
} #Invoke-Command scriptblock

$results | Out-File $outputfile -Append