Difference between "New-Object WindowsPrincipal([WindowsIdentity]::GetCurrent())" and "[WindowsPrincipal] [WindowsIdentity]::GetCurrent()" - powershell

I'm trying to check if Powerhell script is running as Administrator.
After searching the web, I got some sample code that works fine.
In order to get the WindowsPrincipal object, I found two sample code as below.
First:
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
Second:
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
The second one made me confused.
According to this page, I know that the [ ] is a cast operator.
And according to this page, PowerShell is built on the .NET Framework. In my opinion, this means that the above two PowerShell scripts can be converted to C#.
So I try it.
When I convert the first PowerShell script to C#. It work fine as below.
## First PowerShell script
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
// C#
var wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
But when I try to convert the second PowerShell script to C#. I get compile error. The IDE tells me that WindowsIdentity cannot be cast to WindowsPrincipal.
## Second PowerShell script
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
// both C# code below cause compile error
var wp = System.Security.Principal.WindowsIdentity.GetCurrent() as System.Security.Principal.WindowsPrincipal;
var wp2 = (System.Security.Principal.WindowsPrincipal)System.Security.Principal.WindowsIdentity.GetCurrent();
Just as I tried on C#, the System.Security.Principal.WindowsIdentity type cannot be directly converted to the System.Security.Principal.WindowsPrincipal type. But why is the second PowerShell script available?
Or is the [ ] operator in the second PowerShell script not a type conversion operator?
Maybe this operator do more than just convert object type?
What's the difference between first PowerShell script and second PowerShell script?
Did I missing any other things?

