0

I am trying to make powershell commands for git commands using variables, but I cannot make it work when I add Replace function.

$branch_task = 'TEST_01'; $branch_title = 'some_branch_title'; git checkout -b feature/"$branch_task"_"$branch_title"
this one gives success command: git checkout -b feature/TEST_01_some_branch_title

git commit -m ""$branch_task": "$branch_title""
this one gives success command: git commit -m "TEST_01: some_branch_title"

but this one:
git commit -m ""$branch_task.Replace('_', '-')"':' "$branch_title.Replace('_', ' ')""

gives error:
error: pathspec ': ' did not match any file(s) known to git
error: pathspec 'some branch title' did not match any file(s) known to git

Any ideas?

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Do an echo of the command instead of running it so that we can see what the problem might be. – eftshift0 Jun 30 '23 at 11:53
  • 2
    Use the subexpression operator (`$(...)`) to enclose the expressions: `"$($branch_task.Replace('_', '-')): $($branch_title.Replace('_', ' '))"` – Mathias R. Jessen Jun 30 '23 at 11:53
  • Echo: PS D:\Projects\Asseco\FE\portal-personel> echo git commit -m ""$branch_task.Replace('_', '-')": "$branch_title.Replace('_', ' ')"" git commit -m TEST-01 : some branch title – E_someRandomString Jun 30 '23 at 12:04
  • @MathiasR.Jessen solution worked! Thank you very much! Now I will study how and why it worked :D Thank you once again :) – E_someRandomString Jun 30 '23 at 12:06
  • In short: Only variables _by themselves_ can be embedded as-is in expandable strings (`"..."`), e.g. `"foo/$var"` or `"foo/$env:USERNAME"`. To embed _expressions_ or even commands, you must enclose them in `$(...)`. Notably, this includes property and indexed access (e.g., `"foo/$($var.property)"`, `"foo/$($var[0])"`) as well as method calls (e.g. `"foo/$($var.Replace('x', 'y'))"`). See the linked duplicate for details. – mklement0 Jun 30 '23 at 13:03
  • Also not that you should use `"..."`, not `""....""`. If you use the latter, the each `""` becomes the _empty string_ instead of serving to enclose the intervening text. – mklement0 Jun 30 '23 at 13:11
  • Also, to offer an alternative using an _expression_ (`(...)`) based on the [`-f`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#format-operator--f) operator: `git commit -m ('{0}: {1}' -f $branch_task.Replace('_', '-'), $branch_title.Replace('_', ' ')) ` – mklement0 Jun 30 '23 at 13:14

0 Answers0