Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now! Learn more

Reply
Sania198
Frequent Visitor

How to use SQL query data to create a Power BI Workspaces via PowerShell or Rest API Script

Hi,

  1. I want to create a Power BI workspaces by referencing to the view created in our SQL DB.
  2. I am successful in pulling the data by connecting to SQL DB where we have a table with DatabaseName, by using that DatabaseName from DB PBI workspaces should be created if the workspace doesn't exists.
  3. If the workspace already exists then based on the workspace state like (if the workspace is in DELETE State then it should be activated) or If it is already in ACTIVE state then no operation should be performed.

However, when trying it with below PS Script I am getting errors. Below is the error screenshot 

Sania198_0-1667049994965.png

 

PowerShell Script I'm using:

$Query = '
SELECT TOP (3) [DatabaseName]
  FROM [dbo].[vw_ListToAddToPBIws]
'
$SQLFile = Invoke-Sqlcmd -ServerInstance $SqlServer -Database $Database -Query $Query -Username $SqlAuthLogin -Password $SqlAuthPw
$SQLFile = Select-Object

Write-Host
Connect-PowerBIServiceAccount | Out-Null

$workspaceName = $SQLFile

$workspace = Get-PowerBIWorkspace -Name $workspaceName

if($workspace) {
  Write-Host "The workspace named $workspaceName already exists" -ForegroundColor Green
}
else {
  Write-Host "Creating new workspace named $workspaceName" -ForegroundColor DarkBlue
  $workspace = New-PowerBIGroup -Name $workspaceName
}
 

I really appreciate if someone can help me with the above ask.

Thanks in Advance!

1 ACCEPTED SOLUTION
lbendlin
Super User
Super User

$SQLFile returns an object (the table of the rows for your query result). Now you need to run a ForEach on this to address the individual workspaces.

View solution in original post

3 REPLIES 3
Sania198
Frequent Visitor

I played with the script and tried to pass Foreach as you said and it resolved the issue for me

Thanks @lbendlin 

lbendlin
Super User
Super User

$SQLFile returns an object (the table of the rows for your query result). Now you need to run a ForEach on this to address the individual workspaces.

Thanks for the response @lbendlin 

If possible, can you please help me with the script to use the ForEach loop for the above ask

Helpful resources

Announcements
Power BI DataViz World Championships

Power BI Dataviz World Championships

The Power BI Data Visualization World Championships is back! Get ahead of the game and start preparing now!

December 2025 Power BI Update Carousel

Power BI Monthly Update - December 2025

Check out the December 2025 Power BI Holiday Recap!

FabCon Atlanta 2026 carousel

FabCon Atlanta 2026

Join us at FabCon Atlanta, March 16-20, for the ultimate Fabric, Power BI, AI and SQL community-led event. Save $200 with code FABCOMM.