【发布时间】:2019-11-27 17:15:42
【问题描述】:
我正在尝试通过核心 2.2 中的 powershell sdk 创建计划任务,但是当我调用时,我在管道上收到一堆异常,因为找不到 cmdlet:
The term 'Register-ScheduledTask' is not recognized as the name of a cmdlet, function, script file, or operable program.
我使用了 Keith Babinec 的以下博客文章中的代码:https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
这可以很好地运行其他 powershell 脚本(没有“花哨”模块)。
代码如下:
public async Task<int> ExecuteAsynchronously(string script)
{
//This finds the modules but I cannot use them, even when I try to import them with the "Import-Module" command
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModulesFromPath(@"C:\Windows\System32\WindowsPowerShell\v1.0" );
Console.WriteLine("ExecutingPowerShell: " + script);
try
{
using (var runspace = RunspaceFactory.CreateRunspace(iss))
{
runspace.Open();
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.Runspace = runspace;
Pipeline pipeline = runspace.CreatePipeline();
var command = File.ReadAllText(script);
PowerShellInstance.AddScript(command);
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
outputCollection.DataAdded += outputCollection_DataAdded;
PowerShellInstance.Streams.Error.DataAdded += Error_DataAdded;
try
{
Console.WriteLine("running task");
IAsyncResult result = await Task.Run(() => PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection));
Console.WriteLine("finished running task");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Execution has stopped. The pipeline state: " + PowerShellInstance.InvocationStateInfo.State);
foreach (PSObject outputItem in outputCollection)
{
Console.WriteLine(outputItem.BaseObject.ToString());
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return 0;
}
这是ps脚本:
$Trigger = New-ScheduledTaskTrigger -AtStartup
$Settings = New-ScheduledTaskSettingsSet -Hidden -Compatibility Win8
$Settings.ExecutionTimeLimit = 'PT0S'
$Principal = New-ScheduledTaskPrincipal -RunLevel Highest
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Settings
Register-ScheduledTask -TaskName 'Launch Webserver' -InputObject $Task
这里是相关的安装包:
Microsoft.Management.Infrastructure {1.0.0}
Microsoft.PowerShell.SDK {6.2.3}
System.Management.Automation {6.2.3}
这是在 win10 上运行的(我必须在 .pubxml 中添加/破解 win10 x64 目标)。它正在 VS2019 中进行编码。
我有一种在 c# 中创建计划任务的方法,但我希望这种方法能够运行任何使用以下模块的东西:
C:\Windows\System32\WindowsPowerShell\v1.0\Modules
感谢您的帮助!我一脸懵逼!
【问题讨论】:
标签: c# powershell .net-core-2.2