Reputation: 424
I'm relatively new to powershell, and I have found an oddity that I'm not sure how to explain.
This outputs just fine.
write-output $var.Name.padright(40)" - "(get-date -format s)" : Creating on $var1"
This on the other hand, throws an error:
write-warning $var.Name.padright(40)" - "(get-date -format s)" : Creating on $var1"
Write-Warning : A positional parameter cannot be found that accepts argument ' - '.
At Y:\test.ps1:228 char:22
+ write-warning <<<< $var.name.padright(40)" - "(get-date -format s)" : Creating on $var1"
+ CategoryInfo : InvalidArgument: (:) [Write-Warning], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteWarningCommand
Any idea why? If I want to make the above work, I instead do this:
$warning = $var.Name.padright(40) + " - " + (get-date -format s) + " : Creating on $var1"
write-warning $warning
I've found a workaround, as you can see, but I'd like to understand why string concatenation works differently for write-output than write-warning. Is there a reason I should explicitly create the string as a variable first rather than just using the shorthand?
Upvotes: 3
Views: 5971
Reputation: 1095
It's not about how the string is created it's about what the interpreter is looking for. Write-output has a parameter called inputobject that accepts one or more PSobjects. Write-warning is looking for a single string object.
The syntax you're using isn't ideal, when you're using cmdlets try and be really precise with what you send to each parameter.
Here's the actual Code to use in case that wasn't clear:
Write-Warning -Message "$($var.Name.padright(40)) - $(get-date -format s) : Creating on $var1";
That syntax creates a single string object to pass into the -Message
parameter on the Write-Warning
command, which is what it's expecting as the first positional parameter. You can also specify the parameter name (see above example), to ensure that the code is readable by other people, and that the interpreter fully understands your intentions.
Upvotes: 8