PowerShell에서 C# 코드 실행으로 개체 또는 여러 값을 반환하려면 어떻게 해야 합니까?
일부 C# 코드는 인수가 있는 powershell 스크립트를 실행합니다.파워셸 스크립트 안에서 모든 것이 괜찮았는지 파워셸로부터 리턴 코드와 문자열을 받고 싶습니다.
그것을 하는 올바른 방법은 무엇입니까 - 파워셸과 C# 모두에서.
파워셸
# Powershell script
# --- Do stuff here ---
# Return an int and a string - how?
# In c# I would do something like this, if this was a method:
# class ReturnInfo
# {
# public int ReturnCode;
# public string ReturnText;
# }
# return new ReturnInfo(){ReturnCode =1, ReturnText = "whatever"};
C#
void RunPowershellScript(string scriptFile, List<string> parameters)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
Command scriptCommand = new Command(scriptFile);
Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
foreach (string scriptParameter in parameters)
{
CommandParameter commandParm = new CommandParameter(null, scriptParameter);
commandParameters.Add(commandParm);
scriptCommand.Parameters.Add(commandParm);
}
pipeline.Commands.Add(scriptCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke();
//What to do here?
//ReturnInfo returnInfo = pipeline.DoMagic();
}
}
class ReturnInfo
{
public int ReturnCode;
public string ReturnText;
}
Write-Output을 사용하고 "마지막 두 psObjects가 내가 찾고 있는 값입니다"와 같은 관습에 의존하여 이 작업을 수행했지만 매우 쉽게 중단될 수 있습니다.
파워셸 스크립트에서 필요에 따라 해시 테이블을 작성할 수 있습니다.
[hashtable]$Return = @{}
$Return.ReturnCode = [int]1
$Return.ReturnString = [string]"All Done!"
Return $Return
C#에서 P 객체를 다음과 같이 처리합니다.
ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
{
Hashtable ht = p.ImmediateBaseObject as Hashtable;
ri.ReturnCode = (int)ht["ReturnCode"];
ri.ReturnText = (string)ht["ReturnString"];
}
//Do what you want with ri object.
powershell v2.0의 Keith Hill 설명에서와 같이 PsCustom 개체를 사용하려면:
파워셸 스크립트:
$return = new-object psobject -property @{ReturnCode=1;ReturnString="all done"}
$return
c# 코드:
ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
{
ri.ReturnCode = (int)p.Properties["ReturnCode"].Value;
ri.ReturnText = (string)p.Properties["ReturnString"].Value;
}
CB의 답변은 저에게 작은 변화로 큰 도움이 되었습니다.(C# 및 PowerShell과 관련하여) 어디에도 게시된 내용이 없어서 게시하려고 했습니다.
PowerShell 스크립트에서 해시 테이블을 만들고 두 개의 값(부울 값과 Int 값)을 저장한 다음 PSO 개체로 변환했습니다.
$Obj = @{}
if($RoundedResults -ilt $Threshold)
{
$Obj.bool = $true
$Obj.value = $RoundedResults
}
else
{
$Obj.bool = $false
$Obj.value = $RoundedResults
}
$ResultObj = (New-Object PSObject -Property $Obj)
return $ResultObj
그리고 C# 코드에서 CB와 동일한 작업을 수행했지만 사용해야 했습니다.Convert.ToString값을 성공적으로 되돌리려면 다음을 수행합니다.
ReturnInfo ri = new ReturnInfo();
foreach (PSObject p in psObjects)
{
ri.ReturnCode = Convert.ToBoolean(p.Properties["ReturnCode"].Value;)
ri.ReturnText = Convert.ToString(p.Properties["ReturnString"].Value;)
}
StackOverflow 게시물을 통해 이에 대한 답을 찾았습니다. https://stackoverflow.com/a/5577500
키렌 존스톤의 말입니다.
변환을 사용합니다.(이중) 값이 아닌 (이중) 값으로 이동합니다.그것은 객체를 가져가서 당신이 요청한 모든 유형을 지원합니다! :)
와, 좋은 질문입니다!제 머리 위에서 주사를 놓을게요
C#에서 둘 사이에 데이터를 전달하는 데 사용할 구조를 나타내는 클래스를 설계할 수 있습니다.PS 스크립트에서 XmlWriter를 사용하여 XML 응답을 만들고 다음을 사용할 수 있습니다.Write-outputXML 문자열을 뱉습니다.
C# 측에서 표준 출력 응답을 캡처하고 XML을 새 응답 클래스로 역직렬화한 다음 결과를 처리합니다.XML 응답 이외에는 stdout에 쓸 수 없습니다. 그렇지 않으면 클래스에 역직렬화할 수 없습니다.
PowerShell v3.0 및 최신 버전의 경우 더욱 간단합니다.
$myObject = [PSCustomObject]@{
Name = 'Kevin'
Language = 'PowerShell'
State = 'Texas'
}
$myObject.Name = 'Mark'
return $myObject
언급URL : https://stackoverflow.com/questions/10106217/how-would-i-return-an-object-or-multiple-values-from-powershell-to-executing-c-s
'programing' 카테고리의 다른 글
| ES6 클래스 인스턴스의 클래스 이름을 가져옵니다. (0) | 2023.08.05 |
|---|---|
| C++의 std:: 문자열로 전체 파일을 읽는 방법은 무엇입니까? (0) | 2023.08.05 |
| 인쇄 스타일시트를 디버깅하기 위한 제안사항은 무엇입니까? (0) | 2023.07.31 |
| 현재 노드를 포함하는 jQuery find(...) 메서드를 찾고 있습니다. (0) | 2023.07.31 |
| 회전을 제대로 처리하는 아이폰용 뷰포트 메타를 설정하는 방법은? (0) | 2023.07.31 |