I'm rather new to Powershell and am working on setting up my profile.ps1 file. I have a few managed DLLs that I use often to maintain processes throughout the day which I'd like to be able to load up with quick function calls. So I created this function in my ps1 file:
function LoadSomeDll
{
[System.Reflect.Assembly]::LoadFrom("c:\wherever\SomeLib.dll")
return new-object "SomeLib.SomeObject"
}
Then, in Powershell, I do this:
PS > $myLibInstance = LoadSomeDll
The problem is that $myLibInstance, though it appears to be loaded, doesn't behave the way I expect it to or if it would if I explicitly load it without the function. Say SomeLib.SomeObject has a public string property "ConnectionString" that loads itself (from the registry, yuck) when the object is constructed.
PS > $myLibInstance.ConnectionString
//Nothing returned
But, if I do it without the function, like this:
PS > [System.Reflect.Assembly]::LoadFrom("c:\wherever\SomeLib.dll")
PS > $myOtherLibInstance = new-object "SomeLib.SomeObject"
I get this:
PS > $myOtherLibInstance.ConnectionString
StringValueOfConnectionStringProperty
Why does this happen? Is there any way that I can return an instantiated new-object from a Powershell function?
Thanks in advance.
The problem you're running into is that your original function is returning an array of objects, not a single object.
One of the tricks in PowerShell is understanding that in a function, every statement which evaluates no a non-void value will be written to the pipeline. The return "value" of a function is simply the contents of the pipeline.
The call to LoadFrom returns an assembly. So the actual return of the function LoadSomeDll is an array containing an assembly and an instance of your object. You're actually calling ConnectionString on the type Object[] and hence it silently fails.
Try switching the function to the following. I intentionally left off the keyword return because it's confusing in the context of powershell.
function LoadSomeDll
{
[System.Reflect.Assembly]::LoadFrom("c:\wherever\SomeLib.dll") | out-null
new-object "SomeLib.SomeObject"
}
Related
I am trying to populate a tree structure in Powershell windows form. The only difference is my tree structure will have textboxes, which I found is not possible using TreeView. So I am using a recursive function to populate the form step by step. However, when I try to add_click on any of the form control, it throws an error saying the object is null. I am new on this and would appreciate any suggestions on how to solve this. The exact message is
Cannot bind argument to parameter 'panel' because it is null.
My functions look like this. The click event binds successfully and calls the toggleVisible function, however at runtime when the click happens it does not pass the correct value to the function.
Function handlePanelClick{
$hash | ForEach-Object{
$_.Label.Add_Click({toggleVisible $_.Panel});
}
}
Function toggleVisible{
Param(
[Parameter(Mandatory = $true, Position = 1)]
[System.Object]$panel
)
$panel.Visible = $false;
}
Assuming that $hash is a hashtable, as the name suggests, it is not enumerated in the pipeline, so that $_ in your $hash | ForEach-Object{ ... } command refers to $hash itself, not its entries.
To enumerate the entries, use $hash.GetEnumerator().
Inside a script block ({ ... }) serving as an event delegate, the automatic $_ variable is not defined.
Use the automatic $this variable to refer to the event sender (the object triggering the event).
I've got very weird behaviour which I suppose is related to dot-sourcing somehow, but I cannot wrap my head around it. Here's what I have:
A script sourced.ps1 which contains the two functions and a class:
class MyData {
[string] $Name
}
function withClass() {
$initialData = #{
Name1 = "1";
Name2 = "2";
}
$list = New-Object Collections.Generic.List[MyData]
foreach ($item in $initialData.Keys) {
$d = [MyData]::new()
$d.Name = $item
$list.Add($d)
}
}
function withString() {
$initialData = #{
Name1 = "1";
Name2 = "2";
}
$list = New-Object Collections.Generic.List[string]
foreach ($item in $initialData.Keys) {
$list.Add($item)
}
}
I also have a script caller.ps1 which dot-sources the one above and calls the function:
$ErrorActionPreference = 'Stop'
. ".\sourced.ps1"
withClass
I then call the caller.ps1 by executing .\caller.ps1 in the shell (Win terminal with PS Core).
Here's the behaviour I cannot explain: if I call .\caller.ps1, then .\sourced.ps1 and then caller.ps1 again, I get the error:
Line |
14 | $list.Add($d)
| ~~~~~~~~~~~~~
| Cannot find an overload for "Add" and the argument count: "1".
However, if I change the caller.ps1 to call withString function instead, everything works fine no matter how many times I call caller.ps1 and sourced.ps1.
Furthermore, if I first call caller.ps1 with withString, then change it to withClass, there is no error whatsoever.
I suppose using modules would be more correct, but I'm interested in the reason for such weird behaviour in the first place.
Written as of PowerShell 7.2.1
A given script file that is both dot-sourced and directly executed (in either order, irrespective of how often) creates successive versions of the class definitions in it - these are distinct .NET types, even though their structure is identical. Arguably, there's no good reason to do this, and the behavior may be a bug.
These versions, which have the same full name (PowerShell class definitions created in the top-level scope of scripts have only a name, no namespace) but are housed in different dynamic (in-memory) assemblies that differ by the last component of their version number, shadow each other, and which one is effect depends on the context:
Other scripts that dot-source such a script consistently see the new version.
Inside the script itself, irrespective of whether it is itself executed directly or dot-sourced:
In PowerShell code, the original version stays in effect.
Inside binary cmdlets, notably New-Object, the new version takes effect.
If you mix these two ways to access the class inside the script, type mismatches can occur, which is what happened in your case - see sample code below.
While you can technically avoid such errors by consistently using ::new() or New-Object to reference the class, it is better to avoid performing both direct execution and dot-sourcing of script files that contain class definitions to begin with.
Sample code:
Save the code to a script file, say, demo.ps1
Execute it twice.
First, by direct execution: .\demo.ps1
Then, via dot-sourcing: . .\demo.ps1
The type-mismatch error that you saw will occur during that second execution.
Note: The error message, Cannot find an overload for "Add" and the argument count: "1", is a bit obscure; what it is trying to express that is that the .Add() method cannot be called with the argument of the given type, because it expects an instance of the new version of [MyData], whereas ::new() created an instance of the original version.
# demo.ps1
# Define a class
class MyData { }
# Use New-Object to instantiate a generic list based on that class.
# This passes the type name as a *string*, and instantiation of the
# type happens *inside the cmdlet*.
# On the second execution, this will use the *new* [MyData] version.
Write-Verbose -Verbose 'Constructing list via New-Object'
$list = New-Object System.Collections.Generic.List[MyData]
# Use ::new() to create an instance of [MyData]
# Even on the second execution this will use the *original* [MyData] version
$myDataInstance = [MyData]::new()
# Try to add the instance to the list.
# On the second execution this will *fail*, because the [MyData] used
# by the list and the one that $myDataInstance is an instance of differ.
$list.Add($myDataInstance)
Note that if you used $myDataInstance = New-Object MyData, the type mismatch would go away.
Similarly, it would also go away if you stuck with ::new() and also used it to instantiate the list: $list = [Collections.Generic.List[MyData]]::new()
I'm using a function that I call from another script. It prompts a user for input until it gets back something that is not empty or null.
function GetUserInputValue($InputValue)
{
do{
$UserValue = Read-Host -Prompt $InputValue
if (!$UserValue) { $InputValue + ' cannot be empty' }
}while(!$UserValue)
$UserValue
return $UserValue
}
The issue is quite strange and likely a result of my lack of powershell experience. When I run the code and provide empty results, the messages from the if statement queue up and only display when I finally provide a valid input. See my console output below.
Console Results
test:
test:
test:
test:
test:
test:
test: 1
test cannot be empty
test cannot be empty
test cannot be empty
test cannot be empty
test cannot be empty
test cannot be empty
1
I can make this work however in the main file with hard coded values.
do{
$Server = Read-Host -Prompt 'Server'
if (!$Server) { 'Server cannot be empty' }
}while(!$Server)
I'm working Visual Studio Code. This is a function I have in another file I've named functions.ps1.
I call this from my main file like this,
$test = GetUserInputValue("test")
$test
When you put a naked value in a script like "here's a message" or 5 or even a variable by itself $PID what you're implicitly doing is calling Write-Output against that value.
That returns the object to the pipeline, and it gets added to the objects that that returns. So in a function, it's the return value of the function, in a ForEach-Object block it's the return value of the block, etc. This bubbles all the back up the stack / pipeline.
When it has nowhere higher to go, the host handles it.
The console host (powershell.exe) or ISE host (powershell_ise.exe) handle this by displaying the object on the console; this just happens to be the way they handle it. Another host (a custom C# application for example can host the powershell runtime) might handle it differently.
So what's happening here is that you are returning the message that you want to display, as part of the return value of your function, which is not what you want.
Instead, you should use Write-Host, as this writes directly to the host, skipping the pipeline. This is the correct command to use when you want to display a message to the user that must be shown (for other information you can use different commands like Write-Verbose, Write-Warning, Write-Error, etc.).
Doing this will give you the correct result, and prevent your informational message from being part of the return value of your function.
Speaking of which, you are returning the value twice. You don't need to do:
$UserValue
return $UserValue
The first one returns the value anyway (see the top of this answer); the second one does the same thing except that it returns immediately. Since it's at the end of the function anyway, you can use wither one, but only use one.
One more note: do not call PowerShell functions with parentheses:
$test = GetUserInputValue("test")
This works only because the function has a single parameter. If it had multiple params and you attempted to call it like a method (with parentheses and commas) it would not work correctly. You should separate arguments with spaces, and you should usually call parameters by name:
$test = GetUserInputValue "test"
# better:
$test = GetUserInputValue -InputValue "test"
I have a C# project that I'm consuming with PowerShell.
A method returns an object that have not been fully initialized and that calls P/Invoke under the hood through get properties.
When I call the method, the script crashes because of an accessViolationException that is caused by the call of a property on that partially initialized object, but I didn't call it.
Why do Powershell act like this? is there an option to disable that "eager property evaluation"?
The original issue is the one posted here: https://github.com/ZeBobo5/Vlc.DotNet/issues/330
Add-Type -Path ".\Other\VLC\Vlc.DotNet.Core.dll"
Add-Type -Path ".\Other\VLC\Vlc.DotNet.Core.Interops.dll"
$Cameras = New-Object System.Collections.ArrayList
$Test = New-Object System.Uri("rtsp://192.168.0.50/axis-media/media.amp?camera=1")
$Cameras.Add($Test)
$VlcLibDirPath = (Get-Location).Path + ".\Other\VLC\libvlc_x64"
$VlcLibDir = New-Object System.IO.DirectoryInfo($VlcLibDirPath)
$VlcOpt = "--rtsp-user=admin", "--rtsp-pwd=12345"
$Plyr = New-Object Vlc.DotNet.Core.VlcMediaPlayer($VlcLibDir, $VlcOpt)
for ($i=0; $i -lt $Cameras.Count; $i++)
{
$Plyr.SetMedia($Cameras[$i]) #Fails here with System.AccessViolationException
$Plyr.Play
$Plyr.Stop
}
SetMedia returns a VlcMedia, which contains a Statistics property, which is automatically invoked by PowerShell.
Code for VlcMedia can be found here : https://github.com/ZeBobo5/Vlc.DotNet/blob/develop/src/Vlc.DotNet.Core/VlcMedia/VlcMedia.cs
It's difficult to tell without seeing your code, but there's tons of ways this could be happening. If the object is being displayed at all, the properties are probably all being read.
You should change those to methods, and then they won't get read without specifically being invoked.
Or, change your getters to detect an uninitialized object (you should be doing this already if it's possible for consumers to end up with such an object).
Edit:
With your code posted, it's clear:
$Plyr.SetMedia($Cameras[$i]) #Fails here with System.AccessViolationException
SetMedia returns a VlcMedia, which contains a Statistics property, which is automatically invoked by PowerShell.
Everything returned in PowerShell goes somewhere. If you don't assign it or redirect it, it gets sent to the pipeline.
It seems that you don't want or need the output from this method, so you should either assign it to a variable or dispose of the return in one of a few ways:
[null]$Plyr.SetMedia($Cameras[$i])
$null = $Plyr.SetMedia($Cameras[$i])
$Plyr.SetMedia($Cameras[$i]) | Out-Null
(note: piping to Out-Null is the least performant, which is magnified since you're doing this in a loop)
If you want to use the value later (not shown in your code), assign it and use it later.
I have a strange one I have searched the existing Q&A and haven't found a match.
I have written my functions using parameter validation using the basic format
function FunctioName
{
[CmdletBinding()]
Param(
[parameter(Mandatory)]
[String]$VariableName
)
When I set the parameter to Mandatory as above I get a parameter binding exception indicating a null value was passed. Running the script in debug I can see the function parameter being passed is not null and is a valid string.
When I run the script in the exact same way without the mandatory flag the string is passed into the function and it executes correctly.
Has anyone got any ideas, what could be the issue. This problem is affecting a number of functions in my application interestingly it appears that the affected functions all have only a single parameter functions with multiple parameters do not appear to be affected.
Ok thanks guys for your feedback its much appreciated. BTW i am using powershell 5 .
Further to the issue, looking into it further I found that the variable was being passed to the function as an array of strings, however an empty string value was being appended into the array which I believe was the cause for the issue. This is where it starts to get interesting, I will need to give a bit more background.
The script I am running queries active directory for user attributes meeting specific conditions, those that match I create an array of strings with each value a delimited value of the user,hostname and other attribute properties.
To ensure that I am getting the latest values I use the ASDI GetInfo method,which seems to trigger the odd behavior.
At a high level the functions are
Function GetuserAttr
{
$inscopeusers = New-Object System.Collections.ArrayList
$accountlist = (Get-ADUser -Filter { attribute1 -eq "value"} -Properties attribute1).SamAccountName
foreach ($user in $accountlist)
{
$DN = getDN($user) # basically a funtion I wrote to create ASDI object for user account.
$DN.GetInfo() # this method call appears to cause issues
$attr1 = $DN.Get("Attribute1")
$attr2 = $DN.Get("Attribute2")
$hoststring = "$($user)|$($attr1)|$($attr2)"
$inscopeusers.Add($hoststring) > null
}
return $inscopeusers
}
The string array returned in this function is fed into a number of other functions, one of which is the one that was giving the error that I originally brought up.
The thing is when I use the GetInfo method the array returned by this function contains several null values in the array, when I remove the command the array has no null strings.
Even more strange when I am operating on the array in other functions it appears that the array looses some of its properties when the GetInfo method is used. So for instance I am able to use the foreach loop to iterate through array values but I cannot access an array value by index such as $array[1].
By simply commenting out the GetInfo method call in the function the array returned seems to function normally and you can access array values by index.
I have another function that also uses GetInfo and returns a hash table, when I try to operate on the returned hashtable I cannot access values using a key value such as $hashtable['key'], but I can access them using $hashtable.key. I know this is really weird and can't really think what it could be
Has any one else experienced a similar problem.
You're missing an argument.
Function Test
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[String]
$Variable
)
Write "$Variable"
}