Powershell soap using New-WebServiceProxy namespace and object issue - powershell

I'm trying to write a soap request in powershell the service is up I can request it with soapui.
After reading this and this, I don't manage to put my paramater in the ns.param object.
I don't even manage to create the ns.param object.
I try to be as much exhaustive as possible if you need more information to answer I will provide it ASAP.
I want to call this method :
search Method ns.resultats search(string login, string password, ns.entite entite, bool entiteSpecified, ns.searchCriteria criteres, bool details, bool c...
in the IDE the auto-completion show me that critere is type of ns.param[]
enter image description here
When I try to get-Member of the the $scParam variable I have an error message :
gm : Le champ ou la propriété «Value» du type «ns.param» ne diffère que par la casse du champ ou de la propriété «value». Le type doit être compatible avec la spécification CLS (Common
Language Specification).
Au caractère C:\Users\edoua\Documents\test.ps1:13 : 12
$scParam | gm
~~
CategoryInfo : NotSpecified: (:) [Get-Member], ExtendedTypeSystemException
FullyQualifiedErrorId : NotACLSComplaintProperty,Microsoft.PowerShell.Commands.GetMemberCommand
Finally I have wrote the same method with python and zeep library and when I pass this dictionnary as param it work juste fine :
{
'login': 'log',
'password': 'pass',
'entite': 'personne',
'criteres': {
'critere': {
'name': 'matricule',
'value': '001002',
'operator': 'eq'
},
'pageNum': 1,
'pageSize': 100
},
'details': True,
'completePath': False
}
Finnaly the code thank you for any help :
$url = "http://localhost:8081/search/V1?WSDL"
$WS = New-WebServiceProxy -Uri $url -Namespace ns
$type = $WS.GetType().NameSpace
#Type of object
$typeSc = $type + '.searchCriteria'
$typeScParam = $type + '.param'
# create object
$sc = new-object $typeSc
$scParam = new-object $typeScParam
$scParam | gm
#all crits
$crits = #{}
#one crit
$crit = #{}
$crit["name"] = "matricule"
$crit["operator"] = "eq"
$crit["value"] = "001002"
$crits["critere"] = $crit
# trying to cast crits into sc_param but the first issue is not here
$scParam = $crits
$sc.pageNum = 1
$sc.pageSize = 100
$sc.critere = $scParam

Related

Unable to modify value of a nested property in PS custom object

I have a PS custom object:
TourCode : s
TournamentNumber : 524
TournamentName : Mitsubishi Electric Championship at Hualalai
EnvironmentType : PGA Tour
TournamentRootPath : /mitsubishi-electric-championship-at-hualalai
SValues : {#{S1=championstour; S2=tournaments; S3=mitsubishi-electric-championship-at; S4=}}
I can easily modify values of the top level properties like TourCode or TournamentName:
PS C:\Users\yuriy> $testTournament.TourCode = 'r'
PS C:\Users\yuriy> $testTournament
TourCode : r
TournamentNumber : 524
TournamentName : Mitsubishi Electric Championship at Hualalai
EnvironmentType : PGA Tour
TournamentRootPath : /mitsubishi-electric-championship-at-hualalai
SValues : {#{S1=championstour; S2=tournaments; S3=mitsubishi-electric-championship-at; S4=}}
But I'm stuck getting strange error message when trying to modify properties S1, S2, S4, or S4 within SValues property:
PS C:\Users\yuriy> $testTournament.SValues.S3 = 'newvalue'
The property 'S3' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:1
+ $testTournament.SValues.S3 = 'newvalue'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Why is it saying it cannot find the property? I can get its value easily by referring to it like this:
PS C:\Users\yuriy> $testTournament.SValues.S3
mitsubishi-electric-championship-at
What am I doing wrong?
UPD: Output of gm -i $testTournament.SValues is on screenshot: http://i.imgur.com/BeRr2aJ.png
JSON fragment is on screenshot: http://i.imgur.com/BBK2nsi.png (similar data)
The JSON file is read and converted using this code:
$testData = Get-Content -Raw -Path "Test Data.json" | ConvertFrom-Json
Then $testTournament is created:
$testTournament = $testData.Tournaments | Get-Random

Override Creation for Monitors and Rules

I want to create PowerShell scripts to override some parameter of my monitor and rule. I used the below code, but I have some errors. I want override my overidable parameter not enabled or something else. How can I doe this?
$mps = Get-SCOMManagementPack | ? {$_.Name -like "test"}
$overrideMp = Get-SCOMManagementPack -DisplayName "Overrides"
$overridename = "testmonitor.Overrides"
$monitor = 'testmonitor'
$override = New-Object Microsoft.EnterpriseManagement.Configuration.ManagementPackMonitorPropertyOverride($overrideMp,$overridename)
$override.Monitor = $monitor
$override.Property = 'WarningThreshold'
$override.Value = 80
$override.DisplayName = "Overrides"
$overrideMp.Verify()
$overrideMp.AcceptChanges()
Errors:
error1: Exception setting "Property": "Cannot convert value "WarningThreshold" to
type "Microsoft.EnterpriseManagement.Configuration.ManagementPackMonitorProperty".
Error: "Unable to match the identifier name WarningThreshold to a valid enumerator
name. Specify one of the following enumerator names and try again: Enabled,
TraceEnabled, Algorithm, AlgorithmPercentage, DefaultState, GenerateAlert,
AutoResolve, AlertPriority, AlertOnState, AlertSeverity, AlertMessage,
AlertParameter1, AlertParameter2, AlertParameter3, AlertParameter4,
AlertParameter5, AlertParameter6, AlertParameter7, AlertParameter8,
AlertParameter9, AlertParameter10, MemberInMaintenance, MemberUnavailable,
IgnoreMemberInMaintenance, IgnoreMemberUnavailable""
At line:1 char:2
+ $override.Property = $parametername
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
error2 : Exception calling "AcceptChanges" with "0" argument(s): "Database error.
MPInfra_p_ManagementPackInstall failed with exception: Failed to validate item:
testrule1"
At line:193 char:1
+ $MP.AcceptChanges()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ManagementPackException
The error message looks rather clear to me. There is no property WarningThreshold in the ManagementPackMonitorProperty enumeration. I don't have much experience with SCOM, but you probably need to override the property AlertOnState for monitors where the property AlertSeverity has the value Warning.
Try something along the lines of this:
$mps | Get-SCOMMonitor | Where-Object {
# (other selection criteria) -and
$_.AlertSettings.AlertSeverity -eq 'Warning'
} | ForEach-Object {
$ctx = Get-SCOMClass -Id $_.Target.Id
# ...
$override = New-Object ...
$override.Monitor = $_
$override.Property = 'AlertOnState'
$override.Value = 80
$override.Context = $ctx
# ...
}
Code adopted from here (probably the same place where you found it). Not sure if this works, though. Like I said, I have very little experience with SCOM, and I don't have a SCOM server available for testing.
I'll try to debug it tomorrow in the office.
BTW, there is a third-party tool for override management called MPTuner: http://mpwiki.viacode.com/default.aspx?g=mptuner
It's free so you should try.
Roman.
It's quite confusing, but there are two different type of overrides for each workflow type. For a monitor there are:
MonitorPropertyOverride
MonitorConfigurationOverride
You are using the first one, wgich is for standard parameters only, like Enabled, for example. For any custom parameters use Configuration Override.

PowerShell and VB6 COM+ modules: Object variable or With block variable not set

I´m trying to use powershell to do automatic tests in my system, but 30% of this system is VB6 modules used thru COM. Some os these modules uses private variables that are globals inside the module. With VB6 functions that don´t use these variables, everything works fine, but with the functions that rely on these "private globals", I´m getting the error "Object variable or With block variable not set". Unfortunately, migrate this VB6 code will not occur in short term.
This is a piece of this legacy code:
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
Persistable = 0 'NotPersistable
DataBindingBehavior = 0 'vbNone
DataSourceBehavior = 0 'vbNone
MTSTransactionMode = 1 'NoTransaction
END
Attribute VB_Name = "Data"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Attribute VB_Ext_KEY = "SavedWithClassBuilder6" ,"Yes"
Attribute VB_Ext_KEY = "Top_Level" ,"Yes"
Option Explicit
Private oConn As ADODB.Connection
Private oRs As ADODB.Recordset
Public Function rsOperadora(ByVal sUser As String, _
ByVal sPassword As String, _
ByVal sIP As String, _
ByVal sSystem As String, _
ByVal sModule As String)
Dim sSql As String
sSql = "select * from operator"
Call Connect(sUser, sPassword, sSystem, sModule, sIP)
oRs.CursorType = adOpenStatic
oRs.CursorLocation = adUseClient
oRs.Open sSql, oConn, , adLockBatchOptimistic
oRs.ActiveConnection = Nothing
Set rsOperadora = oRs
Set oConn = Nothing
End Function
What I tried to do:
PS E:\aazevedo> $tsdb = New-Object -ComObject "TSDB.Data"
PS E:\aazevedo> $tsdb.rsOperadora
OverloadDefinitions
-------------------
Variant rsOperadora (string, string, string, string, string)
PS E:\aazevedo> $tsdb.rsOperadora("ADMIN","8482867D8B958F0E","","DESENV11","")
Exception calling "rsOperadora" with "5" argument(s): "Object variable or With block variable not set"
At line:1 char:1
+ $tsdb.rsOperadora("ADMIN","8482867D8B958F0E","","DESENV11","")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
PS E:\aazevedo> $oRs = New-Object -ComObject "ADODB.Recordset"
PS E:\aazevedo> $tsdb.rsOperadora("ADMIN","8482867D8B958F0E","","DESENV11","")
Exception calling "rsOperadora" with "5" argument(s): "Object variable or With block variable not set"
At line:1 char:1
+ $tsdb.rsOperadora("ADMIN","8482867D8B958F0E","","DESENV11","")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
PS E:\aazevedo> oRs = New-Object -ComObject "ADODB.Recordset"
oRs : The term 'oRs' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ oRs = New-Object -ComObject "ADODB.Recordset"
+ ~~~
+ CategoryInfo : ObjectNotFound: (oRs:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
In this example, the function Connect open a database connection using ADO, assigning to the variable oConn.
I think my problem is the variable oRs.
Inside ASP Classic this module works.
PS: sorry for my poor english.

How do I instantiate CorRuntimeHost from mscoree.tlb in PowerShell?

I want to enumerate all the AppDomains in the current process from PowerShell. The process happens to be Visual Studio, which is hosting StudioShell. To do that I need to instantiate CorRuntimHost, which is part of mscoree.tlb, so I can adapt this C# code..
I tried to get the proper name of CorRunTimeHost and pass it to New-Object -COMObject "objectName". Based on this forum posting, I searched the registry and I think the correct name is CLRMetaData.CorRuntimeHost. However, while New-Object -ComObject 'CLRMetaData.CorRuntimeHost' -Strict does return an object, it only exposes the methods intrinsic to a COM object.
Based on this stackoverflow question I tried [Activator]::CreateInstance(). However, the following two statements give me the same problem as New-Object, namely I can't call the ICorRuntimeHost::EnumDomains() method.
$corRuntimeHost = [Activator]::CreateInstance([Type]::GetTypeFromProgID('CLRMetaData.CorRuntimeHost'));
$enumerator = $null;
$corRuntimeHost.EnumDomains([ref]$enumerator);
Method invocation failed because [System.__ComObject] doesn't contain a method named 'EnumDomains'.
At line:1 char:1
+ $corRuntimeHost.EnumDomains([ref]$enumerator)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
To get it working in PowerShell 3.0 I ended up having to use an AssemblyBuilder. Below is the working code:
The problem seems to be that there is no public constructor for mscoree.CorRuntimeHostClass in .NET 4.0 but there is in 3.5.
I later tested this on a Windows 7 VM with powershell 2.0 and now this code will work in PowerShell 2.0 and 3.0.
$tlbName = Split-Path -Parent ([AppDomain]::CurrentDomain.GetAssemblies() | Where { $_.Location -Match '\\mscorlib.dll$' }).Location
$tlbName = Join-Path $tlbName 'mscoree.tlb';
$csharpString = #"
//adapted from here http://blog.semanticsworks.com/2008/04/enumerating-appdomains.html
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
public class ListProcessAppDomains
{
[DllImport( `"oleaut32.dll`", CharSet = CharSet.Unicode, PreserveSig = false )]
private static extern void LoadTypeLibEx
(String strTypeLibName, RegKind regKind,
[MarshalAs( UnmanagedType.Interface )] out Object typeLib);
private enum RegKind
{
Default = 0,
Register = 1,
None = 2
}
private class ConversionEventHandler : ITypeLibImporterNotifySink
{
public void ReportEvent( ImporterEventKind eventKind, int eventCode, string eventMsg )
{
Console.Error.WriteLine("Kind: {0} Code: {1} Message");
}
public Assembly ResolveRef( object typeLib )
{
string stackTrace = System.Environment.StackTrace;
Console.WriteLine("ResolveRef ({0})", typeLib);
Console.WriteLine(stackTrace);
return null;
}
}
public static AssemblyBuilder LoadMsCoreeDll( ref Object typeLib ) {
ConversionEventHandler eventHandler = new ConversionEventHandler();
string assemblyName = "PoshComWrapper.dll";
LoadTypeLibEx( #"$($tlbName)", RegKind.None, out typeLib );
TypeLibConverter typeLibConverter = new TypeLibConverter();
return typeLibConverter.ConvertTypeLibToAssembly( typeLib, assemblyName, 0, eventHandler, null, null, null, null );
}
}
"#
# So we can run this scipt multiple times
try { [ListProcessAppDomains] } catch { Add-Type -TypeDefinition $csharpString }
function Get-AppDomain {
$typeLib = $null;
$assemblyBuilder = [ListProcessAppDomains]::LoadMsCoreeDll([ref] $typeLib)
$corRuntimeHostClass = $assemblyBuilder.CreateInstance('PoshComWrapper.CorRuntimeHostClass')
$enumHandle = [IntPtr]::Zero
$corRuntimeHostClass.EnumDomains([ref] $enumHandle);
$appDomain = $null;
do
{
$corRuntimeHostClass.NextDomain($enumHandle, [ref] $appDomain);
if ($appDomain -ne $null -and $appDomain.GetType() -eq [AppDomain]) { $appDomain; }
} while ($appDomain -ne $null)
}
Get-AppDomain

Multiple parameter in powershell

I have a powershell script to call the SP which is shown below
$sqlTableConnection = New-Object [System.Data.SqlClient.SqlConnection]("Server=1xx.xx.xxx; Database=dbName; Integrated Security= True");
$sqlTableCmd = New-Object [System.Data.SqlClient.SqlCommand]
$sqlTableCmd.CommandText = "[System_Control].[usp_Check_system]"
$sqlTableCmd.Connection = $sqlTableConnection;
$jobName1 = "MASTER_JOB";
$sqlTableCmd.Parameters.AddWithValue("#JobName", $jobName1) ;
$outParameter = new-object System.Data.SqlClient.SqlParameter;
$outParameter.ParameterName = "#JobSatatus";
$outParameter.Direction = [System.Data.ParameterDirection]'Output';
$outParameter.DbType = [System.Data.DbType]'Boolean';
$sqlTableCmd.Parameters.Add($outParameter) ;
$sqlTableCmd.Connection = $sqlTableConnection
$sqlTableConnection.Open();
$sqlTableCmd.ExecuteNonQuery();
$truth = $sqlTableCmd.Parameters["#JobSatatus"].Value;
$sqlTableConnection.Close();
$truth;
but when I am running this I am getting below error
Exception calling "ExecuteNonQuery" with "0" argument(s): "The variable name '#
JobName' has already been declared. Variable names must be unique within a quer
y batch or stored procedure."
At line:15 char:33
+ $sqlTableCmd.ExecuteNonQuery <<<< ();
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Where I am doing mistake?
You should only be getting that error if you aren't re-initializing the SqlCommand object and so it has #JobName already defined.
I suspect you are getting this when you run it manually, not when you execute the script as a whole..
OR, if you are seeing it all the time, then maybe you moved this code into a function but the original $sqlTableCmd was initialized in the main code and now when this executes, it is in a different scope, but is getting confused by the one that was defined in the higher scope?
As I understand it, this line here is the one that should be setting things up fresh for you:
$sqlTableCmd = New-Object [System.Data.SqlClient.SqlCommand]