Home > Net >  Run multiple Powershell commands and export results to csv
Run multiple Powershell commands and export results to csv

Time:11-26

I'm hoping this is a nice quick one. I have 11 scripts setup to check whether Microsoft Licenses are directly assigned or not. I then have a master.ps1 that will run all these scripts one after the other. What I want to achieve, is to basically export the results from the master.ps1 after it's finished running. All the scripts are the same, the only difference being that the license names change. So for example, checking the EMS license:

$skuId = "contoso:SPE_E3"
`Get-MsolUser -All | where {$_.isLicensed -eq $true -and $_.Licenses.AccountSKUID -eq $skuId} | select UserPrincipalName,
@{Name="SkuId";Expression={$skuId}}, 
@{Name="AssignedDirectly";Expression={(UserHasLicenseAssignedDirectly $_ $skuId)}}, 
@{Name="AssignedFromGroup";Expression={(UserHasLicenseAssignedFromGroup $_ $skuId)}}`

The master.ps1 will be as follows:

&"$PSScriptroot\Script1.ps1"
&"$PSScriptroot\Script2.ps1"
&"$PSScriptroot\Script3.ps1"

Etc

I've tried adding Export-CSV after the master file but it doesn't work, can anyone assist please?

Many thanks,

A

CodePudding user response:

Make sure your capture the output from all the scripts when exporting to CSV:

@(
  & "$PSScriptroot\Script1.ps1"
  & "$PSScriptroot\Script2.ps1"
  & "$PSScriptroot\Script3.ps1"
) |Export-Csv ...

Alternatively, export the output from each script one at a time, then use Export-Csv -Append for subsequent scripts:

& "$PSScriptroot\Script1.ps1" |Export-Csv ...
& "$PSScriptroot\Script2.ps1" |Export-Csv -Append ...
& "$PSScriptroot\Script3.ps1" |Export-Csv -Append ...

CodePudding user response:

Here is an approach using a ForEach-Object pipeline:

'Script1', 'Script2', 'Script3' | ForEach-Object {
    & "$PSScriptroot\$_.ps1"
} | Export-Csv ...

This passes an array literal consisting of the script names to ForEach-Object. The output of the ForEach-Object script block is then passed to Export-Csv, as it is generated (a streaming approach).

If you want to keep separate script calls (which might be more straightforward in case the scripts need different arguments), you can create just a script block {} and run it immediately, using the & operator:

& {
    & "$PSScriptroot\Script1.ps1"
    & "$PSScriptroot\Script2.ps1"
    & "$PSScriptroot\Script3.ps1"
} | Export-Csv ...

This has the same advantage as the ForEach-Object variant above, that it is a streaming approach, requiring less memory to store intermediate output (only for internal buffering, independent of the scripts output size).

  • Related