I'm writing a NavigationCmdletProvider for PowerShell. Through the GetItem and GetChildItems overrides, there are various types of objects that are written to the pipeline.
The docs for IPropertyCmdletProvider interface tell us the following:
Developers should implement this
interface under the following
conditions:
When users must use cmdlets such as the Get-Property and Set-Property
cmdlets.
For a providers that derive from the ItemCmdletProvider,
ContainerCmdletProvider, or
NavigationCmdletProvider classes.
Confusion:
Not a lot of useful information in my opinion because how would a user know if they must use the Get-Property and Set-Property cmdlet's? I would imagine that's up to the Cmdlet author. The big confusion (for me at least) is if the Cmdlet writes the objects to the pipeline; and those objects have properties exposed that are callable (i.e. get/set); what benefits does calling Get-Property/Set-Property have over manipulating the object(s) directly?
Question:
Under what circumstances should the IPropertyCmdletProvider interface be implemented?
I know I'm missing something here! Any insight would be greatly appreciated.
Wow those docs are a bit old. There are no Get/Set-Property cmdlets. This must be referring to the Get/Set-ItemProperty cmdlets. In the case of the RegistryProvider, these cmdlets are essential because it is the only way to access registry values. That is, the Get-Item/ChildItem cmdlets only return RegistryKey objects and never a registry value object (they don't exist in .NET). You have to use Get/Set-ItemProperty to get/set specific regvals under a regkey.
OTOH the FileSystem provider allows you to directly access containers (dirs) and leafs (files). You can get the content of a file directly. Still, you can use Get-ItemProperty if you want to get the LastWriteTime of a file:
PS> Get-ItemProperty -Path .\DotNetTypes.format.ps1xml -Name LastWriteTime
PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Win
dows\System32\WindowsPowerShell\v1.0\DotNetT
ypes.format.ps1xml
PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Win
dows\System32\WindowsPowerShell\v1.0
PSChildName : DotNetTypes.format.ps1xml
PSDrive : C
PSProvider : Microsoft.PowerShell.Core\FileSystem
LastWriteTime : 4/24/2009 11:21:46 AM
However, I wouldn't normally access this property in this fashion. I find the output is way to verbose. I would do this:
PS> (Get-Item .\DotNetTypes.format.ps1xml).LastWriteTime
Friday, April 24, 2009 11:21:46 AM
As for guidance, I would say that you really need to implement this interface if you take the RegistryProvider approach but it is less important if you go the route the FileSystem provider went because you can easly access the properties directly of the objects returned by Get-Item/ChildItem.
Related
I have a few questions about the following code.
Get-DBAAgentJob -SqlInstance *instancename* | Where-Object { $_.HasSchedule -Match "False" }| Out-GridView
In the Where-Object, there is $.HasSchedule. What is '$.HasSchedule'? I looked in the help for Where-Object and online and I don't understand what that is. Is it a function?
What does this syntax signify/do $_ ?
What all can I filter for in Where-Object other than .HasSchedule? Also,where I can find out how to figure that out please? If it's not in help or books online or a google search, I'm not sure. My google search algorithm is probably not good enough to get me in the ballpark.
I'm curious what are all the things I can filter on in the Where-Object in this line of code. For example, instead of has schedule, if I wanted to look where the job is not enabled, is there a .NotEnabled?
Thanks for the help.
The Where-Object clause is a way to filter objects returned from a cmdlet on a certain property.
In your example, it is filtering objects on the HasSchedule property. The example's filter says this property needs to be False in order for the objects to get piped through the pipeline where the next cmdlet takes them as input.
It tests the objects using the $_ Automatic variable, which represents each object in sequence that is coming in from the Get-DbaAgentJob cmdlet.
Usually, to find out what an object would look like, you can simply google for it.
In this case, if you look for Get-DBAAgentJob, you will find this page, where you can look at the function itself.
Here you can find what properties each returned object has:
ComputerName, InstanceName, SqlInstance, Name, Category, OwnerLoginName, IsEnabled, LastRunDate, DateCreated, HasSchedule, OperatorToEmail.
As you can see, there is a property IsEnabled, so you can filter on Not enabled with
Where-Object { -not $_.IsEnabled }
See: PowerShell Logical Operators
If you click the home page for dbatools you'll fine a section called docs where you can learn more.
Browse for free ebooks on PowerShell
Hope that helps
In case someone finds this useful in the future, #Theo's answer was helpful in giving me the base understanding of my question.
I learned more on this today and I will post it to help others in the future.
To answer my question:
The .hasSchedule is one of the many properties of Get-DBAAgentJob.
The . 'dot'. "The most common way to get the values of the properties of an object is to use the dot method." Books Online (BOL)
"All Properties and Methods for a given object are called members... Help files for any given command do not tell you what kinds of objects, properties, and methods are available, the only way to tell is to use the Get-Member' cmdlet. Learning PowerShell Jonathan Hassall
This code will tell you all of the properties and methods for a member, in this case the one I was interested in learning more about.
Get-DBAAgentJob -SqlInstance instancename | get-member
This shows me all the properties and methods available, including hasSchedule and isenabled
BOL: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_properties?view=powershell-7
In my new project team, for each powershell cmdlet they have written proxy function. When i asked the reason for this practice, they said that it is a normal way that automation framework would be written. They also said that If powershell cmdlet is changed then we do not need to worry ,we can just change one function.
I never saw powershell cmdlets functionality or names changed.
For example, In SQL powershell module they previously used snapin then they changed to module. but still the cmdlets are same. No change in cmdlet signature. May be extra arguments would have added.
Because of this proxy functions , even small tasks taking long time. Is their fear baseless or correct? Is there any incident where powershell cmdlets name or parameter changed?
I guess they want to be extra safe. Powershell would have breaking changes here and here sometimes but I doubt that what your team is doing would be impacted by those (given the rare nature of these events). For instance my several years old scripts continue to function properly up to present day (and they were mostly developed against PS 2-3).
I would say that this is overengineering, but I cant really blame them for that.
4c74356b41 makes some good points, but I wonder if there's a simpler approach.
Bear with me while I restate the situation, just to ensure I understand it.
My understanding of the issue is that usage of a certain cmdlet may be strewn about the code base of your automation framework.
One day, in a new release of PowerShell or that module, the implementation changes; could be internal only, could be parameters (signature) or even cmdlet name that changes.
The problem then, is you would have to change the implementation all throughout your code.
So with proxy functions, you don't prevent this issue; a breaking change will break your framework, but the idea is that fixing it would be simpler because you can fix up your own proxy function implementation, in one place, and then all of the code will be fixed.
Other Options
Because of the way command discovery works in PowerShell, you can override existing commands by defining functions or aliases with the same name.
So for example let's say that Get-Service had a breaking change and you used it all over (no proxy functions).
Instead of changing all your code, you can define your own Get-Service function, and the code will use that instead. It's basically the same thing you're doing now, except you don't have to implement hundreds of "empty" proxy functions.
For better naming, you can name your function Get-FrameworkService (or something) and then just define an alias for Get-Service to Get-FrameworkService. It's a bit easier to test that way.
One disadvantage with this is that reading the code could be unclear, because when you see Get-Service somewhere it's not immediately obvious that it could have been overwritten, which makes it a bit less straightforward if you really wanted to call the current original version.
For that, I recommend importing all of the modules you'll be using with -Prefix and then making all (potentially) overridable calls use the prefix, so there's a clear demarcation.
This even works with a lot of the "built-in" commands, so you could re-import the module with a prefix:
Import-Module Microsoft.PowerShell.Utility -Prefix Overridable -Force
TL;DR
So the short answer:
avoid making lots and lots of pass-thru proxy functions
import all modules with prefix
when needed create a new function to override functionality of another
then add an alias for prefixed_name -> override_function
Import-Module Microsoft.PowerShell.Utility -Prefix Overridable -Force
Compare-OverridableObject $a $b
No need for a proxy here; later when you want to override it:
function Compare-CanonicalObject { <# Stuff #> }
New-Alias Compare-OverridableObject Compare-CanonicalObject
Anywhere in the code that you see a direct call like:
Compare-Object $c $d
Then you know: either this intentionally calls the current implementation of that command (which in other places could be overridden), or this command should never be overridden.
Advantages:
Clarity: looking at the code tells you whether an override could exist.
Testability: writing tests is clearer and easier for overridden commands because they have their own unique name
Discoverability: all overridden commands can be discovered by searching for aliases with the right name pattern i.e. Get-Alias *-Overridable*
Much less code
All overrides and their aliases can be packaged into modules
I have a PowerShell function Sort-VersionLabels. When I add this function to a module, Import-Module complains:
WARNING: Some imported command names include unapproved verbs which might make
them less discoverable. Use the Verbose parameter for more detail or type
Get-Verb to see the list of approved verbs.
According to this, Sort is a "reserved verb".
What could be a good (and approved) alternative?
Update
The function takes a array of version numbers in the form: <major>.<minor>.<revision>[-<milestone[nr]>]. Milestone can be dev, alpha, beta or stable (in that order). So the standard Sort-Object function won't work.
It outputs the sorted array to the pipe line.
I think something like ConvertTo-SortedVersionLabels, while a little bit awkward, uses an approved and non-reserved verb but is still clear.
You could also make sorting a parameter to a different function, like Get-VersionLabels -Sorted.
How you would work that in depends on your module as a whole and whether you have such a function to modify. It's unclear from your current post, but if you edit it with more details we might be able to provide more suggestions.
The core of this issue will generate opinionated results. This creates a conundrum since you are looking for something specific that the current answers have been unable to address. I understand that you are looking for a solution that logically fits your function while being in the standard verb list, which is admirable. To continue from an earlier comment I made I am going to try and state a case for all the approved verbs that might fit your situation. I will refer to the Approved Verbs List linked in your question frequently and will use "AVL" for brevity going forward.
Group: The comments on the AVL refers to using this in place of Arrange. Arrange being a synonym for Sort would be a good fit. Sticking with the recommendation then we should use Group
Set: It is a synonym for Sort. However, in the AVL, it is associated with Write, Reset, Assign, or Configure which are not related to your cmdlet. Still, it is in the list and could fit if you are willing to put aside the discombobulation that it creates with existing PowerShell cmdlets.
I dont really have a number 3.
Update: This is a weak case but the AVL refers its use as a way to maintain [a cmdlets] state [and] accuracy.
Order/Organize: Not in the AVL but I find these very fitting and dont currently conflict with any existing verbs.
Ultimately, AVL be damned and do whatever you want. Sort is a very good fit for what you are trying to do. You can also just use -DisableNameChecking when importing your module. It is only a warning after all. Briatist's answer is also good in my opinion.
Bonus from comments
Not that you asked for it, but when you said we have to enable name checking I thought about this. Just for fun!
$reservedVerbs = "ForEach","Format","Group","Sort","Tee"
$approvedVerbList = (Get-Verb).Verb
Get-Command -Module Microsoft.WSMan.Management | ForEach-Object{
If ($approvedVerbList -notcontains ($_.Name -split "-")[0]){
Write-Warning "$($_.Name) does not use an approved verb."
}
If ($reservedVerbs -contains ($_.Name -split "-")[0]){
Write-Warning "$($_.Name) is using a reserved verb."
}
}
Whenever I need a verb that is not an approved PowerShell verb, I use Invoke-* instead. So in your case, you could name it Invoke-SortVersionLabels
You shouldn't need a special cmdlet at all. If a VersionLabel is an object, just take the collection and pipe it to Sort-Object using the property(ies) you need.
# Assuming a versionlabel has a 'Name' Property...
$VersionLabelCollection | Sort-Object -Property:Name
I'm coming from a unix background where I've written some scripts using bash and bourne. But I need to write some scripts using powershell and I'm having a hard time finding information.
For example, in *nix, I can do man bash and read all about how to use bash and I can do man some_command to read about a specific command. So far, I found some powershell equivalents like get-command to see all available commands, but getting and using objects is really confusing me.
For instance, I'm trying to create a new scheduled task using powershell and found some sample code here on SO. Here is a snippit:
$schedule = new-object -com Schedule.Service
$schedule.connect()
$tasks = $schedule.getfolder("\").gettasks(0)
$tasks | select Name, LastRunTime
foreach ($t in $tasks) {
foreach ($a in $t.Actions) {
$a.Path
}
}
I understand what this script is doing, but without experience how would I know to do the following:
Know to use new-object -com Schedule.Service
Know that this object has a .connect method
Know that this object has a .getfolder and .gettasks object
A lot of the code seems ambiguous to me, so where would I find out the above information natively using powershell?
So you found Get-Command. That's a good start it will show you the available cmdlets. There may be even more available after importing snapins/modules. Use Get-PSSnapin -Registered and Get-Module -ListAvailable to see additional modules that may be imported to give you even more cmdlets.
The nice thing about PowerShell is that the creators built in an alias system. One of the goals of it was to make it easier to learn PowerShell when you have a bash/DOS background. For example if you type man Get-Process it will give you the documentation for the Get-Process cmdlet. To see all documentation for it use man Get-Process -Full. man doesn't actually exist, it is an alias for Get-Help which has the same functionality as man on UNIX/Linux. You can use the Get-Alias cmdlet to show the registered alias' and their definitions.
The script you found is working with a COM object. You can tell because of the -com parameter that was used for New-Object (which is actually short for -ComObject). Unlike .NET objects, COM objects are not built in to PowerShell however PowerShell has support for them the same way VBScript has support for them. The Get-Member cmdlet will unveil both .NET and COM type object members (properties and methods). More about Get-Member below.
The script you found uses the New-Object cmdlet to create an instance of the COM object named Schedule.Service. There are two main ways to find out more information about this object. The first is that you can list its properties and methods directly within PowerShell using the Get-Member cmdlet. This cmdlet works for both .NET and COM objects. It is an invaluable cmdlet that will show you what you can do with your objects. Use man or Get-Help Get-Member to learn about it. In fact you can use Get-Member to discover the object members you asked about such as the .connect method. The second way is to look up the documentation for the object on MSDN which is Microsoft's developer documentation website. This is probably the best page for that particular object.
I am not familiar with powershell scripting but found this, maybe some reference to use:
http://technet.microsoft.com/eng-us/scriptcenter/powershell%28en-us%29.aspx
http://technet.microsoft.com/en-us/library/hh857339.aspx#BKMK_wps4
On the first link are PowerShell Scripting Webcasts to find and more.
Scheduling Jobs with the Windows PowerShell API: http://msdn.microsoft.com/en-us/library/windows/desktop/jj150476%28v=vs.85%29.aspx
Guide to getting started with Windows PowerShell: http://technet.microsoft.com/library/ee221100.aspx
About Windows PowerShell, following help topics:
get-command : Gets information about cmdlets from the cmdlet code.
get-member : Gets the properties and methods of an object.
where-object : Filters object properties.
about_object : Explains the use of objects in Windows PowerShell.
about_remote : Tells how to run commands on remote computers.
Conceptual help files are named "about_", such as:
about_regular_expression.
The help commands also display the aliases of the cmdlets. These
are alternate names or nicknames that are often easier to type.
For example, the alias for the Invoke-Command cmdlet is "remote".
To get the aliases, type:
get-alias
Hopefully this will help a little.
The first hit on Google for "powershell create scheduled task" leads here, where one of the answers refers to the Schedule.Service COM object. That object's documentation gives you a list of all the methods and properties of the object.
You can also use get-member to discover all the methods & properties of any variable or object in your session.
$schedule = new-object -com Schedule.Service
TypeName: System.__ComObject#{2faba4c7-4da9-4013-9697-20cc3fd40f85}
Name MemberType Definition
---- ---------- ----------
Connect Method void Connect (Variant, Variant, Variant, Variant)
GetFolder Method ITaskFolder GetFolder (string)
GetRunningTasks Method IRunningTaskCollection GetRunningTasks (int)
NewTask Method ITaskDefinition NewTask (uint)
Connected Property bool Connected () {get}
ConnectedDomain Property string ConnectedDomain () {get}
ConnectedUser Property string ConnectedUser () {get}
HighestVersion Property uint HighestVersion () {get}
TargetServer Property string TargetServer () {get}
The Component Object Model is a core piece of Windows and there are hundreds if not thousands of COM objects available in default Windows installation for interacting with both the OS and other software installed (software can install its own set of objects as well). A lot of it can be replaced with .NET Framework assemblies and PowerShell modules, snap-ins and cmdlets now.
How do you discover COM objects? Usually via Google - running searches for the things you're trying to do, and typically you'll find someone has already posted something about similar, or your search will key off words in the object's own documentation online.
If you're using PowerShell 3, you don't need to use Schedule.Service at all - there's a set of cmdlets for working with scheduled tasks. See New-ScheduledTask for a starter.
If you're looking for a generic PowerShell tutorial, I usually point people at this one
You're on the right track in that Get-Command *foo* will list all Cmdlets containing the word foo, and Get-Help New-Object will show you the help file for the New-Object cmdlet.
However, you then go straight into using COM objects, which far predate Powershell. COM programming is old and can be quite archaic. Powershell lets you interface with COM, but it's not really the "Powershell way" of doing things.
In Powershell 3, I was able to find Register-ScheduledJob:
The Register-ScheduledJob cmdlet creates scheduled jobs on the local computer.
If possible I would say that is the preferred approach over using the COM interface, just because it's likely easier and more Powershelley.
I am a newbie when it comes to PowerShell and come from a BASH background from long ago. PowerShell's built-in documentation and help on the web is pretty good, but one area where I keep stumbling is understanding Methods and Properties (are these called members/classes?). I know that I can see which Methods and Properties I can use by doing, as in example:
ls | get-member
How do .Exists, .Trim, .SubString, or .Split, etc. actually work?
When you do Get-Member, you will see the TypeName, something like:
TypeName: System.IO.DirectoryInfo
You can search for that type and look at its members.
These are .NET framework objects and its members and properties, so you can make use of the extensive documentation at msdn.
For example this is the doc for DirectoryInfo: http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
I just posted a script to the scripting repository that may help you with this. http://gallery.technet.microsoft.com/scriptcenter/Finding-reference-b12324bc
It takes away the effort for you so now you can do something like:
Get-ChildItem C:\Windows | Get-Member | .\Find-TypeReference.ps1
Which would cause the script to open up the MSDN search page for you with the FileInfo and DirectoryInfo types as the query.