Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, November 1, 2018 11:04 AM
Hi Experts,
Could you please help me to concatenate Object Property and String , please look code is like below.
#$source=Reading content from File
$a = New-Object psobject -Property @{
'Student Name'= $source.Name;
'TotalMark' = $source.TotalMark;
'Percentage%' = [Math]::Round((($source.TotalMark/80) * 100));
}
I want to assign this variable value into another value to concatenate the result like .
$Result="<Table><TH>StudentName</TH><TH>TotalMark</TH><TH>Percentage</TH>"
+ "<TR><TD>$a.Student Name</TD><TD>$a.TotalMark</TD><TD>$a.Percentage</TD></TR>"
Getting following error while executing this code.
Cannot convert value "<TR><TD>" to type "System.Int32". Error: "Input string was not in a correct format."
At \Test.ps1:63 char:5
+ +<TR><TD>+$a.Percentage%'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
Regards,
Niraj Sevalkar
All replies (4)
Thursday, November 1, 2018 11:40 AM ✅Answered
You can change the percent value from int to string.
'Percentage%' = ([Math]::Round((($source.TotalMark/80) * 100))).ToString();
Thursday, November 1, 2018 12:29 PM ✅Answered
Hi tickermcse76,
You are right, I have tried with this and it has worked for me, Thank you for your valuable suggestion.
But I have found another problem with my code i.e.
Reference: https://ss64.com/ps/syntax-concat.html
Concatenate numbers with strings:
PS C:\ $int1 = 42
PS C:\ $string2 = 'def'
PS C:\ $int1 + ", " + $string2
Cannot convert value "," to type "System.Int32". Error: "Input string was not in a correct format."
The expression above is evaluated from left to right so converting the string to an integer fails, if we swap around the order they will both convert to a string without error:
PS C:\ $string2 + ", " + $int1
def, 42
Regards,
Niraj Sevalkar
Thursday, November 1, 2018 1:19 PM | 1 vote
I would just suggest if you know you need to work with a specific data type - you declare it explicitly; otherwise PowerShell will choose it for you.
$int = 41
$int | Get-Member ### This is Type Int32
$int = '41'
$int | Get-Member ### This is Type String
[int]$int = '41'
$int | Get-Member ### This is Type Int32
Thursday, November 1, 2018 5:30 PM
**You can concat this way.
**
$int1 = 42
$string2 = 'def'
"$int1, $string2"
42, def