0

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.

1 Answer 1

2

Its only null because you never declared it.

$c= ''
for ($i = 0; $i -lt $chars.Length; $i++,($c = $chars[$i])) {

Just like Java and C#, declaring variables and parenthesis still apply.

Sign up to request clarification or add additional context in comments.

5 Comments

Why is $c = $chars[$i] not a declaration where $i = 0 is?
That statement says "Index into chars array at the value of $i, and then assign the value to C" The script errors only on the first iteration of the loop. Because, like other languages, the order of operations for a for loop is for(do first;condition;execute after). So you try to do a $c.tostring before c=$chars[$i++]
So to answer your question directly. They are both declarations! you just needed to declare it earlier
Ah... Totally forgot that it executes after the loop has completed. Thanks!
No problem man. The sooner you start treating powershell like any other Object Oriented language, the easier it gets.IMO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.