Save script output to the file

Hi,

I am very new to Powershell.
I have a below script and I want the script output to be saved in a file.

$Workspaces = Get-PowerBIWorkspace -Name ‘Test_Workspace’
$TopN=1

foreach($workspace in $Workspaces)
{

$DataSets = Get-PowerBIDataset -WorkspaceId $workspace.Id | where {$_.isRefreshable -eq $true}
foreach($dataset in $DataSets)
{

$URI = “groups/” + $workspace.id + “/datasets/” + $dataset.id + “/refreshes/?`$top=$($TopN)”
#$OutFile = $ExportFolder + '' + $workspace.Name + ‘-’ + $dataset.Name + ‘.json’
$Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

foreach($result in $Results.value)
{
if($result.status -eq “Failed”)
{
$errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

$row = New-Object psobject
$row | Add-Member -Name “Workspace” -Value $workspace.Name -MemberType NoteProperty
$row | Add-Member -Name “Dataset” -Value $dataset.Name -MemberType NoteProperty
$row | Add-Member -Name “refreshType” -Value $result.refreshType -MemberType NoteProperty
$row | Add-Member -Name “startTime” -Value $result.startTime -MemberType NoteProperty
$row | Add-Member -Name “endTime” -Value $result.endTime -MemberType NoteProperty
$row | Add-Member -Name “status” -Value $result.status -MemberType NoteProperty
$row | Add-Member -Name “errorCode” -Value $errorDetails.errorCode -MemberType NoteProperty
$row | Add-Member -Name “errorDescription” -Value $errorDetails.errorDescription -MemberType NoteProperty
Write-Host $row
}}}}

I tried with Out-file command but the file is getting generated with no output in it.
Can anyone please help me on that?

Thanks,
Poonam

For starts it helps if you go back and format your code as code with the ‘</>’ button. Also include what you tried with Out-File as that should work.

Can we see what options you are using for your “Out-File” pipeline?

What I would suggest is to use switches like -NoClobber -Append and -NoTypeData

I think the issue is your use of Write-Host. You might read this to understand the idea of output streams.

A couple of suggestions.

  • Add your objects ($row) to an array, then output the array to a file
$row = @()
foreach {
$row += new-object ...
}
$row | out-file (or export-csv, or whatever format is good for you)

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.