About constants in powershell scripting language using .NET types

If I want to create a .NET object in powershell, I will write something like the following:

[System.Reflection.Assembly]::LoadWithPartialName("System.Xml") | out-null"
$doc = new-object -typename System.Xml.XmlDocument"

      

If I want to call a .Net static method, I use a command similar to the following line:

$path = [System.String]::Format("{0} {1}", "Hello", "World")

      

I don't see this rule. If it works in the first example, why can't I use it System.String.Format

in the second?

0


source to share


6 answers


The parentheses are used when you use a static method on a given class. When you create a new object of a specific class, you don't need parentheses.

Brackets are also used to pass variables to a specific type



PS C:\> $i = [int]"1"
PS C:\> $i.gettype().Name
Int32
PS C:\> $j = "1"
PS C:\> $j.gettype().Name
String
PS C:\>

      

+3


source


I believe you are confusing types and members here.

// type "Assembly" in the "System.Reflection" namespace
[System.Reflection.Assembly] 

// member method "LoadWithPartialName" of type "Assembly"
[System.Reflection.Assembly]::LoadWithPartialName 

// type "String" in the "System" namespace
[System.String] 

// member method "Format" of type "String"
[System.String]::Format

      



It works as it should. Where does your confusion come from?

+2


source


Yes, the way you phrased your question is a little confusing. System.Xml.XmlDocument and System.String are defined as classes, so you can use a new object for each to create an object of a specific type.

Just because you have "foo.bar.joe" does not mean that you are doing anything other than "abc.def". Both are valid classes, it just happens that they have a different length / namespace definition.

0


source


I see, probably my question was a little confusing.

What I was asking: What is the reason for this syntax with brackets and colons? Why hasn't Microsoft defined it the way it is in C # - everything is separated by dots?

The question arose when I saw the following line (in fact, I wanted to pay attention):

$doc = new-object -typename "System.Xml.XmlDocument"

      

Obviously sometimes the parenthesis / colon syntax is unnecessary, so why does it even exist?

0


source


I'm guessing the new object is just passing it to the Activator, which expects a period-limited name - powershell doesn't actually control that part.

0


source


In case of line:

$doc = new-object -typename "System.Xml.XmlDocument"

      

no parentheses are needed because the -typename argument is of type string. Technically, we could call it like this:

$doc = new-object -typename "TypeThatDoesntExsit" 

      

and it will show an error because it is trying to dynamically resolve the type for the string.

0


source







All Articles