Powershell pitfalls

后端 未结 21 1194
梦谈多话
梦谈多话 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:36
    # $x is not defined
    [70]: $x -lt 0
    True
    [71]: [int]$x -eq 0
    True
    

    So, what's $x..?

    0 讨论(0)
  • 2020-12-23 02:38

    This one has tripped me up before, using $o.SomeProperty where it should be $($o.SomeProperty).

    0 讨论(0)
  • 2020-12-23 02:42

    On Functions...

    • The subtleties of processing pipeline input in a function with respect to using $_ or $input and with respect to the begin, process, and end blocks.
    • How to handle the six principal equivalence classes of input delivered to a function (no input, null, empty string, scalar, list, list with null and/or empty) -- for both direct input and pipeline input -- and get what you expect.
    • The correct calling syntax for sending multiple arguments to a function.

    I discuss these points and more at length in my Simple-Talk.com article Down the Rabbit Hole- A Study in PowerShell Pipelines, Functions, and Parameters and also provide an accompanying wallchart--here is a glimpse showing the various calling syntax pitfalls for a function taking 3 arguments: function syntax pitfalls


    On Modules...

    These points are expounded upon in my Simple-Talk.com article Further Down the Rabbit Hole: PowerShell Modules and Encapsulation.

    • Dot-sourcing a file inside a script using a relative path is relative to your current directory -- not the directory where the script resides! To be relative to the script use this function to locate your script directory: [Update for PowerShell V3+: Just use the builtin $PSScriptRoot variable!]

      function Get-ScriptDirectory
      { Split-Path $script:MyInvocation.MyCommand.Path }
      
    • Modules must be stored as ...Modules\name\name.psm1 or ...\Modules\any_subpath\name\name.psm1. That is, you cannot just use ...Modules\name.psm1 -- the name of the immediate parent of the module must match the base name of the module. This chart shows the various failure modes when this rule is violated:

    module naming requirements


    2015.06.25 A Pitfall Reference Chart

    Simple-Talk.com just published the last of my triumvirate of in-depth articles on PowerShell pitfalls. The first two parts are in the form of a quiz that helps you appreciate a select group of pitfalls; the last part is a wallchart (albeit it would need a rather high-ceilinged room) containing 36 of the most common pitfalls (some adapted from answers on this page), giving concrete examples and workarounds for most. Read more here.

    0 讨论(0)
提交回复
热议问题