首页 > 解决方案 > 使用powershell将文件保存在服务器上

问题描述

我正在尝试在 C# 中创建 xml 文件,并使用 powershell 将新创建的文件保存在本地机器中。在本地创建新文件,但不保存内容。

我正在 C# 中创建简单的 xml 文件,如下所示

XDocument doc = new XDocument(new XElement("body",
                                       new XElement("level1",
                                           new XElement("level2", "text"),
                                           new XElement("level2", "other text"))));

我将“doc”作为参数传递给powershell脚本并调用powershell如下

Dictionary<string, XDocument> parameters = new Dictionary<string, XDocument>() { { "VMConfigFile", doc } };
powershell.AddCommand("PowershellFunc").AddParameters(parameters);
Collection<PSObject> results = powershell.Invoke();
Collection<ErrorRecord> errors = powershell.Streams.Error.ReadAll();

powershell 功能为

function PowershellFunc
{
  [CmdletBinding()]
  Param
  (
    [Parameter(Mandatory=$true, 
                Position=0,
                HelpMessage='Please Provide Config File')]
    [ValidateNotNullOrEmpty()]
    [xml]$VMConfigFile
  )

  try
  { 
    $txt = $VMConfigFile
    $Session = New-PSSession 127.0.0.1
    Invoke-Command -Session $Session -ScriptBlock { Param($Txt) New-Item -Path c:\test\newFile.xml -Value $txt }  -ArgumentList $txt 
    #Get-PSSession | Remove-PSSession
    Write-Output "`file save successfully."              
  }
  catch
  {
    Throw $_.exception.message
  }
}

文件是在脚本运行后创建的,但它只包含命名空间(“System.Xml.XmlDocument”),不包含文件内容。

我也试图找出与我的问题相关的问题,但大多数问题都属于从给定路径读取的 xml 文件。

问题 :-

  1. 如何将xml文件作为参数传递给powershell?(我所做的对吗?)
  2. 如何在 $txt 中获取该文件(在 powershell 变量中)?(我觉得我错了,但我不知道该怎么做)
  3. 有没有更好的方法来做到这一点?(最佳实践)

标签: c#powershellfile

解决方案


  1. 由于您将命名空间作为输出,因此该文档看起来可以很好地用于 Powershell。

  2. New-Item 只是调用变量的 ToString 方法并将其粘贴到文件中。对于 Powershell 中的很多对象,这只是对象的类型或命名空间。只有真正简单的对象才能真正按照您期望的方式输出。您应该使用.Save()XMLDocument 类型中的方法来正确导出它。Export-Clixml也是一种选择。

    XMLDocument .Save()https ://docs.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.save?view=netcore-3.1#System_Xml_XmlDocument_Save_System_String _

    Export-Clixml 文档:https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/export-clixml?view=powershell-7

  3. 这里没有详细说明为什么您从 C# 开始然后切换到 Powershell,但两者非常紧密地交织在一起,并且System.Xml.XmlDocument是一个 .Net 命名空间,可以在两种语言中访问。除非有必要的理由,否则将所有这些都保存在一种语言中可能会更容易。


推荐阅读