Install arguments breaking an automated PowerShell install - powershell

I'm installing SQL Data Tools via a PowerShell script. I run my script, but the final part where the Data Tools are installed fails (inside of the SQL installer window). If I run the script without that part, and install Data Tools manually it works.
The error is:
VS Shell installation has failed with exit code -2147205120.
The parts before this install .NET and SQL Server Management Studio. I don't think they're relevant to my issue, but I will post that part if requested. Here are the relevant parts. The first try block installs SQL SP1 (removed now for readability), the second installs Data Tools and SNAC_SDK.
try
{
Write-Host "Lauching SQL Server Data Tools install ..."
& "\\mynetworkpath\SSDTBI_x86_ENU.exe" "/ACTION=INSTALL" "/FEATURES=SSDTBI,SNAC_SDK" "/Q" "/IACCEPTSQLSERVERLICENSETERMS"
Write-Host "Installer launched ..."
}
catch
{
Write-Host "SQL Server Data Tools installation failed"
exit
}
I have tried juggling around the arguments for the Data Tools install part, and playing with the -wait verb to make sure SP1 is done for sure, but no luck.
EDIT: Per Matt's suggestion I added /NORESTART to my argument list, but now it doesn't install anything, and doesn't error either...
EDIT: Added updated code with quoted arguments. Still doesn't work, but I think it's closer than it was originally.

I think the comma in the arguments is the culprit here because powershell interprets entities separated by comma as an array.
You can see how parameters get passed with this little hack
& { $args } /ACTION=INSTALL /FEATURES=SSDTBI,SNAC_SDK /Q /IACCEPTSQLSERVERLICENSETERMS
which gives
/ACTION=INSTALL
/FEATURES=SSDTBI
SNAC_SDK
/Q
/IACCEPTSQLSERVERLICENSETERMS
To get rid of this problem you need to quote at least the FEATURES argument. I usually quote everything in those cases, just to be consistent, so
& { $args } "/ACTION=INSTALL" "/FEATURES=SSDTBI,SNAC_SDK" "/Q" "/IACCEPTSQLSERVERLICENSETERMS"
gives you the wanted parameters:
/ACTION=INSTALL
/FEATURES=SSDTBI,SNAC_SDK
/Q
/IACCEPTSQLSERVERLICENSETERMS
Update: Many installers return immediately after they have been called while the install process still runs in the background, which can be a bugger when the rest of the script depends on the install.
There are several methods to make powershell wait for a process exit. One of the shortest is to use Out-Null like this:
& "\\mynetworkpath\SSDTBI_x86_ENU.exe" "/ACTION=INSTALL" "/FEATURES=SSDTBI,SNAC_SDK" "/Q" "/IACCEPTSQLSERVERLICENSETERMS" | Out-Null
You may also want to look at $? or $LASTEXITCODE afterwards to check for errors.

Related

PS1 uninstallation script in SCCM

