PowerShell Script in PostBuild

2019-02-04 08:03发布

问题:

Continuous Integration

I have been working on a PowerShell script to keep our development process streamlined. I was planning on running it as a post-build event, but I'm having some trouble.

From the PowerShell prompt, the following works wonderfully:

PS C:\> ./example.ps1

However, when attempting to run this from cmd.exe as follows:

C:\> powershell -command "&\"C:\path to script\example.ps1\""

The script executes but I get a round of errors back from PowerShell, consisting mostly of path resolution errors from the resolve-path function:

Resolve-Path : Cannot find path 'C:\Documents and Settings\bdunbar\My Documents \Visual Studio 2008\Projects\CgmFamilyComm\FamilyComm\iirf\cms\isapirewrite4.dl l' because it does not exist. At C:\Documents and Settings\bdunbar\My Documents\Visual Studio 2008\Projects\C gmFamilyComm\scripts\cms.ps1:4 char:27 + $iirfpath = (resolve-path <<<< ../iirf/cms/isapirewrite4.dll).path,

Resolve-Path : Cannot find path 'C:\Documents and Settings\bdunbar\My Documents \Visual Studio 2008\Projects\CgmFamilyComm\FamilyComm\familycomm' because it do es not exist. At C:\Documents and Settings\bdunbar\My Documents\Visual Studio 2008\Projects\C gmFamilyComm\scripts\cms.ps1:5 char:27 + $vdirpath = (resolve-path <<<< ../familycomm).path

Is there a way to work around this? Could it be an issue with running resolve-path under cmd.exe?

[Update]

I've been able to change things to get around the errors that are occurring, but I still receive errors that work perfectly fine from the powershell command prompt. I can't figure out what the difference is.

回答1:

I've made this work in the past (see http://sharepointpdficon.codeplex.com/SourceControl/changeset/view/13092#300544 if interested):

C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -NoLogo -NonInteractive -Command .'$(ProjectDir)Deployment\PostBuildScript.ps1' -ProjectDir:'$(ProjectDir)' -ConfigurationName:'$(ConfigurationName)' -TargetDir:'$(TargetDir)' -TargetFileName:'$(TargetFileName)' -TargetName:'$(TargetName)

Then throw these parameters in the first line of your post-build script (if you think you may be able to use them):

param($ProjectDir, $ConfigurationName, $TargetDir, $TargetFileName)

Also I should point out, I am not using this presently. I did like using it as a quick scratchpad to reload test data for running integration tests.



回答2:

Looks like your problem is how relative paths are resolved. Relative paths are resolved based on the current location (stored in $pwd) and not based on the location of the script. So if you launched the script from C:\, it definitely would not work.

I would suggest you calculate the paths based on an argument (like Peter Seale shows), or grab the actual location of the script from:

$MyInvocation.MyCommand.Path