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. 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
  4. 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
  5. for a 90MB file, Measure-Object -line -word -character takes a minute, while cygwin's wc takes 2 seconds. Jeesh

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

    ReplyDelete
  7. 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
  8. Thank you, but I won't take your advice :))

    ReplyDelete
  9. 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
  10. (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
  11. *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
  12. 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
  13. 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
  14. 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
  15. This comment has been removed by the author.

    ReplyDelete
  16. 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
  17. 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
  18. I really appreciate your professional approach.These are pieces of very useful information that will be of great use for me in future.

    หนังออนไลน์

    ReplyDelete
  19. Really nice post. Thank you for sharing amazing information.
    DevOps Training
    DevOps Online Training

    ReplyDelete
  20. ยินดีต้อนรับสู่ UPLAY365.COM เว็บพนันออนไลน์ All In One ที่รวมเว็บพนันออนไลน์อันดับ 1 ไว้ที่เดียวกันมากที่สุด ไม่ว่าจะเป็น เกมส์ไพ่ ที่เป็นที่นิยม เช่นบาคาร่า แบล็คแจ็ค เสือมังกร หรือจะเป็น รูเล็ต สล็อตออนไลน์ คีโน โป๊กเกอร์ forex ไก่ชน เกมส์ยิงปลา แทงบอล แทงบาส เทนนิส ESPORT แทงมวยไทย และอื่นๆอีกมากมาย พร้อมเทคโนโลยีชั้นนำจากผู้ผลิตซอฟต์แวร์เกมส์ระดับโลก ความน่าเชื่อถือได้มาเป็นอันดับ 1 สามารถเล่นได้ทั้งบนคอมพิวเตอร์ , มือถือ ระบบ android และ IOS *คาสิโนออนไลน์ : สามารถเลือกเล่นกับคาสิโนชั้นนำดังนี้ SexyBaccarat, AG Casino, GOLD Casino, SA Casino, W88 Casino, D88 Casino, WM Casino, GD Casino เป็นต้น *แทงบอล : U กีฬา (U SPORTS) , S กีฬา (S SPORTS) มั่นใจได้เลยว่า อัตราการจ่ายค่าน้ำดีที่สุดต้อง uplay365 เหมาะสำหรับทั้งนักพนันมืออาชีพและ มือใหม่ โดยทางเรามีพนักงานคอยสอนเรื่องการแทงบอลเบื้องต้น แทงง่าย อัตราจ่ายดี *สล็อตออนไลน์ ,เกมส์ยิงปลา : JOKER123,PLAYTECH และอื่นๆ อีกมากมาย ทั้งหมดนี้ สามารถเล่นได้ใน 1 ยูสเซอร์เท่านั้น สนใจสมัครสมาชิกรับเครดิตฟรี สามารถสมัครได้ตนเองที่หน้าเว็บ หรือติดต่อ Callcenter โดย ทางเรามีพนักงานไว้บริการและแก้ปัญหา ตลอด 24 ชั่วโมง สอบถามข้อมูลเพิ่มเติมได้กับแอดมินได้ตลอด 24 ชม.ค่ะ


    W88 Club
    W88

    ReplyDelete
  21. Рейтинг онлайн-казино включает клубы, предлагающие хорошо продуманную мотивационную программку. Посетителей ждут разноплановые призы — приветственные, бездепозитные, фриспины, релоад. Некоторые порталы дарят поощрения воскресение, праздничным, ко деньку рождения. Кроме этого рабочие казино, поддерживают программку лояльности со статусами, позволяющую получить дополнительные подарки за активность. Одновременно ведутся турниры, лотереи, сезонные акции. Благодаря этому гости выигрывают больше, все хорошо рассеяться, вложив минимум.

    ReplyDelete