问题
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