0

I am new to PowerShell and was working on a script, where I got stuck with a problem. When I Write-Host from inside a function, the variables are printed first and then the string. Otherwise it works normal, as expected.

PS C:\> function a($a,$b,$c) {
write-host "From a Function"
write-host "$a, "*", $b, "*" ,$c"
}
$a=2
$b=3
$c=4

#Calling the Function
a($a,$b,$c)

# Write-Host without function
write-host "Directly from the script"
write-host "$a, "*", $b, "*" ,$c"



- **BELOW IS THE OUTPUT**

From a Function
2 3 4,  *, , * ,
Directly from the script
2,  *, 3, * ,4

PS C:\> 

Output should be the same, is the approach to a powershell function different while executing.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 3
    You're using the wrong syntax for invoking the function. Change `a($a,$b,$c)` to `a $a $b $c` and it'll work as expected – Mathias R. Jessen Nov 16 '22 at 12:12
  • In short: PowerShell functions, cmdlets, scripts, and external programs must be invoked _like shell commands_ - `foo arg1 arg2` - _not_ like C# methods - `foo('arg1', 'arg2')`. If you use `,` to separate arguments, you'll construct an _array_ that a command sees as a _single argument_. See the [linked duplicate](https://stackoverflow.com/q/4988226/45375) and [this answer](https://stackoverflow.com/a/65208621/45375) for more information. – mklement0 Nov 16 '22 at 12:49
  • Thanks Mathias and Mklemento. I understood the issue. But what happens when we put brackets. If the syntax is wrong it should throw an error, or not work. Whats the difference between using a bracket while calling a function and using it without brackets. – Anirvan Lahiri Nov 16 '22 at 17:31

0 Answers0