Why is Enumeration Name property not working? - powershell

I have a script that i want to display the connection strings of a database
Import-Module SqlServer
$AS = New-Object Microsoft.AnalysisServices.Server
$AS.connect("server1")
Now if i use the FindByName() property
$db = $AS.Databases.FindByName("database1")
$db.DataSources[0].ConnectionString
I get back the connection string successfully
however if i use Enumerator
foreach ($db in $AS.Databases.GetEnumerator())
{ $dbName = $db.Name
$dbName
$dbName.DataSources[0].ConnectionString
}
I get back the database name along with error/exception (because it couldnt get connection string for some reason):
database1
Cannot index into a null array.
database2
Cannot index into a null array.
I tried the following also:
$database1 = "database1"
$database1.DataSources[0].ConnectionString
and i also get back the same exception
So why is it that only FindByName works?
for additional info, this is what GetEnumerator lists:
$AS.Databases.GetEnumerator()
but also $AS.Databases
outputs the same thing...so whats even the point of the enumerator?
gm -i $AS.Databases
gm -i $AS.Databases..GetEnumerator()

Part of what you're seeing is PowerShell's handling of (some) enumerables. Many (most?) are unrolled by PowerShell automatically, so the call to .GetEnumerator() isn't needed.
That's what's happening in your last example, looking at $AS.Databases vs $AS.Databases.GetEnumerator(). But it's only because you sent it out to the pipeline in that case; it's the display process that did the unrolling (in both cases).
If you did gm -i $AS.Databases vs gm -i $AS.Databases.GetEnumerator() you're going to see the difference; same if you assigned each of those to a variable and tried to call methods on them.
But back to using foreach it should again be redundant: foreach ($db in $AS.Databases) should work the same as foreach ($db in $AS.Databases.GetEnumerator()) but I don't have this type in my env right now to test that.
So back to the issue at hand inside the foreach, I suggest you start checking types again. Compare:
$db = $Analysis_Server.Databases.FindByName("database1")
gm -i $db
to
foreach ($db in $AS.Databases.GetEnumerator())
{
gm -i $db
break
}
You might find the types aren't what you think.
This is especially true because you're using dot . notation, because PowerShell has another array shortcut built-in since version 3, whereby you can use . on an array of types, to return an array of the .Property of each item. For example:
$p = Get-Process chrome # choose your own adventure
$p.Count
$p[0].Name
$p.Name
So a property you thought you were accessing on a single object, may have been on an array of objects, and may have been returning an array (or a single object), and handing that in the foreach may have returned a different quantity, or something, resulting in your attempt to index into what used to be an array, no longer work.
But again it's speculation on my part because I don't have those objects. Hopefully this helps you dig deeper into it though.

PowerShell does its own enumerating.
This done the trick!
foreach ($db in $AS.Databases){
Write-Hst $db.Name -Fore green
$db.DataSources | ForEach-Object{$_.ConnectionString}
}

Related

Error when running a dot-sourced script after executing it

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()

How to delete previous database snapshot using regex?

We are restoring a database called Cube1 as "snapshots" using below command.
$CUBE = "$CUBE-Snapshot-$dateStamp"
Restore-ASDatabase -Server $Target_Server -RestoreFile $BFile -Name $CUBE -Security:$SecurityChoice -AllowOverwrite -ErrorAction Stop
However, this is supposed to run weekly indefinitely and our server memory capacity will be diminished leading to performance issues eventually, which we don't want.
Therefore, I'd like to delete existing snapshots, so ultimate result would be something like this (1 snapshot only weekly):
I tried the following:
Import-Module sqlserver
$AnalysisServer = New-Object Microsoft.AnalysisServices.Server
$AnalysisServer.connect("$Target_Server")
$AnalysisServer.Databases["*$CUBE-Snapshot*"].Drop()
and the drop operation failed.
You cannot call a method on a null-valued expression.
When specifying manually the snapshot name:
$AnalysisServer.Databases["Cube1-Snapshot-05-30-2021-0314PM"].Drop()
The drop operation succeeds.
I suppose I need to use some sort of regex then since wildcards didn't seem to work for the name, so how do I accomplish that?
Using [...] to index into the .DataBases collections corresponds to the parameterized .Item[] property, which supports (a) targeting a database by numerical index or (b) by verbatim name - using patterns to match database names is not supported.
Therefore, you need to filter the database collection explicitly, which you can do with the .Where() array method, combined with member-access enumeration, which allows you to call the .Drop() method on every matching database:
$AnalysisServer.Databases.Where({ $_.Name -like "*$CUBE-Snapshot*" }).Drop()
Note: If no databases match, the above will generate a statement-terminating error; to avoid that, use a two-step approach:
$matchingDbs = $AnalysisServer.Databases.Where({ $_.Name -like "*$CUBE-Snapshot*" })
if ($matchingDbs) { $matchingDbs.Drop() }
To delete all snapshots except the most recent one, based on the naming convention shown in the question:
$matchingDbs = $AnalysisServer.Databases.Where({ $_.Name -like "*$CUBE-Snapshot*" })
if ($matchingDbs.Count -ge 2) {
($matchingDbs | Sort-Object Name -Descending | Select-Object -Skip 1).Drop()
}