TLDR: PowerShell can do Magic. C# can't do Magic.
PowerShell can juggle Chainsaws, bowling pins, and balls at the same time.
C# can only juggle balls if they are defined ahead of time. Trying to add a new Chainsaw into the juggling routine causes the juggler(compiler) to complain.
The issues are the differences between Functions, Object types, and how to cast object types.
System.Security.Principal is the base .NET library. The library can be used by C# and PowerShell.
WindowsIdentity.GetCurrent() is a function in the library.
WindowsPrincipal is an object type e.g. like string or int.
Calling WindowsIdentity.GetCurrent() returns a WindowsIdentity object, which you can then use in your code.
Since WindowsIdentity is not necessarily the object type you want to work with, we want to use a WindowsPrincipal object. Unfortunately we cannot directly cast from WindowsIdentity to WindowsPrincipal object. We have to use the WindowsPrincipal constructor.
In PowerShell, you create a new object either by the New-Object cmdlet, or by simply using a variable for the first time. This convenience is because PowerShell is a scripting language, where using a variable e.g. $a = 1 implicitly creates a new variable. e.g.
PS C:\> Get-Variable test
Get-Variable : Cannot find a variable with the name 'test'.
At line:1 char:1
+ Get-Variable test
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (test:String) [Get-Variable], ItemNotFoundException
+ FullyQualifiedErrorId : VariableNotFound,Microsoft.PowerShell.Commands.GetVariableCommand
PS C:\> $test = 1
PS C:\> Get-Variable test
Name Value
---- -----
test 1
Using the New-Object example:
New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
This is the right way to do it. You are creating a new object of type WindowsPrincipal, and passing the Windows Identity to the constructor.
The second method:
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
Is "wrong" because it uses casting, and earlier we stated that we cannot directly cast from WindowsIdentity to WindowsPrincipal object. So how does this work? Well, I said earlier that PowerShell does Magic, well I'll get to that in a minute. First let's see the correct C# Code:
Calling .NET Framework specific functions in C# do differ in Syntax than PowerShell. And the reason for the specific compile error you are getting is because we are trying to cast the object, which we can't.
The example:
using System.Security.Principal;
var wp = WindowsIdentity.GetCurrent() as WindowsPrincipal; // compile error
The Compiler translates it to:
WindowsIdentity.GetCurrent()
Run function GetCurrent()
as WindowsPrincipal;
Expect a return type of WindowsPrincipal <-- compile time error. The compile error is because the function does not return a type of WindowsPrincipal, instead it returns a type WindowsIdentity.
Second example is also a variation that doesn't work because it can't cast the object directly. e.g.
using System.Security.Principal;
var wp = (WindowsPrincipal) WindowsIdentity.GetCurrent(); // compile error
The Compiler translates it to:
WindowsIdentity.GetCurrent()
Run function GetCurrent() and return with the WindowsIdentity object.
(WindowsPrincipal) WindowsIdentity.GetCurrent();
Take the WindowsIdentity object and directly cast it to a WindowsPrincipal type, which it can't.
The correct C# code also needs the new keyword is:
var wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
The Compiler translates it to:
WindowsIdentity.GetCurrent()
Run function GetCurrent() and return with the WindowsIdentity object.
new WindowsPrincipal(WindowsIdentity.GetCurrent())
Create a new WindowsPrincipal object passing the WindowsIdentity object into the constructor. Which now works.
So why does the second example:
[Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
Work in PowerShell by doing something that is "wrong"? Because PowerShell is a scripting language, and is interpreted on the fly, and can use Magic, it can interpret the above and perform some Type Conversion Magic Quote:
Direct assignment. If your input is directly assignable, simply cast your input to that type.
Language-based conversion. These language-based conversions are done when the target type is void, Boolean, String, Array, Hashtable, PSReference (i.e.: [ref]), XmlDocument (i.e.: [xml]). Delegate (to support ScriptBlock to Delegate conversions), and Enum.
Parse conversion. If the target type defines a Parse() method that takes that input, use that.
Static Create conversion. If the target type defines a static ::Create() method that takes that input, use that.
Constructor conversion. If the target type defines a constructor that takes your input, use that.
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.
IConvertible conversion. If the source type defines an IConvertible implementation that knows how to convert to the target type, use that.
IDictionary conversion. If the source type is an IDictionary (i.e.: 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.
PSObject property conversion. 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. . If a name maps to a method instead of a property, invoke that method with the value as its argument.
TypeConverter conversion. If there is a registered TypeConverter or PSTypeConverter that can handle the conversion, do that. You can register a TypeConverter through a types.ps1xml file (see: $pshome\Types.ps1xml), or through Update-TypeData.
Basically, whenever you do a type conversion in PowerShell, it will perform Magic and try each method to convert the type dynamically on the fly for you. That is why it can handle you throwing a new Chainsaw or bowling pin at the juggler. PowerShell can interpret that we aren't trying to convert a chainsaw into a ball, and instead that a chainsaw is just another object, and we already know how to juggle objects.
This interpretation isn't a part of .NET, and so C# can't do that, and we have to explicitly define everything, and do everything correctly. This means that you can convert all C# and .NET code into valid PowerShell code, but not the other way around.

Related

Why is a plus operator required in some Powershell type names?

Why is it that, in Powershell, the System.DayOfWeek enum can be referred to like [System.DayOfWeek], whereas the System.Environment.SpecialFolder enum must be referred to like [System.Environment+SpecialFolder] (note the plus character)?
My guess is because SpecialFolder is part of the static Environment class and DayOfWeek is sitting directly in the System namespace, but I'm having trouble finding any information on this. Normally static members would use the "static member operator", but that doesn't work in this case, nor does anything else I try except the mysterious plus character...
[System.DayOfWeek] # returns enum type
[enum]::GetValues([System.DayOfWeek]) # returns enum values
[enum]::GetValues([System.Environment.SpecialFolder]) # exception: unable to find type
[enum]::GetValues([System.Environment]::SpecialFolder) # exception: value cannot be null
[enum]::GetValues([System.Environment+SpecialFolder]) # returns enum values
System.Environment.SpecialFolder is definitely a type, and in C# both enums work the same way:
Enum.GetValues(typeof(System.Environment.SpecialFolder)) // works fine
Enum.GetValues(typeof(System.DayOfWeek)) // also works
I'd really like to understand why there's a distinction in Powershell and the reasoning behind this behaviour. Does anyone know why this is the case?
System.Environment.SpecialFolder is definitely a type
Type SpecialFolder, which is nested inside type Environment, is located in namespace System:
C# references that type as a full type name as in the quoted passage; that is, it uses . not only to separate the namespace from the containing type's name, but also to separate the latter from its nested type's name.
By contrast, PowerShell uses a .NET reflection method, Type.GetType(), to obtain a reference to the type at runtime:
That method uses a language-agnostic notation to identify types, as specified in documentation topic Specifying fully qualified type names.Tip of the hat to PetSerAl.
In that notation, it is + that is used to separate a nested type from its containing type (not ., as in C#).
That is, a PowerShell type literal ([...]) such as:
[System.Environment+SpecialFolder]
is effectively the same as taking the content between [ and ], System.Environment+SpecialFolder, and passing it as a string argument to Type.GetType, namely (expressed in PowerShell syntax):
[Type]::GetType('System.Environment+SpecialFolder')
Note that PowerShell offers convenient extensions (simplifications) to .NET's language-agnostic type notation, notably the ability to use PowerShell's type accelerators (such as [regex] for [System.Text.RegularExpressions.Regex]), the ability to omit the System. prefix from namespaces (e.g. [Collections.Generic.List`1[string]] instead of [System.Collections.Generic.List`1[string]]), and not having to specify the generic arity (e.g. `1) when a list of type argument is passed (e.g. [Collections.Generic.List[string]] instead of [Collections.Generic.List`1[string]] - see this answer) for more information.

Cannot convert value of type "System.String" to type "System.Type"

I am trying to build a tfs workstation using PowerShell, but I've become stuck.
In my code are the lines
$teamProjectCollection = [Microsoft.TeamFoundationClient.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$ws = $teamProjectCollection.GetService([type] "Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore")
I got those lines from this answer on another question I recently asked. The answer solved the problem I had then, but unfortunately that second line gets an exception when trying to convert the string to Type. Specifically, the error I get is:
Cannot convert the "Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore" value of type "System.String" to type "System.Type".
I know that the GetService function I'm using expects a System.Type parameter. I also haven't found a means to convert a System.String object into a System.Type object strictly through PowerShell.
So, how do I either fix this or get around this problem?
You must add an assembly to gain access to the [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore] type. Assuming you are in the directory that contains the assembly file, you can run the following in your current PowerShell session.
Add-Type -Path ".\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"

Powershell - convert local time to different timezone

I am trying to convert my system time (EST) to a different timezone (GMT Standard Time) using PowerShell. I have to run this PowerShell command through my RPA automation software so I am looking to use a single command (instead of PS script) to accomplish this task if possible. Here's the command I am trying to use:
$test = Get-Date
[System.TimeZoneInfo}::ConvertTime($test, 'GMT Standard Time')
First line is just to show the logic I am thinking but I will pass it as a variable and so that I truly have to execute only one line of code. However, I get the following error:
PS C:\Users\samsi> [System.TimeZoneInfo]::ConvertTime($test, 'GMT Standard Time')
Cannot find an overload for "ConvertTime" and the argument count: "2".
At line:1 char:1
+ [System.TimeZoneInfo]::ConvertTime($test, 'GMT Standard Time')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Clearly, I don't know much about PowerShell, can someone please help me with this command.
Try this and see if it gets you what you're after.
[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($(Get-Date), [System.TimeZoneInfo]::Local.Id, 'GMT Standard Time')
or if you prefer storing the current date in a variable first (the way you have it in your code)
$test = Get-Date
[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($test, [System.TimeZoneInfo]::Local.Id, 'GMT Standard Time')
Let's look at how to diagnose this.
The error message:
Cannot find an overload for "ConvertTime" and the argument count: "2".
is a common one on PowerShell when calling methods on objects. Sometimes it's misleading. It always means that given the arguments you supplied, none of the method's overloads matched.
Aside: each method has one or more ways you can call it, with parameters of different types, or different number or order of parameters.
In PowerShell, you can see all the overloads by "invoking" the method without parentheses or arguments. So:
[System.TimeZoneInfo]::ConvertTime
Result:
OverloadDefinitions
-------------------
static System.DateTimeOffset ConvertTime(System.DateTimeOffset dateTimeOffset, System.TimeZoneInfo destinationTimeZone)
static datetime ConvertTime(datetime dateTime, System.TimeZoneInfo destinationTimeZone)
static datetime ConvertTime(datetime dateTime, System.TimeZoneInfo sourceTimeZone, System.TimeZoneInfo
destinationTimeZone)
The error message in PowerShell always references the number of arguments, but it sometimes also means that you didn't use the correct type.
So in your example, you did supply 2 arguments, which makes the error confusing.
But the second argument you supplied is a [string]. Looking at the available overloads, you can see that none of the second arguments take a string, they are all looking for an object of type [System.TimeZoneInfo].
Sometimes, you can use a different type, if there's an implicit cast available. For example if a method takes a parameter of type [System.Net.IPAddress] then you can give a string like '127.0.0.1'. That's because [System.Net.IPAddress] knows how to convert an IP string into the object. You can see this by doing something like '127.0.0.1' -as [System.Net.IPAddress] or [System.Net.IPAddress]'127.0.0.1'.
Going back to your use case: it seems you either cannot cast a string to the TimeZoneInfo type, or your string is not valid for that purpose (that is, the cast failed).
So you should first figure out how to create or retrieve a TimeZoneInfo object that represents what you want.
It looks to me like [System.TimeZoneInfo]::GetSystemTimeZones() returns an array of all the time zones on your system.
Filtering that list to find the one you want seems like a good idea. Looking at the list, I can see the string you want to use is in the StandardName property so I'll use this to get the right one:
$gmt = [System.TimeZoneInfo]::GetSystemTimeZones().Where({$_.StandardName -eq 'GMT Standard Time'})[0] # it's an array, so get the first one
Then you can call your original method with that object:
[System.TimeZoneInfo]::ConvertTime($test, $gmt)

How to specify custom COM enum as PowerShell method parameter

How can I create a reference for a enum declared inside a COM object to pass to a method that requires it? Specifically, there is a method SetHomeDir on a 3rd-party COM object that takes in an enum as the only parameter. The definition that parameter expects is basically:
typedef enum
{
abFalse = 0,
abTrue = 1,
abInherited = -2
} SFTPAdvBool;
It appears to be defined somewhere in the COM object, but not as an object that I can create with New-Object. I have tried the following and they all give the same MX Error: 7 response:
$obj.SetHomeDir($true)
$obj.SetHomeDir(1)
$obj.SetHomeDir([Object]1)
$obj.SetHomeDir([Int16]1)
Exception calling "SetHomeDir" with "1" argument(s): "MX Error: 7 (00000007)"
Here are the results from trying some other approaches:
PS C:\> New-Object -ComObject SFTPCOMINTERFACELib.SFTPAdvBool
New-Object : Cannot load COM type SFTPCOMINTERFACELib.SFTPAdvBool.
PS C:\> [SFTPAdvBool]::abTrue
Unable to find type [SFTPAdvBool]:
make sure that the assembly containing this type is loaded.
PS C:\> [SFTPCOMINTERFACELib.SFTPAdvBool]::abTrue
Unable to find type [SFTPCOMINTERFACELib.SFTPAdvBool]:
make sure that the assembly containing this type is loaded.
The method signature that COM exposes to PowerShell looks like this:
PS C:\> $user.SetHomeDir
MemberType : Method
OverloadDefinitions : {void SetHomeDir (SFTPAdvBool)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : void SetHomeDir (SFTPAdvBool)
Name : SetHomeDir
IsInstance : True
Note: This is running under PowerShell 2.0 on Windows Server 2008 R2, but I would consider upgrading the Windows Management Framework to a newer version if necessary.
Update: Here is a screenshot from the Visual Studio object explorer, in case that offers up any clues.
We ended up using a compiled C# interop wrapper around the COM object. I was able to specify an int as the parameter and just used a case statement to pass the correct value from the enum. As far as I can tell there isn't a way to do this directly from Powershell and requires wrapping the COM object in managed code.
We have opened a dialog with Globalscape and hopefully this will be something they address in a future release.
We can try to fool the com object by creating the enum on your own and pass it to the function:
If you can upgrade to Powershell 5 try (in Powershell - enum is a new keyword in ver 5):
Enum SFTPAdvBool
{
abFalse = 0
abTrue = 1
abInherited = -2
}
And call:
$obj.SetHomeDir([SFTPAdvBool]::abTrue)
for anything older than PS 5 you can try:
$code = #"
namespace SFTPCOMINTERFACELib {
public enum SFTPAdvBool {
abFalse = 0,
abTrue = 1,
abInherited = -2
}
}
"#
Add-Type -TypeDefinition $code -Language CSharpVersion3
And call:
$obj.SetHomeDir([SFTPCOMINTERFACELib.SFTPAdvBool]::abTrue)
This will basically create a C# enum and will add it as a type into Powershell.
PowerShell v2.0 is archaic at this point, but it shouldn't be stopping you here. SFTPAdvBool appears to be from the GlobalScape EFT Server COM API, so that's what I'm assuming.
The issue is that you need a value of type SFTPAdvBool, according to the C# scripting examples (See ConfigureUser.cs for one use). For a .Net object, you'd define that as [SFTPAdvBool]::abTrue or [SFTPCOMINTERFACELib.SFTPAdvBool]::abTrue, but I'm not sure if that will work. I've not worked with COM enums in PowerShell before. You might need New-Object -ComObject SFTPCOMINTERFACELib.SFTPAdvBool or some variant.
If nothing works, you could use VBScript, or C#, or contact GlobalScape in the hopes they join the 21st century and drop COM, or use WinSCP's .Net library... but I'm betting you can't since you're working someplace that paid for EFT Server.
There are some hints in their knowledge base that the library doesn't always work correctly out of process, so that would apply remotely, or when using the 32-bit library from a 64-bit process.
For example:
http://forums.globalscape.com/PrintTopic38567.aspx
The solution would be to use the 32-bit powershell in C:\Windows\SysWOW64\WindowsPowerShell\ If you need to call that remotely you may have to do it explicitly using the & operator.

How can I specify the type of a parameter when the object type is from a web service?

I'm writing a PowerShell module. I have a Get-MyPerson function which accepts an Identity parameter, calls a web service and returns an object of type PERSON (the return type from the web service).
I'm now working on a Set-MyPerson object to update a couple of properties. What I want to be able to do is:
Set-MyPerson 1234 -GolfHandicap 22
Get-MyPerson JDoe | Set-MyPerson -GolfHandicap 22
(the latter following Get-ADUser | Set-ADUser usage)
This requires Set-MyPerson to accept a parameter of type string for the former and a parameter of type Person for the latter, using parameter sets to distinguish.
I have the basic functionality working for a string but am struggling with the parameter for Person objects.
[Parameter(ParameterSetName="Person",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[PERSON]$Person,
won't work because PowerShell doesn't recognize PERSON (as expected):
Set-MyPerson : Unable to find type [PERSON]: make sure that the assembly containing this type is loaded.
How can I get PowerShell to recognize my PERSON class?
Do you try with [object] or [psbject] ?
My own solution, which came to me in a moment of echoey isolation, was rather more hassle than #JPBlanc's:
I used the WSDL command to generate a CSharp file:
wsdl http://server.dns.name/webservice/path/service?wsdl
Then I used the CSharp command-line compiler to create an assembly:
csc /target:library PersonService.cs
which created a DLL called PersonService.dll.
And then used:
$assemblyPath = "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\PersonModule\PersonService.dll"
Add-Type -Path $assemblyPath
to load it.