A little background: I am writing a short method to transform SomethingLikeThis into something_like_this. I was using a foreach loop on the .ToCharArray of $name, but that has not worked out as expected for input such as BIOS and PCIDevices. I opted to go for a for loop so I can check the previous character. To be clear, I do not need help on that portion of the code... Please read on.
function Get-FileName {
param([string] $name)
$out = ''
$chars = $name.ToCharArray()
for ($i = 0; $i -lt $chars.Length; $i++, $c = $chars[$i]) {
if ($c -ge 'A' -and $c -le 'Z' -and -not $out.Length -eq 0) {
$out += '_'
}
Write-Host $c
$out += $c.ToString().ToLower()
}
return $out;
}
Get-FileName "BIOS"
The error this gives me is:
Invalid assignment expression. The left hand side of an assignment operator needs to be something that can be assigned to like a variable or a property.
Ideally I would have for ($i = 0; $i -lt $chars.Length; $c = $chars[$i++])
But that causes this to happen
You cannot call a method on a null-valued expression.
At C:\Users\kylestev\Desktop\test.ps1:145 char:32
+ $out += $c.ToString <<<< ().ToLower()
B
I
O
b_i_o
I come from a Java and C# background so this not working is kind of a let down. Anyone know of a workaround for making this work as a one liner? I would rather not have to assign a value to $c in the body of the loop, but I can if there is no workaround.