Not able to log the sql server installation progress when running with powershell - powershell

I am installing SQL Server 2008R2 with Powershell.
Below is the command
function install{
$Command ="SQL_SERVER_CDs\SQL2008_R2\R2_ENTERPRISE\Setup.exe /q /ACTION=Install /IACCEPTSQLSERVERLICENSETERMS /INDICATEPROGRESS /FEATURES=SQLENGINE,REPLICATION,FULLTEXT /INSTANCENAME=DEMO5 /SECURITYMODE=SQL /SAPWD=Me#inv2011 /SQLSYSADMINACCOUNTS=CORP\R-PITTUR CORP\AIMFUNDS-G-Admin-SQL /SQLSVCACCOUNT=RAMU-PC\RAMU /SQLSVCPASSWORD=***** /AGTSVCACCOUNT=RAMU-PC\RAMU /AGTSVCPASSWORD=***** /ISSVCACCOUNT=RAMU-PC\RAMU /ISSVCPASSWORD=***** /INSTANCEDIR=S:\\ /INSTALLSHAREDDIR=C:\Program Files\Microsoft SQL Server /SQLUSERDBDIR=I:\DB_DATA /SQLUSERDBLOGDIR=H:\DB_LOGS /SQLTEMPDBDIR=T:\DEMO5 /SQLBACKUPDIR=S:\DEMO5 /SQLCOLLATION=SQL_Latin1_General_CP1_CI_AS"
Invoke-Expression $Command
}
When i call this install function, SQL installation is happenening but nothing is displayed in the Powershell console though i put Indicateprogress in the above installation string. How can we display logging of sql server installation. Is it possible to redirect the output to any control like Richtextbox using Powershell.

Some of your command options contain spaces, for eg:
/INSTALLSHAREDDIR=C:\Program Files\Microsoft SQL Server
wrap them in quotes like this:
`"/INSTALLSHAREDDIR=C:\Program Files\Microsoft SQL Server`"
note the use of the backtick character (`) to escape the quote within the string.

/q means quite install, right?
Here's the command I use to run SQL 2008 R2 installs:
$command += 'setup.exe /CONFIGURATIONFILE=`"$configFile`" /SAPWD=`"$sysadminPassword`" /SQLSVCPASSWORD=`"$servicePassword`" /AGTSVCPASSWORD=`"$servicePassword`" /FTSVCPASSWORD=`"$servicePassword`" /ISSVCPASSWORD=`"$servicePassword`"'
Invoke-Expression $command

Related

'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

Running CMD command in PowerShell

I am having a bunch of issues with getting a PowerShell command to run. All it is doing is running a command that would be run in a CMD prompt window.
Here is the command:
"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
I have tried the following with no success (I have tried many iterations of this to try and get one that works. Syntax is probably all screwed up):
$TEXT = $textbox.Text #$textbox is where the user enters the PC name.
$CMDCOMMAND = "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"
Start-Process '"$CMDCOMMAND" $TEXT'
#iex -Command ('"C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe"' $TEXT)
The command will just open SCCM remote connection window to the computer the user specifies in the text box.
Try this:
& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.
It is a much safer way than running batch files!
One solution would be to pipe your command from PowerShell to CMD. Running the following command will pipe the notepad.exe command over to CMD, which will then open the Notepad application.
PS C:\> "notepad.exe" | cmd
Once the command has run in CMD, you will be returned to a PowerShell prompt, and can continue running your PowerShell script.
Edits
CMD's Startup Message is Shown
As mklement0 points out, this method shows CMD's startup message. If you were to copy the output using the method above into another terminal, the startup message will be copied along with it.
For those who may need this info:
I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.
Sometimes you may have to pre-launch this command with cmd.exe /c
Examples
Calling git from a PS script
I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a package manager for Windows) which massively uses PS scripts.
I found out that, once git is in the PATH, commands like
$ca_bundle = git config --get http.sslCAInfo
will store the location of git crt file in $ca_bundle variable.
Looking for an App
Another example that is a combination of the present SO post and this SO post is the use of where command
$java_exe = cmd.exe /c where java
will store the location of java.exe file in $java_exe variable.
You must use the Invoke-Command cmdlet to launch this external program. Normally it works without an effort.
If you need more than one command you should use the Invoke-Expression cmdlet with the -scriptblock option.

CSPack and CSRun for running site in azure emulator from powershell

I have spend some time trying to get the cspack and csrun command working to run a website locally in the azure emulator.
So far this is what I get, but its not working
I use psake
Task StartAzureEmulator {
& 'C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\v2.2\bin\cspack' sitename.azure\ServiceDefinition.csdef /out:Sitename.csx /role:sitename;sitename /sites:Vola;Web;Web /copyOnly
& 'C:\Program Files\Microsoft SDKs\Windows Azure\Emulator\csrun' sitename.csx sitename.Azure\ServiceConfiguration.Local.cscfg /useiisexpress /launchbrowser
}
Basically I am not very impressed with how the azure commandline tools works with powershell.
Has anyone got example of this working?
In PowerShell the ; character is a statement separator. You can escape it by preceding it with a backtick or if you are V3 or higher you can user --% to switch PowerShell into a simpler (dumber) parser mode. Try this:
Task StartAzureEmulator {
& 'C:\Program Files\Microsoft SDKs\Windows Azure\.NET SDK\v2.2\bin\cspack' --% sitename.azure\ServiceDefinition.csdef /out:Sitename.csx /role:sitename;sitename /sites:Vola;Web;Web /copyOnly
& 'C:\Program Files\Microsoft SDKs\Windows Azure\Emulator\csrun' --% sitename.csx sitename.Azure\ServiceConfiguration.Local.cscfg /useiisexpress /launchbrowser
}

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

How to call SQLPS from TSql in SQL Server 2008

I see lots of examples on running SQLPS from SQL Server Agent, but how do you call a powershell script from TSQL on demand?
I'm replacing a C# CLR function with a PowerShell script. The script will simply get a path and date modified for files in a directory structure.
What's the command to call a PowerShell script from a T-SQL stored procedure?
Something like this:
set #sql = 'powershell.exe -file "YourScript.ps1" -nologo'
EXEC xp_cmdshell #sql