Out-File inside a foreach statement

时间:2015-06-25 18:23:46

标签: powershell sharepoint

im trying to run this script, it works but every time that it changes from item on the list it erases the file and starts over. what i need this to do is to get from the list of items all the users and put them all in a single text file.

$sitios = Get-Content -Path C:\sitios.txt
Connect-SPOService -Url https://aaa.sharepoint.com/ -Credential Admin@aaa.onmicrosoft.com
foreach ($sitio in $sitios){
$sitio
Get-SPOUser -Site $sitio -Limit ALL | Out-File -FilePath C:\usuarios.txt
}

any help is appreciated

2 个答案:

答案 0 :(得分:1)

You could use the -Append switch of Out-File but all you should have to do is move it outside the loop.

(foreach ($sitio in $sitios){

    Write-Host $sitio
    Get-SPOUser -Site $sitio -Limit ALL 

}) | Out-File -FilePath C:\usuarios.txt

That way all output will be sent to Out-File. I added Write-Host $sitio so that was not going to be in the file. You could also use Set-Content which is considered the preferential choice over Out-File

The brackets are needed around the loop so that we can use the pipe output. That foreach construct cannot have data directly piped from it. An answer here covers the reason.

That all being said you could then do something like this

$sitios | ForEach-Object{
    Write-Host $_
    Get-SPOUser -Site $_ -Limit ALL 
} | Set-Content C:\usuarios.txt

This output should be a complex object that might not have a proper tostring equivalent. You can still get all the data with something like this instead.

$sitios | ForEach-Object{
    Write-Host $_
    Get-SPOUser -Site $_ -Limit ALL 
} | Export-CSV C:\usuarios.txt -NoTypeInformation

答案 1 :(得分:0)

You can use the Add-Content Cmdlet:

https://technet.microsoft.com/en-us/library/ee156791.aspx

Instead of Out-File use Add-Content

as in:

[...] | Add-Content C:\usuarios.txt