Invoke-Sqlcmd cmdlet was not available. SQL Server PowerShell components may not be installed - powershell

I am getting the exception as mentioned when I am trying to execute sql queries using PowerShell
[ERROR] Invoke-Sqlcmd cmdlet was not available.
SQL Server PowerShell components may not be installed.
The weird thing I figured out was with this path $env:PSMODULEPATH. I am having the paths set as follows
%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules\;C:\Program Files\WindowsPowerShell\Modules\
Instead of the above if I just move the following path before SQL Server or to the first position it is working fine
C:\Program Files\WindowsPowerShell\Modules\
When I update this is how it looks
%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files\WindowsPowerShell\Modules\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules\
So is there any way to move it to the first place or above to the SQL PS module path

NOw you just need to set the environmental variable to point to that path externally:
Set-Item -Path env:psmodulepath -Value "C:\Program Files\WindowsPowerShell\Modules\;%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\PowerShell\Modules\;"
This should do our job.
Hope it helps.

Related

How do I import the correct version of SQLASCMDLETS in PowerShell?

I'm trying to write a PowerShell script to automate some SQL Server Analysis Services tasks. However there are two copies of SQLASCMDLETS on my system:
PS C:\Windows\system32> get-module -ListAvailable -name 'SQLASCMDLETS' | Format-Table -Property Name, Version, Path
Name Version Path
---- ------- ----
SQLASCMDLETS 1.0 C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\SQLASCMDLETS\SQLASCMDLETS.psd1
SQLASCMDLETS 1.0 C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SQLASCMDLETS\SQLASCMDLETS.psd1
The older version under the \110\ folder contains a bug which incorrectly splits the query into invalid statements and the script fails with an error. I've confirmed that the later version under the \120\ folder works correctly, by changing the extension of the older version and restarting the PS session. However, that is not an ideal solution if this script is to be shared with other users.
Given that both copies have the same name and version number, how can I make sure I use the correct version when I import this module?
Try this:
Import-Module -Name 'C:\Program Files (x86)\Microsoft SQL Server\120\Tools\PowerShell\Modules\SQLASCMDLETS\SQLASCMDLETS.psd1'

"The Azure PowerShell session has not been properly initialized" error message in Octopus

I am trying to run the Get-AzureRmEventHubNamespaceKey cmdlet in an Azure Powershell step within Octopus.
I am getting the following error:
Get-AzureRmEventHubNamespaceKey : The Azure PowerShell session has not been properly
initialized. Please import the module and try again
The module is installed in the following directory on the Octopus server:
C:\Program Files (x86)\Microsoft
SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.EventHub
I have tried importing the module first as part of the same step:
Import-Module –Name "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.EventHub" -Verbose
And I can see in the output that it has been imported:
VERBOSE: Importing cmdlet 'Get-AzureRmEventHubNamespaceKey'.
But it is immediately followed by the above error. If I RDP to the octopus server and run directly from there it runs fine.
Any ideas on what might be causing this?
To use any Azure related commands from your machine, you need to log in first.
Note that there are several Azure modules, and each has a different login cmdlet, but the link above is specific to the module you're using.

'Invoke-Sqlcmd' is not recognized as the name of a cmdlet

