Build step 'Windows PowerShell' marked build as failure, why? - powershell

Below are three PowerShell Commands run in Jenkins and the build result. Why it fails? Which command could be failing? I've read this post: How/When does Execute Shell mark a build as failure in Jenkins?, but couldn't figure out. I am not familiar with MS stuffs.
Command 1:
& "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.com" "$env:WORKSPACE\ETL\OnePnL.sln" /Build
Command2:
###########################
# Deploy SSIS package #
###########################
$csource ="$env:WORKSPACE\ETL\Project Type 0\bin\DEFAULT\OnePnL.ispac"
$cserver = "SSASDBDEV01"
$cdest = "/SSISDB/OnePnL/OnePnL"
echo $env:GIT_BRANCH
if ($env:GIT_BRANCH -like '*master*')
{
# Call IS Deployment Wizard
echo "Deploying SSIS package to $cdest on $cserver"
# "C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\ISDeploymentWizard.exe" "/Silent /SourcePath:""$csource"" #/DestinationPath:""$cdest"" /DestinationServer:""$cserver""" -Wait
Start-Process "C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\ISDeploymentWizard.exe" "/Silent /SourcePath:""$csource"" /DestinationPath:""$cdest"" /DestinationServer:""$cserver""" -Wait
}
Command 3:
#####################
# Copy Files to O: drive #
#####################
#Make build directory
#$outputparentdir = "\\orion\Shared\AppUpload\ApplicationPackage\OnePnL Cube\SSIS Jenkins Builds"
$outputparentdir = "\\inv\Shared\Transfer - Deleted Weekly\Jenkins\BI\OnePnL\SSIS Jenkins builds"
$outputdir = "$outputparentdir\${env:GIT_BRANCH}\Build ${env:BUILD_NUMBER}"
echo "Branch"
echo ${env:GIT_BRANCH}
echo "Output directory"
echo $outputdir
if (!(Test-Path "$outputparentdir"))
{
mkdir $outputparentdir
}
mkdir $outputdir
ROBOCOPY "$env:WORKSPACE\ETL\Project Type 0\bin\DEFAULT" "$outputdir" /E /v
echo "Done Copy"
Build result:
[OnePnL SSIS] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\SVC_TE~1\AppData\Local\Temp\hudson3790190217372968147.ps1'"
Microsoft (R) Microsoft Visual Studio 2012 Version 11.0.50727.1.
Copyright (C) Microsoft Corp. All rights reserved.
------ Build started: Project: OnePnL, Configuration: DEFAULT ------
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
[OnePnL SSIS] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\SVC_TE~1\AppData\Local\Temp\hudson2769520726749517170.ps1'"
origin/release
[OnePnL SSIS] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\SVC_TE~1\AppData\Local\Temp\hudson7860003244522954499.ps1'"
Branch
origin/release
Output directory
\\inv\Shared\Transfer - Deleted Weekly\Jenkins\BI\OnePnL\SSIS Jenkins builds\origin/release\Build 74
Directory: \\inv\Shared\Transfer - Deleted Weekly\Jenkins\BI\OnePnL\SSIS
Jenkins builds\origin\release
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 10/26/2015 4:29 PM Build 74
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows
-------------------------------------------------------------------------------
Started : Monday, October 26, 2015 4:29:01 PM
Source : D:\te_jenprodslave_1\workspace\Trade_Efficiencies\BI\OnePnL SSIS\ETL\Project Type 0\bin\DEFAULT\
Dest : \\inv\Shared\Transfer - Deleted Weekly\Jenkins\BI\OnePnL\SSIS Jenkins builds\origin\release\Build 74\
Files : *.*
Options : *.* /V /S /E /DCOPY:DA /COPY:DAT /R:1000000 /W:30
------------------------------------------------------------------------------
1 D:\te_jenprodslave_1\workspace\Trade_Efficiencies\BI\OnePnL SSIS\ETL\Project Type 0\bin\DEFAULT\
New File 516475 OnePnL.ispac
0%
25%
50%
76%
100%
------------------------------------------------------------------------------
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1 0 0 0 0 0
Files : 1 1 0 0 0 0
Bytes : 504.3 k 504.3 k 0 0 0 0
Times : 0:00:00 0:00:00 0:00:00 0:00:00
Speed : 43039583 Bytes/sec.
Speed : 2462.744 MegaBytes/min.
Ended : Monday, October 26, 2015 4:29:01 PM
Done Copy
Build step 'Windows PowerShell' marked build as failure

