I am a developer by trade so am very used to using generics and reflection in C#, however, today I was faced with trying to grab an ‘SPPersistedObject’ from the ‘SPFarm.Local.Services.GetValue<T>()’ method.
So, in C# I wanted to do this :
Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsService msDiagnosticService = SPFarm.Local.Services.GetValue<Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsService>("clbDiagnosticService"); if (msDiagnosticService != null) { msDiagnosticService.Delete(); }
The above is removing a logger called ‘clbDiagnosticService’ if one exists. The problem line comes on the method ‘GetValue’ as that takes a generic type..
So, after a bit of “Googling” + trial and error .. the final Powershell looks like this :
and in code for those that want to copy and modify it :
# First load object models [System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.Practices.SharePoint.Common”) [System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) $farm = [Microsoft.SharePoint.Administration.SPFarm]::Local # Now we need to use Reflection to get the "GetValue" method.. $method = [Microsoft.SharePoint.Administration.SPServiceCollection].GetMethod("GetValue", [string]) Try { $closedmethod = $method.MakeGenericMethod[Microsoft.Practices.SharePoint.Common.Logging.DiagnosticsService]) # get the service! $service = $closedmethod.Invoke($farm.Services,"clbDiagnosticService") # Do your stuff here... if ($service) { Write-host $service.Id } } Catch { "Collaboris Logger Not Found - Stopping." } Hope this helps!