c# - 为什么 powershell 无法识别 Windows 服务调用的脚本中的 cmdlet?

标签 c# azure powershell service

我们有一个以本地系统帐户运行的 Windows 服务。它调用 PowerShell 脚本并检索输出以进行进一步处理。它在 Windows Server 2016 下工作起来就像一个魅力,但现在需要移动到 Windows Server 2012 R2。在此计算机上,它无法识别 Azure 特定的 cmdlet。

我尝试通过 -Scope AllUsers 安装特定的 cmdlet。我们还以本地系统用户身份直接登录 PowerShell;它确实可以正确识别 cmdlet(例如 Add-AzureRMAccount)。

C#:

PowerShell psInstance = PowerShell.Create();
psInstance.AddScript(scriptBase + "getVMs.ps1");
var azureVMList = psInstance.Invoke();

获取VMs.ps1:

$finalPassword = ConvertTo-SecureString -String $password -AsPlainText -Force

$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList $accountName, $finalPassword

$trash = Add-AzureRmAccount -Credential $psCred -TenantId $tenantID -ServicePrincipal`

我们不明白为什么 cmdlet 在服务器 2016 上的相同情况下运行良好,并且如果我们直接以用户身份运行它们。

任何提示表示赞赏

最佳答案

我在这里建议一个解决方法,在您的 C# 代码中,直接导入包含 cmdlet 的模块。

1.您可以使用此命令获取模块文件(我使用的是az模块,请随意更改为azureRm模块):

(Get-Module -Name az.accounts).Path

然后你可以看到模块文件路径,在我这边,它是“C:\Program Files\WindowsPowerShell\Modules\Az.Accounts\1.5.2\Az.Accounts”。

2.在你的c#代码中:

InitialSessionState initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] {"the full path of Az.Accounts.psd1, if it does not work, try full path of Az.Accounts.psm1"} );
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();     
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(scriptBase + "getVMs.ps1");
var azureVMList = psInstance.Invoke();

关于c# - 为什么 powershell 无法识别 Windows 服务调用的脚本中的 cmdlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57460554/

相关文章:

windows - 使用 PowerShell 获取最新卷

c# - 在 aspnet core Razor Page 中验证失败时重新填充表单数据

azure - 从构建服务器构建和部署 Azure Functions 应用程序

azure - 需要从 Azure App Insights 查找每个 API 调用的峰值使用情况

azure - 自定义负载均衡器,能够指定应处理请求的服务器

azure - 在 AzurePowerShellV5 内联脚本中引用 yaml 变量

windows - 用于向 IIS 添加证书和绑定(bind)的 Powershell 脚本 - 权限问题

c# - 适用于 .NET 的 Google Analytics API

c# - VS2012 中的代码覆盖率未显示所覆盖的用于 Dapper 的动态类型对象

c# - PInvoke lmdif1 签名