Hi I am rewriting a powershell script to refresh the non production env from production env. its working fine while executing from powershell prompt. But when I executed same script from Sql server Agent job. Job is successfully complete . But DB restore has not done it. Very strange . I am not sure why "Restore-SqlDatabase" has not been recognised. any one has any idea
script:
script:
Invoke-Sqlcmd -ServerInstance $TargetSqlServerInstance -Query "ALTER DATABASE $TargetDb MODIFY FILE (NAME='$SourceLogicalLogFileName', NEWNAME='$TargetLogicalLogFileName')"
begin script configuration here
$TargetSqlServerInstance = "SQLDEST1" # target server instance
$TargetDb = "CRMDBTST" # target database
$BackupDir = "\sqlbackups\" # directory / share where backups are stored
$SourceLogicalDataFileName = "CRMPRD" # logical data file name of source db
$SourceLogicalLogFileName = "CRMPRD_log" # logical log file name of source db
$TargetLogicalDataFileName = "CRMDBTST" # logical name you want to change logical data file on target db to
$TargetLogicalLogFileName = "CRMDBTST_log" # logical name you want to change logical log file on target db to
$TargetPhysicalDataFileName = "U:\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\CRMDBTST.mdf" # full path\file of target db physical data file
$TargetPhysicalLogFileName = "L:\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\CRMDBTST_log.ldf" # full path\file of target db physical log file
$CompatLevel = 130 # compatibility level to set target database to (2019=150, 2017=140, 2016=130, #
import sqlserver module
Import-Module sqlserver
$SQLSERVER="SQLDEST1"
$databaseName="CRMDBTST"
latest full backup file name is dynamically determined and appended to backup directory
$LatestFullBackupFile = Get-ChildItem -Path $BackupDir -Filter *.bak | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$FileToRestore = $BackupDir + '\' + $LatestFullBackupFile
kill any connections in target database
$KillConnectionsSql=
"
USE master
GO
ALTER DATABASE $TargetDb SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE master
GO
ALTER DATABASE $TargetDb SET MULTI_USER
GO
GO
"
Invoke-Sqlcmd -ServerInstance $TargetSqlServerInstance -Query $KillConnectionsSql
import sqlserver module
Import-Module sqlserver
restore
$RelocateData = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("$SourceLogicalDataFileName", "$TargetPhysicalDataFileName")
$RelocateLog = New-Object Microsoft.SqlServer.Management.Smo.RelocateFile("$SourceLogicalLogFileName", "$TargetPhysicalLogFileName")
Restore-SqlDatabase -ServerInstance $TargetSqlServerInstance -Database $TargetDb -BackupFile $FileToRestore -RelocateFile @($RelocateData,$RelocateLog) -ReplaceDatabase
end restore
+++++++++++++++++++++++++++++