We have recently started using SQL Server 2012 SP3 and building the SQL server 2012 using a PowerShell script. There is a requirement in our automation process to run multiple database scripts on a db and I have found Invoke-Sqlcmd very reliable until I found this issue.
When I run Invoke-sqlcmd with a proper set of parameters in PowerShell's debug mode on the system on which the SQL server is installed recently, I don't have problem.
PowershellCommand   : Invoke-Sqlcmd -InputFile $sStrJBSPExecRolePath -ServerInstance $sStrSQLName -ErrorAction Stop
But when I execute same query through a PowerShell automation script after rebuilding the same server, I end up getting below error 
The term 'Invoke-Sqlcmd' 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 did research online many suggested to Import SQLPS, etc., so for testing I added the below command in my script
get-pssnapin -Registered
Import-Module “sqlps” -DisableNameChecking**
Even after adding the above into the script, I still end up with same error. But when I run the same script manually it runs perfectly fine. I don't understand what is wrong.
PowerShell automation script - This script installs the .Net Framework 3.5, SQL Server 2012, SQL Server 2012 SP3, and then loads the SMO assembly that I use to change SQL settings such as the Max Memory limit of SQL.
Open up PowerShell as an Administrator and install the sqlserver module by Install-Module sqlserver
After the module has installed, the module commands including the Invoke-sqlcmd should be readily available.
You can check the same using Get-Command -Module sqlserver.
If this module is not readily available, you can Import-Module sqlserver after installing it.
This is not a complete solution, but just a work around which is working for me.
When you execute the query from automation the user which is executing that is not having access to the sqlcmd. Execute you command for the directory where your sqlcmd.exe is present.
Just put
CD "C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn".
to get the location for sqlcmd search the location for SQLCMD.exe in the search box.
if not found, you need to install that where it is missing, but in your case I think it is present, you just need to get the location right.
Also you will need set the path variable for the user executing the automation script or else it will only recognize the sqlcmd, but wont execute that.
$env:Path += ";C:\Program Files (x86)\Microsoft SQL Server\130\DTS\Binn\"
you can get this path from you local user for which it is working by $Env:Path

Cannot load SharePoint powershell cmdlets in visual studio pre-deployment script

