Backup-SqlDatabase is not recognized - powershell

I have a PowerShell script to backup a database. But today it has stoped working with next error:
Backup-SqlDatabase : The term 'Backup-SqlDatabase' is not recognized as
the name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and
try again.
I didn't change the script. What could be the reason for that?
UPDATE:
Installed SqlServer module. Now I have next:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Temp> import-module sqlserver -erroraction stop -verbose
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\sqlserver\21.0.17224\sqlserver.psd1'.
VERBOSE: Loading 'TypesToProcess' from path 'C:\Program
Files\WindowsPowerShell\Modules\sqlserver\21.0.17224\sqlprovider.types.ps1xml'.
VERBOSE: Loading 'FormatsToProcess' from path 'C:\Program
Files\WindowsPowerShell\Modules\sqlserver\21.0.17224\sqlprovider.format.ps1xml'.
VERBOSE: Populating RepositorySourceLocation property for module sqlserver.
VERBOSE: Loading module from path 'C:\Program Files\WindowsPowerShell\Modules\sqlserver\21.0.17224\SqlServer.psm1'.
VERBOSE: Exporting function 'SQLSERVER:'.
VERBOSE: Exporting alias 'Encode-SqlName'.
VERBOSE: Exporting alias 'Decode-SqlName'.
VERBOSE: Importing function 'SQLSERVER:'.
VERBOSE: Importing alias 'Decode-SqlName'.
VERBOSE: Importing alias 'Encode-SqlName'.
PS C:\Temp> Get-Command -Name Backup-SqlDatabase
Get-Command : The term 'Backup-SqlDatabase' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ Get-Command -Name Backup-SqlDatabase
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Backup-SqlDatabase:String) [Get-Command], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException,Microsoft.PowerShell.Commands.GetCommandCommand
UPDATE 2: Uninstalled SqlServer module, directory were removed. After that reinstalled it. Installation log:
PS C:\WINDOWS\system32> Install-Module -Name SqlServer -Repository PSGallery -Verbose
VERBOSE: Repository details, Name = 'PSGallery', Location = 'https://www.powershellgallery.com/api/v2/'; IsTrusted
= 'False'; IsRegistered = 'True'.
VERBOSE: Using the provider 'PowerShellGet' for searching packages.
VERBOSE: Using the specified source names : 'PSGallery'.
VERBOSE: Getting the provider object for the PackageManagement Provider 'NuGet'.
VERBOSE: The specified Location is 'https://www.powershellgallery.com/api/v2/' and PackageManagementProvider is
'NuGet'.
VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='SqlServer'' for ''.
VERBOSE: Total package yield:'1' for the specified package 'SqlServer'.
VERBOSE: Performing the operation "Install-Module" on target "Version '21.0.17224' of module 'SqlServer'".
Untrusted repository
You are installing the modules from an untrusted repository. If you trust this repository, change its
InstallationPolicy value by running the Set-PSRepository cmdlet. Are you sure you want to install the modules from
'PSGallery'?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y
VERBOSE: The installation scope is specified to be 'AllUsers'.
VERBOSE: The specified module will be installed in 'C:\Program Files\WindowsPowerShell\Modules'.
VERBOSE: The specified Location is 'NuGet' and PackageManagementProvider is 'NuGet'.
VERBOSE: Downloading module 'SqlServer' with version '21.0.17224' from the repository
'https://www.powershellgallery.com/api/v2/'.
VERBOSE: Searching repository 'https://www.powershellgallery.com/api/v2/FindPackagesById()?id='SqlServer'' for ''.
VERBOSE: InstallPackage' - name='SqlServer',
version='21.0.17224',destination='C:\Users\Oleg\AppData\Local\Temp\1981035148'
VERBOSE: DownloadPackage' - name='SqlServer',
version='21.0.17224',destination='C:\Users\Oleg\AppData\Local\Temp\1981035148\SqlServer\SqlServer.nupkg',
uri='https://www.powershellgallery.com/api/v2/package/SqlServer/21.0.17224'
VERBOSE: Downloading 'https://www.powershellgallery.com/api/v2/package/SqlServer/21.0.17224'.
VERBOSE: Completed downloading 'https://www.powershellgallery.com/api/v2/package/SqlServer/21.0.17224'.
VERBOSE: Completed downloading 'SqlServer'.
VERBOSE: Hash for package 'SqlServer' does not match hash provided from the server.
VERBOSE: InstallPackageLocal' - name='SqlServer',
version='21.0.17224',destination='C:\Users\Oleg\AppData\Local\Temp\1981035148'
VERBOSE: Catalog file 'SqlServer.cat' is not found in the contents of the module 'SqlServer' being installed.
VERBOSE: Valid authenticode signature found in the file 'SqlServer.psd1' for the module 'SqlServer'.
VERBOSE: Module 'SqlServer' was installed successfully to path 'C:\Program
Files\WindowsPowerShell\Modules\SqlServer\21.0.17224'.
Even after that Import-Module SqlServer -ErrorAction Stop -Verbose hasn't changed and Backup-SqlDatabase is still is not available. What could be the reason?

That function is provided by the sqlps (old & busted) and sqlserver (current) modules. sqlps and older versions of sqlserver were provided by the SQL Server Management Studio installation, but sqlserver is now in the PowerShell Gallery. Assuming you have a current version of PowerShell/Windows Management Framework, you can install-module sqlserver (run in an Administrator PowerShell session) and get the latest version installed globally.
As to what happened to your script:
Possibility #1: You're using a very old version of PowerShell which doesn't auto-load modules and you're not explicitly importing the sqlserver or sqlps module into the session/script where you're calling this function. Solution: upgrade to a current release of PowerShell which does support auto-loading modules and/or explicitly import the proper module into your script/session with import-module.
Possibility #2: Someone uninstalled or moved the module that you're getting that function from, or it's not in your module search path. Solution: Check $PSModulePath and then look in each location for the module. Easiest would be to reinstall it in a global scope.

You need to import the SQL Server PowerShell module to be able to access the cmdlets it contains:
Import-Module SQLPS -ErrorAction Stop
Run this code to see if the function is available to you or not:
Get-Command -Name Backup-SqlDatabase
Here are the results from my machine:
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Backup-SqlDatabase 14.0 SQLPS

I too have the same issue but with Delete-SqlDatabase from SQLPS.
In my case I was trying to call a function Delete-SqlDatabase which I declared and consuming in my code.
The mistake I did is to call the function which was down below.
You see in Powershell in order for a function to be visible, you have to declare it on top. The main function should be the last section hierarchy wise.
Its such a silly thing. I am sure you figured this out within a day.
I am 100% certain this is your issue. I know this thread is too old but it might help other's like me who can potentially save an hours time.

Related

Why can't I install PSReadLine

I am trying to install the PSReadLine module:
PS> Find-Module PSReadLine | Install-Module -scope currentUser -force
This command runs and terminates without any message or any indication that something was unsuccessful.
However, when I want to load the module, I get an error message:
PS> import-module PSReadLine
import-module : The specified module 'PSReadLine' was not loaded
because no valid module file was found in any module directory.
So, I am wondering how I can install and/or load this module.
Feedback on comments
As per #Lee_Dailey's comment, I do indeed have a path with a lowercase l:
PS> ls 'C:\Program Files\WindowsPowerShell\Modules\psread*' -name
PSReadline
Unfortunately, I cannot change that lowercase l to a L because I have this issue on a machine without admin privileges.
As per #Scepticalist comment, I should find the module in one of the module paths' locations. It turns out: I don't. The following command returns/prints nothing:
foreach ($mp in $Env:PSModulePath -split ';') { ls "$mp\psread*" }
Thus, also the command suggested by #pwnosh returns nothing:
($env:PSModulePath -split ';' | Get-ChildItem -Filter 'PSReadLine' | Get-ChildItem).FullName
Find-Module PSReadLine returns (echoes)
Version Name Repository Description
------- ---- ---------- -----------
2.1.0 PSReadLine PSGallery Great command line editing in the PowerShell console host
Running Register-PSRepository -Default results in an error message:
PackageManagement\Register-PackageSource : Module Repository 'PSGallery' exists.
Set-PSRepository 'PSGallery' -InstallationPolicy Trusted runs and terminates without any message echoed to the console. Yet, after running this command, I am still unable to import the module.

Updating SSL bindings for IIS with Powershell 7

I'm trying to update a PS5 script to PS7, mainly because the script does work that requires a PS Core module.
Part of the script involved updating IIS bindings to use a different SSL Certificate. The cert is in the store and ready to be used - I just need to change the thumbprint on the binding.
My PS5 script used Get-WebConfiguration to get the bindings and then just looped through, calling RebindSslCertificate on relevant bindings.
I've tried using Set-WebConfigurationProperty and Set-WebBinding; neither errors but neither actually updates the binding with IIS - example:
Set-WebConfigurationProperty -Name 'certificateHash' -Value $newCert.Thumbprint -PSPath "IIS:\\" `
-Filter "/system.applicationHost/sites/site/bindings/binding[#protocol='https'][#bindingInformation='*:443:hostname']" `
Could anyone help point me in the right direction for what I'm missing?
Thanks,
Mark.
P.S., Apologies if this is a repeat question but all I can find is old stuff that doesn't work or relates to "-Set-Item IIS:\SslBindings" Maybe there is someway to get the IIS drive working with remoting?
Ran into this on 9/10/2021 using Powershell 7.1.4.
As of date of writing, this is an open issue on github for PowerShell.
Link for reference: https://github.com/PowerShell/PowerShellModuleCoverage/issues/14
Issue is that PowerShell 7 is based on .NET Core and the PS module WebAdministrator is based on .NET Framework.
When you run
Import-Module WebAdministration
WARNING: Module WebAdministration is loaded in Windows PowerShell using WinPSCompatSession remoting session; please note that all input and output of commands from this module will be deserialized objects. If you want to load this module into PowerShell please use 'Import-Module -SkipEditionCheck' syntax.
Notice the mention of 'WinPSCompatSession' in the warning. If the module manifest doesn't indicate that the module is compatible with PowerShell Core, then it gets loaded via the Windows PowerShell Compatibility Feature.
It seems this module partially works in compatibility mode, however if you try to work with IIS:\ then you start getting errors.
Alternatively, if you run the parameter in the warning you get this.
Import-Module -SkipEditionCheck WebAdministration
Import-Module: Could not load type 'System.Management.Automation.PSSnapIn' from assembly 'System.Management.Automation, Version=7.1.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
A quick test in PowerShell 7.1.4 will show you that you can't access the IIS connector.
PS C:\Windows\System32> Import-Module WebAdministration
WARNING: Module WebAdministration is loaded in Windows PowerShell using WinPSCompatSession remoting session; please note that all input and output of commands from this module will be deserialized objects. If you want to load this module into PowerShell please use 'Import-Module -SkipEditionCheck' syntax.
PS C:\Windows\System32> cd IIS:\
Set-Location: Cannot find drive. A drive with the name 'IIS' does not exist.
However, if you open up PowerShell 6 you can do this no problem.
PS C:\WINDOWS\system32> Import-Module WebAdministration
PS C:\WINDOWS\system32> cd IIS:\
PS IIS:\> dir
Name
----
AppPools
Sites
SslBindings
My next step is trying to get this to work by loading the .NET assembly directly. Will update with the solution
[System.Reflection.Assembly]::LoadFrom("$env:systemroot\system32\inetsrv\Microsoft.Web.Administration.dll")

Powershell cmdlet is not recognized despite having the correct module installed

I am trying to run a powerhsell script (my_script). The script is stored in this_folder on the desktop. I am executing the command at the the correct path by using C:\Users\me\desktop\this_folder> .\my_script. When I try to do this I get the error
The term 'Add-AzureRmAccount' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again
I know that the Add-AzureRmAccount is a part of the AzureRM.Profile module. When I got to the modules folder, I see that AzureRM.Profile is listed. To get these modules, I ran Install-Module -name AzureRM and Import-module AzureRM.
Any ideas what might be going on?
---Update---
When I ran Get-Module commands I saw that only that AzureRM module was listed. I thne tried to run Install-Module -Name AzureRM.Profile and got the error:
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:1772 char:21
+ ... $null = PackageManagement\Install-Package #PSBoundParameters
Since I see the AzureRM.Profile folder with a nupkg at one of the paths listed by $env:PSModulePath I thought I could just run Import-Module -Name AzureRM.Profile and I get the error
import-module : The specified module 'AzureRM.Profile' was not
loaded because no valid module file was found in any module directory.
Any ideas?
You say that you've installed and imported the AzureRM module, but have you connected the Azure account with the Connect-AzureRmAccount cmdlet?
I know a number of other modules does not expose all of the available cmdlets until there is an active connection to an account/subscription.
Be aware that scripts can ignore the context in which they are run so you might need to add the following to the start of the script:
Import-Module AzureRM
Connect-AzureRmAccount
Rather than running them manually in the console and then running the script.
You might want also want to look at using the Az module instead as the AzureRM module is being retired, and will only get bug-fixes till the end of December 2020: Introducing the new Azure PowerShell Az module

