How to pass a custom enum to a function in powershell - powershell

When defining a function, how can you reference a custom enum?
Here's what I'm trying:
Add-Type -TypeDefinition #"
namespace JB
{
public enum InternetZones
{
Computer
,LocalIntranet
,TrustedSites
,Internet
,RestrictedSites
}
}
"# -Language CSharpVersion3
function Get-InternetZoneLogonMode
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[JB.InterfaceZones]$zone
)
[string]$regpath = ("HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\{0}" -f [int]$zone)
$regpath
#...
#Get-PropertyValue
}
Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
But this gives the error:
Get-ZoneLogonMode : Unable to find type [JB.InterfaceZones]. Make sure that the assembly that contains this type is loaded.
At line:29 char:1
+ Get-ZoneLogonMode -zone [JB.InternetZones]::TrustedSites
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (JB.InterfaceZones:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
NB: I'm aware I could use ValidateSet for similar functionality; however that has the disadvantage of only having a name value; as opposed to allowing me to program using friendly names which are then mapped to ints in the background (I could write code for that; but enum seems more appropriate if possible).
I'm using Powershell v4, but ideally I'd like a PowerShell v2 compatible solution as most users are on that version by default.
Update
I've corrected the typo (thanks PetSerAl; well spotted).
[JB.InterfaceZones]$zone now changed to [JB.InternetZones]$zone.
Now I'm seeing error:
Get-InternetZoneLogonMode : Cannot process argument transformation on parameter 'zone'. Cannot convert value "[JB.InternetZones]::TrustedSites" to type
"JB.InternetZones". Error: "Unable to match the identifier name [JB.InternetZones]::TrustedSites to a valid enumerator name. Specify one of the following
enumerator names and try again: Computer, LocalIntranet, TrustedSites, Internet, RestrictedSites"
At line:80 char:33
+ Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-InternetZoneLogonMode], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-InternetZoneLogonMode

The ISE gave this one away to me but your attempted syntax was not completely incorrect. I was able to do this and get it to work.
Get-InternetZoneLogonMode -Zone ([JB.InternetZones]::TrustedSites)
Again, If you look at the highlighting you will see how I came to that conclusion.

Per comments by PetSerAl & CB:
Corrected typo in function definition
from [JB.InterfaceZones]$zone
to [JB.InternetZones]$zone
Changed function call
from Get-InternetZoneLogonMode -zone [JB.InternetZones]::TrustedSites
to Get-InternetZoneLogonMode -zone TrustedSites

Related

Add xml object to xml file in PowerShell

