SQL Agent embedded PowerShell script in CmdExec step fails with import-module sqlps SQL Server 2008R2
PowerShell 2.1 

I am trying to create a SQL Agent job that dynamically backs up all non-corrupted SSAS databases on an instance without the use of SSIS. In my SQL Agent job, when I create a CmdExec step and point to a PowerShell script file (.ps1) like this:

powershell.exe "c:\MyPSFile.ps1" 


the job executes successfully (or at least gets far enough to only encounter logic or other syntax issues).

This approach won't work for a final solution, because there is a requirement to keep the PowerShell script internal to SQL. So I have a different CmdExec step that embeds the PowerShell script like so:

powershell.exe "import-module sqlps –DisableNameChecking

$server_name = "localhost"
$backup_location = "C:\BackupsGoHere"

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices") | out-null
$server = New-Object Microsoft.AnalysisServices.Server
$server.connect($server_name)

# Generate an array of databases to be backed up
foreach ($database in ($server.get_Databases() | Where {$_.EstimatedSize -gt 0 -and $_.Cubes.Count -gt 0})) {
    $directory_path = $backup_location + "\" + $database.Name
    if (!(Test-Path -Path $directory_path)) {
        New-Item $directory_path -type directory | out-null
    }
    [string] $timestamp = date
    $timestamp = $timestamp.Replace(':','').Replace('/','-').Replace(' ','-')
    $database.Backup("$directory_path\$database-$timestamp.abf")
}
$server.disconnect()"


However, when executed with the embedded script, the job errors out quickly with the following response:


  The specified module 'sqlps' was not loaded because no valid module
  file was found in any module directory.


Why can't I reference the module from an embedded script, but doing so in a ps1 file works just fine?
Since you are using SQL Server 2008 R2 you can simply create your SQL Agent Job with the step configured as a "PowerShell" type, instead of trying to use the CmdExec. You only need to include the "meat" of your script. Since you are using the PowerShell type of a SQL Agent step it has already called the powershell.exe and imported the SQLPS module for you. So an example:


With your code I believe you can simply configure the step as shown below: