Exception calling "Put" with "0" argument(s): "" on Win32_TerminalServiceSetting - powershell

I have created a Powershell function to enable or disable session logons remotely on a server. It is basically the Powershell equivalent of "change logon /enable".
It works on most machines, but for some reason I don't understand, for some it returns the following error :
Exception : System.Management.Automation.MethodInvocationException: Exception calling "Put" with "0" argument(s): "" ---> System.IO.FileNotFoundException
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.Put(PutOptions options)
at System.Management.ManagementObject.Put()
at Put(Object , Object[] )
at System.Management.Automation.MethodInformation.Invoke(Object target, Object[] arguments)
at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[]
originalArguments)
--- End of inner exception stack trace ---
at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[]
originalArguments)
at System.Management.Automation.DotNetAdapter.MethodInvokeDotNet(String methodName, Object target, MethodInformation[] methodInformation,
PSMethodInvocationConstraints invocationConstraints, Object[] arguments)
at System.Management.Automation.DotNetAdapter.MethodInvoke(PSMethod method, PSMethodInvocationConstraints invocationConstraints, Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method, PSMethodInvocationConstraints invocationConstraints, Object[] arguments)
at System.Management.Automation.PSMethod.Invoke(PSMethodInvocationConstraints invocationConstraints, Object[] arguments)
at System.Management.Automation.PSMethod.Invoke(Object[] arguments)
at System.Management.Automation.Language.PSInvokeMemberBinder.InvokeAdaptedMember(Object obj, String methodName, Object[] args)
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : DotNetMethodException
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
The error stack trace doesn't help me.
I'm running the same code with the same local admin user on all machines.
Here is the actual code snippet :
$TSConnector = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace "root/cimv2/terminalservices" -Authentication PacketPrivacy
$TSConnector.Logons = 0
$TSConnector.Put()
Any idea ?

So it turns out that, on Windows Server 2008R2, if the Remote Desktop Session Host role is not installed, the server is configured for "Remote Desktop for Administration".
As explained on this technet article :
The following are limitations of Remote Desktop for Administration:
The default connection (RDP-Tcp) only allows a maximum of two simultaneous remote connections.
Licensing settings cannot be configured.
RD Connection Broker settings cannot be configured.
User logon mode cannot be configured.
So in the end I had to catch that exception and revert back to using change logon /disable in that particular case.
Kudos to #GrigorySergeev for pointing me in the right direction!

Related

Connect-AzureRmAccount : accessing_ws_metadata_exchange_failed

I get the following error when attempting to connect to Azure using PowerShell. This account previously worked, but not sure what changed. Multi-factor authentication was enabled for organization, but this account should be excluded. This is an organizational account; not a Microsoft account. I have found similar errors online, but not this particular issue...
Connect-AzureRmAccount –Credential $Credential -Verbose
VERBOSE: Performing the operation "log in" on target "User account in environment 'AzureCloud'".
Connect-AzureRmAccount : accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unexpected error
occurred on a send.
At line:1 char:1
+ Connect-AzureRmAccount –Credential $Credential -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Connect-AzureRmAccount], AadAuthenticationFailedException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
I enabled Debug output for more information...
DEBUG: AzureQoSEvent: CommandName - Connect-AzureRmAccount; IsSuccess - False; Duration - 00:00:19.9521148; Exception - Microsoft.Azure.Commands.Common.Authentica
tion.AadAuthenticationFailedException: accessing_ws_metadata_exchange_failed: Accessing WS metadata exchange failed: The underlying connection was closed: An unex
pected error occurred on a send. ---> Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: accessing_ws_metadata_exchange_failed: Accessing WS me
tadata exchange failed ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Una
ble to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existin
g connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpWebRequestWrapper.<GetResponseSyncOrAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.MexParser.<FetchMexAsync>d__4.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T](Task`1 task)
at Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.DoAcquireToken(AdalConfiguration config, PromptBehavior promptBehavior, Action`1 promptActi
on, String userId, SecureString password)
at Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.SafeAquireToken(AdalConfiguration config, String showDialog, Action`1 promptAction, String
userId, SecureString password, Exception& ex)
--- End of inner exception stack trace ---
at Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.AcquireToken(AdalConfiguration config, String promptBehavior, Action`1 promptAction, String
userId, SecureString password)
at Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.GetAccessToken(AdalConfiguration config, String promptBehavior, Action`1 promptAction, Stri
ng userId, SecureString password, String credentialType)
at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzureAccount account, IAzureEnvironment environment, String ten
ant, SecureString password, String promptBehavior, Action`1 promptAction, IAzureTokenCache tokenCache, String resourceId)
at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.AcquireAccessToken(IAzureAccount account, IAzureEnvironment environment, String tenantId, Se
cureString password, String promptBehavior, Action`1 promptAction)
at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.ListAccountTenants(IAzureAccount account, IAzureEnvironment environment, SecureString passwo
rd, String promptBehavior, Action`1 promptAction)
at Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient.Login(IAzureAccount account, IAzureEnvironment environment, String tenantId, String subscrip
tionId, String subscriptionName, SecureString password, Boolean skipValidation, Action`1 promptAction, String name)
at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.<>c__DisplayClass83_0.<ExecuteCmdlet>b__0(AzureRmProfile localProfile, RMProfileClient profile
Client, String name)
at Microsoft.Azure.Commands.Profile.Common.AzureContextModificationCmdlet.ModifyContext(Action`2 contextAction)
at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.SetContextWithOverwritePrompt(Action`3 setContextAction)
at Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 11:22:02 AM - ConnectAzureRmAccountCommand end processing.
DEBUG: 11:22:02 AM - ConnectAzureRmAccountCommand end processing.
The issue was that the Connect-AzureRMAccount cmdlet used TLS 1.0 by default. Centrify disabled TLS 1.0 support which caused the authentication attempts to close connection. The issue was resolved by adding the following to the PowerShell scripts to force TLS 1.2 security protocol:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Error while loading PowerShell ISE. Unable to run cmdlets

When I try to open PowerShell in my server it shows below error on loading:
The following error occurred while loading the extended type data
file: Microsoft.PowerShell.Core, C
:\Windows\System32\WindowsPowerShell\v1.0\types.ps1xml: The file was
skipped because of the followin g validation exception: File
C:\Windows\System32\WindowsPowerShell\v1.0\types.ps1xml cannot be
loade d because its operation is blocked by software restriction
policies, such as those created by using Group Policy.. Errors
occurred while loading the format data file:
Microsoft.PowerShell.Core, , C:\Windows\System32
\WindowsPowerShell\v1.0\DotNetTypes.format.ps1xml: The file was
skipped because of the following val idation exception: File
C:\Windows\System32\WindowsPowerShell\v1.0\DotNetTypes.format.ps1xml
cannot be loaded because its operation is blocked by software
restriction policies, such as those created b y using Group Policy..
Errors occurred while loading the format data file:
Microsoft.PowerShell.Core, , C:\Windows\System32
\WindowsPowerShell\v1.0\FileSystem.format.ps1xml: The file was skipped
because of the following vali dation exception: File
C:\Windows\System32\WindowsPowerShell\v1.0\FileSystem.format.ps1xml
cannot be loaded because its operation is blocked by software
restriction policies, such as those created by using Group Policy..
Errors occurred while loading the format data file:
Microsoft.PowerShell.Core, , C:\Windows\System32
\WindowsPowerShell\v1.0\PowerShellCore.format.ps1xml: The file was
skipped because of the following validation exception: File
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShellCore.format.ps1xml
c annot be loaded because its operation is blocked by software
restriction policies, such as those cre ated by using Group Policy..
The 'set-variable' command was found in the module
'Microsoft.PowerShell.Utility', but the module could not be
loaded.For more information, run 'Import-Module
Microsoft.PowerShell.Utility'.At line:0 char:0
Rest of the logged in users are able to run scripts but i'm unable to.
When I try to run any cmdlet for example
write-host 'test'
I get an error like this
writeErrorStream : True Exception :
System.Management.Automation.CommandNotFoundException: The
'write-host' command was found in the module
'Microsoft.PowerShell.Utility', but the module could
not be loaded. For more information, run 'Import-Module Microsoft.PowerShell.Utility'. --->
System.Management.Automation.CmdletInvocationException: File
C:\windows\system32\windowspowershell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psm1
cannot be loaded because its operation is
blocked by software restriction policies, such as those created by using Group Policy. --->
System.Management.Automation.PSSecurityException: File
C:\windows\system32\windowspowershell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psm1
cannot be loaded because its operation is
blocked by software restriction policies, such as those created by using Group Policy. --->
System.UnauthorizedAccessException: File
C:\windows\system32\windowspowershell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psm1
cannot be loaded because its operation is
blocked by software restriction policies, such as those created by using Group Policy.
--- End of inner exception stack trace ---
at System.Management.Automation.AuthorizationManager.ShouldRunInternal(CommandInfo
commandInfo, CommandOrigin origin, PSHost host)
at Microsoft.PowerShell.Commands.ModuleCmdletBase.GetScriptInfoForFile(String
fileName, String& scriptName, Boolean checkExecutionPolicy)
at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModule(PSModuleInfo
parentModule, String fileName, String moduleBase, String prefix,
SessionState
ss, Object privateData, ImportModuleOptions& options, ManifestProcessingFlags manifestProcessingFlags, Boolean&
found, Boolean& moduleFileFound)
at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleNamedInManifest(PSModuleInfo
parentModule, ModuleSpecification moduleSpecification, String
moduleBase, Boolean searchModulePath, String prefix, SessionState ss, ImportModuleOptions options,
ManifestProcessingFlags manifestProcessingFlags, Boolean
loadTypesFiles, Boolean loadFormatFiles, Object privateData, Boolean& found, String shortModuleName)
at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleManifest(String
moduleManifestPath, ExternalScriptInfo scriptInfo, Hashtable data,
Hashtable
localizedData, ManifestProcessingFlags manifestProcessingFlags, Version version, Version requiredVersion,
Nullable1 requiredModuleGuid,
ImportModuleOptions& options, Boolean& containedErrors)
at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModuleManifest(ExternalScriptInfo
scriptInfo, ManifestProcessingFlags manifestProcessingFlags,
Version version, Version requiredVersion, Nullable1 requiredModuleGuid, ImportModuleOptions& options)
at Microsoft.PowerShell.Commands.ModuleCmdletBase.LoadModule(PSModuleInfo
parentModule, String fileName, String moduleBase, String prefix,
SessionState
ss, Object privateData, ImportModuleOptions& options, ManifestProcessingFlags manifestProcessingFlags, Boolean&
found, Boolean& moduleFileFound)
at Microsoft.PowerShell.Commands.ImportModuleCommand.ImportModule_LocallyViaName(ImportModuleOptions
importModuleOptions, String name)
at Microsoft.PowerShell.Commands.ImportModuleCommand.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
--- End of inner exception stack trace ---
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable
input)
at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace
rs, Boolean performSyncInvoke)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection1
input, PSDataCollection1 output, PSInvocationSettings
settings)
at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection1
input, PSDataCollection1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.InvokeT
at System.Management.Automation.CommandDiscovery.AutoloadSpecifiedModule(String
moduleName, ExecutionContext context, SessionStateEntryVisibility
visibility, Exception& exception)
--- End of inner exception stack trace ---
at System.Management.Automation.CommandDiscovery.TryModuleAutoDiscovery(String
commandName, ExecutionContext context, String originalCommandName,
CommandOrigin commandOrigin, SearchResolutionOptions searchResolutionOptions, CommandTypes
commandTypes, Exception& lastError)
at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String
commandName, CommandTypes commandTypes, SearchResolutionOptions
searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String
commandName, CommandOrigin commandOrigin, Nullable1 useLocalScope)
at System.Management.Automation.ExecutionContext.CreateCommand(String
command, Boolean dotSource)
at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor
pipe, CommandParameterInternal[] commandElements, CommandBaseAst
commandBaseAst,
CommandRedirection[] redirections, ExecutionContext context)
at System.Management.Automation.PipelineOps.InvokePipeline(Object input,
Boolean ignoreInput, CommandParameterInternal[][] pipeElements,
CommandBaseAst[]
pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
at System.Management.Automation.Interpreter.ActionCallInstruction6.Run(InterpretedFrame
frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame) TargetObject : write-host CategoryInfo :
ObjectNotFound: (write-host:String) [], CommandNotFoundException
FullyQualifiedErrorId : CouldNotAutoloadMatchingModule ErrorDetails
: InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at , : line 1
PipelineIterationInfo : {}
please suggest me a solution to overcome this error.
On the context, I can see that powershell is not able to load any of the default modules. Not only that but also it is failing to understand the ps1xml files.
This issue happens when a system is having some critical issue.
I believe you should do a system restore or you should try a deep scan using sfc.
Hope this helps you

Upload a file as iFile using iControl

Is there a way to update the contents of an existing iFile? I didn't see any way to update the contents. So, I started looking at deleting and creating a file by uploading a local file to the BigIP using the iControl. I understand there are two objects to use - iFileFile and then iFile in that order.
Can somebody please provide usage for this? Below is what I started with and get the error below. What would be the correct parameters for iFileFile.create() if I have a file named random_key_file1 in the same location as the powershell script? After creating the iFileFile object, how do I use the same in the iFile.create().
Below links have documentation but lack the ussage examples : https://devcentral.f5.com/wiki/iControl.LocalLB__iFile__create.ashx https://devcentral.f5.com/wiki/iControl.LocalLB__iFileFile__create.ashx
Appreciate the help.
Add-PSSnapIn iControlSnapIn
$conn = Initialize-F5.iControl -HostName $hostName -Username $username -Password $password
if($conn) {
Try
{
Write-Output "Connected to load balancer - $hostName"
$ic = Get-F5.iControl
$iFileFileObjectNames = #("file1")
$filePaths = #("random_key_file1")
$ic.LocalLBiFileFile.create($iFileFileObjectNames,$filePaths)
Write-Output ("file created")
}
Catch
{
Write-Output($error[0]|format-list -force)
}
}
else
{
Write-Error "Connection to loadbalancer failed"
}
ERROR
Exception : System.Management.Automation.MethodInvocationException: Exception calling "create" with "2"
argument(s): "Exception caught in LocalLB::urn:iControl:LocalLB/iFileFile::create()
Common::InvalidArgument
" ---> System.Web.Services.Protocols.SoapHeaderException: Exception caught in
LocalLB::urn:iControl:LocalLB/iFileFile::create()
Common::InvalidArgument
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[]
parameters)
at CallSite.Target(Closure , CallSite , Object , Object , Object )
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : SoapHeaderException
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, D:\test.ps1: line 35
at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails :
Answer this Question 0

Retrieving session ID from COM method

I have a method named GoLogon in a COM object named BS.Logon which requires 5 parameters:
Username
Password
ApplicationID
XMLRoot
IPAddress
This method logins to the web server with the username, password, and other details, and returns the session ID.
I have written the Powershell script to call the method GoLogon as below.
$obj=New-Object -ComObject BS.Logon
$sessionid=$obj.GoLogon([ref]$bUsername,$bPassword,$appid,$xmlroot,[ref]$ipad)
Write-Host $sessionid
When the script is executed, the method makes successful login. I can see the session ID details in the database, but I am not able to get the session ID details through script. The variable $sessionid returns null. Also the script throws exception as
Exception calling "GoLogon" with "5" argument(s): "Invalid callee. (Exception from HRESULT: 0x80020010 (DISP_E_BADCALLEE))"
At E:\Logon.ps1:18 char:1
+ $obj.Login([ref]$bUsername,$bPassword,$appid,$xmlroot,[ref]$ipad)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation`
The stacktrace is:
Exception : System.Management.Automation.MethodInvocationException: Exception calling "GoLogon" with "5" argument(s): "Invalid callee. (Exception from HRESULT: 0x80020010 (DISP_E_BADCALLEE))" ---> System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: Invalid callee. (Exception from HRESULT: 0x80020010 (DISP_E_BADCALLEE))
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
--- End of inner exception stack trace ---
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method, PSMethodInvocationConstraints invocationConstraints, Object[] arguments)
at System.Dynamic.UpdateDelegates.UpdateAndExecute6[T0,T1,T2,T3,T4,T5,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
at System.Management.Automation.Interpreter.DynamicInstruction 7.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : ComMethodTargetInvocation
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, E:\Logon.ps1: line 18
PipelineIterationInfo : {}
PSMessageDetails :
Please suggest me how to get the session ID value from the method.
PowerShell seems to have a problem with COM parameters defined as VARIANT.
This is the case here, as the C++ signature of GoLogon suggests.
STDMETHODIMP CLOG::GOLogon(VARIANT *pvEmailId, BSTR bsPassword, BSTR bsIPAddress, BSTR bsSoloBuildVer, VARIANT *pvXML, BSTR *bsSessionId)
The answer suggested in this post "Invalid callee" calling a com object is to use a VariantWrapper.
In you case this should do the trick.
#define VariantWrapper for variables to be passesed as VARIANT
$wrapbUservame = New-Object Runtime.InteropServices.VariantWrapper($bUsername)
$wrappvXML = New-Object Runtime.InteropServices.VariantWrapper($pvXML)
#pass a [ref]VariantWrapper to .COM method
$sessionid=$obj.GoLogon([ref]$wrapbUservame,$bPassword,$appid,[ref]$wrappvXML,$ipad)

Powershell and BizTalk

I've tried the scripts which hugh posted here: PowerShell BizTalk scripts WITHOUT using BizTalk provider for PowerShell
It almost worked perfectly... Except for the Create-BTS-SendHandler-part...
I keep getting a strange error:
Exception calling "Invoke" with "2" argument(s): "Failed during call to one of administration components."
At line:22 char:23
+ $methodInfo.Invoke <<<< ($objSendHandler, $putOptions)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
$error[0]|Format-List -Force gives this:
System.Management.Automation.MethodInvocationException: Exception calling "Invoke" with "2" argument(s): "Failed during call to one of administration components." ---> System.Runtime.InteropServices.COMExcep tion (0xC0C02306): Failed during call to one of administration components.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.Put(PutOptions options)
--- End of inner exception stack trace ---
at System.Management.Automation.DotNetAdapter.AuxiliaryMethodInvoke(Object target, Object[] arguments, MethodInformation methodInformation, Object[] originalArguments)
at System.Management.Automation.DotNetAdapter.MethodInvokeDotNet(String methodName, Object target, MethodInformation[] methodInformation, Object[] arguments)
at System.Management.Automation.DotNetAdapter.MethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.PSMethod.Invoke(Object[] arguments)
at System.Management.Automation.ParserOps.CallMethod(Token token, Object target, String methodName, Object[] paramArray, Boolean callStatic, Object valueToSet)
at System.Management.Automation.MethodCallNode.InvokeMethod(Object target, Object[] arguments, Object value)
at System.Management.Automation.MethodCallNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : DotNetMethodTargetInvocation
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {}
PSMessageDetails :
I have tried to use both x86 and normal ISE to make sure it is not related to 32-bit. I've also checked that I have the rights to create Send-Handlers.
Any one who has an idea?
/Joakim
You need to use the proper names for BizTalk adapters, as specified in the
Platform Settings -> Adapters
list in BizTalk administrator. These are case sensitive.