I am trying to create an RDCMan file (.rdg xml file) using PowerShell. I have started by defining this template
$newFileTemplate = '<?xml version="1.0" encoding="utf-8"?>
<RDCMan programVersion="2.7" schemaVersion="3">
<file>
<properties>
<expanded>False</expanded>
<name>Office Servers</name>
</properties>
<displaySettings inherit="None">
<liveThumbnailUpdates>True</liveThumbnailUpdates>
<allowThumbnailSessionInteraction>False</allowThumbnailSessionInteraction>
<showDisconnectedThumbnails>True</showDisconnectedThumbnails>
<thumbnailScale>1</thumbnailScale>
<smartSizeDockedWindows>True</smartSizeDockedWindows>
<smartSizeUndockedWindows>False</smartSizeUndockedWindows>
</displaySettings>
</file>
</RDCMan>
'
before creating an xml object like so
$File = 'D:\Test.rdg'
Set-Content $File $newFileTemplate
[XML]$XMLFile = [XML](Get-Content $File)
I would then like to define a function for adding a group of servers
# This function adds a new group element
Function Add-NewGroup($GroupName,$RDCManFile) {
[xml]$GroupXML = #"
<group>
<properties>
<expanded>False</expanded>
<name>$GroupName</name>
</properties>
</group>
"#
$Child = $RDCManFile.ImportNode($GroupXML.group, $true)
$RDCManFile.Configuration.AppendChild($Child)
}
And call it by running
Add-NewGroup('DCs',$XMLFile)
This would allow me to populate the xml file with all of the OUs in AD.
Is anyone able to tell me where I am going wrong?
Thanks
Update: The error I am getting is
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:179 char:5
+ $Child = $RDCManFile.ImportNode($GroupXML.group, $true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:180 char:5
+ $RDCManFile.Configuration.AppendChild($Child)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
And I am trying to do what was suggested here https://stackoverflow.com/a/29693625/2165019
The property 'Configuration' cannot be found on this object. Verify that the property exists. error at $RDCManFile.Configuration.AppendChild($Child).
If I can accept a .rdg file format and structure as defined in the Script to create a Remote Desktop Connection Manager group from Active Directory Technet article then I'd use
$RDCManFile.RDCMan.file.AppendChild($Child)
Follow the Theo's answer about calling a function.
Pass parameters as positional
Add-NewGroup 'DCs' $XMLFile
or as named
Add-NewGroup -GroupName 'DCs' -RDCManFile $XMLFile
This error (and second) most likely means that $RDCManFile is null.
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:179 char:5
+ $Child = $RDCManFile.ImportNode($GroupXML.group, $true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try adding $RDCManFile | Out-Host at the top of the Add-NewGroup function to check what's contained in that variable.
You need to change the way you are calling the function.
Because of the comma in between the parameters, PowerShell sees this as one array value, so only parameter $GroupName will receive something.
Furthermore, you should not use brackets around the params, call the function like this:
Add-NewGroup 'DCs' $XMLFile
or send the parameters using their names:
Add-NewGroup -GroupName 'DCs' -RDCManFile $XMLFile

How to test a (possible) unknown type?

PowerShell Core appears to have semantic versioning which includes a new type accelerator called [semver] and is based on the System.Management.Automation.SemanticVersion class .
To test for this specific type in the PowerShell Core environment, you would probably use the syntax:
$PSVersionTable.PSVersion -is [semver]
But if you implement this in a script and run this in the Windows PowerShell environment, you will get an error:
Unable to find type [semver].
At line:1 char:31
+ $PSVersionTable.PSVersion -is [semver]
+ ~~~~~~~~
+ CategoryInfo : InvalidOperation: (semver:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
A similar error appears when I compare it to a type name (string):
$PSVersionTable.PSVersion -is `semver`
Cannot convert the "semver" value of type "System.String" to type "System.Type".
At line:1 char:1
+ $PSVersionTable.PSVersion -is 'semver'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], RuntimeException
+ FullyQualifiedErrorId : RuntimeException
(It would have been nice/correct if PowerShell differentiates between providing a [Type] or a 'String' as comparison and just return $False if the string cannot be converted)
What is the best way to test for a type and prevent any error if the type is unknown (as happens with the -is operator for certain types in a specific environment)?
Thanks to vexx32 for this answer:
(see also: Feature Request: -Is operator: suppress "Cannot convert"error #10504)
'UnknownType' -as [type] -and $object -is [UnknownType]
E.g.:
'semver' -as [type] -and $PSVersionTable.PSVersion -is [semver]
The best answer so far were I can come up with myself is:
$Object.PSTypeNames -Contains '.NET Framework type'
e.g.:
$PSVersionTable.PSVersion.PSTypeNames -Contains 'System.Management.Automation.SemanticVersion'
But that will make the use of a type accelerators impossible.

PowerShell error 'can't call null-value expresssion' [duplicate]

I am simply trying to create a powershell script which calculates the md5 sum of an executable (a file).
My .ps1 script:
$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"
If (Test-Path $someFilePath){
$stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$hash
$stream.Close()
}
Else{
Write-Host "Sorry, file $answer doesn't seem to exist."
}
Upon running my script I receive the following error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+ $hash = [System.BitConverter]::ToString($md5.Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
To my understanding, this error means the script is attempting to do something, but another part of the script does not have any information to permit the first part of the script to work properly. In this case, $hash.
Get-ExecutionPolicy outputs Unrestricted.
What is causing this error?
What exactly is my null valued expression?
Any help is appreciated. I apologize if this is trivial and will continue my research.
References:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/27/troubleshoot-the-invokemethodonnull-error-with-powershell.aspx
How to get an MD5 checksum in PowerShell
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Unable to Run [System.__ComObject].InvokeMember within PowerShell Function

I've been trying to write a program to access properties and methods of a 3rd party OLE DLL.
Below code runs fine.
[System.__ComObject].InvokeMember("AppName", [System.Reflection.BindingFlags]::GetProperty, $null, $appObj, $null)
As the invocation is going to be repetitive, I want to call a wrapper like below.
function Get-Property {
param(
$objOLE,
[String] $propertyName
)
[System.__ComObject].InvokeMember($propertyName,[System.Reflection.BindingFlags]::GetProperty,$null,$objOLE,$null)
}
When the script runs
Get-Property($appObj, "AppName")
I got this error:
Exception calling "InvokeMember" with "5" argument(s): "Method 'System.__ComObject.ToString' not found."
At F:\Scripts\test.ps1:21 char:36
+ [System.__ComObject].InvokeMember <<<< ($propertyName,[System.Reflection.BindingFlags]::GetProperty,$null,$objOLE,$null)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
This is confusing. Anybody has an insight? Thank you in advance.
Remember your function is a PowerShell function/command and not a .NET method i.e. don't use parens and don't comma separate args:
Get-Property $appObj AppName
The way you had it, your function gets one argument that is an array with two elements.

Calling [ADSI] with external parameter

I am not very familiar with powershell scripting and I'm stuck on this problem -
I need to make some operations on object retrieved like this:
$object = [ADSI]'LDAP://CN=Test User,OU=Dept,OU=Users,DC=example,DC=org'
...
$object.Commit()
this works fine, but I have to use distinguished name stored in variable - my test script looks like this, but its not working:
$object = [ADSI]'LDAP://$variable'
...
$object.Commit()
the first call to [ADSI] itself doesn't cause error, but any following operation crashes with message:
The following exception occurred while retrieving member "commit": "The server is not operational.
"
At line:1 char:10
+ $object.commit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
I'm pretty sure, that the parameter is sent in some wrong way, but I don't know, how to fix it, can anybody help?
tahnks
Try:
$object = [ADSI]"LDAP://$variable"
Single quotes don't expand variables.