在不同的服务器上运行 PowerShell 脚本 - 从 SQL Server 作业内部

Mar*_*lli 5 sql-server ssas powershell linked-server maintenance-plans

我有一个备份 SSAS 数据库程序

这是一种魅力。

现在我的服务器被 SSAS 备份填满,我想删除超过 2 天的备份文件。

为了实现这一点,我使用了以下 POWERSHELL 脚本:

#-------------------------------------------------------------------------------
# Script to delete old SSAS backup files
#
# Marcelo Miorelli
# 
# 19-novembre-2014 Wed
#-------------------------------------------------------------------------------


#-- connect to the remote server -- SQLBILON1
#
ENTER-PSSESSION sqlbilon1


#-- set the Path where the backup files (.abf) are located
#
$path = 'H:\SQLBackups'

#-- set the number of days backups should be deleted -- in this case 2
#
$NumberOfDays = 2

#-- calculate the date of the backup files - if they are older than $days they will be deleted
#
$days = (Get-Date).AddDays(-$NumberOfDays)

#--get the list of the backup files to be deleted and delete them
#
Get-ChildItem $Path -Recurse '*.abf' | ? {$_.CreationTime -lt $days} | Remove-Item
Run Code Online (Sandbox Code Playgroud)

这个脚本的问题是我使用 MYSQLSERVER1 服务器来备份 SQLBILON1 服务器上的数据库。备份文件位于 SQLBILON1 的文件夹 H:\SQLBackups 中。

作业失败并显示以下错误消息:

 The job script encountered the following errors. These errors did not stop the script:
A job step received an error at line 13 in a PowerShell script. 
The corresponding line is 'ENTER-PSSESSION sqlbilon1'. 
Correct the script and reschedule the job. The error information returned by PowerShell is: 
'Connecting to remote server failed with the following error message : 
Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.'
Run Code Online (Sandbox Code Playgroud)

问题,如何在远程服务器上运行 PowerShell 脚本?此脚本从 sql server 作业运行。

我可以创建代理并使用它连接到远程服务器吗?

小智 3

如果您在域环境中,您可以设置一个具有SQLBILON1. 然而,使用远程 PowerShell 有点矫枉过正,并且增加了不必要的故障排除层。如果您没有在两台服务器上启用远程 PowerShell,并且没有正确配置服务器之间的防火墙访问,则会出现问题。

我会简单地使用服务器的 UNC 路径。无论您使用管理员共享\\SQLBILON1\H$\SQLBackups还是直接创建共享到\\SQLBILON1\SQLBackups. 除非您想向 SQL 代理服务授予MYSQLSERVER1该备份目录的权限,否则您需要创建一个具有适当权限的代理帐户。

如果您遵循以下路线,您的脚本将会更加简单:

#-------------------------------------------------------------------------------
# Script to delete old SSAS backup files
#
# Marcelo Miorelli
# 
# 19-novembre-2014 Wed
#-------------------------------------------------------------------------------


#-- set the Path where the backup files (.abf) are located
#
$path = '\\SQLBILON1\H$\SQLBackups' # OR \\SQLBILON1\SQLBackups

#-- set the number of days backups should be deleted -- in this case 2
#
$NumberOfDays = 2

#-- calculate the date of the backup files - if they are older than $days they will be deleted
#
$days = (Get-Date).AddDays(-$NumberOfDays)

#--get the list of the backup files to be deleted and delete them
#
Get-ChildItem $Path -Recurse '*.abf' | ? {$_.CreationTime -lt $days} | Remove-Item
Run Code Online (Sandbox Code Playgroud)