I'm a nub scripter and am trying to write a really simple script to taskkill 2 programs and then uninstall 1 of them.
I wrote it in Powershell and stuck it in SCCM for deployment...however every time I deploy it, it's not running the last line to uninstall the program.
Here's the code:
# Closing Outlook instance
#
taskkill /IM outlook.exe /F
#
# Closing Linkpoint instance
#
taskkill /IM LinkPointAssist.exe /F
#
# Uninstalling Linkpoint via uninstall string if in Program Files
#
MsiExec.exe /X {DECDCD14-DEF6-49ED-9440-CC5E562FDC41} /qn
#
# Uninstalling Linkpoint via WmiObject if installed manually in AppData
Get-WmiObject -class win32_product -Filter "Name like '%Linkpoint%'" | ForEach-Object { $_.Uninstall()}
#
Exit
Can someone help? SCCM says the script completes with no error and I know it's able to execute it since the taskkills work...but it's not uninstalling the program.
Thanks in advance for any input.
So, SCCM is running this script, and nothing in the script is going to throw an error.
If you want to throw an error which SCCM can return to know how the deployment went, you need to add an extra step.
$result = Get-WmiObject -class win32_product -Filter "Name like '%Linkpoint%'" | ForEach-Object { $_.Uninstall()}
if ($result.ReturnValue -ne 0){
[System.Environment]::Exit(1603)
}else
{
[System.Environment]::Exit(0)
}
I see a lot of these kinds of questions come through on SO and SF: Someone struggling with unexpected behavior of an application, script, or ConfigMgr and very little information about the assumptions I can make about their environment. At that stage, it would typically be days of interaction to narrow the problem to a point where a solution is possible.
I'm hoping this answer can serve as a reference for future such questions. The first question to OP should be "Which of these 9 principles are you violating?" You could think of it as a sort of Joel Test for ConfigMgr application packaging.
Nine Steps to Better ConfigMgr Application Packages
I have found that installing and uninstalling applications reliably using ConfigMgr requires carefully sticking to a bunch of principles. I learned these principles the hard way. If you're struggling to figure out why an application is not working right under ConfigMgr, odds are that you will answer "no" to one of the following questions.
1. Are you testing the entire lifecycle?
In order to have any hope of reliably managing an application you need to test the entire lifecycle of an application. This is the sequence I test:
Detect: make sure the detection script result is negative
Install: install the application using your installation script
Detect: make sure the detection script result is positive when run
Uninstall: uninstall using your uninstallation script
I run this sequence repeatedly making tweaks to each step until the whole sequence is working.
2. Are you testing independently of ConfigMgr first?
Using ConfigMgr to test your application's lifecycle is slow and has its own ways of failing that can mask problems with your application package. The goal, then, is to be able to test an application's installation, detection, and uninstallation separate from but equivalent to the ConfigMgr client. In order to achieve that goal you end up with three separate scripts for each application:
Install-Application.bat - the entry point for your installation script
Detect-Application.ps1 - the script that detects whether the application is install
Uninstall-Application.bat - the entry point for your uninstallation script
Each of these three scripts can be invoked directly by either you or the ConfigMgr client. For applications installed as system you need to use psexec -s to invoke scripts in the same context as ConfigMgr (caveat).
3. Are you aware of context?
Installers can behave rather differently depending on the context they are invoked in. You need to consider whether an application is installed for a user or the system. If it is installed for the system, when you test independently of ConfigMgr, use psexec -s to invoke your script.
4. Are you aware of user interaction?
An installer can also behave rather differently depending on whether a user can interact with it. To test a script as system with user interaction, use psexec -i -s.
5. Did you match ConfigMgr to the tested context and user interaction?
Once you have the full lifecycle working, make sure you select the correct corresponding options for context (installed for user vs. system) and interaction (user can interact with application, or not). If you don't do this, the ConfigMgr client will be installing the application different from the way you tested, so you really can't expect success.
6. Are you aware of the possibility of application detection context mismatch?
The context that detection scripts run in depends on whether the application is deployed to users or systems. This means that in some cases the installation and detection contexts won't matched. Keep this in mind when you write your detection scripts.
7. Have you structured your scripts so that exit codes work?
ConfigMgr needs to see exit codes from your installation and uninstallation scripts in order to do the right thing. Installers signal failure or the need to reboot using exit codes. In order for exit codes to get to the ConfigMgr client you need to ensure that your install and uninstall scripts are structured correctly.
for batch scripts, use exit /b %errorlevel% to pass the exit code of your executable out to the ConfigMgr client
for PowerShell scripts, this is the only way I have seen work reliably
8. Are you using PowerShell scripts for detection?
ConfigMgr has a nice user interface for checking things like the presence of files, registry keys, etc as a proxy for whether an application is installed. The problem with that scheme is that there is no way to test application detection separately from and equivalent to the ConfigMgr client. If you want to test the application lifecycle independent of the ConfigMgr client (trust me, you want that), all your detection must occur using PowerShell scripts.
9. Have you structured your PowerShell detection scripts correctly?
The rules ConfigMgr uses to interpret the output of a PowerShell detection script are arcane. Thankfully, they are documented.

