Saturday, June 20, 2009

Unix Equivalents in Powershell

I come from Linux background which I really like . There are lot more utilities in Unix/Linux which provide more convenient way of doing some work. They are really very useful in speeding up the work and automating repetitive tasks.

Since the release of Windows Powershell, it has proven to be one of the most powerful shells available now.

As I started using Powershell, I find myself most of the times searching for UNIX equivalents in windows powershell. Here are a few which i came across

wc in Powershell: Measure-Object


[jagadish.g@localhost Scripts]$ cat test.csv | wc
4 13 277
[jagadish.g@localhost Scripts]$ cat test.csv | wc -l
4


PS C:\Scripts> Get-Content test.csv | Measure-Object -line -word -character

Lines Words Characters Property
----- ----- ---------- --------
4 13 273

PS C:\Scripts> Get-Content test.csv | Measure-Object -line

Lines Words Characters Property
----- ----- ---------- --------
4

time in Powershell: Measure-Command


[jagadish.g@localhost Scripts]$ time sleep 5

real 0m5.003s
user 0m0.000s
sys 0m0.001s


PS C:\Scripts> Measure-Command { Sleep 5 }

Days : 0
Hours : 0
Minutes : 0
Seconds : 4
Milliseconds : 999
Ticks : 49996681
TotalDays : 5.78665289351852E-05
TotalHours : 0.00138879669444444
TotalMinutes : 0.0833278016666667
TotalSeconds : 4.9996681
TotalMilliseconds : 4999.6681

GREP in Powershell: Select-String


[jagadish.g@localhost Scripts]$ cat test.csv | grep "Tony Passaquale"
1,Tony Passaquale,7920,20090222 21:59:00,800,4.78,3824,Follow-up


PS C:\Scripts> Get-Content test.csv | Select-String "Tony Passaquale"

1,Tony Passaquale,7920,20090222 21:59:00,800,4.78,3824,Follow-up

NOTE, Select-String is Case-Insensitive by default. Use -CaseSensitive switch parameter to make it case sensitive.

Now lets try to get one line after the line with the match


[jagadish.g@localhost Scripts]$ cat test.csv | grep -A1 "Tony Passaquale"
1,Tony Passaquale,7920,20090222 21:59:00,800,4.78,3824,Follow-up
2,Nigel Shan Shanford,30316,20090405 16:34:00,400,9.99,3996,New-Opportunity


PS C:\Scripts> Get-Content test.csv | Select-String "Tony Passaquale" -Context 0,1

> 1,Tony Passaquale,7920,20090222 21:59:00,800,4.78,3824,Follow-up
2,Nigel Shan Shanford,30316,20090405 16:34:00,400,9.99,3996,New-Opportunity

The -Context parameter in the Select-String cmdlet is used to capture the specified number of lines before and after the line with the match. If you look at the above code window, I have passed '0,1' value to the -Context parameter. The first integer specifies the number of lines to print before the match (in this case, it is 0) and the next integer specifies the number of lines to print after the match (in this case, it is 1)

Select-String cmdlet is using regular expression matching by default. So you can use use regex patterns to select the required lines.


[jagadish.g@localhost Scripts]$ cat test.csv | grep "y$"
2,Nigel Shan Shanford,30316,20090405 16:34:00,400,9.99,3996,New-Opportunity
4,Allen James,95140,20090405 16:31:00,1000,9.99,9990,New-Opportunity


PS C:\Scripts> Get-Content test.csv | Select-String "y$"

2,Nigel Shan Shanford,30316,20090405 16:34:00,400,9.99,3996,New-Opportunity
4,Allen James,95140,20090405 16:31:00,1000,9.99,9990,New-Opportunity

AWK in Powershell

Powershell has lot of features and abilities for text parsing. AWK is one of very powerful commands available for text parsing in Unix/Linux. We do not have a Awk like cmdlet in Powershell. But we can do everything in Powershell that can be done with Awk.

Powershell combined with .Net Classes provide very powerful regular expressions for text parsing. read more...

cd - in Powershell

One of the cool features of linux bash is the ability to go to the previous working directory. In Bash, we can go to the previous working directory using "cd -" command.

Unfortunately, we do not have an equivalent of "cd -" in Powershell. So I just wrote a simple powershell function for this cool feature. read more...

find command in Powershell

Find is one of the most often used commands in day to day work life. Unix find command provides lot of features and options that enable users to find files/directories more effectively

In Powershell, we can use Get-ChildItem cmdlet to search for files. But it doesn't give you all the fun. So I have developed Find-ChildItem Powershell cmdlet which is equivalent to Unix find command. read more...

30 comments:

  1. Have you tried:
    Get-Service | Select-String "Running"?

    ReplyDelete
    Replies
    1. This doesn't appear to work.

      Delete
    2. Try this instead:

      Get-Service | Where-Object {$_.Status -eq "Running"}

      Delete
  2. It is highly redundant and bad scripting to run cat with grep or awk.
    Better use grep "y$" test.csv

    ReplyDelete
  3. I recommend Skype Call Recorder. Helps me a lot for recording interviews, podcasts

    ReplyDelete
  4. Walter, agreed. Also took me a while to realize that using grep before awk was usually redundant, when...

    grep "y$" test.csv | awk -F , '{print $1}'

    ...is the equivalent of...

    awk -F , '/y$/ {print $1}'

    (Sorry if I screwed up any of the syntax. It has been a while.)

    ReplyDelete
  5. Oops! I see at least one screw-up already. That last command was missing a file name, so it should (at least) have read...

    awk -F , '/y$/ {print $1}' test.csv

    ReplyDelete
  6. for a 90MB file, Measure-Object -line -word -character takes a minute, while cygwin's wc takes 2 seconds. Jeesh

    ReplyDelete
  7. for find I just use "get-childitem | ?{$_.(something you care about) -is "What you want"}"

    ReplyDelete
  8. Powershell really is junk. Take my advice... If you have to perform any real scripting work use cygwin or do it on a *nix platform.

    ReplyDelete
    Replies
    1. Talked nonsense because he lacked knowledge. Supporter team does the same.

      Delete
    2. I was talking exactly the same about *nix years ago because I did not understand it - now I would say that I was an idiot ;-). Don't comment on something you don't understand.

      Delete
  9. Thank you, but I won't take your advice :))

    ReplyDelete
  10. Get-Service | where { $_.Status -match "Running" }

    ReplyDelete
    Replies
    1. good reply sir. actually this particular item is returned by PS as example if we type man get-service -full. This last bit -full is quite useful.

      Delete
  11. (Get-Content test.csv | Select-String "Tony Passaquale" -Context 0,1)

    You can do that, but with PowerShell use Objects whenever you can. So, (Import-Csv test.csv | Where-Object {$_.name -eq 'Tony Passaquale'}) is more fun for me.

    ReplyDelete
  12. *nix cat doesn't mess with what it pumps through, unless you ask it to. Powershell "objectifies" stuff. OMG! Had to find the "-encoding" flag to keep if from doubling my file size by turning it into Unicode. It still modifies characters that don't fit its idea of whatever encoding it is using. How about a freakin' -kiss flag, huh!!!

    ReplyDelete
  13. i really likes your blog and You have shared the whole concept really well. and Very beautifully written,
    soulful read! thanks for sharing.
    gclub casino
    goldenslot casino
    goldenslot

    ReplyDelete
  14. Fun on the site. Online casino
    คาสิโนAn online casino site that is open to the online measurement of Asian gamblers. For the provider of this measurement is considered one of the most popular online casino games provider of the day. Online gambling games are considered to be excellent because they have the highest number of gamblers. And importantly, playing online casino games on the web pages of online casinos also offers online casino games to choose from. You can choose to play all online gambling games on our online casino site. By just surfing the internet, every time a player has an Internet connection, he or she can play online games of all kinds on the web. Online casinos have enjoyed the challenge and excitement, you can become a billionaire by players just starting to play online bets with us. You can play all online gambling games. And also be able to contribute money into the pockets of the player with a player can start to welcome and start playing online gambling online more than a hundred forms on our online casino. Day and night, the player can join us at any part of the site. Sbobet

    ReplyDelete
  15. Enjoy playing games on the go.
    Gclub Is an online gaming site for you to enjoy the game of betting to make rich users of gambling. Online multiplayer games are designed to allow gamblers to gamble comfortably. And in order to meet your needs, you have the opportunity to gamble online to bet on the service in real time. To create a better taste and enjoyment. Win online games suitable for modern people. Bet easy and fast by playing on your mobile or computer. You can also gamble online without having to download it because it can be directly bet on the website. The best online casino games that will give you an advantage of the game and the type of games that allow users to bet on the game and earn real money. Join the best online gambling services. We are ready to meet every lifestyle of our customers with our website. With the launch of friendly service. All you have to do is go online. We combine the front row game with the customers to enjoy. All the time at the site. .Gclub มือถือ

    ReplyDelete
  16. Safety in playing online casino games.
    บาคาร่าIs a site of online gambling and betting sites with high criteria and high ranking in Thailand and Asia. It is a very trustworthy site. Group of gamers gamble. Because our site is technologically advanced. Always see users ranked first. Impress from the beginning. To apply for a team with us. Get it right now. Dividends at the opening of the new book 30 percent of the minimum asset replenishment of 500 baht up to 30000 baht is not only exhausted. For all our internet betting site bettors. There is a huge jackpot at the end of the month. With a gold necklace worth 10000 baht is not exhausted, you also have fun in the game, our internet gambling lot more. You can easily conquer it. Because on our online betting site, we have accumulated good tips to overcome the risky game easily. Accumulated by the expert gambler. Come join in this fun with your own. Our website has a team of experts. Keep commenting You can continue to ask questions 24 hours a day. Gclub มือถือ

    ReplyDelete
  17. Casino games to play a variety of games.
    Goldclub Slot It is another online gambling site where online gamblers enjoy their favorite games without compromising on the internet. Open up to the most popular online gambling games and offer more than 100 selections. Gambling online gambling alternatives can fulfill and reward real customers. Online risk games are considered popular games in this phase. Due to the risk of getting comfortable. Make better bets by using the internet. Along with online gambling games, there are many games that will give the user full enjoyment. The easy-to-understand online betting game types can be wagered on you. No matter where you gamble, you can always carry your favorite online games anywhere. We offer a new online casino games that can be played without any problems. Full of fun, which gives you money and riches for your users. Want to gamble on online gambling games that you do not miss? Update games and meet all your needs. Join the online casino games of online casino games site. It's because all the games are designed to meet all your

    ReplyDelete
  18. Have fun with your favorite gambling games.
    บาคาร่าออนไลน์ Is an online gambling services website where consumers will experience a new gamble. Because of the online risk that has been improved to the risk of comfort. And a gambler who is ready to entertain at any time for you. Choose from a wide variety of online casinos, including a variety of free online casino games. Fun to play with. With the advantage to you. We are a popular and trustworthy online casino site. Because the site is open to honest service and cutting-edge games, it is a must for modern-day gamblers. Giving to the players at any time with online gambling games that will make you happy and earn money from the game. Online casino games are real fun new look that makes it like a risk in the real world. Not only that, you can also learn how to find good tips. Before the risk. Have fun with other online players in the game. And find the easy profits to win online. รูบี้888

    ReplyDelete
  19. Online Casinos Service over level
    Gclub Online Casino Site Is a new regime game That will not make you repeatedly monotonous. And the drudgery anymore. You can also choose to play at any time, even if you have your own secret code. You can also accumulate points. The game of the casino online. There are a variety of games and methods and different types of play out. And there are recipes that will make you more victorious. But how? Your own play will determine whether you will win or lose each game. Online casinos also offer prizes and promotions, as well as good activities. Always give you Only you can join. In our online casino. You will be able to get that right now. And you can enjoy the game. You are the one who set the prize for yourself in an unknowingly boring. Do not decide whether the online casino is a scam or not. Because our online casinos actually pay real money, you get really rewarding. You do not have to be tired. And playing games is no longer a waste of time. If you are interested, please visit our website. Royal1688

    ReplyDelete
  20. I really appreciate your professional approach.These are pieces of very useful information that will be of great use for me in future.

    หนังออนไลน์

    ReplyDelete