Forum Discussion

rvizzini71's avatar
rvizzini71
Copper Contributor
May 10, 2024

Output in CSV file

Good morning,

i have the following code:

 

 

$PdlList = Get-Content "C:\Temp\Computers.txt"

Foreach($Pdl in $PdlList)
{
 
   Invoke-Command -ComputerName $Pdl -ScriptBlock{Get-LocalGroupMember -Name 'Administrators' | where {($_.PrincipalSource -ne "ActiveDirectory" )} } | select PSComputerName, Name, PrincipalSource 
   
}
| Export-Csv c:\temp\test.csv -Append -NoTypeInformation -Encoding UTF8

 

 

I can't insert the result into a csv file, every time I run the script the file remains empty. Can someone help me?

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    rvizzini71 

     

    Hi, Roberto.

     

    I can't see any issue with your script. Have you tried leaving off the Export-Csv to see if anything is indeed being returned? (I'd expect nothing is being returned.)

     

    I ran a slight variation of your script and it worked just fine, as shown.

     

    Source TXT file

     

    To screen

     

    To file

     

     

    Script

    Note: You'll likely want to exclude -UseSSL from Invoke-Command (as I run only secure WinRM) and include -Append on Export-Csv.

     

    Invoke-Command -UseSSL -ComputerName (Get-Content -Path "D:\Data\Temp\Forum\forum.txt") -ScriptBlock {
        Get-LocalGroupMember -Name 'Administrators' |
            Where-Object { ($_.PrincipalSource -ne "ActiveDirectory" ); }
    } |
        Select-Object -Property PSComputerName, Name, PrincipalSource |
            Export-Csv -NoTypeInformation -Path "D:\Data\Temp\Forum\forum.csv" -Encoding UTF8;

     

    Cheers,

    Lain

    • rvizzini71's avatar
      rvizzini71
      Copper Contributor
      Hi Lain,
      Thanks for the precise and quick response. I tested the script with your changes and it works perfectly. Good day.
      Roberto.

Resources