The answer is sort of in the post you linked.
the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step
I get that you understand that much, but what makes it come into play is the return code for robocopy which was you last command. While the link is for server 2008 I won't be surprised if they are OS common.
Value Description
0 No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped.
1 All files were copied successfully.
If all the files were copied successfully then the return code is 1. Anything other than 0 is reported as a failure by the build step as we have read in the linked question.
I think what you need to do is check the return code of robocopy and change it.
To check it you need to look at a PowerShell automatic variable $?
$?
Contains the execution status of the last operation. It contains
TRUE if the last operation succeeded and FALSE if it failed.
So the last couple of lines could be...
ROBOCOPY "$env:WORKSPACE\ETL\Project Type 0\bin\DEFAULT" "$outputdir" /E /v
If($?){exit 0}
What this should do is take any non zero result from robocopy and force the script to return true. Again, be aware that this would return OK for all return codes. If this is not desirable then you could easily build some logic for certain codes.
I cannot really test this code as I do not have your environment but in theory it should work or at least get you started on where you need to be.

Related

PowerShell, only "> $out" catch full error of failed 7Zip extract, why?

I tried all suggestion on how to catch errors of 7Zip as explained in:
powershell - How to capture output in a variable rather than a logfile? - Stack Overflow
Redirecting output to $null in PowerShell, but ensuring the variable remains set - Stack Overflow
and played with try / catch.
Second contains only
Cannot find drive. A drive with the name ' 7-Zip 18.05 (x64) ' does
not exist.
in Error[0]
If I write the console output
7-Zip 18.05 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2018-04-30
Scanning the drive for archives:
1 file, 51273 bytes (51 KiB)
Extracting archive: \\...\850\DAY01
--
7z.exe : ERROR: Data Error : DAY01.RAW
At C:\Users\MyUser\Code\7Zip.ps1:6 char:1
+ & $7ZIP_FullPath x $IN_FullPath -o$OUT_Directory -y
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: Data Error : DAY01.RAW:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Path = \\...\850\DAY01
Type = gzip
Headers Size = 20
Sub items Errors: 1
Archives with Errors: 1
Sub items Errors: 1
in a variable, the variable will contain only
7-Zip 18.05 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2018-04-30
Scanning the drive for archives:
1 file, 51273 bytes (51 KiB)
Extracting archive: \\...\850\DAY01
--
Path = \\...\850\DAY01
Type = gzip
Headers Size = 20
Sub items Errors: 1
Archives with Errors: 1
Sub items Errors: 1
It looks like, that
7z.exe : ERROR: Data Error : DAY01.RAW
At C:\Users\MyUser\Code\7Zip.ps1:6 char:1
+ & $7ZIP_FullPath x $IN_FullPath -o$OUT_Directory -y
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (ERROR: Data Error : DAY01.RAW:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
is created by PowerShell (what explaiuns 7z.exe : ERROR:..) and can only be captured if I use $out:
& $7ZIP_FullPath x $IN_FullPath -o$OUT_Directory -y > $out
It looks like $out triggers something but what?
7zip is not a PowerShell command so you can’t use the ordinary try{}catch{} with the -ErrorAction Stop
But 7zip has the ability to send out the %errorlevel% values in batch. Which is a better way to find an error
So According to the documentation these are the possible exit codes (%ERRORLEVEL% values):
Code Meaning
==== =======
0 No error
1 Warning (Non fatal error(s)). For example, one or more files were
locked by
some other application, so they were not compressed.
2 Fatal error
7 Command line error
8 Not enough memory for operation
255 User stopped the process
==== =======
In cmd or in a .bat file, there is no problem to run the 7zip command, and on the second line take out the %errorlevel% value, but in powershell you can’t really do that.
If you write the following code in powershell
To Zip:
& cmd.exe /c 'C:\"Program Files"\7-Zip\7z.exe a –mx1 "c:\DestinationFolder\NameOnZipFiles" c:\FolderToZip\*&echo:%errorlevel%'
To Unzip:
& cmd.exe /C 'C:\"Program Files"\7-Zip\7z.exe x "c:\SourceFolder" -o"D:\DestinationFolder" -y&echo:%errorlevel%'
You will notice that the %errorlevel% will always be 0, even if the command fails.
That’s because the %errorlevel% you get is the errorlevel before the command has run.
So to fix that problem you will have to enable the “DelayedExpansion” in cmd with “cmd.exe /v /c
the “%” will also have to be changed to “!” to use the delayed function.
So the correct command needs to be written like this to get the correct errorlevel
To Zip:
& cmd.exe /v /c 'C:\"Program Files"\7-Zip\7z.exe a –mx1 "c:\DestinationFolder\NameOnZipFiles" c:\FolderToZip\*&echo:!errorlevel!'
To Unzip:
& cmd.exe /v /C 'C:\"Program Files"\7-Zip\7z.exe x "c:\SourceFolder" -o"D:\DestinationFolder" -y&echo:!errorlevel!'
More info about the “DelayedExpansion” in cmd https://ss64.com/nt/delayedexpansion.html
Also If you only want to display the errorlevel after command has run, add the following 7zip options “-bso0 -bsp0 -bse0”
To Zip:
& cmd.exe /v /c 'C:\"Program Files"\7-Zip\7z.exe a –mx1 "c:\DestinationFolder\NameOnZipFiles" c:\FolderToZip\* -bso0 -bsp0 -bse0&echo:!errorlevel!'
To Unzip:
& cmd.exe /v /C 'C:\"Program Files"\7-Zip\7z.exe x "c:\SourceFolder" -o"D:\DestinationFolder" –y -bso0 -bsp0 -bse0&echo:!errorlevel!'
But in your case, if your only after having the error text in the same variable just add the 7zip option -bse1
$out=& $7ZIP_FullPath x $IN_FullPath -o$OUT_Directory -y -bse1
#daniel comments got me on the right track but still, I can not explain fully why only this solution is working.
$7ZIPExtractResult= & $7ZIP_FullPath x $IN_FullPath -o$OUT_Directory -y *>&1
Redirects the specified stream to the Success stream.
My guess is, that only that way it can be stored in a variable.
I found help in What does 2>&1 Mean in PowerShell - Stack Overflow and about_Redirection - PowerShell | Microsoft Docs.
In addition, the variable $7ZIPExtractResult is a System.Object[], so I have to do convert an array to a string doing 7ZIPExtractResultAsString = "$7ZIPExtractResult", expecting that is always possible and not throwing a different error.
It is still unknown to me why this error is not caught by
try {
}
catch {
}

Jenkins Build Taking Too Long

Once upon a time, they had Jenkins build our program in minutes. Now it's taking over 2 hours. I've copied below the area where it seems to hang up. From my understanding, it's building successfully, but it's held up when moving some files around. Can anybody point me in the right direction?
Done Building Project "C:\dev\cd\src\webservices\PricingEngineService\PricingEngineService\PricingEngineService.csproj" (Package target(s)).
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:00.67
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\CDIUSE~1.CLE\AppData\Local\Temp\jenkins2991160982461640193.ps1'"
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\CDIUSE~1.CLE\AppData\Local\Temp\jenkins3998493390681688005.ps1'"
[10:27:53] Using gulpfile C:\dev\cd\src\jedi\gulpfile.js
[10:27:53] Starting 'deleteDistFolder'...
Deleted folder: [ 'C:\\dev\\cd\\src\\jedi\\dist' ]
[10:27:54] Finished 'deleteDistFolder' after 528 ms
[10:27:54] Starting 'sass-build'...
[10:27:54] Finished 'sass-build' after 107 ms
[10:27:54] Starting 'minifyHTML'...
[10:27:54] Finished 'minifyHTML' after 360 ms
[10:27:54] Starting 'build'...
[10:27:54] Finished 'build' after 33 ms
[10:27:54] Starting 'build-app-module'...
[10:27:55] Finished 'build-app-module' after 160 ms
[10:27:55] Starting 'copy-files'...
[10:27:58] Finished 'copy-files' after 3.01 s
[10:27:58] Starting 'bower-install'...
[10:27:58] Using cwd: ./src/
[10:27:58] Using bower dir: lib
[10:28:10] Finished 'bower-install' after 13 s
[10:28:10] Starting 'bower'...
[10:28:17] Finished 'bower' after 6.43 s
[10:28:17] Starting 'dist'...
[10:28:17] Finished 'dist' after 2.93 μs
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\CDIUSE~1.CLE\AppData\Local\Temp\jenkins3818291352140264878.ps1'"
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\CDIUSE~1.CLE\AppData\Local\Temp\jenkins3645201150751239660.ps1'"
[workspace] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\CDIUSE~1.CLE\AppData\Local\Temp\jenkins8091378399438661373.ps1'"
Invoke-Command : Cannot find path 'C:\dev\cd\src\cdi-conf\scripts\DesployIIS.PS1' because it does not exist.
At C:\Users\cdiuser.cd\AppData\Local\Temp\jenkins8091378399438661373.ps1:1 char:1
+ Invoke-Command -ComputerName devopsweb01 -FilePath \dev\cd\s ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\dev\cleardem...\DesployIIS.PS1:String) [Invoke-Command], ItemNotFoun
dException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
Finished: SUCCESS
The error message says it can't find your file:
Invoke-Command : Cannot find path
'C:\dev\cd\src\cdi-conf\scripts\DesployIIS.PS1' because it does not
exist.
But it also says this error comes from the script C:\Users\cdiuser.cd\AppData\Local\Temp\jenkins8091378399438661373.ps1.
This is a temporary file created by Jenkins, which means that this is likely a PowerShell build step in the Jenkins job/pipeline.
In Jenkins, as you navigate the web interface to look at the configuration, this will be just a text box, and the script contents will be in there. When it runs it generates a temporary file on the worker.
So you need to look at that code in the job, and determine where it has referenced the file 'C:\dev\cd\src\cdi-conf\scripts\DesployIIS.PS1' and then figure out why that file doesn't exist on the target worker server (or why this script thinks it should exist), and fix that issue.

robocopy and source folder name/encoding

On windows 8 I am trying to copy a folder using robocopy
robocopy /MIR /E /DCOPY:T /s "c:\test\xupdate can’t be deployed" "c:\test\out\"
But it fails with:
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows
-------------------------------------------------------------------------------
Started : 9. april 2015 10:56:35
Source : C:\test\xupdate canÈÃÍt be deployed
Dest : C:\test\out\
Files : *.*
Options : *.* /S /DCOPY:T /COPY:DAT /PURGE /MIR /R:1000000 /W:30
2015/04/09 10:59:44 ERROR 2 (0x00000002) Accessing Source Directory C:\test\xupdate canÈÃÍt be deployed
The system cannot find the file specified.
So the problem is obviously the ’ character in the source folder name. But why can't robocopy read that character?
Using character set 1252 works on my windows 7 machine.
chcp 1252
robocopy /MIR /E /DCOPY:T /s "c:\test\xupdate can't be deployed" "c:\test\out"
According to Notepad++ the .bat file is encoded:
UTF-8 without BOM
Result:
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows
-------------------------------------------------------------------------------
Started : Fri Aug 28 12:35:13 2015
Source : c:\test\xupdate can't be deployed\
Dest : c:\test\out\
Files : *.*
Options : *.* /S /COPY:DAT /DCOPY:T /PURGE /MIR /R:1000000 /W:30
------------------------------------------------------------------------------
1 c:\test\xupdate can't be deployed\
------------------------------------------------------------------------------
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1 0 1 0 0 0
Files : 1 0 1 0 0 0
Bytes : 245 0 245 0 0 0
Times : 0:00:00 0:00:00 0:00:00 0:00:00
Ended : Fri Aug 28 12:35:13 2015
I used windows notepad to create the bat file.
Unfortunately I cannot recreate the above when creating a new .bat file with the same encoding. Robocopy fails regardless of encoding, the best I get is:
-------------------------------------------------------------------------------
ROBOCOPY :: Robust File Copy for Windows
-------------------------------------------------------------------------------
Started : Fri Aug 28 12:37:20 2015
Source : c:\test\xupdate can't be deployed\
Dest : c:\test\out\
Files : *.*
Options : *.* /COPY:DAT /R:1000000 /W:30
------------------------------------------------------------------------------
2015/08/28 12:37:20 ERROR 2 (0x00000002) Accessing Source Directory c:\test\xupd
ate can't be deployed\
The system cannot find the file specified.
I have to copy the original .bat files text into a new batch file to get it to work.
If you are making batch command file and save file with UTF-8 encoding, use chcp 65001 at first line of batch file.
I'm from Czech Republic and have similiar issue.

