Welcome to MSDN Blogs Sign in | Join | Help

Comparative Examples in MSH and KSH

 

Most shells (such as Windows CMD.EXE and the UNIX shells SH, KSH, CSH, and BASH) operate by executing a command or utility in a new process, and presenting the results (or errors) to the user as text. Text-based processing is the way in which system interaction is done with these shells. Over the years, a large number of text processing utilities—such as sed, AWK, and PERL—have evolved to support this interaction. The heritage of this operational process is very rich.

MSH is very different from these traditional shells. First, this shell does not use text as the basis for interaction with the system, but uses an object model based on the .NET platform. Second, the list of built-in commands is much larger; this is done to ensure that the interaction with the object model is accomplished with the highest regard to integrity with respect to interacting with the system. Third, the shell provides consistency with regard to interacting with built-in commands through the use of a single parser, rather than relying on each command to create its own parser for parameters.

This document constrasts the Korn Shell (KSH) and MSH by providing a number of examples of each.

Example 1

To stop all processes that begin with the letter "p" on a UNIX system, an administrator would have to type the following shell command line:

$ ps -e | grep " p" | awk '{ print $1 }' | xargs kill

The ps command retrieves list of processes and directs (|) the grep command to determine which process begins with "p"; which in turn directs (|) the awk command to select the 1st column (which is in the process id) and then passes (|) those to the xargs command which then executes the kill command for each process.  The fragility of this command line may not be evident, but if the ps command behaves differently on different systems, where the "-e" flag may not be present, or if the processed command is not in column 1 of the output, this command-line procedure will fail.

MSH:

MSH> get-process p* | stop-process

Thus, the command line may now be expressed as "get the processes whose name starts with "p" and stop them".  The get-process Cmdlet takes an argument that matches the process name; the objects returned by get-process are passed directly to the stop-process Cmdlet that acts on those objects by stopping them.

The second, more convoluted example, which stops processes that use more than 10 MB of memory becomes quite simple.

Example 2

Another, even more complex example, such as "find the processes that use more than 10 MB of memory and kill them" can lead to an equally failed outcome:

$ ps -el | awk '{ if ( $6 > (1024*10)) { print $3 } }' | grep -v PID | xargs kill

The success of this command line relies on the user knowing that the ps -el command will return the size of the process in kilobytes (kb) in column 6 and that the PID of the process is in column 3.  It is still required that the first row is removed.

Comparing Example 1 using a standard shell to Example 1a using MSH, we can see that the commands act against objects rather than against text.

MSH:

MSH> get-process | where { $_.WS -gt 10MB } | stop-process

There is no issue about determining the column that contains the size of the process, or which column contains the ProcessID.  The memory size may be referred to logically, by its name.  The where Cmdlet can inspect the incoming object directly and refer to its properties.  The comparison of the value for that property is direct and understandable.

Example 3

For example, if you wanted to calculate the number of bytes in the files in a directory, you would iterate over the files, getting the length and adding to a variable, and then print the variable:

$ tot=0; for file in $( ls )

> do

>     set -- $( ls -log $file  )

>     echo $3

>     (( tot = $tot + $3 ))

> done; echo $tot

This example uses the set shell command that creates numbered variables for each white space separated element in the line rather than the awk command as in the examples above.  If the awk command were used, it would be possible to reduce the steps to the following:

$ ls –l | awk ‘{ tot += $5; print tot; }’ | tail -1

This reduces the complexity, but requires specific knowledge of a new language, the language that is associated with the awk command.

The MSH loop is similar; each file in the directory is needed, but it is far simpler as the information about the file is already retrieved:

MSH:

MSH> get-childitem | measure-object -Property length -Sum

The measure-object Cmdlet interacts with objects and if it is provided with a property from the object, it will sum the values of that property.  Because the property length represents the length of the file, the measure-object Cmdlet is able to act directly on the object by referring to the property name rather than “knowing” that the length of the file is in column 3 or column 5.

Example 4

Many objects provided by the system are not static, but dynamic.  This means that after an object is acquired, it is not necessary to acquire the object at a later time.  The data in the object is updated as the conditions of the system change.  Also, changes to these objects are reflected immediately in the system.

As an example, suppose one wanted to collect the amount of processor time that a process used over time.  In the traditional UNIX model, the ps command would need to be run iteratively and the appropriate column in the output would need to be found and then the subtraction would need to be done.  With a shell that is able to access the process object of the system, it is possible to acquire the process object once, and since this object is continually updated by the system; all that is necessary is to refer to the property.  The following examples illustrate the differences, where the memory size of an application is checked in ten second intervals and the differences are output:

$ while [ true ]

do

   msize1=$( ps -el | grep application | grep -v grep | awk '{  print $6 }' )

   sleep 10

   msize2=$( ps -el | grep application | grep -v grep | awk '{  print $6 }' )

   expr $msize2 - $msize1

   msize1=$msize2

done

MSH:

MSH> $app = get-process application

MSH> while ( 1 ) {      

>> $msize1 = $app.VS

>> start-sleep 10

>> $app.VS - $msize1  

>> }

Example 5

It is even more difficult to determine whether a specific process is no longer running.  In this case, the UNIX user must collect the list of processes and compare them to another list. 

