我正在尝试通过Core 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脚本(没有“ fancy”模块)。
以下是代码:
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
感谢您的帮助!我被弄糊涂了!
答案 0 :(得分:0)
还要努力使用Powershell脚本模块。
我创建了一个简单的模块,该模块返回一个字符串,所以没什么花哨的。但是无论我尝试什么,我都无法导入。
我尝试了InitialSessionState.ImportPSModulesFromPath(“ path”),但似乎没有导入,然后在命令上抛出了一个错误,提示该错误不存在。
如果我创建一个ps1脚本并调用它,然后导入该模块并运行该命令,那么它将起作用。 但是然后,我将不得不为所有自定义函数创建“运行”脚本,并在各处编写双重代码。