mjolinor에 의해 코드는 잘 작동하지만, 그것을 이해하는 나에게 몇 분이 걸렸다.
코드는 간단한 일을한다 - 내장 된 매개 변수를 스크립트 블록의 콘텐츠 생성 : 그런 다음이 스크립트 블록이 호출-명령을 전달한다
&{
Param (
[string]$P3,
[string]$P2,
[string]$P1
)
Write-Output "P1 Value:" $P1
Write-Output "P2 Value:" $P2
Write-Output "P3 Value:" $P3
} -P1 1 -P2 2 -P3 3
합니다.
코드를 단순화하기 위해 :
".{$(get-content $ScriptPath -Raw)} $(&{$args} @params)"
$scriptContent = Get-Content $ScriptPath -Raw
$formattedParams = &{ $args } @params
# The `.{}` statement could be replaced with `&{}` here, because we don't need to persist variables after script call.
$scriptBlockContent = ".{ $scriptContent } $formattedParams"
$sb = [scriptblock]::create($scriptBlockContent)
가의 기본적인 C#을 구현을 만들어 보자 :
void Run()
{
var parameters = new Dictionary<string, string>
{
["P1"] = "1",
["P2"] = "2",
["P3"] = "3"
};
var scriptResult = InvokeScript("Test.ps1", "server", parameters)
Console.WriteLine(scriptResult);
}
string InvokeScript(string filePath, string computerName, Dictionary<string, string> parameters)
{
var innerScriptContent = File.ReadAllText(filePath);
var formattedParams = string.Join(" ", parameters.Select(p => $"-{p.Key} {p.Value}"));
var scriptContent = "$sb = { &{ " + innerScriptContent + " } " + formattedParams + " }\n" +
$"Invoke-Command -ComputerName {computerName} -ScriptBlock $sb";
var tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".ps1");
File.WriteAllText(tempFile, scriptContent);
var psi = new ProcessStartInfo
{
FileName = "powershell",
Arguments = [email protected]"-ExecutionPolicy Bypass -File ""{tempFile}""",
RedirectStandardOutput = true,
UseShellExecute = false
};
var process = Process.Start(psi);
var responseText = process.StandardOutput.ReadToEnd();
File.Delete(tempFile);
return responseText;
}
코드는 임시 스크립트를 생성하고 실행한다.
스크립트 예 :
$sb = {
&{
Param (
[string]$P3,
[string]$P2,
[string]$P1
)
Write-Output "P1 Value:" $P1
Write-Output "P2 Value:" $P2
Write-Output "P3 Value:" $P3
} -P1 1 -P2 2 -P3 3
}
Invoke-Command -ComputerName server -ScriptBlock $sb
[? 내가 호출-명령으로 명명 된 매개 변수를 전달하려면 어떻게] (의
가능한 중복 http://stackoverflow.com/questions/4225748/how-do-i-pass- named-parameters-with-invoke-command) –