Powershell pitfalls

后端 未结 21 1360
梦谈多话
梦谈多话 2020-12-23 01:44

What Powershell pitfalls you have fall into? :-)

Mine are:

# -----------------------------------
function foo()
{
    @(\"text\")
}

# Expected 1, a         


        
21条回答
  •  伪装坚强ぢ
    2020-12-23 02:17

    Another one I ran into recently: [string] parameters that accept pipeline input are not strongly typed in practice. You can pipe anything at all and PS will coerce it via ToString().

    function Foo 
    {
        [CmdletBinding()]
        param (
            [parameter(Mandatory=$True, ValueFromPipeline=$True)]
            [string] $param
        )
    
        process { $param }
    }
    
    get-process svchost | Foo
    

    Unfortunately there is no way to turn this off. Best workaround I could think of:

    function Bar
    {
        [CmdletBinding()]
        param (
            [parameter(Mandatory=$True, ValueFromPipeline=$True)]
            [object] $param
        )
    
        process 
        { 
            if ($param -isnot [string]) {
                throw "Pass a string you fool!"
            }
            # rest of function goes here
        }
    }
    

    edit - a better workaround I've started using...

    Add this to your custom type XML -

    
    
      
        System.String
        
          
            StringValue
            
              $this
            
          
        
      
    
    

    Then write functions like this:

    function Bar
    {
        [CmdletBinding()]
        param (
            [parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True)]
            [Alias("StringValue")]
            [string] $param
        )
    
        process 
        { 
            # rest of function goes here
        }
    }
    

提交回复
热议问题