尝试创建如下函数:
Function Get-SqlErrorLogPrevious24 {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,Position=1)]
[Microsoft.SqlServer.Management.Smo.Server]$Server
)
($Server.ReadErrorLog()).where{$_.logdate -ge ((Get-Date).AddHours(-24))}
}
不过我注意到,我可以只传入一个字符串而不是服务器对象。
Powershell 中是否有一种方法可以强制执行传入的数据类型,或者它是否始终将字符串隐式转换为 SMO 对象?
最佳答案
您可以实现自定义转换属性,如果类型不同,它会抛出异常:
Add-Type @'
using System;
using System.Management.Automation;
public class EnforceTypeAttribute : ArgumentTransformationAttribute {
private Type type;
public EnforceTypeAttribute(Type type) {
this.type=type;
}
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) {
if(type.IsInstanceOfType(inputData)) {
return inputData;
} else {
throw new Exception("Incorrect type.");
}
}
}
'@
function f {param([int]$i) $i}
function g {param([EnforceType([int])][int]$i) $i}
f 1 #OK
f '1' #OK
g 1 #OK
g '1' #Error
关于Powershell 函数限制数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40345196/