If System.Management.Automation.Runspaces.Runspace.Open() happens to be inside a System.Transactions.TransactionScope it apparently changes Transaction.Current which in turns causes 'System.InvalidOperationException' at transaction's dispose time.
So this:
using (var scope = new TransactionScope())
{
using (var runspace = RunspaceFactory.CreateRunspace())
{
runspace.Open();
}
scope.Complete();
}
Throws: "Transaction.Current has changed inside of the TransactionScope."
I was wondering if I am missing any crucial parameter in Transaction or Runspace or it has something to do with my power-shell/MSDTC/etc configurations?
Had the same issue myself. My Runspace is buried within several nested TransactionScope layers. Upon executing Runspace.Open(), the Transaction.Current is changed and the Exception is thrown as per the OP's question.
The solution for me was to wrap the code inside another TransactionScope, but this time with the TransactionScopeOption.Suppress parameter.
using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
IEnumerable<Object> results = null;
using (Runspace runSpace = RunspaceFactory.CreateRunspace())
{
runSpace.Open();
using (Pipeline pipeline = runSpace.CreatePipeline())
{
Command command = new Command(script, true, true);
if (parameters != null && parameters.Any())
foreach (var param in parameters)
command.Parameters.Add(param.Key, param.Value);
pipeline.Commands.Add(command);
results = pipeline.Invoke();
}
runSpace.Close();
transactionScope.Complete();
return results;
}
}
This works perfectly for me. No more exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With