PowerShell vs. the Unix Shell

powershellshellunix

I've heard some things about the features of the PowerShell. Some of it seems like typical features of Unix shells.

So it seems Powershell includes piping and the commandlets, similar to shell scripts. But I didn't try it yet (no Windows), so I may be wrong.

So my question is: Is Powershell similar to a Unix shell or is the concept different?
If the latter: In what points the concept differs?

Best Answer

PowerShell is superficially similar to Unix shells. PowerShell has aliases for many of the commands you are used to in Unix, like ls, rm, cp, mv, etc. However, the way that the cmdlets behind the aliases work is quite different.

In a *nix shell, everything is text based, so output from one command can be piped to another, but the receiving program must know how to parse/interpret the text from the pipeline. This is the main difference between PowerShell and *nix shells... in PowerShell, everything that gets passed around is an object.

The consequence of this is that piping from one command to another is not just piping stdout to stdin. It's piping a full-fledged .net object to the receiver. Therefore, the receiver just needs to know how to handle an object of that type. It doesn't need to implement any parsing of text, but it needs to understand how to call methods and properties (members) of the input object.

In a *nix command line program, you would write code that reads from stdin and parses its information from the text another program generated. In PowerShell, you would do something like this:

function changeName($myObject)
{
    if ($myObject.GetType() -eq [MyType])
    {
        #print the current name to screen
        $myObject.Name
        #change string in the 'name' property
        $myObject.Name = "NewName"
    }
    return $myObject
}

Calling this code on the command line might look like:

PS> $myObject = New-Object MyType -arg "OriginalName"
PS> $myObject = changeName $myNewObject
OriginalName
PS> $myObject.Name
NewName

You could also do the same as above using the piping mechanism, but you can see the major difference here in that we're passing an object and not text:

PS> $myObject = New-Object MyType -arg "OriginalName" | changeName
OriginalName
PS> $myObject.Name
NewName

Forgetting this major difference, I would say there are other superficial similarities, but mostly just syntactically. PowerShell syntax seems to have been designed with the *nix shell users in mind, so a lot of the language style is similar.

Related Question