简体   繁体   English

Powershell函数限制数据类型

[英]Powershell Function Restrict Data Type

Trying to create a function like the following: 尝试创建如下函数:

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))}
}

What I've noticed though, is that I can pass in just a string and not a Server object. 我注意到的是,我只能传入一个字符串而不是Server对象。

Is there a way in Powershell to strongly enforce the data type being passed in or will it always implicitly convert a string to an SMO object? 在Powershell中是否有一种方法可以强制执行传入的数据类型,或者它是否总是隐式地将字符串转换为SMO对象?

You can implement custom transformation attribute, which would throw exception if type is different: 您可以实现自定义转换属性,如果类型不同,则会抛出异常:

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

No. PowerShell has several "strategies" that it uses to make sure what you receive in a function is the correct type. 不,PowerShell有几个“策略”,用于确保您在函数中收到的内容是正确的类型。 If it can use one of them to transform the value passed (in this case a string) to the required type (an SMO object) it will do that. 如果它可以使用其中一个将传递的值(在本例中为字符串)转换为所需类型(SMO对象),它将执行此操作。

Here is a great post which lists 10 different strategies. 这是一篇很棒的文章,列出了10种不同的策略。

  1. Direct assignment. 直接分配。 If your input is directly assignable, simply cast your input to that type. 如果您的输入可以直接分配,只需将输入转换为该类型即可。
  2. Language-based conversion. 基于语言的转换。 These language-based conversions are done when the target type is void, Boolean, String, Array, Hashtable, PSReference (ie: [ref]), XmlDocument (ie: [xml]). 当目标类型为void,Boolean,String,Array,Hashtable,PSReference(即:[ref]),XmlDocument(即:[xml])时,将完成这些基于语言的转换。 Delegate (to support ScriptBlock to Delegate conversions), and Enum. 委托(支持ScriptBlock委派转换)和Enum。
  3. Parse conversion. 解析转换。 If the target type defines a Parse() method that takes that input, use that. 如果目标类型定义了获取该输入的Parse()方法,请使用该方法。
  4. Static Create conversion. 静态创建转换。 If the target type defines a static ::Create() method that takes that input, use that. 如果目标类型定义了一个采用该输入的static :: Create()方法,请使用它。
  5. Constructor conversion. 构造函数转换。 If the target type defines a constructor that takes your input, use that. 如果目标类型定义了一个获取输入的构造函数,请使用它。
  6. Cast conversion. 转换转换。 If the target type defines a implicit or explicit cast operator from the source type, use that. 如果目标类型从源类型定义隐式或显式强制转换运算符,请使用它。 If the source type defines an implicit or explicit cast operator to the target type, use that. 如果源类型为目标类型定义隐式或显式强制转换运算符,请使用它。
  7. IConvertible conversion. IConvertible转换。 If the source type defines an IConvertible implementation that knows how to convert to the target type, use that. 如果源类型定义了一个知道如何转换为目标类型的IConvertible实现,请使用它。
  8. IDictionary conversion. IDictionary转换。 If the source type is an IDictionary (ie: Hashtable), try to create an instance of the destination type using its default constructor, and then use the names and values in the IDictionary to set properties on the source object. 如果源类型是IDictionary(即:Hashtable),请尝试使用其默认构造函数创建目标类型的实例,然后使用IDictionary中的名称和值来设置源对象的属性。
  9. PSObject property conversion. PSObject属性转换。 If the source type is a PSObject, try to create an instance of the destination type using its default constructor, and then use the property names and values in the PSObject to set properties on the source object. 如果源类型是PSObject,请尝试使用其默认构造函数创建目标类型的实例,然后使用PSObject中的属性名称和值来设置源对象的属性。 . If a name maps to a method instead of a property, invoke that method with the value as its argument. 如果名称映射到方法而不是属性,则以值作为其参数调用该方法。
  10. TypeConverter conversion. TypeConverter转换。 If there is a registered TypeConverter or PSTypeConverter that can handle the conversion, do that. 如果有可以处理转换的已注册TypeConverter或PSTypeConverter,请执行此操作。 You can register a TypeConverter through a types.ps1xml file (see: $pshome\\Types.ps1xml), or through Update-TypeData. 您可以通过types.ps1xml文件(请参阅:$ pshome \\ Types.ps1xml)或通过Update-TypeData注册TypeConverter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM