Access DLL classes using PowerShell - class

I'm trying to use PowerShell to control a Bluethooth dongle which has API document and dll released.
There is an MasterEmulator class under namespace "Nordicsemi" available, I tested it with C#, I can new an instance with MasterEmulator constructor like below, all other functions work fine too.
MasterEmulator masterEmulator = new MasterEmulator();
However I try to do the same with PowerShell with below script.
[System.Reflection.Assembly]::LoadFile($fullpath)
$MasterEmulatorInstance = New-Object Nordicsemi.MasterEmulator
And I get below error:
+ $MasterEmulatorInstance = New-Object Nordicsemi.MasterEmulator
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object],MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
The dll seems to be loaded correctly, I just can't get the constructor to work, I've checked other related posts but New-Object seems to be the only way to access a class from a .Net dll. Not sure what I'm doing wrong here, any hint would be appreciated, thanks.
Update:
Thanks for the replies, I tried more methods of loading assembly like below.
[System.Reflection.Assembly]::LoadFrom($fullpath) | Out-Null
and also without Out-Null cmdlet
[System.Reflection.Assembly]::LoadFrom($fullpath)
the output shows
GAC Version Location
--- ------- --------
False v4.0.30319 D:\Test\MasterEmulator.dll
and still gives me the same error, I also tried below methods.
[reflection.assembly]::loadwithpartialname("MasterEmulator.dll") | Out-Null
Add-Type -Path $fullpath
and still no luck, all of these methods give me the exact same error when I call the constructor.
New-Object : 以 "0" 引數呼叫 ".ctor" 時發生例外狀況: "無法載入檔案或組件 'IronPython, Version=2.7.0.40, Culture=neutral, PublicKeyToken=7f709c5b713576e1' 或其相依性的其中之一。 系統找不到指定的檔案。"
位於 D:\Test\test.ps1:3 字元:27
+ $MasterEmulatorInstance = New-Object Nordicsemi.MasterEmulator
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object],MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
sorry about the Chinese in the error message since the system I'm running is in Chinese, any other ideas?

Try using LoadFrom. Here is how I load MSTranslitTools.DLL which does transliteration.
function load_transliterate(){
$dll = Resolve-Path ".\tools\transliterate\MSTranslitTools.DLL"
[System.Reflection.Assembly]::LoadFrom($dll) | out-null
$specfile = Resolve-Path "Serbian Cyrillic to Latin.tms"
$tspec = [System.NaturalLanguage.Tools.TransliteratorSpecification]::FromSpecificationFile($specfile)
$script:trans = [System.NaturalLanguage.Tools.Transliterator]::FromSpecification($tspec)
Write-Verbose "Transliteration: $($trans.Input) -> $($trans.Output)"
}
Read about the difference here. See also this SO question.

Related

System.IO.Compression.ZipFileExtensions - CreateEntryFromFile giving "because it is being used by another process" on zip

I am trying to compress 1 file into a new archive. The below code works.... most of the time. However, once in a while (network issues?) I changed the code (see below) to create a unique name, but I still occasionally get this error.
Is there any way to work around this problem? I'm on powershell 3 so compress-archive isn't an option, though I can probably get pscx installed.
Exception calling "Open" with "2" argument(s): "The process cannot access the file '\\path\share$\folder\filename_20200221_14__20200224_102143.zip' because it is being used by another process."
At line:3 char:5
+ [System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile] ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : IOException
Here's the code I'm using.
I'm doing a "foreach ($file in $files_to_process)", but was able to duplicate the error by using a foreach {} to set variables, then run the below code. Subsequent runs are working, naturally.
$timestamp = (get-date).ToString("yyyyMMdd_HHmmss")
# Now create the zip file and remove the old one
[string]$zipFN = "$OnPremDirectoryDone$($file.basename)__$($timestamp).zip"
[string]$fileToZip = "$OnPremDirectory$($file.name)"
[System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Update))
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf))
$ZipFile.Dispose()
remove-item "$fileToZip"