Desktop App to UWP using Desktop App Converter

I have desktop application and want to convert it to an uwp application.
I use desktop app converter with powershell.
I am trying to convert my startup projects exe, but everytime i try execution stops at
Running Installer in Isolated Environment
VERBOSE: No installer valid exit codes specified. Using defaults: 0
VERBOSE: Replace any occurence of in -InstallerArguments
with C:\installer\logs VERBOSE: Running installer command in isolated
environment: VERBOSE: Command Line =
"C:\installer\X.Framework.Main.exe" /passive
part. Is the exe i try to convert is wrong or -InstallerArgument i write? What should i change to end the conversion succesfully?
My PowerShell command:
PS C:\Users\EccE\Desktop\convert> .\DesktopAppConverter.ps1 -Installer
C:\Users\EccE\Desktop\X\X-wpf-framework\bin\Debug\X.Framework.Main.exe
-InstallerArguments "/passive" -Destination C:\Users\EccE\Desktop\X\X-out\ -PackageName "XApp"
-Publisher "CN=X" -Version 0.0.0.1 -MakeAppx -Verbose
Edit:
When i tried to convert project solution i got the following error:
Running Installer in Isolated Environment
VERBOSE: No installer valid exit codes specified. Using defaults: 0
VERBOSE: Replace any occurence of in -InstallerArguments
with C:\installer\logs VERBOSE: Running installer command in isolated
environment: VERBOSE: Command Line =
"C:\installer\X.Framework.sln" /passive VERBOSE: Moving any logs
in
C:\DesktopAppConverter\e931cac0-58a1-46dc-9efd-f5f442a0d814\shared\logs
to C:\DesktopAppConverter\e931cac0-58a1-46dc-9efd-f5f442a0d814\logs
VERBOSE: Cleaning up by removing isolated environment shared folder
'C:\DesktopAppConverter\e931cac0-58a1-46dc-9efd-f5f442a0d814\shared'
VERBOSE: An error occurred. Refer to logs in
C:\DesktopAppConverter\e931cac0-58a1-46dc-9efd-f5f442a0d814\logs
Exception calling "RunIsolatedProcessWithMappedDirectoryAndExport"
with "6" argument(s): " geçerli bir Win32 uygulaması değil. (HRESULT
özel durum döndürdü: 0x800700C1)" At
C:\Users\EccE\Desktop\convert\converter_util\Sequencer.ps1:141 char:9
+ $installerExitCode = [Microsoft.Centennial.Tools.DesktopAppCo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : BadImageFormatException
VERBOSE: No installer valid exit codes specified
This is due to we need to package our executable program as a installer first, this converter can run your desktop installers through the converter in an unattended (silent) mode and obtain an AppX package that you can install by using the Add-AppxPackage PowerShell cmdlet on your development machine.
See the first paragraph in this document: Desktop App Converter Preview (Project Centennial)
See also the points of Preparing your desktop app for conversion to UWP
Your app installation requires user interaction. Your app installer must be able to run silently, and it must install all of its prerequisites that aren't on by default on a clean OS image.
You can create a MSI package and use converter to generate Appx as you want.

Cannot import user-defined module

I have some PowerShell functions and I want to import them into my server 2008 R2 via command Import-Module. So I created a psd1 file and in psm1 I use: Export-ModuleMember -Function "*-*" -Alias *.
However when I execute command:
PS C:\Windows\system32> import-module Myloader -DisableNameChecking -Verbose
VERBOSE: Loading module from path 'C:\Tools\Myloader.psd1'.
VERBOSE: Loading module from path 'C:\Tools\Myloader.psm1'.
I expect it should import my functions but it does not and there is no errors shown up. Then I execute Get-Module -ListAvailable, my function is listed out but there is no information about ExportedCommands
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 3.0 MyLoader
Script 3.0 MyLoader
But when I run it on my local machine it is OK. Have anyone faced with this issue before?
This issue happens on Windows Server 2008 R2, PowerShell 5.0.
When using a module manifest you do the exports inside the .psd1 file. Remove the Export-ModuleMember statement from your .psm1 file and make sure the .psd1 file contains the following lines:
ModuleToProcess = 'MyLoader.psm1'
FunctionsToExport = '*-*'
AliasesToExport = '*'