0

I have the following code example. I am just trying to print the value from a hashtable key.

function New-Article()
{
  param ($volume, $issue, $title)

  $article = @{}
  $article.volume = $volume
  $article.issue = $issue
  $article.title = $title

  return $article
}

$article = New-Article(1, 2, "Article Title")
Write-Host "Article title: $article.title" # Output = Article title: System.Collections.Hashtable.title
Write-Host "Article title: $($article.title)" # Output = Article title: 
Write-Host "Article volume: $($article.volume)" # Output = Article volume: 1 2 Article Title

$article = New-Article 1, 2, "Article Title"
Write-Host "Article title: $($article.title)" # Output = Article title: 

Edit added a line to test what is mentioned in the possible duplicate (relating to properties, not hashtables)

Edit Added more examples based on comments and answers

5
  • Possible duplicate of How can you use an object's property in a double-quoted string? Commented Sep 19, 2018 at 16:49
  • According to that answer, I can add $() around the variable to print (for properties anyway), that resulted in an empty string when used with a hashtable Commented Sep 19, 2018 at 16:50
  • stackoverflow.com/q/11060833 Commented Sep 19, 2018 at 16:54
  • Not sure how that is supposed to be relevant Commented Sep 19, 2018 at 16:57
  • Output: Article volume: 1 2 Article Title Commented Sep 19, 2018 at 16:59

1 Answer 1

4

You have 2 problems. In addition to enclosing the hashtable property access expression in a $(), you are invoking the function incorrectly. In powershell, arguments are passed to a function separated by spaces, with no brackets:

function New-Article()
{
  param ($volume, $issue, $title)

  $article = @{}
  $article.volume = $volume
  $article.issue = $issue
  $article.title = $title

  return $article
}

$article = New-Article 1 2 "Article Title"
Write-Host "Article title: $($article.title)"
Sign up to request clarification or add additional context in comments.

2 Comments

When I removed the parenthesis from the call to New-Article, it resulted in the same output
remove the commas too, the commas tell powershell to create an array.

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.