PowerShell -as Type Operator

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 5 months ago.

  • Author
    Posts
  • #5425

    by GuyThomas at 2013-01-11 04:52:47

    My immediate mission is to discover options for -as string. For example I have used:
    23.6969123 -as [Int]

    My secondary question is how can I research the types for myself, thus apply the principle to other operators.

    by Klaas at 2013-01-11 07:49:10

    http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx
    should give you all the possibilities

    In your console you can type
    Get-Help about_Type_operators

    by nohandle at 2013-01-11 09:01:37

    [quote="GuyThomas"]My immediate mission is to discover options for -as string. For example I have used:
    23.6969123 -as [Int][/quote]
    Is there any particular purpose you plan to use this operator for?

    by GuyThomas at 2013-01-11 09:10:01

    I checked Get-Help about_Type_operators, that revealed [DateTime], but I suspect there are more options.

    I just want to understand the boundaries of this operator.

    by DonJ at 2013-01-11 09:18:28

    The -as operator can attempt to cast/convert any object into another type. You can specify any .NET type name in square brackets, such as [System.Diagnostics.Process]. In practical terms, only simple objects usually support conversion, like converting a string to an integer or vice-versa. You can use full .NET type names, such as [System.String]. PowerShell usually lets you omit the "System." part, so [string], [int], [boolean], and so forth. There is not a comprehensive internal list of available short-type-names that you can access – the list you're looking for doesn't exist.

    Common ones include [single], [double], [int], [int32], [int64], [string], [float], [xml], [datetime], and so on. Some of those are technically type accelerators, like [xml]. But, again, there isn't a way within the shell to retrieve a complete list of supported types, and the list has evolved through each version.

    by nohandle at 2013-01-11 09:20:21

    All of the objects inherit from the System.Object that opens the whole .NET for you :] The only restriction is that the source type can be 'converted' to the resulting type. The conversion is in my opinion using more like the parse static method of the class not casting. Because the resulting [datetime] follows the same rules as if you would do [datetime]::parse('13/1/2013') not as if you would do [datetime]'13/1/2013' (obvious on non en-us systems :)).

You must be logged in to reply to this topic.