c# - 使用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 文件。
问题 :-
- 如何将xml文件作为参数传递给powershell?(我所做的对吗?)
- 如何在 $txt 中获取该文件(在 powershell 变量中)?(我觉得我错了,但我不知道该怎么做)
- 有没有更好的方法来做到这一点?(最佳实践)
解决方案
由于您将命名空间作为输出,因此该文档看起来可以很好地用于 Powershell。
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
这里没有详细说明为什么您从 C# 开始然后切换到 Powershell,但两者非常紧密地交织在一起,并且
System.Xml.XmlDocument
是一个 .Net 命名空间,可以在两种语言中访问。除非有必要的理由,否则将所有这些都保存在一种语言中可能会更容易。
推荐阅读
- javascript - 一种使用 Bootstrap 4 下拉菜单在部分之间切换的方法
- r - 成功登录后无法导航到闪亮的仪表板
- magento-2.3 - 在 Magento Ui 表单中使用 SwitcherConfig 隐藏整个选项卡
- mysql - 错误 1062 (23000):键 'PRIMARY' 的重复条目 'DP1'
- angular6 - 有没有办法在 Angular 中创建文件资源管理器以使用 Angular 6 访问本地文件夹及其子文件夹?
- javascript - 无法在基于反应类的组件中安装组件
- android - Android 移动指示应用程序在新构建的应用程序中包含病毒
- quarkus - Quarkus REST Jackson 对象映射器配置似乎不起作用
- android - 无法兑换 Google Play 促销代码,出现“兑换错误代码:BM-BQ-01”
- github - 更改托管 github 页面的 URL