Why am I not getting the desired output 'a' in $d and why am I getting the error in $c in powershell?

Sachin007 1 Reputation point
2022-03-05T11:24:31.83+00:00

180250-p16.png

Why am I not getting the desired output 'a' in $d and why am I getting the error in $c in powershell?

Windows for business | Windows Server | User experience | PowerShell
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 129.5K Reputation points MVP Volunteer Moderator
    2022-03-05T14:33:56.21+00:00

    Hi @Sachin007 ,

    [char]$c means variable $c is defined as character = single character. 0suvu is a sting and not a single character.

    Please try this:

    [char]$d = "a"  
    [string]$c= "0suvu"  
    $c  
    $d  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    0 comments No comments

  2. Rich Matheisen 48,026 Reputation points
    2022-03-05T15:49:41.513+00:00

    The screenshot of your problem has some very basic faults. One of which is that on lines 2 and 3 the values to the right on the equal sign are being interpreted as calls to a function, cmdlet, script, or executable program.

    If those don't generate exceptions then the examples you've shown are missing the functions "a" and "0suvu".

    [char]$d = a
    
    a : The term 'a' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the 
    name, or if a path was included, verify that the path is correct and try again.
    
    [char]$c = 0svsu
    
    0svsu : The term '0svsu' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of   
    the name, or if a path was included, verify that the path is correct and try again.
    

    If, on the other hand, it's your intention to assign a single character to the variable $d you must surround the value with quotation marks (either single or double quotes). Becasuse you've cast the variable as "[char]" PowerShell will convert the string "a" to a single character (which is not the same as a string with a length of 1).

    In the case of assigning a value to the variable $c, it's unclear what result you want. Do you want to place the string "0svsu" into the variable? In that case, as before, protect the string with quotes AND change the type of $c from [char] to [string]. If you want instead to produce an array of characters change the type of the variable to [char[]] (i.e. an array of char). The result will be an array of length 5 with each element of the array containing a single character from the string.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.