I have a Powershell script to backup MSSQL on a Windows Server 2008 R2 box. It backs up a specific DB to a local disk, then moves the backup to a Network mounted CIFS volume. It works 100% fine when run locally no matter how I invoke it. I installed Freesshd (latest) to be able to start the script using a scheduler (not windows task scheduler ). I am constantly getting cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help abo
ut_signing"
I connect via SSH, invoke powershell, then run .\scriptname. Running get-executionpolicy
returns remoteSigned
. I am logged in as the local Administrator account via password authentication.
#################
# Backup MSI #
# A POwershell #
# Script. #
#################
#load SQL snap-in
Add-PSSnapin *SQL*
#pull the current date
$date = Get-Date -Format yyyyddMM
#set location of backup files and create it if not present
$DIRECTORY = "D:\Temp\"
if (-Not (Test-Path $DIRECTORY) ) { md $directory }
#Grab the database names into an array
$dbname = dir 'SQLSERVER:\SQL\MYHOST\MYDBMSSQL\Databases' | Select Name
#Backup each database found which matches the regex "stats".
$dbname | foreach { $_.Name.ToString() }|where { $_ -match "stats" } | foreach {$bakfile = "$DIRECTORY" + $_ + "_" + $date + ".bak";
"Backing up Database: $_"; Invoke-Sqlcmd -QueryTimeout 10000 -SuppressProviderContextWarning -Query "BACKUP DATABASE $_ TO DISK=N'$bakfile' WITH INIT";}
# Move Backup from local disk to CIFS mount
Copy-Item $DIRECTORY\*.bak \\e-nfs-01.mycompany.net\backup-bi-em\Backups
Remove-Item $DIRECTORY\*.bak
cd \\e-nfs-01.mycompany.net\backup-bi-em\Backups
#Get array of existing Backups
$backups=@( ls \\e-nfs-01.mycompany.net\backup-bi-em\backups\*.bak|sort-object -property CreationTime -descending|foreach { $_.Name } )
#Delete Anything Beyond 3 Newest Backups
if ($backups.Length -gt 3 ) {
foreach ($_ in $backups[3..$backups.Length]) { Remove-Item $_ }
}