How do i return compatibility level of just one database?

I referenced this page: https://technet.microsoft.com/en-us/hh213141(v=sql.100)
Import-Module SqlServer
$as = New-Object Microsoft.AnalysisServices.Server
$as.connect("$Server")
$as.databases
Write-Host "Compatibility level ="$as.DefaultCompatibilityLevel
but this returns ALL databases back...
I want to specify just one database to get the compatibility level of...
I tried this,
$as.databases["$Database"]
the DB i am interested in has lvl 1103,
but it seems not to return the proper level, because its returning 1200...
I am not familiar with this API, but I see that the $as.Databases property is of type DatabaseCollection. The DatabaseCollection class does have indexers that take either an Int32 or a String, like you're attempting to use with $as.databases["$Database"].
Note that the documentation for the String indexer says the parameter is an "identifier" for the database to be returned. Also note that the Database class has separate properties for ID and Name, so there is a distinction between the two. So, my suggestion is, make sure you are passing the ID, not the name, when you try to retrieve a Database instance that way.
Alternatively, if you do want to search by name you could use the FindByName method...
$as.Databases.FindByName($Database)
...or GetByName method...
$as.Databases.GetByName($Database)
...with the difference being that the former returns $null if no such database exists and the latter throws an exception.
If all else fails you could retrieve the desired database like this...
$as.Databases | Where-Object { $_.ID -eq $Database }
...or like this...
$as.Databases | Where-Object { $_.Name -eq $Database }
...depending on which property corresponds to the value in $Database.
Finally, in your code you are attempting to access a DefaultCompatibilityLevel property, which I don't see defined in the Database class. There is, however, a CompatibilityLevel property.

Why does powershell executes my property getters

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.

How to make a PSCustomObject with Nested Values

I am trying to create a PSCustomObject with nested values and am having a really tough time, I see plenty of examples of hash tables and pscustom objects but for only extremely basic sets of data.
I am trying to create a a pscustom object that will have a server name property and then another property that has an array of services as well as their current running status.
I was able to make a hash table of the services and their running status but when I try to make an object with the has table it doesnt work very well:
hash table contains service names and their running status (stopped or running)
$hashtable
$myObject = [PSCustomObject]#{
Name = "$server"
Services = "$hashtable"
}
I am open to anything really, I have plenty of examples of how to convert items from JSON or XML and would love be able to use those as well but still having the same issue with being able to format the data in the first place.
edit: sorry about some of the vagueness of this post. As some people have already mentioned, the problem was the double qoutes around the hashtable. Everything is working now
As #t1meless noted in the comments, when you enclose a variable in double quotes it will attempt to convert that value to a string. For a Hashtable object, rather than give any information on from the object this will return "System.Collections.Hashtable". If you remove the double quotes, it will store the value of the hashtable as you are intending.
Here is a full example of what pulling the service information from a server and storing the values in a custom object. Note that $server can still be left in quotes as it is a string, but since it's already a string this would be unnecessary.
$myObject = Foreach ($Server in $Servers) {
$hashtable = #{}
Get-Service -ComputerName $Server | ForEach-Object { $hashtable.Add($_.name,$_.Status}
[PSCustomObject]#{
Name = "$Server"
Services = $hashtable
}
}