How to send one character at a time to a function in powershell?

Viewed 363

I have a function that takes one parameter of type char, of course that means only one character at a time.

I made a for-loop in order to send one character at a time to the function. But of course this wouldn't work, because $mystring is a string and can't be processed like a char. What would the solution be?

$mystring = "ABCDEFG";

function Characters {
    $lettertoascii = [int][char]$args[0];
}

for($i=1; $i -le 10; $i++){
    Characters $mystring
}
3 Answers

You could convert your string into a char array and process it with a foreach loop to call your function char by char:

$mystring = "ABCDEFG";

function characters{
     $lettertoascii = [int][char]$args[0];
}

$mystring.ToCharArray() | foreach {
    Characters $_
}

I suggest an advanced function:

function Get-Character
{
    [CmdletBinding()]
    [OutputType([System.Int32[]])]
    param
    (
        [Parameter(Position = 0, ValueFromPipeline)]
        [System.Char[]]
        $Letter
    )

    process
    {
        foreach ($item in $Letter)
        {
            [int]$item
        }
    }
}

Then you can pass a char array to it through pipeline:

'abcdefg' | Get-Character

or otherwise:

Get-Character 'abcdefg'

Here's documentation on the ToCharArray method, and another link about advanced powershell functions.

Edit:
Turns out powershell is smart and will automatically typecast a string to a char array so you can just pass a string.

Or simply loop over the characters in the string like this:

$myString = 'ABCDEFG'
for ($i = 0; $i -lt $myString.Length; $i++) {
    # call your function one System.Char at a time
    Characters $myString[$i]
}
Related