Using this code to run my Powershell code from C#, everything works fine
using(PowerShell powershellCommand = PowerShell.Create())
{
powershellCommand.AddScript(File.ReadAllText(@"C:\Path_to_script")).Invoke();
System.Collections.ObjectModel.Collection<System.Management.Automation.PSObject> results = powershellCommand.Invoke();
foreach (PSObject result in results)
{
logg.AppendText(result + "");
}
}
Code in scriptfile.
$env:tmp = "env_location"
Import-PSSession $(New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri
server_url) | Out-Null
$device = Get-Mailbox -Identity IDENTITY | Get-MailboxStatistics | Select-Object TotalItemSize
return $device
IDENTITY is the problem here since i want it to be dynamic so it can't be hard coded into the scriptfile. I have tried the solution in Execute multiple line PowerShell Script from C# like so:
using(PowerShell powershellCommand = PowerShell.Create())
{
string script = @"
$env:tmp = 'env_location'
Import-PSSession $(New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri server_url) | Out-Null
$device = Get-Mailbox -Identity DYNAMIC_IDENTITY | Get-MailboxStatistics | Select-Object TotalItemSize
return $device
";
powershellCommand.AddScript(script)).Invoke();
System.Collections.ObjectModel.Collection<System.Management.Automation.PSObject> results = powershellCommand.Invoke();
foreach (PSObject result in results)
{
logg.AppendText(result + "");
}
}
It feels like this should work, but there is no output at all. No crash either, any ideas?
Thanks
BeginInvoke()andEndInvoke()instead.