1

How to create a char array of length $Count in powershell?

PS C:\Users\Administrator> $Count
415
PS C:\Users\Administrator> $chars = New-Object System.Char ($Count)
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Char.
At line:1 char:10
+ $chars = New-Object System.Char ($Count)
+          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

I tried 
[Char[]] $chars = @(415)

I had a class which needed a char array, but I basically I found a solution to my problem by using Strings. But I just wanted to ask if any one knows how to create an empty char array of variable length.

Eg: How do I do this in powershell? C# -> var chars = new Char[Count];

1

1 Answer 1

4

In PowerShell 5.0, you can use the new() constructor method:

PS C:\> $Count = 415
PS C:\> $chars = [char[]]::new($Count)
PS C:\> $chars.Count
415

In earlier versions, use the New-Object cmdlet, and indicate that you want an array with []:

$chars = New-Object -TypeName 'char[]' -ArgumentList $Count
Sign up to request clarification or add additional context in comments.

3 Comments

You could also use [Array]::CreateInstance([char],415).
Thanks. The 2 methods provided by Mathias and one by PetSerAl all work!
@ComedianNinja If this answered your question, please accept the answer (check box below the up/down voting buttons on the left).

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.