title: SQLASCmdlets was not loaded because no valid module file was found in any module directory
body: <p>I have a script that fails due to missing SQLASCmdlets module.</p>
  
  <blockquote>
    <p>The specified module 'SQLASCmdlets' was not loaded because no valid
    module file was found in any module directory.</p>
  </blockquote>
  
  <p>In order to run this I know I needed SQLPS which I can found using </p>
  
  <blockquote>
    <p>Get-Module -ListAvaiable</p>
  </blockquote>
  
  <pre><code>ModuleType Version    Name
  ---------- -------    ---- 
  Manifest   1.0        SQLPS 
  </code></pre>
  
  <p>I have installed 
   - SQL Sever 2016
   - SQL Management Studio 2017</p>
  
  <p>Error:</p>
  
  <pre><code>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.
  </code></pre>
  
  <p>When I rerun my script again it works. How do I make it work on first time?</p>
  
  <p>The code that I used is:</p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p>Based on this article
  <a href="https://stuart-moore.com/day-13-of-31-days-of-sql-server-backup-and-restore-using-powershell-reading-the-contents-of-a-backup-file/" rel="nofollow noreferrer">PowerShell to restore database</a></p>