powershellpowershell-core

What is ScopedItemOptions?


I've read some discussion on github metioned that Item cmdlets have Options. The only documentation I found is this


Solution

  • Are options only specific to Item cmdlets?

    They're specific to what the .NET doc describes: "for session state items like variables, aliases, and functions".

    What are these dedicated options for? To describe the state of the item under a PSDrive?

    Also described in the .NET doc: "The options that define some of the constraints...". The items that can have these constraints are under a Provider.

    If you wanted to check all types that have a property of type ScopedItemOptions, you could do:

    $target = [System.Management.Automation.ScopedItemOptions]
    [psobject].Assembly.GetTypes() |
        Where-Object IsPublic |
        Where-Object { $target -in $_.GetProperties().PropertyType }
    

    Or if you have ClassExplorer Module, this would give you a better look as it also includes the members:

    Find-Type -Namespace System.Management.Automation |
        Find-Member -ParameterType System.Management.Automation.ScopedItemOptions
    

    Are we allowed to specify some of options in custom function?

    Sure:

    New-Item 'function:Test-Function' -Value { 'foo' } -Options Constant
    function Test-Function { 'bar' }
    # Fails with Cannot write to function Test-Function because it is read-only or constant.
    

    If we could specify options for function, what are the cases that we would need it?

    Up to you, normally ScopedItemOptions is used more on PSVariables, but perhaps if you want a function that can't be overridden like the above example. Another example could be a function that is Private to the scope it was declared in and doesn't exist in other scopes, i.e.:

    New-Item 'function:Test-Function2' -Value { 'foo' } -Options Private
    Test-Function2       # Works
    & { Test-Function2 } # Doesn't exist here