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

使用PowerShell执行Invoke-Sqlcmd时出现类型初始化异常求助

解决Invoke-Sqlcmd中Microsoft.Data.SqlClient.InOutOfProcHelper类型初始化异常

执行以下PowerShell脚本时出现类型初始化异常:

Invoke-Sqlcmd -Query "select 'Y' from sys.databases" -ServerInstance .

错误信息:

Invoke-Sqlcmd : The type initializer for 'Microsoft.Data.SqlClient.InOutOfProcHelper' threw an exception.
At C:\temp\Untitled5.ps1:2 char:1
+ Invoke-Sqlcmd -Query "select 'Y' from sys.databases" -ServerInstance  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidResult: (.:PSObject) [Invoke-Sqlcmd], TypeInitializationException
    + FullyQualifiedErrorId : ExecutionFailed,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

可行解决方案

  • 更新SqlServer PowerShell模块
    旧版本模块可能存在兼容性问题,步骤如下:

    1. 查看已安装的模块版本:
      Get-Module -ListAvailable SqlServer
      
    2. 卸载旧版本(如果存在):
      Uninstall-Module -Name SqlServer -AllVersions
      
    3. 安装最新版本(需管理员权限):
      Install-Module -Name SqlServer -Force -AllowClobber
      

    注意:执行前确保已设置允许脚本执行:Set-ExecutionPolicy RemoteSigned

  • 修复Microsoft.Data.SqlClient组件
    该组件损坏可能导致初始化失败,可通过NuGet重新安装:

    Install-Package Microsoft.Data.SqlClient
    

    若为全局程序集问题,可检查GAC(全局程序集缓存)中的相关文件,尝试重新注册或替换为最新版本。

  • 验证PowerShell版本兼容性
    旧版PowerShell可能不兼容最新的SQL客户端组件,确保使用PowerShell 5.1或更高版本(推荐PowerShell 7+):

    $PSVersionTable.PSVersion
    
  • 检查SQL Server实例访问权限
    确认执行PowerShell的账号拥有本地SQL Server实例的连接权限,可通过SSMS尝试连接同一实例验证权限是否正常。

  • 修复.NET运行时
    异常可能与.NET运行时损坏有关:

    • 对于.NET Core/.NET 5+:运行dotnet repair命令修复
    • 对于.NET Framework:通过控制面板的程序和功能,找到对应的.NET Framework版本进行修复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:47:11