Powershell V2.0 error:Cannot bind parameter 'FilterScript'

I'm trying to create a dictionary in Powershell. Here is the script, I'm working on,
$environmentId = "Test"
$Dictionary = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$xml = [xml] (Get-Content "deploy.config")
$xml.SelectNodes("descendant::configuration/environment[#id='$($environmentId)']/descendant::text()[normalize-space()]") | ? Value | % {
$Dictionary.Add($_.ParentNode.ToString(), $_.Value)
}
write-output $Dictionary
This script is working in Powershell Version 4.0. But currently we are using Version 2.0. When I run this script on 2.0 version, throwing following error,
Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "Value" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
At C:\Users\pwsp_kkumar\Desktop\dictionary.ps1:6 char:129
+ $xml.SelectNodes("descendant::configuration/environment[#id='$($environmentId)']/descendant::text()[normalize-spa
ce()]") | ? <<<< Value | % {
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WhereObjectCommand
Can someone please suggest me the Powershell version 2.0 equivalent command, to fix the above error. Thank you.
The problem is with this part of the pipeline:
? Value
If you're trying to make sure that the Value property is not null, you could use
? {$_.Value}
That should work with no problem. It also matches what you're adding later ($_.Value).

Delete a wiki page with powershell

I need help with my code.
I first tried to create a new wiki page in SharePoint 2013 and that worked perfectly.
Now I'm trying to delete a wiki page and that doesn't work very well.
My code:
Add-Type –Path "C:\Users\Benutzername\AppData\Local\Apps\OfficeDevPnP.PowerShell.V15.Commands\Modules\OfficeDevPnP.PowerShell.V15.Commands\Microsoft.SharePoint.Client.dll"
Add-Type –Path "C:\Users\Benutzername\AppData\Local\Apps\OfficeDevPnP.PowerShell.V15.Commands\Modules\OfficeDevPnP.PowerShell.V15.Commands\Microsoft.SharePoint.Client.Runtime.dll"
Function Delete-WikiPage ([Microsoft.SharePoint.Client.ClientContext]$Context, [string]$WikiLibraryTitle,[string]$PageName)
{
$wikiLibrary = $context.Web.Lists.GetByTitle($wikiLibraryTitle)
$context.Load($wikiLibrary.RootFolder.Files)
$context.ExecuteQuery()
$wikiPage = $wikiLibrary.RootFolder.Files | Where {$_.Name -eq $pageName}
$context.Load($wikiPage)
$context.DeleteObject()
}
$Url = "hhtps://sharepoint.com"
$context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
$pageName = "Testlauf.aspx"
Delete-WikiPage -Context $context -WikiLibraryTitle "Testwiki" -PageName $pageName
I got an error message about the DeleteObject() method but I didn't find anything how I can fix that:
Error when calling the method [Microsoft.SharePoint.Client.ClientContext] no method found with the name "DeleteObject".
In C:\Users\Benutzername\Desktop\Projektarbeit_Wiki\PowerShell\Delete_WikiPage.ps1:12 Zeichen:5
+ $context.DeleteObject()
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
I can only work with methods from the Add-Types. Can anyone help me with this?
You use the CSOM in PowerShell. (you load the CSOM DLL ).
So you should search information with SharPoint CSOM.
To answer you question, you use : DeleteObject() on you object : context. This methode doesn't exist on the Context Object. But the methode exist on the File.
Si you should try something like :
$wikiPage = $wikiLibrary.RootFolder.Files | Where {$_.Name -eq $pageName}
$context.Load($wikiPage)
$context.ExecuteQuery() //Get the item, but not sure this is needed
$wikiPage.DeleteObject()
$context.ExecuteQuery()
personal Note :
You should use CAML query to retrieve your WikiPage, not this: $wikiPage = $wikiLibrary.RootFolder.Files | Where {$_.Name -eq $pageName}
With this kind of query you have bad performance, and you can raise exception list threshold

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.

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.