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

本文介绍了使用Powershell进行参数验证的方法,包括限制字符串长度、利用正则表达式验证输入、查看及转换对象类型、限制数值参数范围等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

限制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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值