saml
saml

Reputation: 463

Optionally pass argument to MSBuild from powershell

In my Build.proj file, I have the following property:

<DbName Condition="$(DbName) == ''">MyDB</DbName>
<ConnectionString Condition="$(ConnectionString) == ''">"Data Source=localhost;Initial Catalog=$(DbName);Integrated Security=SSPI;MultipleActiveResultSets=True"</ConnectionString>

I have a PowerShell function as follows:

function Update-Database
{
    param(
        $DbName=""
    )
    msbuild $MSBuildFile /maxcpucount /verbosity:Minimal /target:DatabaseUpdate /p:DbName=$DbName
}

Running the function in PowerShell I get the following results:

If I modify this line:

msbuild $MSBuildFile /maxcpucount /verbosity:Minimal /target:DatabaseUpdate /p:DbName=$DbName

To this:

msbuild $MSBuildFile /maxcpucount /verbosity:Minimal /target:DatabaseUpdate

Running "UpdateDatabase" uses the default 'MyDB' and all is well.

If I want to have the option to use the default or pass in a new value, do I have to wrap the whole msbuild... command in an if else? or is there a way to conditionally pass in the argument?

UPDATE

I am trying to avoid setting the default in the ps function. Basically I want to emulate this behaviour without the if:

function Update-Database
{
    param(
        $DbName=""
    )
    if($DbName -eq "")
    {
        msbuild $MSBuildFile /maxcpucount /verbosity:Minimal /target:DatabaseUpdate
    }
    else
    {
        msbuild  $MSBuildFile /maxcpucount /verbosity:Minimal /target:DatabaseUpdate /p:DbName=$DbName
    }
}

Upvotes: 1

Views: 466

Answers (2)

Nick Nieslanik
Nick Nieslanik

Reputation: 4458

While a great answer has already been identified, an alternative would be to use Invoke-Expression in powershell and dynamically build the msbuild cmd you want to run. I have a gist on GitHub with an example (you could easily alter it to accommodate the optional db name:

https://gist.github.com/nnieslan/c631add56c5f7f3e7d6e#file-build-functions-ps1

Upvotes: 1

fsimonazzi
fsimonazzi

Reputation: 3013

The property you specify in the command line becomes a global property, which will take precedence over what's specified in the file. You can define a new property instead to avoid this behavior, like this:

<_DbName>$(DbName)</DbName>
<_DbName Condition="$(_DbName) == ''">MyDB</_DbName>
<ConnectionString Condition="$(ConnectionString) == ''">"Data Source=localhost;Initial Catalog=$(_DbName);Integrated Security=SSPI;MultipleActiveResultSets=True"</ConnectionString>

Upvotes: 2

Related Questions