2015-01-06 3 views
4

명명 된 매개 변수를 3 개 허용하는 PowerShell 스크립트가 있습니다. 명령 줄에서 같은 것을 전달하는 방법을 알려주십시오. 코드 아래에서 시도했지만 동일하지 않습니다. 전체 값을 P3에만 할당합니다. 내 요구 사항은 P1이 1, P2는 2, P3은 3을 할당해야한다는 것입니다.PowerShell은 명명 된 매개 변수를 ArgumentList에 전달합니다.

Invoke-Command -ComputerName server -FilePath "D:\test.ps1" -ArgumentList {-P1 1 -P2 2 -P3 3} 

아래는 스크립트 파일 코드입니다.

Param (
    [string]$P3, 
    [string]$P2, 
    [string]$P1 
) 
Write-Output "P1 Value :" $P1 
Write-Output "P2 Value:" $P2 
Write-Output "P3 Value :" $P3 
+0

가능한 중복 http://stackoverflow.com/questions/4225748/how-do-i-pass- named-parameters-with-invoke-command) –

답변

9

하나의 옵션 :

$params = @{ 
P1 = 1 
P2 = 2 
P3 = 3 
} 

$ScriptPath = 'D:\Test.ps1' 

$sb = [scriptblock]::create(".{$(get-content $ScriptPath -Raw)} $(&{$args} @params)") 

Invoke-Command -ComputerName server -ScriptBlock $sb 
+0

예 위의 코드를 사용하여 결과를 얻을 수 있습니다. –

+1

내 요구 사항이 C#에서 PowerShell 스크립트를 실행하는 것과 동일한 방법으로 C# 코드를 사용하여 달성하는 방법을 알려주십시오. –

+0

죄송 합니다만 C#을 사용하면 변환 할 수 있습니다. – mjolinor

3

해시 테이블을 사용

icm -ComputerName test -ScriptBlock{$args} -ArgumentList @{"p1"=1;"p2"=2;"p3"=3} 
+0

자세한 내용을 제공해 주시겠습니까? –

+0

이 게시물을보십시오 http://stackoverflow.com/a/4226027/381149 –

2

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 
[? 내가 호출-명령으로 명명 된 매개 변수를 전달하려면 어떻게] (의
관련 문제