我正在创建多个条件语句来查看不同的 PowerShell 命令。我遇到的一个问题是get-hotfix
我想使用,where-object
但当我调用 PSCommand 时,我得到了这个错误
System.Management.Automation.RemoteException: '无法绑定参数 'FilterScript'。无法将类型为“System.String”的“$_.InstalledOn -gt $StartTimeGenerated”值转换为类型为“System.Management.Automation.ScriptBlock”。'
这是我的代码:
if(command == "get-hotfix")
{
_HotFixViewAll = ReadInfo("ViewAllHotFix");
_hotfixInterval = Convert.ToDecimal(ReadInfo("HotFixInterval"));
if (_HotFixViewAll != "Y")
{
DateTime DateNow = DateTime.Now;
TimeSpan datetimeInterval = TimeSpan.FromDays((double)_hotfixInterval);
DateTime StartTimeGenerated = DateNow.Subtract(datetimeInterval);
var filterScript = ScriptBlock.Create("$_.InstalledOn -gt $StartTimeGenerated");
var whereCommand = new Command("Where-Object");
whereCommand.Parameters.Add("FilterScript", filterScript);
whereCommand.Parameters.Add("ArgumentList", StartTimeGenerated);
pipeline.Commands.Add(whereCommand);
}
var sortCommand = new Command("Sort-Object");
sortCommand.Parameters.Add("Property", "InstalledOn");
sortCommand.Parameters.Add("Descending");
pipeline.Commands.Add(sortCommand);
}
我该如何解决这个问题?
全面方法
using (var runspace = RunspaceFactory.CreateRunspace(connectioninfo))
{
runspace.Open();
using (var pipeline = runspace.CreatePipeline())
{
// Command to execute remotely
var psCommand = new Command(command);
pipeline.Commands.Add(psCommand);
if(command == "get-hotfix")
{
_HotFixViewAll = ReadInfo("ViewAllHotFix");
_hotfixInterval = Convert.ToDecimal(ReadInfo("HotFixInterval"));
if (_HotFixViewAll != "Y")
{
DateTime DateNow = DateTime.Now;
TimeSpan datetimeInterval = TimeSpan.FromDays((double)_hotfixInterval);
DateTime StartTimeGenerated = DateNow.Subtract(datetimeInterval);
var filterScript = ScriptBlock.Create("$_.InstalledOn -gt $StartTimeGenerated");
var whereCommand = new Command("Where-Object");
whereCommand.Parameters.Add("FilterScript", filterScript);
whereCommand.Parameters.Add("ArgumentList", StartTimeGenerated);
pipeline.Commands.Add(whereCommand);
}
var sortCommand = new Command("Sort-Object");
sortCommand.Parameters.Add("Property", "InstalledOn"); // Sort by InstalledOn column
sortCommand.Parameters.Add("Descending"); // Sort in descending order
pipeline.Commands.Add(sortCommand);
}
else if (command == "Get-ADDomainController")
{
psCommand.Parameters.Add("Server", machinename); // Add the target parameter
}
else if(command == "Get-ADReplicationPartnerMetadata")
{
psCommand.Parameters.Add("Server", machinename); // Add the target parameter
}
// Execute the command
var results = pipeline.Invoke();