PowerShell 7中Invoke-Sqlcmd连接SQL Server失败,PS 5可正常运行
我有一段基础PowerShell脚本,在PowerShell 5中运行完全正常,但切换到PowerShell 7执行时每次都会失败。
脚本代码如下:
$cr = Import-Clixml -Path 'C:\Users\{me}\Desktop\cred.xml' $cs = ('Data Source={0};Initial Catalog={1};User ID={2};Password={3};Persist Security Info=False;TrustServerCertificate=True;' -f $env:ComputerName, 'master', $cr.UserName, $cr.GetNetworkCredential().Password) $rs = Invoke-Sqlcmd -Query 'select name DatabaseName from sys.databases order by name' -ConnectionString $cs $rs
使用PowerShell 5命令提示符运行.\demo.ps1时每次都能成功执行,但PowerShell 7中执行会报错:
Invoke-Sqlcmd: C:\Users{me}\Desktop\demo.ps1:4
Line |
4 | $rs = Invoke-Sqlcmd -Query 'select name DatabaseName from sys.databas …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server
was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured
to allow remote connections. (provider: HTTP Provider, error: 0 - )None of those issues are an issue for PS5 - why are they an issue with 7?
我已经尝试过以下几种连接方式和调整,均未解决问题:
- 使用可信连接(我拥有sysadmin角色)
- 使用SqlConnection(我们常规的连接方式)
- 将
TrustServerCertificate从连接字符串$cs移至PowerShell命令参数中 - 同时在连接字符串
$cs和PowerShell命令参数中保留TrustServerCertificate - 多次验证远程连接已启用(尽管是本地调用)
- 确认实例名称为默认值(机器名称)
- 检查过本地防火墙规则
请问为何该脚本在PowerShell 7中会出现连接问题?
内容的提问来源于stack exchange,提问作者SqlNightOwl