While working on a SharePoint 2010 solution in Visual Studio 2012, I want to run a PowerShell script to remove a lookup field from one of my lists, allowing Visual Studio to automatically resolve the script deployment conflict by deleting the existing list and replacing it with the one in my solution.
However, when running PowerShell from the project's "Pre-deployment Command Line" in Visual Studio, when my script attempts to use get-spweb, PowerShell reports that the object is not found. Scrolling upward in the Visual Studio's output window, I see that Add-PsSnapin Microsoft.SharePoint.PowerShell is reporting various problems:
(Note: actual error message has the expanded $(ProjectDir) value rather than "$(ProjectDir)" as text. Trying various levels of indirection to ensure I'm using the correct, 64-bit version of PowerShell does not change this working directory, nor does using cd or set-location commands prior to calling my script make any difference in this directory. I'm wondering if an invalid working directory is part of the problem...)
The local farm is not accessible. Cmdlets with FeatureDependencyId are not registered.
Could not read the XML Configuration file in the folder CONFIG\PowerShell\Registration\.
Could not find a part of the path '$(ProjectDir)\CONFIG\PowerShell\Registration'.
No xml configuration files loaded.
Unable to register core product cmdlets.
Could not read the Types files in the folder CONFIG\PowerShell\types\.
Could not find a part of the path '$(ProjectDir)\CONFIG\PowerShell\types'.
"No Types files Found."
Could not read the Format file in the folder CONFIG\PowerShell\format\.
Could not find a part of the path '$(ProjectDir)\CONFIG\PowerShell\format'.
No Format files Found.
Running the PowerShell script directly from a Command Prompt window works fine, the SharePoint snapin loads correctly, but running from Visual Studio always fails. Previous research indicated potential problems with SharePoint and SQL Server permissions, yet my account has full admin in both. Visual Studio is running "as administrator". Research also turned up possible problems with 32-bit vs 64-bit. My Pre-deployment Command Line now calls %comspec% /c to ensure 64-bit.
Pre-deployment Command Line:
%comspec% /c ""$(ProjectDir)PowerShell Scripts\predeployment-command.cmd" "$(SharePointSiteUrl)" "$(ConfigurationName)" "$(ProjectDir)""
*.cmd file:
echo off
rem pre-deployment script
rem call from pre-deployment command line like
rem %comspec% /c ""$(ProjectDir)PowerShell Scripts\predeployment-command.cmd "$(SharePointSiteUrl)" "$(ConfigurationName)" "$(ProjectDir)""
rem
echo Running "predeployment-command.cmd" file
echo
echo %%1 = %~1
echo %%2 = %~2
echo %%3 = %~3
echo
cd "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14"
cd
echo on
powershell.exe -file "%~3PowerShell Scripts\predeployment-script.ps1" -targetWeb "%~1" -CONFIG "%~2"
PowerShell script file:
<#
.SYNOPSIS
Pre-deployment script for Visual Studio development deployments
add command to run this script in the project's pre-deployment command-line box
.EXAMPLE
powershell .\dev-predeployment-script.ps1
#>
param(
[string] $targetWeb = $(throw "Please specify the site to which Visual Studio is deploying!"),
[string] $CONFIG = $(throw "Please specify the active configuration!")
)
write-host "Running Pre-Deployment PowerShell Script";
# Ensure SharePoint extensions are loaded
$snapin = $(Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue");
if($snapin -eq $null) {
Add-PsSnapin Microsoft.SharePoint.PowerShell;
}
$ErrorActionPreference = 'Stop';
#echo back parameter values:
write-host "TargetWeb = $targetWeb"
write-host "Configuration = $CONFIG"
#get web-site
$web = get-spweb $targetWeb;
if($web -ne $null) {
$recipients = $web.lists["Recipients"];
if($recipients -ne $null) {
$lookupField = $recipients.Fields["Request ID"];
if($lookupField -ne $null) {
$recipients.fields.remove($lookupField);
}
}
}
I'm developing on a 64-bit Windows Server 2008 r2 virtual machine.
Hi I know this was from a billion years ago, but I just struggled with and solved the same problem, so posting here in case others run into it.
Two problems are happening and fighting with each other:
Problem #01: Spaces in paths: At first glance I see a lot of 'em.
Make your life easier and get rid of these (if/when possible).
Examples:
"$(ProjectDir)PowerShell Scripts"
"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14"
"$(SharePointSiteUrl)" "$(ConfigurationName)" "$(ProjectDir)" <-- This is the problem!!!
maybe others too? you've got multiple levels there that's hard to visualize.
Call chain is (I think?):
LVL1: %comspec% /c
LVL2: predeployment-command.cmd
LVL3: "%~3PowerShell Scripts\predeployment-script.ps1"
which you wish to be: '$(ProjectDir)PowerShell Scripts\predeployment-script.ps1'
but is likely rendering as: 'path with spaces"PowerShell Scripts\predeployment-script.ps1'
Problem #02: Visual Studio Paths always end in backslash "\" (which I hilariously have to escape so that the SO Markdown will display it). BATCH Expansion Escapes the next character. So if you've correctly wrapped quotes around a "path with spaces", but the "path with spaces ends in backslash\", then you end up with "...\" being escaped to %path%" with a trailing or hanging quote " at the end
Visual Studio $(ProjectDir) - with spaces!
if you DO NOT include the quotes, then spaces in path will break it. if you DO include quotes then it gets escaped.
Solution is to include an extra slash at the end, resulting in double backslash \\ which escapes down to single backslash '\'... whew!
Here's my working version if you'd like an example to work off of:
https://stackoverflow.com/a/73409081/738895
Final note:
IF all you need is to ensure (32-bit vs 64-bit), this can be done via the Configuration Manager in Visual Studio
You can google "Visual Studio force build as x86" if you need via msbuild/commandline or follow these instructions
https://learn.microsoft.com/en-us/visualstudio/ide/how-to-configure-projects-to-target-platforms?view=vs-2022

Powershell Copy-item command not working in script although it does work when run from a command line

I am on a Windows 7 machine trying to execute a PowerShell script to copy a template directory to another directory. The command I am executing looks like:
Copy-Item -path "$projectsFolder$SourceFolder" -destination "$Test" -recurse -verbose;
The parameters are as follows:
path: C:\Users\username\Documents\Visual Studio 2010\Projects\TemplateSolution\Source
Destination: C:\Users\username\Documents\Visual Studio 2010\Projects\test\source\main
When I run this command at a PowerShell prompt, the files are copied correctly. If I try and execute the command in the script with verbose enabled, it appears to copy the files and directories, but only the top level directory is created in the file system. I am not sure why this would happen and I would appreciate any guidance or troubleshooting steps to perform.
Make sure you put quotes around the directory names if they have spaces in them. Also, you may need the -Force parameter to create destination directories if they do not exist.