2

Why does the direct access of a static fail, but the indirect works? Note that the file loaded is valid in both examples.

Failure Using Direct To Static

class OpPrj {

[string] $ProjectPath

static [string] $configFile = 'settings.json';

[OpPrj] static GetSettings(){
   return [OpPrj](Get-Content [OpPrj]::configFile | Out-String|ConvertFrom-Json);
}

Works By Assigning to Local

class OpPrj {

  [string] $ProjectPath

  static [string] $configFile = 'settings.json';

  [OpPrj] static GetSettings(){
      $file = [OpPrj]::configFile
      Write-Host $file  # outputs settings.json
      return [OpPrj](Get-Content $file | Out-String | ConvertFrom-Json);
  }
5
  • Because your syntax is wrong: (Get-Content ([OpPrj]::configFile) | ... This is the way you need to reference static properties for any type (or enum!) when dealing with parameter binding, that is, wrapped in parens. I don't understand why the parser works that way here, but it does. Commented Mar 13, 2019 at 14:32
  • Shouldn't you be using the $this automatic variable instead of [OpPrj]::configFile ? Commented Mar 13, 2019 at 14:33
  • @Theo $this doesn't exist for static members because they exist on the type not the object. Commented Mar 13, 2019 at 14:33
  • @TheIncorrigible1 Ah, I didn't know that. Thanks for the heads-up. Commented Mar 13, 2019 at 14:34
  • @TheIncorrigible1 Put it as an answer, and I will mark it as such. thx! Commented Mar 13, 2019 at 14:37

1 Answer 1

3

You have a syntax error in your call to Get-Content:

Get-Content [OpPrj]::configFile

The PowerShell parser is unable to determine where this ends (I am uncertain of the reason), so you need to explicitly wrap it in parentheses (I also recommend being explicit about the parameter you're passing, especially in scripts, for readability):

Get-Content -Path ([OpPrj]::configFile)

You will need to follow this syntax for enums and static class members.


In all (your call to Out-String is unnecessary):

class OpPrj
{
    [string] $ProjectPath

    static [string] $ConfigFile = 'settings.json'

    static [OpPrj] GetSettings()
    {
        return [OpPrj](Get-Content -Path ([OpPrj]::ConfigFile) -Raw | ConvertFrom-Json)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Mr. Ohio...thank you for the info on Out-String too. :-)

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.