【问题标题】:How to interact with .NET object methods from powershell?如何与 powershell 中的 .NET 对象方法进行交互?
【发布时间】:2021-09-05 08:56:09
【问题描述】:

如何在 powershell(Elasticsearch NEST .NET 客户端)中调用 .NET 对象的方法。这是 NEST 客户端的 .NET 代码的基本示例,我正在尝试编写等效的 PS,但我无法设置对象值。这甚至可能与 powershell 中的 .NET 对象有关吗?

.NET

var config = new Nest.ConnectionSettings(pool, httpConnection)
.DefaultIndex("employee_data"); //complete extensions omitted for brevity

Powershell

$config = new-object -Type Nest.ConnectionSettings($pool, $httpConnection)
$config.DefaultIndex("mate")
Method invocation failed because [Nest.ConnectionSettings] does not contain a method named 'DefaultIndex'.

$config | gm



   TypeName: Nest.ConnectionSettings

Name                                MemberType Definition                                                                                                                                                      
----                                ---------- ----------                                                                                                                                                      
ApiKeyAuthentication                Method     Nest.ConnectionSettings ApiKeyAuthentication(string id, securestring apiKey), Nest.ConnectionSettings ApiKeyAuthentication(string id, string apiKey), Nest.Co...
BasicAuthentication                 Method     Nest.ConnectionSettings BasicAuthentication(string username, string password), Nest.ConnectionSettings BasicAuthentication(string username, securestring pass...
ClientCertificate                   Method     Nest.ConnectionSettings ClientCertificate(X509Certificate certificate), Nest.ConnectionSettings ClientCertificate(string certificatePath)                       
ClientCertificates                  Method     Nest.ConnectionSettings ClientCertificates(System.Security.Cryptography.X509Certificates.X509CertificateCollection certificates)                                
ConnectionLimit                     Method     Nest.ConnectionSettings ConnectionLimit(int connectionLimit)                                                                                                    
DeadTimeout                         Method     Nest.ConnectionSettings DeadTimeout(timespan timeout)                                                                                                           
DefaultDisableIdInference           Method     Nest.ConnectionSettings DefaultDisableIdInference(bool disable)                                                                                                 
DefaultFieldNameInferrer            Method     Nest.ConnectionSettings DefaultFieldNameInferrer(System.Func[string,string] fieldNameInferrer)                                                                  
DefaultIndex                        Method     Nest.ConnectionSettings DefaultIndex(string defaultIndex)                                                                                                       
DefaultMappingFor                   Method     Nest.ConnectionSettings DefaultMappingFor[TDocument](System.Func[Nest.ClrTypeMappingDescriptor[TDocument],Nest.IClrTypeMapping[TDocument]] selector), Nest.Co...
DisableAutomaticProxyDetection      Method     Nest.ConnectionSettings DisableAutomaticProxyDetection(bool disable)                                                                                            
DisableDirectStreaming              Method     Nest.ConnectionSettings DisableDirectStreaming(bool b)                                                                                                          
DisableMetaHeader                   Method     Nest.ConnectionSettings DisableMetaHeader(bool disable)                                                                                                         
DisablePing                         Method     Nest.ConnectionSettings DisablePing(bool disable)                                                                                                               
Dispose                             Method     void IDisposable.Dispose()                                                                                                                                      
DnsRefreshTimeout                   Method     Nest.ConnectionSettings DnsRefreshTimeout(timespan timeout)                                                                                                     
EnableApiVersioningHeader           Method     Nest.ConnectionSettings EnableApiVersioningHeader(bool enable)                                                                                                  
EnableDebugMode                     Method     Nest.ConnectionSettings EnableDebugMode(System.Action[Elasticsearch.Net.IApiCallDetails] onRequestCompleted)                                                    
EnableHttpCompression               Method     Nest.ConnectionSettings EnableHttpCompression(bool enabled)                                                                                                     
EnableHttpPipelining                Method     Nest.ConnectionSettings EnableHttpPipelining(bool enabled)                                                                                                      
EnableTcpKeepAlive                  Method     Nest.ConnectionSettings EnableTcpKeepAlive(timespan keepAliveTime, timespan keepAliveInterval)                                                                  
EnableTcpStats                      Method     Nest.ConnectionSettings EnableTcpStats(bool enableTcpStats)                                                                                                     
EnableThreadPoolStats               Method     Nest.ConnectionSettings EnableThreadPoolStats(bool enableThreadPoolStats)                                                                                       
Equals                              Method     bool Equals(System.Object obj)                                                                                                                                  
GetHashCode                         Method     int GetHashCode()                                                                                                                                               
GetType                             Method     type GetType()                                                                                                                                                  
GlobalHeaders                       Method     Nest.ConnectionSettings GlobalHeaders(System.Collections.Specialized.NameValueCollection headers)                                                               
GlobalQueryStringParameters         Method     Nest.ConnectionSettings GlobalQueryStringParameters(System.Collections.Specialized.NameValueCollection queryStringParameters)                                   
IncludeServerStackTraceOnError      Method     Nest.ConnectionSettings IncludeServerStackTraceOnError(bool b)                                                                                                  
MaxDeadTimeout                      Method     Nest.ConnectionSettings MaxDeadTimeout(timespan timeout)                                                                                                        
MaximumRetries                      Method     Nest.ConnectionSettings MaximumRetries(int maxRetries)                                                                                                          
MaxRetryTimeout                     Method     Nest.ConnectionSettings MaxRetryTimeout(timespan maxRetryTimeout)                                                                                               
MemoryStreamFactory                 Method     Nest.ConnectionSettings MemoryStreamFactory(Elasticsearch.Net.IMemoryStreamFactory memoryStreamFactory)                                                         
NodePredicate                       Method     Nest.ConnectionSettings NodePredicate(System.Func[Elasticsearch.Net.Node,bool] predicate)                                                                       
OnRequestCompleted                  Method     Nest.ConnectionSettings OnRequestCompleted(System.Action[Elasticsearch.Net.IApiCallDetails] handler)                                                            
OnRequestDataCreated                Method     Nest.ConnectionSettings OnRequestDataCreated(System.Action[Elasticsearch.Net.RequestData] handler)                                                              
PingTimeout                         Method     Nest.ConnectionSettings PingTimeout(timespan timeout)                                                                                                           
PrettyJson                          Method     Nest.ConnectionSettings PrettyJson(bool b)                                                                                                                      
Proxy                               Method     Nest.ConnectionSettings Proxy(uri proxyAddress, string username, string password), Nest.ConnectionSettings Proxy(uri proxyAddress, string username, securestr...
RequestTimeout                      Method     Nest.ConnectionSettings RequestTimeout(timespan timeout)                                                                                                        
ServerCertificateValidationCallback Method     Nest.ConnectionSettings ServerCertificateValidationCallback(System.Func[System.Object,X509Certificate,System.Security.Cryptography.X509Certificates.X509Chain...
SkipDeserializationForStatusCodes   Method     Nest.ConnectionSettings SkipDeserializationForStatusCodes(Params int[] statusCodes)                                                                             
SniffLifeSpan                       Method     Nest.ConnectionSettings SniffLifeSpan(System.Nullable[timespan] sniffLifeSpan)                                                                                  
SniffOnConnectionFault              Method     Nest.ConnectionSettings SniffOnConnectionFault(bool sniffsOnConnectionFault)                                                                                    
SniffOnStartup                      Method     Nest.ConnectionSettings SniffOnStartup(bool sniffsOnStartup)                                                                                                    
ThrowExceptions                     Method     Nest.ConnectionSettings ThrowExceptions(bool alwaysThrow)                                                                                                       
ToString                            Method     string ToString()                                                                                                                                               
TransferEncodingChunked             Method     Nest.ConnectionSettings TransferEncodingChunked(bool transferEncodingChunked)                                                                                   
UserAgent                           Method     Nest.ConnectionSettings UserAgent(string userAgent)                                                                                                             
ApiKeyAuthenticationCredentials     Property   Elasticsearch.Net.ApiKeyAuthenticationCredentials ApiKeyAuthenticationCredentials {get;}                                                                        
BasicAuthenticationCredentials      Property   Elasticsearch.Net.BasicAuthenticationCredentials BasicAuthenticationCredentials {get;}                                                                          
BootstrapLock                       Property   System.Threading.SemaphoreSlim BootstrapLock {get;}                                                                                                             
Connection                          Property   Elasticsearch.Net.IConnection Connection {get;}                                                                                                                 
ConnectionPool                      Property   Elasticsearch.Net.IConnectionPool ConnectionPool {get;}                                                                                                         
DefaultIndices                      Property   Nest.FluentDictionary[type,string] DefaultIndices {get;}                                                                                                        
DefaultRelationNames                Property   Nest.FluentDictionary[type,string] DefaultRelationNames {get;}                                                                                                  
DisableIdInference                  Property   System.Collections.Generic.HashSet[type] DisableIdInference {get;}                                                                                              
DisablePings                        Property   bool DisablePings {get;}                                                                                                                                        
Headers                             Property   System.Collections.Specialized.NameValueCollection Headers {get;}                                                                                               
HttpPipeliningEnabled               Property   bool HttpPipeliningEnabled {get;}                                                                                                                               
IdProperties                        Property   Nest.FluentDictionary[type,string] IdProperties {get;}                                                                                                          
Inferrer                            Property   Nest.Inferrer Inferrer {get;}                                                                                                                                   
KeepAliveInterval                   Property   System.Nullable[timespan] KeepAliveInterval {get;}                                                                                                              
KeepAliveTime                       Property   System.Nullable[timespan] KeepAliveTime {get;}                                                                                                                  
MaxRetries                          Property   System.Nullable[int] MaxRetries {get;}                                                                                                                          
MetaHeaderProvider                  Property   Elasticsearch.Net.MetaHeaderProvider MetaHeaderProvider {get;}                                                                                                  
PropertyMappingProvider             Property   Nest.IPropertyMappingProvider PropertyMappingProvider {get;}                                                                                                    
PropertyMappings                    Property   Nest.FluentDictionary[System.Reflection.MemberInfo,Nest.IPropertyMapping] PropertyMappings {get;}                                                               
ProxyAddress                        Property   string ProxyAddress {get;}                                                                                                                                      
ProxyPassword                       Property   securestring ProxyPassword {get;}                                                                                                                               
ProxyUsername                       Property   string ProxyUsername {get;}                                                                                                                                     
QueryStringParameters               Property   System.Collections.Specialized.NameValueCollection QueryStringParameters {get;}                                                                                 
RequestResponseSerializer           Property   Elasticsearch.Net.IElasticsearchSerializer RequestResponseSerializer {get;}                                                                                     
RouteProperties                     Property   Nest.FluentDictionary[type,string] RouteProperties {get;}                                                                                                       
SniffInformationLifeSpan            Property   System.Nullable[timespan] SniffInformationLifeSpan {get;}                                                                                                       
SniffsOnConnectionFault             Property   bool SniffsOnConnectionFault {get;}                                                                                                                             
SniffsOnStartup                     Property   bool SniffsOnStartup {get;}                                                                                                                                     
SourceSerializer                    Property   Elasticsearch.Net.IElasticsearchSerializer SourceSerializer {get;}                                                                                              
StatusCodeToResponseSuccess         Property   System.Func[Elasticsearch.Net.HttpMethod,int,bool] StatusCodeToResponseSuccess {get;}                                                                           
UrlFormatter                        Property   Elasticsearch.Net.ElasticsearchUrlFormatter 

如你所见,方法 DefaultIndex 就在那里,所以我被这个错误弄糊涂了。

【问题讨论】:

  • 您能否尝试单独运行 $config.DefaultIndex 作为属性而不是方法并打印您收到的错误或输出中显示的重载?
  • 运行正常,但没有值,因为它没有设置
  • @opti2k4,如果 $config.DefaultIndex 没有输出,这表明它的行为类似于 property,而不是 method - 如果它的行为就像方法一样,您会看到方法 signature(s) (如您的Get-Member 输出中所示)。如果将-Force 添加到Get-Member 调用中,是否会出现其他相关条目?
  • 我确实看到了更多条目,但仍然不确定如何处理这些条目。get_DefaultIndex Method string IConnectionSettingsValues.get_DefaultIndex() 我假设我只能得到这个而不能设置它?
  • DefaultIndex Method Nest.ConnectionSettings DefaultIndex(string defaultIndex)

标签: c# .net powershell elasticsearch nest


【解决方案1】:
$config.GetType().GetMethod("DefaultIndex").Invoke($config, "some_index")

:(不是很直观的方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-12
    • 2015-11-12
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多