通过 SQL Server 代理作业调用时,PowerShell 命令“New-Item”失败

Siv*_*ari 2 sql-server powershell windows-server sql-server-2016

我有以下 PowerShell 脚本可在共享位置创建文件夹。该共享对每个人都具有完全控制权限。我已授予所有测试权限。

问题是当我手动执行时脚本工作正常。当我作为 SQL Server 代理服务帐户执行它时,它也能正常执行。但是当我尝试作为 SQL Server 代理作业的一部分执行时,相同的脚本失败。我在这里错过了什么吗?

$path = "\\server\shared\path\01222020"
New-Item -path $path -ItemType Directory -Force

Exception:
Date        1/22/2020 5:25:10 PM
Log     Job History (test)

Step ID     1
Server      serverA
Job Name        Test
Step Name       Test
Duration        00:00:01
Sql Severity    0
Sql Message ID  0
Operator Emailed    
Operator Net sent   
Operator Paged  
Retries Attempted   0

Message
Executed as user: domain\agent_service_account. A job step received an error at 
line 9 in a PowerShell script. The corresponding line is 'New-Item -path $path 
-ItemType Directory '. Correct the script and reschedule the job. The error 
information returned by PowerShell is: 'Invalid Path: 
'\\server\shared\path\01222020'.  '.  Process Exit Code -1.  The step failed.
Run Code Online (Sandbox Code Playgroud)

Han*_*dyD 7

从 PowerShell 作业步骤访问 UNC 路径或任何非本地驱动器(即注册表)的“位置”时,您需要在路径前加上Microsoft.PowerShell.Core\FileSystem::. 这会告诉 SQLPS 使用哪个提供程序,这在普通 PowerShell 中不是必需的,但在 SQL Server 实现中是必需的。

或者,您可以预先将目录更改为本地驱动器 (cd C:),然后它应该可以在不添加提供程序名称前缀的情况下工作,但您可能希望SQLSERVER:\SQL\SERVERNAME\INSTANCENAME根据脚本需要保留在默认路径中。

更多信息:

https://dbatools.io/agent/

https://social.technet.microsoft.com/Forums/windowsserver/en-US/ec7f3ae8-d196-459e-b9dc-e6ed0df93004/running-powershell-from-sql-server-using-unc-paths