$ processToWatch=$( ps -e | grep application | awk '{ print $1 }'

$ while [ true ]

> do

>     sleep 10

>     processToCheck=$(ps -e | grep application | awk '{ print $1 }' )

>     if [ -z "$processToCheck" -or "$processToWatch" != "$processToCheck" ]

>     then

>        echo "Process application is not running"

>        return

>     fi

> done

MSH:

MSH> $processToWatch = get-process application

MSH> $processToWatch.WaitForExit()

As is seen in this example, the MSH user need only collect the object and then subsequently refer to that object. 

Example 6

For example, suppose the user wanted to determine which processes were compiled as PreRelease code, such as when applications have been compiled in such a way to mark them as "PreRelease".

$ ???

This information is not kept in the standard UNIX executable.  To determine this information, one would need to have a set of specialized utilities to add this information to the binary and then another set of utilities to collect this information.  These utilities do not exist; it is not possible to accomplish this task.

MSH:

MSH> get-process | where {$_.mainmodule.FileVersioninfo.isPreRelease}

Handles  NPM(K)    PM(K)      WS(K) VS(M)   CPU(s)     Id ProcessName

-------  ------    -----      ----- -----   ------     -- -----------

    643      88     1024       1544    15    14.06   1700 AdtAgent

    453      15    25280       7268   199    91.70   3952 devenv

In this example, a cascade of properties is done.  The appropriate property from the process object (MainModule) is inspected, the property "FileVersionInfo" is referenced (a property of MainModule) and the value of the property "IsPreRelease" is used to filter the results.  If IsPreRelease is true, the objects that are output by the get-process Cmdlet are output.

Example 7

Each object may or may not provide methods; MSH provides commands to aid the discovery of methods that are available for a specific object via the get-member Cmdlet.  For example, the string object has a large number of methods:

MSH:

MSH> get-member -input "String" -membertype method | format-table "$_"

"$_"

---------

System.Object Clone()

Int32 Compare(System.String, System.String, Boolean, System.Globalization.Cul..

Int32 CompareOrdinal(System.String, Int32, System.String, Int32, Int32)

Int32 CompareTo(System.String)

System.String Concat(System.String, System.String)

Boolean Contains(System.String)

System.String Copy(System.String)

Void CopyTo(Int32, Char[], Int32, Int32)

Boolean EndsWith(System.String, Boolean, System.Globalization.CultureInfo)

Boolean Equals(System.String, System.StringComparison)

System.String Format(System.String, System.Object, System.Object)

Char get_Chars(Int32)

Int32 get_Length()

System.CharEnumerator GetEnumerator()

Int32 GetHashCode()

System.Type GetType()

System.TypeCode GetTypeCode()

Int32 IndexOf(System.String, Int32)

Int32 IndexOfAny(Char[], Int32, Int32)

System.String Insert(Int32, System.String)

System.String Intern(System.String)

System.String IsInterned(System.String)

Boolean IsNormalized()

Boolean IsNullOrEmpty(System.String)

System.String Join(System.String, System.String[])

Int32 LastIndexOf(Char, Int32)

Int32 LastIndexOfAny(Char[], Int32)

System.String Normalize(System.Text.NormalizationForm)

Boolean op_Equality(System.String, System.String)

Boolean op_Inequality(System.String, System.String)

System.String PadLeft(Int32, Char)

System.String PadRight(Int32, Char)

System.String Remove(Int32)

System.String Replace(System.String, System.String)

System.String[] Split(System.String[], System.StringSplitOptions)

Boolean StartsWith(System.String)

System.String Substring(Int32)

Char[] ToCharArray(Int32, Int32)

System.String ToLower()

System.String ToLowerInvariant()

System.String ToString(System.IFormatProvider)

System.String ToUpper(System.Globalization.CultureInfo)

System.String ToUpperInvariant()

System.String Trim()

System.String TrimEnd(Char[])

System.String TrimStart(Char[])

As can be seen, 46 different methods are available to the string object all of which are available to the MSH user.  Unfortunately, the semantics of these methods is not visible from the shell, but a number of .NET object help is available online.

Example 8

The availability of these methods creates an explosion of possibilities.  For example, if I wanted to change the case of a string from lower to upper I would do the following: (first ksh and then MSH).

$ echo "this is a string" | tr [:lower:] [:upper:]

or

$ echo "this is a string" | tr '[a-z]' '[A-Z]'

MSH:

MSH> "this is a string".ToUpper()

The UNIX example relies on the tr cmdlet. 

Example 9

For example, suppose the string "ABC" was to be inserted after the first character in the word "string" to have the result "sABCtring".  Here are the following, first with ksh, then with MSH:

$ echo "string" | sed "s|\(.\)\(.*)|\1ABC\2|"

MSH:

MSH> "string".Insert(1,"ABC")

Both examples require specific knowledge; however, using the "insert" method is more intuitive than using the capture buffers available in sed.  Moreover, the domain specific knowledge of the "sed" language required may be somewhat more advanced than is required to use the Insert method.





Jim Truher and Jeffrey Snover

[Edit: Monad has now been renamed to Windows PowerShell. This script or discussion may require slight adjustments before it applies directly to newer builds.]

PSMDTAG:FAQ: KSH BASH - how does PowerShell compare to KSH and BASH?
PSMDTAG:DOTNET: Leverage System.String to do KSH/BASH type functions.

Published Tuesday, April 25, 2006 5:18 PM by PowerShellTeam
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Reflections » Cool post on MSH

Monday, May 01, 2006 8:39 PM by Reflections » Cool post on MSH

# Quiddit.ch » Blog Archive » Windows PowerShell

Sunday, May 07, 2006 11:42 AM by Quiddit.ch » Blog Archive » Windows PowerShell

# re: Comparative Examples in MSH and KSH

It looks like the PowerShell is an Object Oriented view of System. But still: is there really something new? I thing all that we already saw somewhere around (AmigaOS, unix/linux, MacOS). We have to wait for applications to start support it (implement methods), then it start to be very interesting.

Friday, October 20, 2006 4:38 PM by Jan

# re: Comparative Examples in MSH and KSH

Isn't the first argument (that 'ps' may behave differently on different systems) silly? Windows is one system, so of course you don't have subtle interoperability problems. 'ps' doesn't work the same for Windows as it does for Unix either; it doesn't work at all! On the other hand, if you're POSIX, this stuff has to work the same way for the same switches (in addition to the vendor's superset of commands for ps, ls, etc)

Example 3 isn't so good either. One would simply use 'du' in that situation.

Example 4 really do the same thing the same way; the only difference is notation. Give me the time now and find the difference. Either way, you had to figure out how to get that metric and fetch it twice.

Example 6 has nothing to do with any Unix shell.

I'm not saying that PowerShell isn't a step forward (I don't know yet, I plan on playing with it at work...but anything beats cmd or wsh), but these arguments are bogus.

Monday, October 30, 2006 2:38 PM by Dave

# re: Comparative Examples in MSH and KSH

Hello,

Easier way to do...

Example 1 :

=> use pkill

# pkill -9 vi

[1]   Killed                  vim

[2]   Killed                  vim

Example 3 :

user du

# du -sh /opt

 18M   /opt

Wednesday, November 15, 2006 7:30 AM by Lex

# re: Comparative Examples in MSH and KSH

Example 3

For example, if you wanted to calculate the number of bytes in the files in a directory, you would do that with MSH:

MSH> get-childitem | measure-object -Property length

Where you just need to call the "du" command in a standard shell:

SH> du

Wednesday, November 15, 2006 12:45 PM by Example 3

# re: Comparative Examples in MSH and KSH

Is their a method to store the result of a get-childitem (or any other command) who should be reusable in the same way as the original result ?

With a standard shell this two commands have same result:

ls|mycommand

and

ls > file

cat file|mycommand

So you can store the result of a command and resuse it later in the same way. Is it possible with PowerShell ?

In this case, is the stored data human readable ?

Do you plan to provide a better terminal emulator than cmd.exe ?

Should MSH be usable in any other terminal emulator like bash, ksh and others do ?

I'd like to add an alias on one of my network interfaces with a new IP address, to set a firewall rule that allow access to port 80 on this address, and then to add a VirtualHost on my IIS server with this IP address. How to with MSH ?

Wednesday, November 15, 2006 4:36 PM by Real life examples

# re: Comparative Examples in MSH and KSH

"cmdlet" ? Since when is this suffix back in style ? Don't you have people in your company whose job is to prevent developpers to use lame suffix ?

Now, excuse-me, but I'm going to take my breakfastlet and then have a showerlet before I go to worklet have my joblet done.

Saturday, November 18, 2006 2:30 AM by omelet

# re: Comparative Examples in MSH and KSH

Very good job by MS. The power of .NET in the fingers of the Windows Administrators.

Sunday, November 19, 2006 5:48 AM by Antonio

# re: Comparative Examples in MSH and KSH

This article want to treat UNIX as a bad thing willfully. There're much simplier solutions like pkill and du commands instead of using awk and OS dependent parameteres of ps, and such. Also please note that even the whole terminology used by Windows nowdays was created by UNIX, eg the filesystem with directories (the notion of directory, or folder or whatever you want they to be called), device nodes as files, pipes (|), etc. Other stuffs are ripped from CP/M, like device letters (C: ...) FCBs and such. So this powershell stuff is good, but don't treat it as a brand new feature which is the default think in UNIX for dozens of years, also do not try to mystify UNIX CLI that it's overcomplicated when there're simple solutions though they're not in this article ... (even simplier than powershell can provide ...).

Monday, December 11, 2006 3:44 AM by Z

# re: Comparative Examples in MSH and KSH

Please send the PowerShell team to a KSH training before creating such examples!

Monday, December 11, 2006 3:47 AM by Tester

# re: Comparative Examples in MSH and KSH

Oh, almost forget: please do not allude to the statement that UNIX has many incomaptible implementations: Windows is much more incomaptible for many standards we have, so it's quite false viewpoint :) Also, you can use much more common and compatible and even simplier solutions like eg pkill than using awk/ps/etc mixed together which - no doubt - requires more knowledge to use of course. Please do not misunderstand me: I don't say powershell and/or Windows are evil. I only say that nobody should say false statements to try to make people think that Windows and its solutions are superior without introduce the GOOD solutions for these problems in UNIX, too.

Monday, December 11, 2006 3:50 AM by Z

# re: Comparative Examples in MSH and KSH

Well, considering how MS bashed Unix into the ground, now they are 'reinventing' the Shell...Oooooo...I bet all the Windows admins will be like, "Wow, MS is awesome, look at this sweet command line stuff we can do now!  I bet those UNIX guys wish they could do this."

History repeats itself...MS just can't get away from UNIX...UNIX is still around today (including Linux) for a good reason!

UNIX/Linux = Nanometer Legos

Windows = Duplos

First they ignore you.

Then they laugh at you.

Then they fight you.

Then you win.

Ah yes, words of wisdom!

Wednesday, December 13, 2006 4:37 PM by Ryan

# re: Comparative Examples in MSH and KSH

> First they ignore you.

> Then they laugh at you.

> Then they fight you.

> Then you win.

I can't tell whether you are at the "laughing at us" or the "fighting us" stage.  :-)

Jeffrey Snover [MSFT]

Windows PowerShell/MMC Architect

Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell

Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Thursday, December 14, 2006 12:04 AM by PowerShellTeam

# re: Comparative Examples in MSH and KSH

Lets be honest, Powershell uses an excellent new paradigm.  It borrows much from unix etc but adds much also.  

However, when doing comparative analysis let's make sure the examples given are reasonable.  

Powershell has much to recommend it, and can hold it's own is a fair comparison.  It's case is hindered by not doing a fair comparison.  

Thursday, December 14, 2006 6:52 AM by Michael Lewis (Thomson Corp)

# re: Comparative Examples in MSH and KSH

> Lets be honest, Powershell uses an excellent new paradigm.  It borrows much from unix etc but adds much also.  

We have deep respect for Unix.  We were cetainly influenced by it but we were also very strongly influenced by VMS and AS400 (those engineers did some superstar work as well).  We are able to do what we do because we are standing on the shoulders of giants.

> It's case is hindered by not doing a fair comparison.  

We believe that it is a fair comparison but, as always, we may be wrong.  Please post counterexamples.

Jeffrey Snover [MSFT]

Windows PowerShell/MMC Architect

Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell

Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Thursday, December 14, 2006 8:53 AM by PowerShellTeam

# re: Comparative Examples in MSH and KSH

Is there any "&" (run job in background) equivalent in powershell?

Example:

   ping -n 50 10.0.2.1 > /dev/null &

   ping -n 50 10.0.2.1 > /dev/null &

   ping -n 50 10.0.2.1 > /dev/null &

   ping -n 50 10.0.2.1 > /dev/null &

   wait

   echo "Pings done"

Thanks in advance!

Friday, December 29, 2006 12:53 PM by Craig Anderson

# re: Comparative Examples in MSH and KSH

> Is there any "&" (run job in background) equivalent in powershell?

Not in V1 but you can achieve the same semantics using NEW-JOB, a script from Jim Truher: http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry

Jeffrey Snover [MSFT]

Windows PowerShell/MMC Architect

Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell

Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Friday, December 29, 2006 1:47 PM by PowerShellTeam

# re: Comparative Examples in MSH and KSH

I have programmed in multi os environments for many years (win and unix). While I like some of MS apps (sql server and .net) the winos platform has always been archaic compared to unix for getting work done. I think a true 'shell' language is sooooo over due. I truly hope that Powershell is even close to the power of kshell, bash, etc. However, these days I usually just use Perl to get 'real work done' efficiently, :-). Even has a built-in debugger, primitive, but useful.  

My suggestion before you post comparative examples is that you should have them written by someone that is knowledgeable about the technologies used because whomever wrote these examples clearly are not very skilled, unless of course they were purposely written so that Powershell would look sooo much better. For example, in unix you don't go writing a script when you can just use a built-in command like 'du' and piping the output of awk into grep (excuse me, are you braindead!) awk can very well do that indicating the author was not very awk savvy.

Friday, February 23, 2007 2:52 PM by jj

# re: Comparative Examples in MSH and KSH

Which version of ksh were you comparing against?  The latest, ksh93s has some great features, and has far more built-ins than the old ksh88.  Likewise, bash has a lot more built-ins than older shells.

BTW, if you want to annoy a Perl person, call it PERL.

Wednesday, February 28, 2007 10:04 AM by Clive Darke

# re: Comparative Examples in MSH and KSH

> ps -e | grep " p" | awk '{ print $1 }' | xargs kill

BTW, most of the time, you don't have to use "grep" when you use "awk". This command does the same:

> ps -e | awk '/ p/ { print $1 }' | xargs kill

That's basic awk ;)

Monday, March 12, 2007 4:05 PM by Nicolas

# re: Comparative Examples in MSH and KSH

I was very impressed when reading about PowerShell, until I read this article.  I have the same mixed feelings here (great product, sneaky marketing) as I have with other Microsoft tools.

Still, I will assume that the authors of these comparisons are not very knowledgeable about UNIX system administration, because I'd rather not believe this was a "stacked" comparison.

What we need is for the proponents of this tool to provide practical comparisons about how to get work done with PowerShell vs. bash, ksh, etc.  Even better would have been if Microsoft has come up with a way to integrate the UNIX utilities into their environment so that UNIX system administators would have had an easier time migrating skills, and this should have happened much earlier than it was attempted.

I can give a specific example of a problem I have encountered with PowerShell.  I use the "less" command ported to Windows on my XP box at home.  I haven't figured a way to get the "PAGER" environment variable to register with Powershell.  Also, I have noticed that Powershell sometimes sends gobbledygook into "Less" when the returned data is large.

I believe this tool ought to be designed in such a way as to increase the synergy between Windows admins and Unix admins' skills, as tends to be the case between different varieties of UNIX these days.  For example, how easy will it be to convert the trillions of Linux or Unix shell scripts, which use many tools not mentioned in the comparisons, to PowerShell scripts?  And vise versa?

All that said, I am inpressed with PowerShell, and hope to see people develop lots of useful scripts to run on it.

Thursday, April 19, 2007 12:59 PM by Chuck

# re: Comparative Examples in MSH and KSH

Chuck was excessively generous.  Microsoft is afraid to make Linux/Unix skills transferrable.  Microsoft believes Open Source is their enemy.  .BAT files used to be not so bad, but they've been continuously dumbed down throuh the years.  Obviously some programmers at Microsoft got annoyed by their lame shell and came up with something better.  They could have given us ksh or csh like Cygwin, but that would be admitting that Linux has long done what MS long ago lost.  So they need to reinvent the wheel in such a way as to try to keep Microsoft skills as distinct as possible from Linux skills.  I like free-BSD underneath Max OS X.  It's eminently doable by MS, but they are too defensive to do it.  Too bad.  Prove me wrong guys -- Give me a native korn shell under Windows.

I'm a professor by the way, and I won't teach my studs. MS skills, because it is in the company's interests to keep changing their tools so you have to keep buying product.  This may be fine for professional programmers, but it leaves technical users having to invest way too much time in staying up to date to learn the latest incantation for what they could do 10 and 20 years ago. I tell my students that their Linux chops will last a lifetime.  \

Again -- Prove me wrong guys

Sunday, May 13, 2007 1:16 AM by Richard Sonnenfeld

# Try designing tools for enthusiasts instead of pros

Hi -- I'll be more pleasant now.  Reading back all the posts bashing Mr. Snover and the Powershell -- and I see he's taking a lot of flack like a man!

I stand by my technical comments though, and I'll add context.  I've been doing computing for 30 years, on VM/CMS ,CPM ,VAX, DOS, OS2, AIX, Windows and Linux.  It has always been from a science/engineering perspective -- programming or shell-scripting to make me more productive at what I was actually being paid to do, rather than developing code or tools for sale. Therefor I cannot afford to become expert in every new tool that comes along, and to the extent that the next tool or shell is something I already know, it is a huge advantage for me.  I don't think I am alone.  I've noticed my students know less about programming than I did 30 years ago, and I think that all this GUI stuff and constant change has disconnected them from the machine so they cannot engage.  

I don't oppose creative programmers providing us with better tools.  I don't suggest using Fortran now that I can use Python.  I certainly don't think the kornshell is so great -- it's pretty annoying sometimes, but never underestimate the value of "mindshare".  If I already know it, I'll use your version of it.  Try to tell the marketing geeks that for us -- will you?

Good luck -- I'm sure your spirits stay up because you can always compare your salary to that of the posters here!

Sunday, May 13, 2007 1:40 AM by Richard Sonnenfeld

# re: Comparative Examples in MSH and KSH

Looks like the author started his programming straight from power shell without any experience in unix. He seems to have missed

a whole bunch of commands/utilities in unix

... pgrep, pkill, df, du, awk ...

Ya more marketing than good technical comparison. Whenever I read about power shell commands, it looks too suspiciously friendly

to me. You can do certain things too easy at

the cost of making certain other things impossible to do.

Tuesday, May 15, 2007 3:36 AM by somename

# re: Comparative Examples in MSH and KSH

Looks like an old article, but I would still like to comment.

First... your not comparing MSH to the Korn Shell at all, your comparing it to how well the command line utilities are in Unix.  The shells in unix are so powerful because of their substitution, piping, multitasking and scripting abilities.

Can MSH do this:

#!/bin/ksh

# loop forever

while true

do

   for file in /path/to/directory/*

   do

        export file

       # run a subprocess

       (HOST=hostname

       USER=user

       PASS=password

       exec 4>&1

       ftp -nv >&4 2>&4 |&

       print -p open $HOST

       print -p user $USER $PASS

       print -p cd /remote/directory

       print -p bin

       print -p put $file

       print -p bye

       wait)

   done

   sleep 600  # ten minutes

done

I doubt it.

On the plus side though... I love the .Net runtime.  I think its one of the best development environments to come around in a long time.

Giving a "Unix and Windows" admin an actual shell for windows is a great idea, its like taking a part of home with you on vacation :)

I am looking forward to actually installing this and being able to telnet/ssh to a windows server and actually accomplish something useful.

Thursday, May 24, 2007 7:46 PM by Nigel Benns

# re: Comparative Examples in MSH and KSH

A new crazy thing from MS. Instead of saying that this is some innovation named Power Shell, I would rather call it that due to increasing price of .NET IDE people can now use a scrapped down version of a crapy language called VBScript from the shell itself.

Friday, June 08, 2007 3:23 AM by Rahul Agrawal

# re: Comparative Examples in MSH and KSH

My PowerShell takes nearly 1 second to give me a prompt. Now that is progress! And it ignores %HOME%, why!?

Saturday, July 14, 2007 8:38 AM by FOO

# re: Comparative Examples in MSH and KSH

What I don't understand... Why reinvent the wheel? Why not just incorporate the bash shell into Windows, then add on to that? Honestly, bash is 90% what keeps me using Unix instead of windows.

Thursday, August 02, 2007 3:55 PM by Heiths

# re: Comparative Examples in MSH and KSH

If you're going to learn a completely new lexicon of tokens that make up the Powershell 'language' .. why not just learn C# and be doing this stuff programatically in an elegant language?

Powershell looks more like line-noise than line-noise does, and the users you're hoping to placate by transitioning away from VB for incidental scripting are only going to become more sullen about what their options are.

I won't waste anyone's time comparing apples and oranges with Powershell vs. any existing Windows or Unix shell, really what people should compare it to is C#, since it's an "object oriented scripting language".. No existing Unix 'shell' has this type of functionality, Unix shells plus interpreted scripting languages like Python or Perl sure, but nothing that really looks like this as a direct interface to OS objects.

* Getting free disk space using WMI ...

Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName . | Measure-Object -Property FreeSpace,Size -Sum

*

In C#, this is:

System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");

Plus, you get the benefit of object property/method expansion and VS.NET wrapped around it..

Seriously guys what were you thinking? The idea of a shell that allows you to pass objects between filters is _great_ but this execution doesn't meet the level of quality that programming C# provides or the level of simplicity that VB provides.

Friday, August 17, 2007 9:46 PM by Nathan Ramella

# re: Comparative Examples in MSH and KSH

All I want to do is be able to run a single

script from a SIGNED file.  Why should I have

to download 354 MB of the .NET SDK in order to

find a tool that will sign a cmdlet file?

Why can I not find a download page for

makecert.exe all by it's flippin self?

I'm starting to think your powershell is

a hoax created to make people fear to do

any scripting at all in Windows.

Microsoft! hort gut zu: give us a way

directly ot self-sign a cmdlet without

downloading reams more MSDN libs or this

thing ain't usable.  Why is it that

Usability and Microsoft are like

Oil and Water?

Sunday, September 09, 2007 2:29 PM by PS

# re: Comparative Examples in MSH and KSH

I have read all comments and the majority is a big critisism. The only one think I would appriciate - for .NET familier developers - it would be easier to learn. But why should I use PowerShell when UNIX utilities for Windows works perfect and if I would like to use C# ... then I use C# script NOT PowerShell!

Wednesday, October 17, 2007 5:20 AM by Libor

# re: Comparative Examples in MSH and KSH

Re: For example, suppose the user wanted to determine which processes were compiled as PreRelease code, such as when applications have been compiled in such a way to mark them as "PreRelease".

This is not quite accurate.  What you're actually saying is to check whether something compiled by a particular compiler holds symbols.  In this case, you're talking about VS.  If you use GCC, there are easy ways to check if GCC is holding debug symbols or not.  One easy way to do this with GCC is do something like the following:

echo "quit" | gdb --quiet $EXECNAME | grep -c "no debugging symbols found"

One line of script to check this.

If you wanted to add a way to check for a certain build, a common way is to add a static array of characters into the executable that identify this.  There are multiple tools that work off of this concept and can easily extract the information.  Again, though, generally what you're asking is a feature of the compiler, not the shell.  That being said, extracting an array of characters is a technique that could be used across all compilers.  It brings back the age old question, why do something the MS-specific way when there's a way that can work in all cases and is easier to understand?

If the claim is an MS product gives you better access to MS object models, I think we'll all likely agree.  However, the honest truth is that it's not useful unless you need MS object models.  Even then, what's the advantage of using PowerShell to any of the other .Net scripting languages, which also would give the same access to .Net?

Monday, October 29, 2007 8:51 AM by Slash

# re: Comparative Examples in MSH and KSH

what patents have you guys dreamed up for this? I'd like to kill them all with prior art. Seriously, PS looks like a long over-due decent shell Windows, which is great. But you don't fool anybody by pretending this is "innovative". Even the object-oriented idea is not new:  look at Plan-9, or BeanShell (which is I think closer to home, being a JVM shell with object hooks into the API... quite like PS's hooks into the CLI API).

I will play with it, since it stands a much better chance of actually being installed on work's servers (hell will freeze before the mgt let me install cygwin on a production box, paranoid androids...), but it's about as new as everything else from MS (that is, you guys still playing catch-up).

It feels a lot more like VMS to me, than Unix, btw. Which makes sense, since WNT + 1 = VMS. At least you're starting to admit that the Registry is a hairbrained idea and giving us good access to it via namespaces, so that they appear like files after all! That one's laudable (and laughable).

Wednesday, November 21, 2007 10:40 PM by mike

# re: Comparative Examples in MSH and KSH

I want to use powershell, but when I need hours to find out how I can implement this:

if exist .\test.txt del .\test.txt

in PS ... Frustrating.

Is there comparative examples for the CMD shell ?

Tuesday, November 27, 2007 10:42 AM by Matthias Steller

# re: Comparative Examples in MSH and KSH

I'm moving from a longtime job using Unix/Linux to an XP world.  In my previous incarnation, I leaned heavily on simple ksh or bash jobs made on the fly, maybe a half dozen times/day; these were the core or my productivity.  Installing cygwin or even Unix Tools on the machines I work with isn’t an option.  I will so miss sed and awk :(

The big attractions of PS for me are:

- Runs on the vast array of remote systems infested with a non-POSIX OS, and

- I can leverage some Unix skills and power using PS aliases

Primary complaints:The alias list is so incomplete, and those that do exist are only partially equivalent, eg ‘diff’.  Underlining this, even the PS examples above can be simplified using supported aliases, e.g. ‘ps y* | kill’.

Saturday, December 01, 2007 12:25 PM by Rob H

# re: Comparative Examples in MSH and KSH

This object-vs-text pipeline is really interesing.  But how would I go about mixing properties from 2 different objects accessed in a script to create a third object?

Tuesday, December 04, 2007 4:51 PM by Chuck Bermingham

# re: Comparative Examples in MSH and KSH

Back in April, Chuck wanted a way to make "less" his "PAGER". Since things such as the function "man" explicitly reference the command "more.com", you need to set 2 aliases to make "less" work everywhere:

set-alias more less

set-alias more.com less.exe

Cheers! -RPM

Friday, December 21, 2007 1:37 PM by Ross Mohn

# re: Comparative Examples in MSH and KSH

I was wondering if I have a couple of files with tablular info is there an easy way to extract only certain colum(s) and extract only certain rows. And then maybe stich them into one big table assuming number of rows is same in all files.

Friday, January 18, 2008 6:45 PM by Sharbat

# re: Comparative Examples in MSH and KSH

Exceptional Microsoft bad faith at work..

Astonishing!

dot sourcing?  WOW! Not THIS is revolutionary...

Ah but yes, you are right, you didn't mention 'dot sourcing' in this article. Sorry I read too many thing on powershell tonight, I had to vent somewhere and this insult to my intelligence of a comparison article is just that.

For other readers who might not have had the chance to read elsewhere, YES, you can now call a batch by sourcing it. ". batch.ps1".

but beware, it may overwrite variables if done on the command line...

Guys at MS never understood that sourcing, used in bash and other Linux shells, is used for calling configuration within a script, thus setting variable is the whole point to it... and it wasn't meant to be used on the commandline, like PS is doing.  At least get the whole point of a function before implementing it...

Instead of this outright rip off of conceptual ideas being developed for years, you should have made a call JPSoft way and BUY 4DOS/4NT/TakeCommand which I have been using since DOS v4, when MS brought the oh-so-innovative move.com just another shame when you realize that it should have been in internal command calling (copy) and (delete) as this is truly what this command was doing.

But enough with history.  This is 2008 and you won't fool much people into thinking you are inventing something, much like it has always been done before, mkay?

Tuesday, January 29, 2008 12:01 AM by Jerome Gauthier

# re: Comparative Examples in MSH and KSH

It's apples and oranges.  I've use dos/wsh/bash/ksh/csh/perl/etc etc. since they were invented.  This is mainly an admin language that they tied jscript/vbscript/etc into.  I think it rocks.  Have you check out the scriptomatic and other helpers?  There's a nice GUI out there too.

Monday, February 04, 2008 2:24 PM by zev dero

# re: Comparative Examples in MSH and KSH

You sense trouble whenever you have people comparing a piece of software which they write with something they probably don't know (or are pretending) the full features of.. A simple example would be of you trying to use ps without the -o pid= option and waxing eloquent about complicated command lines...

Yes, ps behaves differently on different systems, but well, you just have a single app here.. Allow competitors to write their own "PowerShells" for 10 years, and you will see varied differences in the object models for the process object.. you would $_.WS in one, $_.ws in another, and $_.workingSet in the third, and you are back to the same problem. And well, you have a common denominator for all these commands in unices, called POSIX, and you can expect to get that interface in any compliant UNIX system.

Having an object model isn't a panacea. You have troubles which you would never perhaps encounter in a text-based flow, like in the shell. You have interfaces, versioning, incompatibility, and on and on... its just that they have one name called formatting differences in text...

The other flaw seems to be that you seem to be comparing interfaces which are decades old in UNIX with what you have just developed, blissfully ignoring some of the newer shells like zsh which are way more powerful than sh/ksh. You wanted to kill that process starting with p? I do kill p<Tab> and programmatic autocompletion does the rest for me. isn't that better than get-process p* | stop-process? You seem to have ignored the interactive aspect of shells altogether in the comparison. I am not undermining you guys.. you guys have done a good job at this effort, but please don't undermine the presence of such features when putting them under the blanket of 'UNIX shells'.

Yes, readability is important, but well, everyone has his cup of tea. I am a regular user of UNIX shells, and I have used WSH in the past, its just that many a times, the verbose syntax you potray becomes just painful many a times for some...

All that you have demonstrated by comparing examples is shown the presence of some of the commands (methods of objects, as you would prefer it) in MSH, which you think are not there in UNIX (But there might be, as an user above has pointed out for du). But the point here is that you are comparing two *shells*, not the utilities which come. It is going to take less than a few minutes for anyone to put in that script and bundle it up as a wait_for_process. You find it easy to package it because you have just one application which understands it, namely PowerShell. POSIX on the other hand has the approach of putting in minimal required functionality as the common denominator, leaving it to the others to build stuff on top of it. And as your target audience, the system administrators, would agree, simpler is surely better!

Sunday, February 17, 2008 4:24 PM by Ramkumar

# re: Comparative Examples in MSH and KSH

Further to others pointing out better ways of doing Example 1:

The *n*x command as described may actually kill the shell you're running it from!

Viz., the [incorrect] grep " p" picks up the "pts/0 bash" process.

Monday, March 03, 2008 7:13 AM by Anonymous

# re: Comparative Examples in MSH and KSH

Well, if you fork example 5 from your shell in bash

computer:~ user$ sleep 10&

[1] 3798

computer:~ user$ wait

easy!

RE: Example 4

this can cause a headache, as your objects can move under your feet.

Powershell is important for windows as it has never had a decent shell - but why not simply implement a normal POSIX shell, or grab one of the many available shells that are out there.

You might even be able to fork off some of the Public domain stuff and save a lot of development effort.

Finally it seems odd that you don't include the manuals to things offline. I do a lot of script writing whilst in transit (trains, aircraft etc) - man has to be one of the more used commands of mine and it saves my bacon many many times. I often need to quickly reference the documentation - what if one is at a site where the router is down and you are trying to PSH "grep" through log files to figure out why - admins don't always have internet access!

The final question would be how is the programmer to understand the flow of information in constructs such as "get-process p* | stop-process" - I have no idea what is going through that pipe-looking symbol. How does stop-process expect data to come in? Can a write a quick C program to manipulate data in strange ways?

In sh-style implementations I can be fairly sure that there is only text flowing through, and with a little knowledge about the utilities and the context of my task, I can achieve much - particularly performing tasks for which the shell was never directly intended! This is where the flexability is for me - being able to construct strange and arcane looking commands that do what I want, because I know what each of those symbols mean and exactly how they always behave.

Wednesday, March 12, 2008 6:56 AM by Another Anon

# re: Comparative Examples in MSH and KSH

Hi,

I think the PowerShell is a real improvement over traditional shells.

I was astonished about the a agressive reactions from the unix ayatollas, allways defending their holy religion and cheating on the ms devel.

I work as a unix and windows programmer.

Unix shell programs are a messy patchwork of external programs.

- the libraries are external programs.

- there are no compound variables.

- the results of shell y called by shell x cant be communicated back to x

- there is no syntax checking, if there is an

error in some place, it will only show up

if control goes there.

- the syntax is terrible: if [ $a ne $b ]

 there must be a spece between [ and $a

- etc etc

Wednesday, April 02, 2008 2:56 PM by rob

# re: Comparative Examples in MSH and KSH

Interesting shell. Some questions.

I would like to know if you have plans to introduce non-linear pipelines (perhaps like CMS pipelines)?

How do I store the result of a pipe line and reuse it later?

i.e. How do I do ps -e > a ; cat a | grep $me

Any chance of getting named pipes ? (May be even pipes with scoped life time unlike that of unix, where the clean up of these pipes are mostly ugly when used as temporary storages.)

are there things like tee (and fanin and fanout [cms])

A way to introduce a subshell into a pipeline?

Dataflow variables like lucid would be a nice addition.

Saturday, April 05, 2008 3:21 PM by rahul

# re: Comparative Examples in MSH and KSH

Well, I've been in and out of PowerShell since last I posted here, and I have to say it has some potential.  To get there, though:

copy-item should be able to get around MAX_PATH

Getting a deeply-nested file or directory should be able to get around MAX_PATH

Speed improvements when reading deeply-nested directories from a server

Any operation that accesses a directory entry or an ACL should offer the option of preserving the last access date (as LogParser does.)

Either put support back into LogParser, or make sure PowerShell can offer the same capabilities (including, of course, gathering information about deeply-nested files beyone the reach of MAX_PATH.

Then maybe we'll talk.  I have important system administration work to do that I can perfectly-well do fine on UNIX boxes, and I'm getting tired of jumping through hoops to do the same work on Windows.  Powershell is a start.

Other points:

How do I get (at least) the same reasonable expectations for a shell on Windows *without* loading the entire .NET framework?

Well---that's it for now.

Monday, June 30, 2008 3:17 PM by Chuck

# re: Comparative Examples in MSH and KSH

Well, I've been in and out of PowerShell since last I posted here, and I have to say it has some potential.  To get there, though:

copy-item should be able to get around MAX_PATH

Getting a deeply-nested file or directory should be able to get around MAX_PATH

Speed improvements when reading deeply-nested directories from a server

Any operation that accesses a directory entry or an ACL should offer the option of preserving the last access date (as LogParser does.)

Either put support back into LogParser, or make sure PowerShell can offer the same capabilities (including, of course, gathering information about deeply-nested files beyone the reach of MAX_PATH.

Then maybe we'll talk.  I have important system administration work to do that I can perfectly-well do fine on UNIX boxes, and I'm getting tired of jumping through hoops to do the same work on Windows.  Powershell is a start.

Other points:

How do I get (at least) the same reasonable expectations for a shell on Windows *without* loading the entire .NET framework?

Well---that's it for now.

Monday, June 30, 2008 3:33 PM by Chuck Bermingham

# re: Comparative Examples in MSH and KSH

Sorry 'bout that!  I didn't see the posting and I thought it was because I didn't use my full name the first line.  Embarassing!  Please delete the extra one (and this one....)

Tuesday, July 01, 2008 3:32 PM by Chuck Bermingham

# re: Comparative Examples in MSH and KSH

What does "invariant" mean?

What does "normalized" mean?

Saturday, July 25, 2009 5:35 PM by Neil Murhphy

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker