Invoking a Powershell script in C# results returning 0

浪尽此生 提交于 2019-12-24 21:27:14

问题


I'm creating a Windows Service that calls a Powershell script every minute. The Powershell script returns local system information.

    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

When I run in Powershell ISE it works.

My C# Windows Service then tries to invoke the script

                PowerShell ps = PowerShell.Create();

                ps.AddScript("C:\\Scripts\\SystemInfo.ps1");

                Collection<PSObject> results =  ps.Invoke();

                foreach (PSObject result in results)
                {
                    //Do something
                }

When debugging, results is returning a count of 0. This was working fine a few days ago and now it has decided to stop. It has been driving me crazy for hours. What am i doing wrong?


回答1:


Change the build type from 32 bit to 64 bit, this should solve your problem.




回答2:


Actually I did a project and built in "Any CPU" mode and it works fine. My problema was about "Location". I figured out this trying execute the script from another folder, the problem is that in C# I couldn´t see the errors messages.

To solve my problem I inserted the "Set-Location" cmdlet before call my script, eg.: "Set-Location 'c:\myscriptlocation'; c:\myscriptlocation\myscript.ps1".



来源:https://stackoverflow.com/questions/23675422/invoking-a-powershell-script-in-c-sharp-results-returning-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!