c# - Why does powershell not recognize cmdlets in a script called by a windows service?
问题描述
We have a windows service which runs as the local system account. It calls a PowerShell script and retrieves the output for further processing. It works like a charm under windows server 2016 but now needs to be moved to a windows server 2012 R2. On this machine, it does not recognize the azure specific cmdlets.
I tried to install the specific cmdlets via -Scope AllUsers
. We also logged into the PowerShell directly as local system
-user; it does recognize the cmdlets (e.g. Add-AzureRMAccount
) correctly.
C#:
PowerShell psInstance = PowerShell.Create();
psInstance.AddScript(scriptBase + "getVMs.ps1");
var azureVMList = psInstance.Invoke();
getVMs.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`
We don't understand why the cmdlets are working fine under the same circumstances on server 2016 and if we run them directly as the user.
Any hint is appreciated
解决方案
我在这里建议一种解决方法,在您的 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();
推荐阅读
- javascript - 如何在不增加网络负担的情况下推送所有待处理的请求?
- matplotlib - Matplotlib 表格大小和位置
- python - Python PIL 文本放置居中
- azure-cosmosdb - 逻辑应用到 CosmosDB - 从文档中提取的 PartitionKey 与标题中指定的不匹配
- amazon-web-services - AWS EC2 IP 更改影响正在运行的作业
- c++ - C++ const char* 弄乱了多重引导标头
- javascript - 为什么我的代码即使在按 ctrl + s(保存)后也不运行?
- python - 如何检测和改变RGB图片中的颜色
- c++ - 如何全局更改向量内的对象c ++
- mysql - 迭代python mysql输出