Я создаю несколько условных операторов, которые рассматривают различные команды PowerShell. У меня возникла проблема с get-hotfix, где я хочу использоватьwhere-object, но я получаю эту ошибку при вызове PSCommand
System.Management.Automation.RemoteException: «Невозможно привязать параметр FilterScript». Невозможно преобразовать значение «$_.InstalledOn -gt $StartTimeGenerated» типа «System.String» в тип «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();
Подробнее здесь: https://stackoverflow.com/questions/792 ... mmand-in-c
Как я могу использовать Where-Object в PSCommand в С#? ⇐ C#
Место общения программистов C#
-
Anonymous
1732632824
Anonymous
Я создаю несколько условных операторов, которые рассматривают различные команды PowerShell. У меня возникла проблема с get-hotfix, где я хочу использоватьwhere-object, но я получаю эту ошибку при вызове PSCommand
System.Management.Automation.RemoteException: «Невозможно привязать параметр FilterScript». Невозможно преобразовать значение «$_.InstalledOn -gt $StartTimeGenerated» типа «System.String» в тип «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();
Подробнее здесь: [url]https://stackoverflow.com/questions/79227113/how-can-i-use-the-where-object-in-pscommand-in-c[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия