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 @   哥本哈士奇(aspnetx)  阅读(353)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示