【发布时间】:2020-09-12 07:45:08
【问题描述】:
我正在尝试在 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 变量中)? (我觉得我错了,但我不知道该怎么做)
- 有没有更好的方法来做到这一点?(最佳做法)
【问题讨论】:
标签: c# powershell file