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

限制String类型参数的长度

Limiting String Input Length

http://powershell.com/cs/blogs/tips/archive/2010/08/23/limiting-string-input-length.aspx

function Get-FileName {
param(
[ValidateLength(1,8)]
[String]
$FileName
)
"Your filename {0} is {1} chars long" -f $FileName, $FileName.Length
}

调用示例Get-FileName "win.txt"

 

 

用正则验证输入的参数

Validate Input Using Regular Expressions

http://powershell.com/cs/blogs/tips/archive/2010/08/24/validate-input-using-regular-expressions.aspx

function Get-KnowledgeBaseArticle {
param(
[ValidatePattern('^KB\d{6}$')]
[String]
$KB
)
"You entered Knowledgebase ID $KB"
}

调用示例Get-KnowledgeBaseArticle -KB "KB123456"

 

 

Powershell查看对象类型

Finding Object Types with Powershell

http://powershell.com/cs/blogs/tips/archive/2010/08/25/finding-object-types-with-powershell.aspx

'Hallo'.GetType().FullName
(4).GetType().FullName
(2.6).GetType().FullName
(Get-Date).GetType().FullName

结果:

System.String

System.Int32

System.Double

System.DateTime

 

 

转换对象类型

Converting Object Types

http://powershell.com/cs/blogs/tips/archive/2010/08/26/converting-object-types.aspx

[DateTime] '4.5.2010'

以下是获取本地日期格式的方法:

[DateTime]::Parse('4.5.2010')

实际上相当于.net framework下的DateTime.Parst(string).

 

 

限制数字参数范围

Restrict Input to Numeric Ranges

http://powershell.com/cs/blogs/tips/archive/2010/08/27/restrict-input-to-numeric-ranges.aspx

function Set-CursorSize {
param(
[ValidateRange(1,100)]
[Int]
$Percent
)
$Host.UI.RawUI.CursorSize = $Percent
}

int型的参数做一个范围限制。

主要通过[ValidateXXXX]

 

 

 

 

 

以上来自powershell.com

2010年八月份16日到20日的PowerTip of the Day

 

posted @ 2010-08-30 09:26  哥本哈士奇(aspnetx)  阅读(352)  评论(0编辑  收藏  举报