Powershell大印象系列3 解惑,真相?补充一下2011-11-17 博客园 天天爱晴天这个文章主要是把一些Powershell经常让人觉得不习惯的地方,和一些内部处理的方式介绍一下。学 一门高级语言,经常会被它的方便,让你觉得云里雾里,不过我喜欢POWERSHELL的原因,是因为它是裸体 的(至少是若隐若现),呵呵,哪怕它没有公开它的源代码,但是却把实现的逻辑通过Trace-Command公 开了出来。好了,现在正是开始。我比较肤浅,所以说的东西也一样,但是希望有抛砖引玉的伟大作用。1. Return的作用我在想,会不会有人说,"啊?RETURN这么简单都讲?会编程的都知道."但是我还是忍不住,说一下在 POWERSHELL的RETURN的不同,一般的语言,"retrun"有终止函数和返回结果的作用.但是在 POWERSHELL,RETURN就只有前者.不过这个纯属推测,因为表象让人这样觉得.举个例子:
function bar { Write-Host "123" "567" return "234"} $result = bar
这个时候,Result里面会是什么呢?答案是一个数组,里面有567和234.因此可以推论,"567"这个本 来就有返回结果的能力,而RETURN "234"呢?就更像234;retrun的作用。那我们平常要怎样打运行过程的 信息出去呢?就要用WRITE-HOST啦。嗯嗯。2. ParameterBinding的真相运行这个语句Trace-Command -Name ParameterBinding -PSHost -Expression {Get-Process -Name *sql*}结果:
BIND NAMED cmd line args [Get-Process]BIND arg [*sql*] to parameter [Name]COERCE arg type [System.String] to [System.String[]]ENCODING arg into collectionBinding collection parameter Name: argument type [String],parameter type [System.String[]], collection type Array, element type [System.String], coerceElementTypeCreating array with element type [System.String] and 1 elementsArgument type String is not IList, treating this as scalarCOERCE arg type [System.String] to [System.String]Parameter and arg types the same.Adding scalar element of type String to array position 0Executing VALIDATION metadata:[System.Management.Automation.ValidateNotNullOrEmptyAttribute]BIND arg [System.String[]] to param [Name] SUCCESSFULBIND POSITIONAL cmd line args [Get-Process]MANDATORY PARAMETER CHECK on cmdlet [Get-Process]CALLING BeginProcessingCALLING ProcessRecordCALLING EndProcessing