"format-default: There is no Runspace available to run scripts in this thread" is fatally terminating scripts
Describe the bug
Calling the Get-MgUser and other Microsoft.Graph functions often cause my scripts to fail with this error: format-default: There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: …
The problem is more reproducible on virtual machines with 2 virtual CPUs. It seems this occurs when the Microsoft.Graph objects are emitted to the pipeline.
Expected behavior
Emitting Microsoft.Graph object to the pipeline (or screen) should not terminate PowerShell scripts.
How to reproduce
- Deploy a Hyper-V VM running Windows 11 with 2 vCPU and 4 GB RAM
- Install PowerShell 7 with: winget install --id Microsoft.PowerShell --source winget
- Start PowerShell 7 "as Administrator"
- Install Microsoft Graph: Install-Module Microsoft.Graph -Scope AllUsers -Repository PSGallery -Force
- Install Exchange Online PowerShell: Install-Module -Name ExchangeOnlineManagement -Scope AllUsers
- Create a PowerShell script called Test-format-default and paste this text:
[CmdletBinding()]
param(
[Parameter( Position=0,
Mandatory=$true,
ValueFromPipeline=$False,
ValueFromPipelineByPropertyName=$False) ]
[string]
$User,
[Parameter( Position=1,
Mandatory=$true,
ValueFromPipeline=$False,
ValueFromPipelineByPropertyName=$False) ]
[ValidateSet("Graph", "EXO")]
[string]
$Provider
)
$origProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
for ($i = 0; $i -lt 100; $i++) {
Write-Information -MessageData ("Iteration {0}" -f ($i + 1)) -InformationAction Continue
switch ($Provider) {
"Graph" {
$MgUser = Get-MgUser -Filter "DisplayName eq '$User'" -Property $PropertyList | Select-Object -First 1
$MgUser
}
"EXO" {
$EXOMailbox = Get-EXOMailbox -Filter "DisplayName -eq '$User'"
$EXOMailbox
}
}
Start-Sleep -Seconds 2
}
$ProgressPreference = $origProgressPreference
- Use Connect-MGGraph to connect.
- Execute the script. For example:
.\Test-format-default.ps1 -User "John Doe" -Provider Graph
On a 2 vCPU VM, this tends to fail in less than 20 iterations, often in less than 10 iterations. On a 4 vCPU VM, this may not fail in the 100 iterations but I sometimes see it fail after many iterations. If you use the -Provider EXO, it never fails which is why it appears to be a bug in the Microsoft.Graph modules.
SDK Version
ModuleType Version PreRelease Name ExportedCommands ---------- ------- ---------- ---- ---------------- Script 2.24.0 Microsoft.Graph.Authentication {Add-MgEnvironment, Connect-MgGraph, Disconnect-M… Script 2.24.0 Microsoft.Graph.Users {Get-MgUser, Get-MgUserCount, Get-MgUserCreatedOb…
Latest version known to work for scenario above?
No response
Known Workarounds
- Using more virtual CPUs seems to decrease the frequency of the issue but may not avoid it completely.
- Not allowing the object to be emitted to the pipeline seems to work around the issue. For example, if you only return one property of the object to the pipeline, e.g $MGUser.UserPrincipalName, then the error does not occur.
- Does not occur when -Debug argument is used with Get-MGUser
Debug output
Click to expand log
```</details>
### Configuration
-OS: Windows 11
-Architecture: x64
```powershell
Name Value
---- -----
PSVersion 7.4.5
PSEdition Core
GitCommitId 7.4.5
OS Microsoft Windows 10.0.22631
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
Other information
No response
Hi @SiloReed apologies for the delay in responding to this issue. It seems that you have multiple processes running. Maybe you can explore the below options.
- Restart the VM (If possible)
- In your script, you can try to recreate the runspace after a number of iterations.
[runspace]::DefaultRunspace = [runspacefactory]::CreateRunspace()
[runspace]::DefaultRunspace.Open()
Maybe you can try this script.
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[string]$User,
[Parameter(Position=1, Mandatory=$true)]
[ValidateSet("Graph", "EXO")]
[string]$Provider
)
# Backup and modify progress preference
$origProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
# Function to Check and Restore Runspace
function Ensure-Runspace {
if (-not [runspace]::DefaultRunspace -or [runspace]::DefaultRunspace.RunspaceStateInfo.State -ne 'Opened') {
Write-Warning "Restoring PowerShell runspace..."
[runspace]::DefaultRunspace = [runspacefactory]::CreateRunspace()
[runspace]::DefaultRunspace.Open()
}
}
# Function to Retry Commands on Failure
function Invoke-Retry {
param(
[scriptblock]$Command,
[int]$MaxRetries = 3,
[int]$RetryDelay = 5
)
$attempt = 0
do {
try {
$attempt++
return & $Command
} catch {
Write-Warning "Attempt $attempt failed: $_. Retrying in $RetryDelay seconds..."
Start-Sleep -Seconds $RetryDelay
}
} while ($attempt -lt $MaxRetries)
Write-Error "Command failed after $MaxRetries attempts."
}
# Execute Loop with Runspace Handling and Retry Logic
for ($i = 0; $i -lt 100; $i++) {
Write-Information -MessageData ("Iteration {0}" -f ($i + 1)) -InformationAction Continue
# Ensure runspace is available
Ensure-Runspace
switch ($Provider) {
"Graph" {
$MgUser = Invoke-Retry {
Get-MgUser -Filter "DisplayName eq '$User'" -Property "DisplayName,Mail" | Select-Object -First 1
}
$MgUser
}
"EXO" {
$EXOMailbox = Invoke-Retry {
Get-EXOMailbox -Filter "DisplayName -eq '$User'"
}
$EXOMailbox
}
}
Start-Sleep -Seconds 2
}
# Restore original progress preference
$ProgressPreference = $origProgressPreference
This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment.
Closing stale issue
Sorry, the workaround script doesn't work either. If you add this else statement in your Ensure-Runspace function:
} else {
Write-Host "Runspace OK"
}
You will see that the default runspace tests out fine each time. The Invoke-Retry never falls into the catch block either, so the script is being interrupted prematurely. It looks like this on my system:
@timayabi2020 please reopen. See my last comment that your workaround does not work.