I have a script that fails due to missing SQLASCmdlets module.
The specified module 'SQLASCmdlets' was not loaded because no valid module file was found in any module directory.
In order to run this I know I needed SQLPS which I can found using
Get-Module -ListAvaiable
ModuleType Version Name
---------- ------- ----
Manifest 1.0 SQLPS
I have installed - SQL Sever 2016 - SQL Management Studio 2017
Error:
VERBOSE: ******************************
VERBOSE: The specified module 'SQLASCmdlets' was not loaded because no valid module file was found in any module directory.
VERBOSE: Errors: 1
VERBOSE: ******************************
VERBOSE: System.IO.FileNotFoundException: The specified module 'SQLASCmdlets' was not loaded because no valid module file was found in any module directory.
VERBOSE: ScriptHalted The specified module 'SQLASCmdlets' was not loaded because no valid module file was found in any module directory.
When I rerun my script again it works. How do I make it work on first time?
The code that I used is:
Import-Module "SQLPS" -DisableNameChecking
$sqlsvr = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server("WIN-C0BP65U3D4G")
$restore = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Restore
$devicetype = [Microsoft.SqlServer.Management.Smo.DeviceType]::File
$files = gci C:\psbackups
$BackupFiles = @()
foreach ($file in $files){
$restoredevice = New-Object -TypeName Microsoft.SQLServer.Management.Smo.BackupDeviceItem($file.FullName,$devicetype)
$restore.Devices.add($restoredevice)
$errcnt=0
try{
$restore.ReadMediaHeader($sqlsvr)
}
catch [System.Exception]{
Write-Output "$file is not a sql backup file `n"
$errcnt =1
}
finally {
if ($errcnt -ne 1){
Write-Output "$file is a sql backup file `n"
$BackupFiles += $file
}
$errcnt = 0
}
$restore.Devices.remove($restoredevice)
Remove-Variable restoredevice
}
Based on this article PowerShell to restore database