2013-11-25 2 views
7

에서 파워 쉘 스크립트 파일 (example.ps1)을 호출하려면 \ localwindows .ps1 '은 cmdlet, 함수, 스크립트 파일 또는 작동 가능 프로그램의 이름으로 인식되지 않습니다.내가 다음 코드를 사용하여 C에서 # 스크립트 localwindows.ps1을 실행하려고 C#

PSCredential credential = new PSCredential(userName, securePassword); 
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential); 
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
{ 

    runspace.Open(); 

    using (PowerShell powershell = PowerShell.Create()) 
    { 
     powershell.Runspace = runspace;   

     PSCommand new1 = new PSCommand(); 
     String machinename = "machinename"; 
     String file = "C:\\localwindows.ps1"; 
     new1.AddCommand("Invoke-Command"); 
     new1.AddParameter("computername", machinename); 
     new1.AddParameter("filepath", file);   


     powershell.Commands = new1; 
     Console.WriteLine(powershell.Commands.ToString()); 
     Collection<PSObject> results = powershell.Invoke(); 

    } 

내가 오류를 얻고있다 :

그래서 나는 다음과 같은 시도 "경로를 찾을 수 없습니다 'C : \ localwindows.ps1'.이 존재하지 않기 때문에"

로컬 컴퓨터의 powershell에서 'Invoke-Command -ComputerName "컴퓨터 이름"-filepath C : \ localwindows.ps1 "명령을 사용하면 원격 컴퓨터에 새 계정이 만들어졌습니다.

C#에서 localwindows.ps1 스크립트를 호출하는 방법은 무엇입니까? 'Invoke-Command -ComputerName "machineName"-filepath C : \ localwindows.ps1'명령을 C#을 통해 실행하는 방법?

스크립트 localwindows.ps1는

$comp = [adsi]“WinNT://machinename,computer” 
$user = $comp.Create(“User”, "account3") 
$user.SetPassword(“change,password.10") 
$user.SetInfo() 

답변

3

실제로 호출 스타일이 작동해야합니다. 그러나 두 예 모두에서 스크립트 c:\localwindows.ps1은 로컬 컴퓨터에 있어야합니다. Invoke-Command의 경우 로컬 컴퓨터에서 원격 컴퓨터로 복사됩니다.

는 경우, 호출 - 명령의 경우, 스크립트는 이미 원격 컴퓨터에 존재하고 당신은 FilePath 매개 변수를 제거, 그것을 넘어서 복사해야이 추가하지 않은 : 나는했습니다

new1.AddParameter("Scriptblock", ScriptBlock.Create(file)); 
+0

사례 pipeline.Commands.AddScript (System.IO.File.ReadAllText (file));를 시도했습니다. '예상치 못한 토큰' WinNT : // machineName '이 오류가 나타납니다.' 동일한 스크립트는 invoke-command를 사용하여 로컬 사용자 계정을 만듭니다. 해결책을 시도했습니다. pipeline.Commands.AddScript (System.IO.File.ReadAllText ("."+ file)); 프로그램에서 파일을 찾을 수 없습니다. –

+0

시도했습니다 - new1.AddParameter ("Scriptblock", "{."+ file + "}"); ''ScriptBlock '매개 변수를 바인딩 할 수 없습니다.'라는 오류가 나타납니다. "System.Management.Automation.ScriptBlock"유형으로 "System.String"유형의 "{C : \ localwindows.ps1}"값을 변환 할 수 없습니다. ' –

+0

업데이트 된 답변보기문제의 핵심은 스크립트가 로컬 컴퓨터의 'c : \ localwindows.ps1'에 없다는 것입니다. –

0

http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/에서 .NET의 WinRM을 통해 Powershell을 쉽게 실행할 수있는 방법을 설명하는 기사가 있습니다.

코드를 복사하려는 경우이 코드는 단일 파일에 있으며 System.Management.Automation에 대한 참조를 포함하는 NuGet 패키지이기도합니다.

자동으로 신뢰할 수있는 호스트를 관리하고, 스크립트 블록을 실행할 수 있으며, 파일을 보낼 수도 있습니다 (실제로는 지원되지 않지만 해결 방법을 만들었습니다). 반환 값은 항상 Powershell의 원시 개체입니다.

// this is the entrypoint to interact with the system (interfaced for testing). 
var machineManager = new MachineManager(
    "10.0.0.1", 
    "Administrator", 
    MachineManager.ConvertStringToSecureString("xxx"), 
    true); 

// for your specific issue I think this would be easier 
var results = machineManager.RunScript(
    File.ReadAllText("C:\\LocalWindows.ps1")); 

// will perform a user initiated reboot. 
machineManager.Reboot(); 

// can run random script blocks WITH parameters. 
var fileObjects = machineManager.RunScript(
    "{ param($path) ls $path }", 
    new[] { @"C:\PathToList" }); 

// can transfer files to the remote server (over WinRM's protocol!). 
var localFilePath = @"D:\Temp\BigFileLocal.nupkg"; 
var fileBytes = File.ReadAllBytes(localFilePath); 
var remoteFilePath = @"D:\Temp\BigFileRemote.nupkg"; 
machineManager.SendFile(remoteFilePath, fileBytes); 

이 정보가 도움이된다면 답을 표시하십시오. 자동화 된 배치를 사용하여 잠시 사용하고 있습니다. 문제가 있으면 의견을 남기십시오.

관련 문제