简体   繁体   English

使用Powershell复制和远程处理

[英]Copying and remoting using powershell

Hi all I'd like to copy a file to a computer and remote into said machine and run a single command then gather the output file of that command. 大家好,我想将文件复制到计算机上,然后远程复制到该计算机上,然后运行一个命令,然后收集该命令的输出文件。 I've been tasked to use Powershell to copy and remote into the machines. 我受命使用Powershell复制并远程到机器中。 I use this page to help start me out: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C The program I'm using is .net 4 and has to stay that way. 我使用此页面来帮助我入门: http : //www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C我正在使用的程序是.net 4,并且必须保持那样。 I first installed the windows sdk 3.5 then when the code didnt work I installed sdk 4.0 but I still get the same error in my answer string: "Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.\\r\\n" Thanks for the help Casey 我首先安装了Windows sdk 3.5,然后当代码无法正常工作时,我安装了sdk 4.0,但在回答字符串中仍然出现相同的错误:“混合模式程序集是针对运行时版本'v2.0.50727'构建的,无法在其中加载4.0运行时,没有其他配置信息。\\ r \\ n“感谢您的帮助Casey

Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Import-Module BitsTransfer" + Environment.NewLine + "Start-BitsTransfer -Source " + filename + " -Destination \\\\" + host + "\\" + uploadtodir + "\\"+Environment.NewLine);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.

pipeline.Commands.Add("Out-String");
// execute the script

Collection<PSObject> results = new Collection<PSObject>();
try
{
   results = pipeline.Invoke();
}

catch (Exception ex)
{
   results.Add(new PSObject((object)ex.Message));
}

// close the runspace
runspace.Close();
// convert the script result into a single string

StringBuilder stringBuilder = new StringBuilder();

foreach (PSObject obj in results)
{
    stringBuilder.AppendLine(obj.ToString());
}

string answer= stringBuilder.ToString();

In the App.config file of the project you need to add this: 在项目的App.config文件中,您需要添加以下内容:

<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
  </startup>
</configuration>

If you don't have an App.config file just create one. 如果没有App.config文件,则只需创建一个即可。 Hope this helps you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM