您的位置:首页 > 运维架构 > Shell

PowerTip of the Day from powershell.com上周汇总(五)

2010-08-23 10:18 531 查看
对输入参数进行集合验证
Validate Set of Inputs
http://powershell.com/cs/blogs/tips/archive/2010/08/18/validate-set-of-inputs.aspx
限制输入的参数只能是指定一个集合里面的成员:
function Get-24hEventLogEntries {
     param(
          [String]
          [ValidateSet('System','Application')]
          $LogName='System',
          [String]
          [ValidateSet('Error','Warning','Information')]
          $EntryType='Error'
 )
    Get-EventLog -LogName $LogName -EntryType $EntryType -After ((Get-Date).AddDays(-1))
}
这个函数是用来查看系统日志的,带有两个参数,其中LogName只能接收两个值,System和Application,-EntryType只能接收Error,warning,Information三个值。如果输入的参数不在指定的集合中,那么会提示错误。
另,这个方法只在powershell的2.0版本中可用,1.0版本调试无法通过。
 
 
定义属性简称
Defining Alias Properties
http://powershell.com/cs/blogs/tips/archive/2010/08/19/defining-alias-properties.aspx
有时候参数名很长,调用起来很麻烦,但是可以将很长的参数名定义一个简短的简称,比如如下代码,给参数名ComputerName定义了一个简称CN。
function Get-BIOSInfo
{
param([Alias("CN")]$ComputerName = ".")
Get-WmiObject Win32_BIOS -ComputerName $computername
}
这样调用起来既可以这样:
Get-BIOSInfo -ComputerName .
也可以这样:
Get-BIOSInfo -CN .
 
 
根据参数名查找Cmdlets
Finding Cmdlets With a Given Parameter
http://powershell.com/cs/blogs/tips/archive/2010/08/17/finding-cmdlets-by-name-is-easy.aspx
根据名字查找是很容易的:
Get-Command *service* -commandType Cmdlet
如果要根据参数名来查,最简单的就是使用parameter参数:
Get-Command *service* -commandType Cmdlet -parameter computer
(为便于理解,以上代码跟原文略有不同)
或者,可以使用Get-Command,并且自己定义一个filter来实现:
filter Contains-Parameter
{
    param($name)
    $number = @($_ | % { $_.ParameterSets | % { $_.Parameters | ? { $_.Name -eq $name}}}).Count
    if ($number -gt 0)
    {
        $_
    }
}
使用方法:
Get-Command | Contains-Parameter 'list'
后者主要为了演示如何定义一个filter。
 
 
删除所有IE的Cookies
Removing All Internet Explorer Cookies
http://powershell.com/cs/blogs/tips/archive/2010/08/16/removing-all-internet-explorer-cookies.aspx
很简单:
Dir ([Environment]::GetFolderPath("Cookies")) | del –whatif
正式跑的时候记得把whatif去掉。
(不明白老外类似示例代码为什么最近这么爱用whatif)
 
 
限制参数个数
Limiting Number of Arguments
http://powershell.com/cs/blogs/tips/archive/2010/08/20/limiting-number-of-arguments.aspx?CommentPosted=true#commentmessage
原文代码有处错误,正确的应该是:
function Add-Users {
     param(
          [ValidateCount(1,3)]
          [String[]]
          $UserName
     )
    $UserName | ForEach-Object { "Adding $_" }
}
调用方法:
Add-Users -UserName "shanpao","baichi","kele"
三个以内的参数按照定义来说都是允许的,如果超过了,比如上面的字符给四个,那么就会报错。
用法很像之前的ValidateSet。
 
 
 
  
以上来自powershell.com
2010年八月份16日到20日的PowerTip of the Day
 

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

来自博客园aspnetx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息