通过PowerShell以Windows身份验证连接SQL Server任务计划执行报错求助
问题描述
我的SQL Server仅支持Windows身份验证模式,在SQL Server Management Studio中连接正常,手动运行以下PowerShell脚本也能正常连接:
$Path = 'D:\' write "Starting script --------" | Out-File $Path\output.txt $SQLServer = 'server_name,1111' $Database = 'db_name' try { $Connection = New-Object System.Data.SqlClient.SQLConnection $Connection.ConnectionString = "Data Source=$SQLServer;Integrated Security=$true;Initial Catalog=$Database" $Connection.Open() Write-Host 'Open database connection' write "Open database connection" | Out-File $Path\output.txt -Append } catch { Write-Host 'An error occurs' write "error opening connection: $_" | Out-File $Path\output.txt -Append } finally { ## Ensure closing the connection to release the resource / free memory $Connection.Close() Write-Host 'Close database connection' write "Close database connection" | Out-File $Path\output.txt -Append }
但将该脚本通过Windows任务计划以拥有数据库连接权限的同一用户调度执行时,出现如下错误:
error opening connection: Exception calling "Open" with "0" argument(s): "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'."
请问哪里操作有误?
可能的原因及解决办法
任务计划身份验证配置错误
打开任务计划属性的「常规」选项卡:- 如果勾选了「不管用户是否登录都要运行」,必须同时勾选「使用最高权限运行」,否则会导致权限降级;
- 确认任务使用的是你指定的有权限用户身份,不要让系统自动使用匿名账户替代。
跨机器双跳的Kerberos权限问题
若SQL Server和运行任务计划的机器不是同一台,属于「双跳」场景(任务机→SQL Server),Windows默认不允许本地凭据跨机器传递,会降级为匿名登录:- 确保两台机器都加入域环境;
- 在AD中找到运行任务的域用户,右键属性→「委派」选项卡,选择「信任此用户以委派到任何服务(Kerberos only)」(或严格指定SQL Server服务);
- 确保SQL Server服务使用域账户运行,而非本地系统账户。
PowerShell执行环境差异
任务计划执行脚本时的默认环境和手动运行不同,可在任务的「操作」中修改参数:
将程序设为powershell.exe,参数改为-ExecutionPolicy Bypass -File "你的脚本完整路径",强制跳过执行策略限制,避免脚本加载异常。输出目录权限问题
检查D:\目录是否给任务运行的用户分配了读写权限,虽然这不是直接导致数据库登录失败的原因,但目录权限不足可能引发脚本执行异常,建议排查确认。
内容的提问来源于stack exchange,提问作者Vinkesh Shah
相关产品推荐
相关产品推荐