powershell $LastExitCode -1073741502 when calling osql or sqlcmd

I've written a powershell script to call sqlcmd.exe to execute a sql script against a remote sql server. The powershell script checks $LASTEXITCODE. If $LASTEXITCODE is non zero, I throw "Script failed. Return code is $LASTEXITCODE."
The script is used multiple times to execute different sql scripts and is part of a chain of powershell scripts that run during deployment.
The script runs fine most of the time but randomly fails with a return code of -1073741502.
This has only started happening after upgrading to SQL2008 and I cannot reproduce it by running either the single powershell script manually or the sql cmd script manually.
This is the powershell command:
& 'sqlcmd.exe' -S $databaseServer -r -b -E -i '$scriptFullPath'
if($LASTEXITCODE -ne 0)
{
throw "Script failed. Return code is $LASTEXITCODE."
}
The seemingly random nature of the failure is causing a lot of pain. I can't determine if the error is SQL2008, SQLCMD (Although I get the same behaviour with osql.exe) or somehow coupled to powershell.
The actual sql that sqlcmd is executing appears to be unrelated to the problem since a sql script will execute ok for a while and then fail.
The same failure has been seen on many different Workstations and Servers (Win7, Win2003 and Win2008)
Any guidance on how to track this down would be much appreciated.
Don't use sqlcmd and command lines if you are using Powershell!
There are very good built-in tools in V2 that give you a lot more robust interaction with SQL Server, and don't require you to parse the text of return codes to check for errors - they actually return proper error codes.
Here's a technet article on Invoke-SQLCmd
Bear in mind you need to load the snapins first:
Add-PSSnapin SqlServerProviderSnapin100
Add-PSSnapin SqlServerCmdletSnapin100
The root-cause is actually explained elsewhere on here
Exit Code -1073741502 is 0xC0000142 in hex (status_dll_init_failed).
Microsoft's KB2701373 addresses the leaky handles made by Console.Write in Microsoft.powershell.consolehost.dll.
Side-Note: Some "Fixes" on the Internet involve doing something differently, then restarting PowerShell. Yet the actual restart of PowerShell is what addresses the problem (temporarily)

Automatically stop powershell script on bat errors

Generally one can use $ErrorActionPreference to stop the execution of a PS script on error as in the example below that uses an invalid subversion command. The script exits after the first command.
$ErrorActionPreference='Stop'
svn foo
svn foo
Trying the same thing with the maven command (mvn.bat) executes both commands.
$ErrorActionPreference='Stop'
mvn foo
mvn foo
Initially I suspected that mvn.bat does not set an error code and PS just doesn't see the error. However, $? is set properly as demonstrated by the following, when PS exits after the first error:
mvn foo
if (-not $?) {exit 1}
mvn foo
So here's my question: Given that both svn.exe and mvn.bat set an error code on failure, why does the PS script not stop after the mvn error. I find it a lot more convenient to set "$ErrorActionPreference=Stop" globally rather than doing "if (-not $?) {exit 1}" after each command to terminate on error.
Not all command line programs provide errors in the same way. Some set an exit code. Some don't. Some use the error stream, some don't. I've seen some command line programs actually output everything to error, and always output non-zero return codes.
So there's not a real safe guess one could ever make as to it having run successfully, and therefore it's next to impossible to codify that behavior into PowerShell.
$errorActionPreference will actually stop a script whenever a .exe writes to the error stream, but many .exes will write regular output to the console and never populate the error stream.
But it will not reliably work. Neither, for that matter, will $?. If an exe returns 0 and doesn't write to error $? will be true.
While it might be a pain in the butt to deal with each of these individual .exes and their errors in PowerShell, it's a great example of why PowerShell's highly structured Output/Error/Verbose/Warning/Debug/Progress streams and consistent error behavior in Cmdlets beats out plain old .EXE tools.
Hope this Helps
$ErrorActionPreference controls PowerShell's behavior with regard to commandlets and PowerShell functions -- it is not sensitive to exit codes of "legacy" commands. I'm still looking for a work-around for this design decision myself -- for this issue, refer to this thread: How to stop a PowerShell script on the first error?. You'll probably conclude that this custom "exec" function is the best solution: http://jameskovacs.com/2010/02/25/the-exec-problem/
With regard to the stop-on-stderr behavior, I can't reproduce this behavior in PowerShell 3:
Invoke-Command
{
$ErrorActionPreference='Stop'
cmd /c "echo hi >&2" # Output to stderr (this does not cause termination)
.\DoesNotExist.exe # Try to run a program that doesn't exist (this throws)
echo bye # This never executes
}
Update: The stop-on-stderr behavior appears to take effect when using PS remoting.

