[英]Invoking a Powershell script in C# results returning 0
我正在創建一個Windows服務,每分鍾調用一次Powershell腳本。 Powershell腳本返回本地系統信息。
function MachineInformation
{
[hashtable]$machine = @{}
$computerSystem = get-wmiobject Win32_ComputerSystem
$machine.machine = $computerSystem.Name
$machine.key = $computerSystem.Manufacturer
[String]$machine.value = Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
[DateTime]$machine.timestamp = Get-Date
Return $machine
}
MachineInformation
當我在Powershell ISE中運行時,它可以工作。
然后,我的C#Windows服務嘗試調用腳本
PowerShell ps = PowerShell.Create();
ps.AddScript("C:\\Scripts\\SystemInfo.ps1");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject result in results)
{
//Do something
}
調試時,結果返回的計數為0。幾天前此操作正常,現在已決定停止。 幾個小時使我發瘋。 我究竟做錯了什么?
將構建類型從32位更改為64位,這應該可以解決您的問題。
實際上,我做了一個項目,並以“任何CPU”模式構建,並且工作正常。 我的問題是關於“位置”。 我發現嘗試從另一個文件夾執行腳本,問題是在C#中我看不到錯誤消息。
為了解決我的問題,我在調用腳本之前插入了“ Set-Location” cmdlet,例如:“ Set-Location'c:\\ myscriptlocation'; c:\\ myscriptlocation \\ myscript.ps1”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.