我正在try 从ASP.NET Core Web API运行PowerShell脚本.请查看以下环境详细信息:
.NET SDKs installed:
3.1.403 [C:\Program Files\dotnet\sdk]
7.0.200 [C:\Program Files\dotnet\sdk]
7.0.201 [C:\Program Files\dotnet\sdk]
7.0.306 [C:\Program Files\dotnet\sdk]
7.0.400 [C:\Program Files\dotnet\sdk]
8.0.100-preview.3.23178.7 [C:\Program Files\dotnet\sdk]
8.0.101 [C:\Program Files\dotnet\sdk]
该API在.NET 7上运行;以下是.csproj
文件:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.3.9" />
</ItemGroup>
接口代码:
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
public static ScriptResult Run2(string filePath, Dictionary<string,string> parameters)
{
string myScript = File.ReadAllText(filePath);
ScriptResult scriptResult = new ScriptResult();
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.AddScript(myScript);
foreach (var kvp in parameters)
{
ps.AddParameter(kvp.Key, kvp.Value);
}
var result = ps.Invoke();
if (ps.HadErrors)
{
string errorMessage = "";
foreach (var error in ps.Streams.Error)
{
errorMessage += error.ToString() + "\n"; <-- This is where I am getting the error message
}
throw new Exception(errorMessage);
}
foreach (var PSObject in result)
{
var x = PSObject.ToString();
}
}
return scriptResult;
}
输出Get-ExecutionPolicy -List
个:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Unrestricted
LocalMachine Bypass
注意:该脚本包含以下行:
Import-Module MicrosoftTeams
##script to get token##
Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken") | Out-Null
$getUserSettings = Get-CSOnlineUser -Identity $UserEmail -ErrorAction 'stop'
$output = @{
UserConfig = $getUserSettings
}
$output | ConvertTo-JSON
Write-Output $output
PSVersionTable的输出
Name Value
---- -----
PSVersion 5.1.19041.4046
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.4046
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
获取错误:
无法加载文件C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\5.5.0\MicrosoftTeams.psm1,因为此系统上禁用了运行脚本.有关详细信息,请参阅About_Execution_Polures at https://go.microsoft.com/fwlink/?LinkID=135170.