Proper use of Invoke-Expression?

I've just recently completed my first nightly build script (first significant anything script, really) in powershell. I seem to have things working well, if not yet robustly (I haven't handled significant error-checking yet), but I found myself falling into an idiom around the Invoke-Expression cmdlet, and I'm wondering if I'm using it properly.
Specifically, I use a series of variables to build up command-lines that I will use to build the solution, then run the solution's unit tests. e.g., something like:
$tmpDir = "C:\Users\<myuser>\Development\Autobuild"
$solutionPath=$tmpDir+"\MyProj\MyProj.sln"
$devenv="C:\Program Files (x86)\Microsoft Visual Studio 10.0\common7\ide\devenv"
$releaseProfile="Release"
$releaseCommandLine="`"$devenv`" `"$solutionPath`" /build `"$releaseProfile`""
This works well enough, $releaseCommandLine contains the command line that I want to execute when I'm done. I then execute it via this line:
$output = Invoke-Expression "& $releaseCommandLine"
Is this the proper way to execute a manually-built command line from a powershell script? I thought initially that Invoke-Command would do it, but I must have been doing something wrong because I couldn't get that working at all for half an hour, and I got this working almost immediately.
I've followed this same pattern a few other times in this same script. Is this a best-practice?
Looks fine to me. Only thing I'd change is to use more Powershell features in place of fragile assumptions. E.g.:
use Join-Path instead of string concatenation
use the Env:\ provider to look up the %programfiles(x86)% dir (or better yet, use the HKML:\ provider to find the path - it's in SOFTWARE\Microsoft\VisualStudio\\InstallDir)
when I have to write a string that contains literal doublequotes and variable expansion, I usually fall back to the syntax below. Personal preference, obviously.
'"{0}" "{1}" /build "{2}"' -f $devenv, $solutionPath, $releaseProfile
In some cases I'd be inclined to use Process.Start() so that I could capture the stdout & stderr streams independently (and maybe even control stdin interactively, depending on the application).
PS - the '&' is not strictly necessary.
I think it is unnecessary to use Invoke-Expression here. I've done this with a lot of build scripts and it usually looks like this:
$vsroot = "$env:ProgramFiles(x86)\Microsoft Visual Studio 9.0"
$devenv = "$vsroot\Common7\IDE\devenv.exe"
$sln = Join-Path <source_root> Source\MyProj\MyProj.sln
& $devenv $sln /build Release
or
& $devenv $sln /build "Release|Any CPU"
Although lately, I have had some troubles with using devenv.exe (mis-behaving add-ins, etc), so now I use msbuild.exe:
$msbuild = 'C:\Windows\Microsoft.NET\Framework\v3.5\MSBuild.exe'
& $msbuild $sln /p:Configuration=Release
Currently MSBuild can handle C#, VB and C++ (invokes vcbuild) but it can't handle solutions with setup & deployment projects in them. However, I have found it to be more reliable than using devenv.exe.
BTW you typically need to invoke other tools (sn.exe, signtool.exe, mt.exe, etc) in a build script that are specific to the version of Visual Studio/.NET you want to build against. So it is usually best to configure your environment variables in the same way that the VS 2008 command prompt does. With the PowerShell Community Extensions installed, you can enable one line in the PSCX profile header to enable this for .NET 3.5/VS 2008 settings:
$Pscx:Preferences["ImportVisualStudioVars"] = $true

MSBuild fails when run via Powershell

I have an MSBuild script that I want to call from a PowerShell script as part of a deployment process. If I call the build script via a bat file all works well. If I do the exact same thing in PowerShell I get CS1668 error looking for wierd and wonderful paths that dont exist on my machine.
I know I am getting into the MSBuild script as these errors are occuring from within the MSBuild script targets (logging output is showing this).
The bat file and the PowerShell script reside in the same place, right next to the build script.
Errors:
error CS1668 : Warning as error :
Invalid search path 'C:\Program
Files\Microsoft Visual Studio
8\VC\AtlMfc\Lib' specified in 'LIB
environment variable' -- 'The system
cannot find the path specified. '
error CS1668 : Warning as error :
Invalid search path 'C:\Program
Files\Microsoft Visual Studio
8\VC\PlatformSDK\Lib' specified in
'LIB environment variable'-- 'The
system cannot find the path specified.
'
I have checked and neiter of these paths do NOT exist on my machine.
Why would running from PowerShell change what paths MSBuild look for?
Thanks in advance
RhysC
EDIT- adding in code: NB the name of the MSBuild script is AutomatedDebug.build
POWERSHELL SCRIPT:
#Begining of script
$CurrentPath = Split-Path (Split-Path $myinvocation.mycommand.path )
#Assign the Build script paths. 1 is for building and testsing, 1 is for deployment (to keep things clean)
$MSBuildScriptBuildAndTestPath = $CurrentPath + "\Tools\AutomatedDebug.build"
$MSBuildScriptDeployPath = $CurrentPath + "\Tools\Deploy.build"
#Run the automated build with tests
Write-Host "*** Run the automated build with tests ***"
C:\Windows\Microsoft.NET\Framework\v3.5\MSbuild.exe $MSBuildScriptBuildAndTestPath "/t:AllTests" "/l:FileLogger,Microsoft.Build.Engine;logfile=AllTests.log"
if($LastExitCode -ne 0)
{
throw "AllTests failed"
}
Write-Host "*** FINISHED: Run the automated build with tests ***"
Bat File
#C:\Windows\Microsoft.NET\Framework\v3.5\MSbuild.exe AutomatedDebug.build /t:AllTests /l:FileLogger,Microsoft.Build.Engine;logfile="AllTests.log"
#pause
enter code here
Ok, what is actually happening is that I have dowloaded the Powershell Community Extensions (http://pscx.codeplex.com) many moons ago and there is a Environment.VisualStudio2005.ps1 file in there that adds EnvVars that dont exist. This is (I assume) becuase i dont use VS2005. I have commmented this out and all is well. I have tried to look for the 2008 equivilent but dint have too much luck. To be honest i dont use powershell to its full potential so i doubt i even need the PSCX on my machine anyway.
Thanks guys for your help.
It is most likely due to how you are passing parameters into the MSBuild script. There are some key parameter parsing differences between CMD and PowerShell and by using a batch file, you are implicitly using CMD's parameter parsing engine to hand off the parameters to MSBuild. If you post the command line you're using, one of the PowerShell gurus here can probably help debug where the parameters are getting confused.
I am wondering, basically you get "Warning as error" here. You can either try turning off treating warnings as errors (I mean, having a lib path which doesn't exist doesn't sound that bad to me) or you'll let your scripts print out the respective environment variables (using echo %LIB% and $Env:LIB respectively) from the scripts and look for differences.
However, since the envvars for VS aren't set globally by default (that's why there are the three Visual Studio command prompts) you have to set all variables somewhere. If you're doing this within the scripts you may have a typo somewhere?