Nick
Nick

Reputation: 2559

Use variable inside Invoke-Expression string

Very new to Powershell, so I'm not sure I'm doing things the right way at the moment, but I'm struggling pass a variable into an Invoke-Expression string and was hoping someone would be able to help.

$projectLocation = "C:/Users/Admin/Desktop/Projects/repo"

Invoke-Expression 'cmd /c start powershell -Command {
     cd $projectLocation;
     git pull
}'

I've also tried splitting out the string with ' + $projectLocation + ', but still not having much luck.

The only way I've achieved my goal is by inserting the $projectLocation string manually.

I don't think I'm far off, but any help would be great! Thanks.

Upvotes: 1

Views: 218

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

Evaluating a piece of code that spawns cmd in order to launch a new instance of powershell.exe is completely unnecessary:

$projectLocation = "C:/Users/Admin/Desktop/Projects/repo"
cd $projectLocation
git pull

If you want to suppress any output it might generate, just wrap it in a block or function and redirect the output streams to $null:

function Pull-Repo
{
    param(
      [string]
      $projectLocation = "C:/Users/Admin/Desktop/Projects/repo"
    )

    Push-Location $projectLocation
    git pull
    Pop-Location
}

# suppress all output
Pull-Repo *> $null

Upvotes: 3

Related Questions