반응형
C#에서 powershell cmdlet 호출 중
C#에서 PS cmdlet을 호출하는 방법을 배우려고 하는데 PowerShell 클래스를 알게 되었습니다.기본적인 용도로는 잘 작동하지만, 이제 다음 PS 명령을 실행하고 싶었습니다.
Get-ChildItem | where {$_.Length -gt 1000000}
파워셸 수업을 통해 이것을 구축하려고 했지만, 이것을 할 수 없을 것 같습니다.지금까지 제 코드는 다음과 같습니다.
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ChildItem");
ps.AddCommand("where-object");
ps.AddParameter("Length");
ps.AddParameter("-gt");
ps.AddParameter("10000");
// Call the PowerShell.Invoke() method to run the
// commands of the pipeline.
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(
"{0,-24}{1}",
result.Members["Length"].Value,
result.Members["Name"].Value);
} // End foreach.
이 프로그램을 실행하면 항상 예외가 발생합니다.Where-Object cmdlet을 이렇게 실행할 수 있습니까?
Length
,-gt
그리고.10000
에 대한 매개 변수가 아닙니다.Where-Object
매개 변수는 하나뿐입니다.FilterScript
0번 위치에서 활자 값을 사용합니다.ScriptBlock
식을 포함합니다.
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-ChildItem");
ps.AddCommand("where-object");
ScriptBlock filter = ScriptBlock.Create("$_.Length -gt 10000")
ps.AddParameter("FilterScript", filter)
분해해야 하는 더 복잡한 문이 있는 경우 구조를 더 잘 이해하려면 토큰화기(v2 이상에서 사용 가능)를 사용하는 것이 좋습니다.
# use single quotes to allow $_ inside string
PS> $script = 'Get-ChildItem | where-object -filter {$_.Length -gt 1000000 }'
PS> $parser = [System.Management.Automation.PSParser]
PS> $parser::Tokenize($script, [ref]$null) | select content, type | ft -auto
그러면 다음 정보가 덤프됩니다.v3의 AST 파서만큼 풍부하지는 않지만 여전히 유용합니다.
내용 유형------- ----하위 항목 가져오기 명령연산자where-object 명령-filter 명령 매개 변수그룹 시작_ 변수.교환입니다.길이 부재-gt 연산자1000000 번호그룹 종료
이게 도움이 되길 바랍니다.
언급URL : https://stackoverflow.com/questions/17067971/invoking-powershell-cmdlets-from-c-sharp
반응형
'programing' 카테고리의 다른 글
페이지 로드에 대한 페이드인 효과를 위해 CSS 사용 (0) | 2023.09.09 |
---|---|
GET 매개 변수에 대한 SpringMVC 요청 매핑 (0) | 2023.09.04 |
MariaDB 10.4.21에서 세션 없이 읽기 전용으로 테이블을 잠그려면 어떻게 해야 합니까? (0) | 2023.09.04 |
Swift에서 이미지 크기를 조정하는 방법? (0) | 2023.09.04 |
styles.xml의 사용자 지정 특성 (0) | 2023.09.04 |