You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows PowerShell报No Runspace Available错误,ISE中运行正常

问题描述

我有一段处理从Intune获取计算机信息CSV文件的PowerShell脚本,在PowerShell ISE中能正常运行,但在Windows PowerShell中处理约100条条目后抛出错误:

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:

读取的CSV包含以下列:HostID、ComputerName、EmployeeID、Notes、WorkOrder、GroupName、LastLogonUserName、ExternalIP、OSVersion、Serial Number、Model

脚本通过Microsoft Graph API获取OSVersion、Serial Number和Model,其余数据来自Logmein账户,代码片段如下:

$tenantId = 'string for tenant ID'
$appId = 'string for app ID'
$appSecret = 'string for app secret'

#Get the OAuth token
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$tokenBody = @{
    client_id     = $appId
    scope         = 'https://graph.microsoft.com/.default'
    client_secret = $appSecret
    grant_type    = 'client_credentials'
}
$tokenResponse = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $tokenBody
$token = $tokenResponse.access_token


$secureToken = ConvertTo-SecureString -String $token -AsPlainText -Force
Connect-MgGraph -AccessToken $secureToken

$csvData = @()

foreach ($host in $report.Hosts) {
    $jsonEntry = $allBatchData | Where-Object { $_.hosts."$($host.HostID)" -ne $null }
    if ($jsonEntry) {
        $csvData += [PSCustomObject]@{
            "Computer Name"     = $host.ComputerName
            "HostID"            = $host.HostID
            "LastLogonUserName" = $jsonEntry.hosts."$($host.HostID)".lastLogonUserName
            "ExternalIP"        = $jsonEntry.hosts."$($host.HostID)".externalIp
            "Operating System"  = $host.OperatingSystem
        }
    }
}


$csvData = Import-Csv "\CentralData.csv"

foreach ($row in $csvData) {
    $cleanComputerName = ($row.ComputerName -split '\s')[0]
    $hostID = $row.HostID
    $hostDataFromJson = $allBatchData.hosts | Where-Object { $_.id -eq $hostID }
    $matchingDevice = Get-MgBetaDeviceManagementManagedDevice -Filter "DeviceName eq '$cleanComputerName'" | Select-Object OsVersion, SerialNumber, Model -First 1
    
   if ($allBatchData.hosts.$hostID) {
        $row | Add-Member -MemberType NoteProperty -Name "LastLogonUserName" -Value $allBatchData.hosts.$hostID.lastLogonUserName -Force
        $row | Add-Member -MemberType NoteProperty -Name "ExternalIP" -Value $allBatchData.hosts.$hostID.externalIp -Force
    }

    if ($matchingDevice) {
        $row | Add-Member -MemberType NoteProperty -Name "OSVersion" -Value $matchingDevice.OsVersion -Force
        $row | Add-Member -MemberType NoteProperty -Name "Serial Number" -Value $matchingDevice.SerialNumber -Force
        $row | Add-Member -MemberType NoteProperty -Name "Model" -Value $matchingDevice.Model -Force
        Write-Output "Fetched OSVersion and Serial Number for ${cleanComputerName}: $($matchingDevice.OsVersion) and $($matchingDevice.SerialNumber) and $($matchingDevice.Model)"
    } else {
        $row | Add-Member -MemberType NoteProperty -Name "OSVersion" -Value "N/A" -Force
        $row | Add-Member -MemberType NoteProperty -Name "Serial Number" -Value "N/A" -Force
        $row | Add-Member -MemberType NoteProperty -Name "Model" -Value "N/A" -Force
        Write-Output "No OSVersion or Serial Number found for ${cleanComputerName}"
    }
    $csvData | Export-Csv "path to CentralData.csv" -NoTypeInformation

}

$csvData | Export-Csv "path to CentralData.csv" -NoTypeInformation

已尝试的解决方法:

  • 尝试理解PowerShell中的runspace概念,但仍不清楚为何仅在Windows PowerShell中出现此问题
  • 推测是资源或线程问题,参考过相关问题但无法解决

疑问

  1. 线程中缺少runspace的错误信息在我的脚本语境中意味着什么?
  2. 为何该脚本在PowerShell ISE中可正常运行,在Windows PowerShell中却失败?

问题解答

1. 错误信息的含义

这个错误说明脚本执行时,某个后台线程尝试运行脚本块,但找不到可用的PowerShell运行空间(Runspace)。

在你的脚本里,核心触发点是循环中反复调用Get-MgBetaDeviceManagementManagedDevice:Microsoft Graph PowerShell模块内部会用后台线程处理API请求,当请求累积到约100次时,后台线程的Runspace资源被耗尽,后续请求无法获取可用的Runspace,就会抛出这个错误。另外,你在循环内部每次都执行$csvData | Export-Csv,频繁的文件读写会进一步占用Runspace资源,加速问题出现。

2. ISE与Windows PowerShell的差异

  • Runspace管理机制不同:PowerShell ISE使用共享Runspace池,会自动复用、回收Runspace资源,即使大量后台请求也能维持可用性;而Windows PowerShell控制台的Runspace管理更严格,后台线程的Runspace不会自动回收,请求数量超过阈值后就会出现资源耗尽。
  • 执行环境限制差异:ISE对异步操作(比如Graph API请求)的资源限制更宽松;Windows PowerShell控制台的单线程模型对资源占用更敏感,累积的未回收Runspace会快速耗尽可用资源。

内容的提问来源于stack exchange,提问作者Quentin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 05:21:13