首页 > 解决方案 > 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#azurepowershellservice

解决方案


我在这里建议一种解决方法,在您的 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();

推荐阅读