I copied this from the book and try to input into PS, it gives me error. Here is the script
$people = @(
[PSCustomObject] @(Name= ‘John’; age = 30; occupation = ‘engineer’)
[PSCustomObject] @(Name =’Alice’; age =25; occupation = ‘designer’)
[PSCustomObject] @(Name =’Bob’; age = 40; occupation = ‘Manager’)
)
It doesn’t recognize Name age occupation. I tried to put in $Name=‘Alan’, $age=15, occupation=‘none’ in front of this to define them as variables, still won’t work.
Firstly, when posting code, data, or output in the forum, please can you use the pre-formatted text button. It looks like </> in the toolbar. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working).
Either the book is wrong, or you have copied the code incorrectly. You need to use curly brackets (braces - {} ), rather than round brackets (parentheses - () ) when using the [PSCustomObject] type accelerator.
$people = @(
[PSCustomObject] @{Name= 'John'; age = 30; occupation = 'engineer'}
[PSCustomObject] @{Name ='Alice'; age =25; occupation = 'designer'}
[PSCustomObject] @{Name ='Bob'; age = 40; occupation = 'Manager'}
)
Remember, you can use the built-in PowerShell help system to troubleshoot:
Get-Help *PSCustomObject*
Would have shown you exactly where you were going wrong in its final example.
I eliminated the errors. Now this is the second part that display the info as array. It doesn’t work right, it doesn’t show the info. Here is the second part following the original part above:
Foreach ($person in $people) {
Write-Output “$($person.Name) age$($person.age) work as $($person.occupation)”
}
I double check the typing this time.
Thanks
Well, the formatting is a bit off - your spaces are badly placed - but the code is correct and works for me. I am assuming you formatted it after copy/pasting and you don’t actually have curly quote marks in your code?
foreach ($person in $people) {
Write-Output "$($person.Name) age$($person.age) work as $($person.occupation)"
}
#output
John age30 work as engineer
Alice age25 work as designer
Bob age40 work as Manager
For the best help, when something doesn’t work, it really helps us if you can post the actual error text, formatted using the </> button. Just saying “It doesn’t work right, it doesn’t show the info.” isn’t very helpful.
Sorry, I really don’t see it. The only thing I see in your is you put a few spaces in front of the Write-Output. I tried that and it still comes out wrong. This is how it looks,
PS C:\Users\yungm> Foreach ($person in $people) {
>> Write-Output “$($person.Name) age$($person.age) work as $($person.occupation)”
>> }
age work as
age work as
age work as