0

When I convert the variable value which is in string to an array format, it converted data type to an array but the result is not an array.

Example:

cls
#Actual String value concatenated with dot (.)
$EmpInfo="Name.Address.Pincode.Phone"
Write-Host $EmpInfo

#Change string value to array format
$EmpInfoArray= '"'+$EmpInfo.Replace('.',""",""")+'"'
Write-Host $EmpInfoArray
$EmpInfoArray.gettype()

#Convert BaseType value from 'system.object' to 'system.array'
[Array]$ConvertedArray = $EmpInfoArray
$ConvertedArray.GetType()

Write-Host $ConvertedArray.Count
Write-Host $ConvertedArray[0]

Result:

1

"Name","Address","Pincode","Phone"

It is not resulting the value as an array. If it is an array then the result would be array count 4 and first array value 'Name'

Do we have any workaround to result the converted user specified string value to an array.

2 Answers 2

1

Split your EmpInfoArray with ','

[Array]$ConvertedArray = $EmpInfoArray -split ','

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

2 Comments

-split ',' resulting value with Quotation mark. But it should result only the array value (Name) not enclosing with quotation mark ("Name"). For this again I need to replace the Quotation with space.
$EmpInfoArray= $EmpInfo.Replace('.',',') This works as well, along with my above recommendation.
0

Invoke-expression fixed this issue. Now it is resulting as an array.

cls
#Actual String value concatenated with dot (.)
$EmpInfo="Name.Address.Pincode.Phone"
Write-Host $EmpInfo

#Change string value to array format
$EmpInfoArray = invoke-expression ('"'+$EmpInfo.Replace('.',""",""")+'"')
$EmpInfoArray.gettype()
$EmpInfoArray.count
$EmpInfoArray[0]

Result:

4
Name

Comments

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.