为何PowerShell脚本在部分SQL Server实例可运行,部分实例失败?
我接手了前开发者的PowerShell脚本Deploy.ps1,它依赖SqlServer模块与SQL Server实例交互。脚本在两个环境的服务器实例上运行正常,但在另外三个环境中执行失败。
失败发生在脚本的最后一行($folder.Alter()),完整相关代码如下:
$serverName = <load from configuration file> $folderName = <load from configuration file> $catalogPwd = <load from configuration file> $ssisCatalog = "myCatalogName" Import-Module -Name SqlServer -MinimumVersion 22.0.0 $ISNamespace = "Microsoft.SqlServer.Management.IntegrationServices" [Reflection.Assembly]::LoadWithPartialName($ISNamespace) $sqlConnectionString = "Data Source=$serverName;Initial Catalog=master;Integrated Security=SSPI;" $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString $integrationServices = New-Object "$ISNamespace.IntegrationServices" $sqlConnection $catalog = $integrationServices.Catalogs[$ssisCatalog] if (!$catalog) { $catalog = New-Object "$ISNamespace.Catalog" ($integrationServices, $ssisCatalog, $catalogPwd) $catalog.Create() } $folder = $catalog.Folders[$folderName] if (!$folder) { $folder = New-Object "$ISNamespace.CatalogFolder" ($catalog, $folderName, $folderName) $folder.Create() } # Delete and recreate environments foreach ($env in $folder.Environments) { Write-Host "Deleting environment '" $env.Name "' in folder '$folderName'." $folder.Environments.Remove($env) } $folder.Alter()
所有失败环境的错误信息一致:
Exception on line 98
System.Management.Automation.MethodInvocationException: Exception calling "Alter" with "0" argument(s): "Operation 'Alter' on object 'CatalogFolder[@Name='myFolderName']' failed during execution." ---> Microsoft.SqlServer.Management.Sdk.Sfc.SfcCRUDOperationFailedException: Operation 'Alter' on object 'CatalogFolder[@Name='myFolderName']' failed during execution. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.BatchParser, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
已完成的排查:
- 确认所有环境PowerShell版本一致
- 核对微软文档确认PowerShell语法无问题(脚本在部分环境可正常运行)
- 搜索过类似问题
还需排查的方向:
- 检查SQL Server相关组件安装:
Microsoft.SqlServer.BatchParser属于SQL Server客户端工具或SSIS组件,失败环境可能缺少SQL Server Shared Features中的Client Tools SDK或Integration Services组件,或者组件版本不匹配。对比正常环境和失败环境的已安装SQL Server组件列表。 - 验证SqlServer模块实际版本:脚本指定了最低版本22.0.0,但需确认失败环境中实际加载的模块版本。执行
Get-Module SqlServer -ListAvailable查看已安装版本,在脚本开头添加Write-Host "Loaded SqlServer module version: $((Get-Module SqlServer).Version)"确认运行时版本,版本不匹配可能导致依赖组件不一致。 - 检查.NET Framework版本与程序集路径:该程序集依赖特定.NET Framework版本,失败环境可能缺少对应版本,或程序集所在路径不在系统搜索路径内。检查
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SqlServer.BatchParser或SQL Server安装目录(如C:\Program Files\Microsoft SQL Server\130\SDK\Assemblies)下是否存在目标程序集。 - 确认脚本运行用户权限:权限不足可能导致无法访问程序集文件,检查运行脚本的用户是否对SQL Server安装目录和.NET程序集目录有读取权限。
- 核对SQL Server实例SSIS版本:失败环境的SQL Server实例版本可能与客户端模块不兼容(如SQL Server 2016对应版本13),过高版本的SqlServer模块跨版本调用时可能出现依赖缺失,确保客户端模块与服务器端SSIS版本兼容。
内容的提问来源于stack exchange,提问作者Tamora

