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

PowerShell脚本在SQL Server Agent作业中执行失败求助

问题

我会定期收到客户发来的包含数据库备份的Zip文件,需将其恢复至过渡服务器(staging server),后续再处理数据并导入生产环境。因Zip文件名带有时间戳,需修改现有脚本以使用通配符,但问题随之出现。

直接在PowerShell控制台执行以下脚本时运行正常:

if(Test-Path -Path \\VM-NTM-DATA01\<Customer>\Sample*.zip){
    Expand-Archive '\\VM-NTM-DATA01\<Customer>\Sample*.zip' -DestinationPath 'D:\TM5\<Customer>' -Force
}
else{
    Write-Error "The directory was empty!" -EA Stop
}

但将该代码添加至SQL Server Agent作业步骤后,出现如下错误信息:

Executed as user: \agent. A job step received an error at line 1 in a PowerShell script. The corresponding line is 'if(Test-Path -Path \VM-NTM-DATA01<Customer>\Sample*.zip){ '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Cannot retrieve the dynamic parameters for the cmdlet. Invalid Path: '\VM-NTM-DATA01<Customer>'. '. Process Exit Code -1. The step failed.

我也曾尝试使用-LiteralPath参数(包含通配符),但同样无效。请问该如何配置路径,才能让脚本在SQL作业中正常执行?

解决方案

方法1:先枚举文件再处理

SQL Server Agent调用的PowerShell环境对通配符的解析存在差异,建议先通过Get-ChildItem枚举符合条件的文件,再进行后续操作,避免直接在Test-Path和Expand-Archive中使用通配符路径:

$zipFiles = Get-ChildItem -Path "\\VM-NTM-DATA01\<Customer>" -Filter "Sample*.zip" -File
if($zipFiles.Count -gt 0){
    foreach($zip in $zipFiles){
        Expand-Archive -Path $zip.FullName -DestinationPath 'D:\TM5\<Customer>' -Force
    }
}
else{
    Write-Error "The directory was empty!" -ErrorAction Stop
}

这种方式先明确获取所有匹配的zip文件,再逐个解压,绕开路径解析问题。

方法2:检查SQL Agent服务账号权限

错误提示中的路径无效,大概率是SQL Server Agent的运行账号(<DOMAIN>\agent)没有访问\\VM-NTM-DATA01\<Customer>共享目录的权限:

  • 确认该账号对目标共享目录拥有读取权限
  • 验证该账号能正常访问VM-NTM-DATA01服务器(网络连通、DNS解析正常)
  • 可在服务器上用该账号登录,手动访问共享目录确认权限是否正常

方法3:使用本地映射驱动器替代UNC路径(可选)

如果UNC路径在SQL Agent环境中始终存在问题,可以先将共享目录映射为本地驱动器后再操作:

# 映射网络驱动器
New-PSDrive -Name Z -PSProvider FileSystem -Root "\\VM-NTM-DATA01\<Customer>" -Credential (Get-Credential)
# 检查并解压文件
if(Test-Path -Path Z:\Sample*.zip){
    Expand-Archive 'Z:\Sample*.zip' -DestinationPath 'D:\TM5\<Customer>' -Force
}
else{
    Write-Error "The directory was empty!" -ErrorAction Stop
}
# 移除驱动器
Remove-PSDrive -Name Z

注意:若需要自动执行,需配置账号的持久化凭据,不建议在脚本中嵌入明文凭据。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:05:08