Write-Host

Write-Host

http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/

Write-Host Considered Harmful
Write-Host is almost always the wrong thing to do because it interferes with automation. There are typically two reasons why people use Write-Host:

To convey results.

Whenever you write a script, you are addressing a particular problem at hand and you are putting a tool in your toolbox that can be used to solve larger problems down the road. If you use Write-Host to convey results, you have a useless tool in your toolbox.The correct cmdlet to use is Write-Output. Using Write-Output will display the results to the screen when you run you script by itself but, it will also allow your script to be used in a pipeline (or foreach loop) and have the results used by other scripts/cmdlets.

To convey comforting information to the user

What’s that saying about “the road to hell being paved with good intentions”? If you use Write-Host to do this, you are paving a road to hell.PowerShell is about automation. Show comforting information is often helpful the first couple of times you run a script but then after that, it because an annoyance. When you use Write-Host, the user is not able to say when they want this information and when they don’t.

The correct tool is the Write-Verbose cmdlet. This cmdlet allows the user to control whether they see the information or not by invoking your script with the -VERBOSE flag or not

So if Write-Host is almost always the wrong thing to use, you might wonder why it is there in the first place. The answer is in the phrase “almost always”. I often use Write-Host when I’m writing a throw away script or function. It is much faster and simpler to use it than to use Write-Verbose and then specify -VERBOSE. For a throw away script – it doesn’t matter. The key is to throw it away! If you don’t intend to throw it away, you shouldn’t use Write-Host. I always know the scripts I’m going to throw away because they are named T.PS1.

The other scenario to use Write-Host is when you really do want to generate a UX. Write-Host has a number of nice features like the the ability to colorize text that are great to use when you really do intend to generate a UX. For example outputting a graph or my personal favorite:

Write-Host ( g ∗ g* ggraph) -ForegroundColor $GraphColor

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值