【发布时间】:2021-04-09 20:10:34
【问题描述】:
使用此代码从 C# 运行我的 Powershell 代码,一切正常
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 + "");
}
}
脚本文件中的代码。
$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 是这里的问题,因为我希望它是动态的,因此不能硬编码到脚本文件中。 我已经尝试过Execute multiple line PowerShell Script from C# 中的解决方案,如下所示:
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 + "");
}
}
感觉这应该可行,但根本没有输出。也没有崩溃,有什么想法吗?
谢谢
【问题讨论】:
-
您肯定只是希望 Identity 在您的 PowerShell 脚本中成为一个变量,然后在您的 dotnet 程序中成为 pass it as a parameter to that script?
-
另外,您似乎在 PowerShell 命令上调用了两次调用。过去,当我不得不从 dotnet 应用程序调用脚本时,如果我期待 PowerShell 的输出,我倾向于改用
BeginInvoke()和EndInvoke()。 -
@Ash 谢谢,那太好了,但我不明白它的语法。我试过: powershellCommand.AddScript(File.ReadAllText(@"path_to_script")).AddCommand("Get-Mailbox").AddParameter("Identity","test-identity");和: powershellCommand.AddScript(File.ReadAllText(@"path_to_script")).AddParameter("$variable_in_script","test-identity");
标签: c# powershell