How can I load a dump thru Powerdbg's "New-DbgSession" command?

I am trying to use the Powerdbg module to analyse a kernel dump. I have managed to successfully install the module. But I am unable to start a new session.
New-DbgSession -dump F:\Downloads\021715-61105-01.dmp
But it opens a blank command prompt titled "CDB.exe" and does nothing. I have Windbg installed on my machine. and the `debuggerroot' variable is rightly pointed to its path. What could I be doing wrong?
The codeplex Powerdbg discussion page isn't active.
i have been intending to try this so i downloaded the latest package and tested it result is as follows see if you can follow through it
i created a bat file which sets the DebuggingTools Environment variable to windows 8.0 debugger installation (xp virtual machine)
in the bat file i invoke powershell with Import-module
when i get a ps command prompt i start a new verbose dbgSession with a dumpfile test.dmp located at c:\
:dir /b
Install_PowerDbg.bat
PowerDbg.psm1
PowerDbgConsole.ps1
PowerDbg_6.10.10.22.zip
runpdbg.bat
:type runpdbg.bat
set DebuggingTools=c:\Program Files\Windows Kits\8.0\Debuggers\x86
c:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -nologo -noexit -comma
nd "Import-Module" .\powerdbg.psm1
:runpdbg.bat
:set DebuggingTools=c:\Program Files\Windows Kits\8.0\Debuggers\x86
:c:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -nologo -noexit -comm
and "Import-Module" .\powerdbg.psm1
WARNING: Some imported command names include unapproved verbs which might make
them less discoverable. Use the Verbose parameter for more detail or type
Get-Verb to see the list of approved verbs.
WARNING: Some imported command names contain one or more of the following
restricted characters: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? # ` * % +
= ~
PS C:\Documents and Settings\Admin\Desktop\PowerDbg_6.10.10.22> New-DbgSession -
verbose -dump C:\test.dmp
VERBOSE: Using debugging tools from c:\Program Files\Windows
Kits\8.0\Debuggers\x86
VERBOSE: c:\Program Files\Windows Kits\8.0\Debuggers\x86\CDB.exe -z C:\test.dmp
VERBOSE:
Verb :
Arguments : -z C:\test.dmp
CreateNoWindow : False
EnvironmentVariables : {pathext, homepath, symbol_path, clientname...}
RedirectStandardInput : True
RedirectStandardOutput : True
RedirectStandardError : True
StandardErrorEncoding :
StandardOutputEncoding :
UseShellExecute : False
Verbs : {Enable/Disable Digital Signature Icons, open, Open
i
n PPEE (puppy), Open with CFF Explorer...}
UserName :
Password :
Domain :
LoadUserProfile : False
FileName : c:\Program Files\Windows
Kits\8.0\Debuggers\x86\CDB.e
xe
WorkingDirectory : C:\Documents and
Settings\Admin\Desktop\PowerDbg_6.10
.10.22
ErrorDialog : False
ErrorDialogParentHandle : 0
WindowStyle : Normal
VERBOSE: RX (discard)
VERBOSE: TX: .echo PowerDbg connected
VERBOSE: RX: PowerDbg connected
VERBOSE: RX: 0:000> PowerDbg_Complete_184742.640
VERBOSE: RX Complete
VERBOSE: RX (discard) 0:000>
VERBOSE: TX: .printf "%d\n", #$ptrsize
VERBOSE: RX: 4
VERBOSE: RX: 0:000> PowerDbg_Complete_184742.656
VERBOSE: RX Complete
VERBOSE: Connected to 32 bit process/dump
PS C:\Documents and Settings\Admin\Desktop\PowerDbg_6.10.10.22>
this command also seems to start a session correctly (you may need to add debugger path explicitly in $searchpath in powerdbg.psm1 line arount 440 in function Get-DbgToolsLocation()
powershell.exe -nologo -noexit -File PowerDbgConsole.ps1 -verbose -dump c:\test.dmp

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