在过去的几个小时里,我一直在努力做到这一点,所以感谢一些帮助。 尝试将 json 文件作为参数传递以调用和迭代循环,如下所示:
}
Invoke-Command -ComputerName $myHV -ArgumentList $VMName,$finalState,$fileconfig -ScriptBlock{
$VMName = $args[0]
$finalState = $args[1]
$filecopy = $args[2]
$json = Get-Content -Raw -Path $filecopy | ConvertFrom-Json
$json | Select-Object -Property Name,Destination | ForEach-Object {
foreach ($file in $json) {
Copy-VMFile -verbose -Name $VMName -SourcePath c:Temp$VMName$file.Name -DestinationPath $file.Destination -FileSource Host -Force
}
不幸的是,复制虚拟机文件函数不断收到错误:
VERBOSE: Copy-VMFile will copy the file into the virtual machine "TEST123"
Failed to copy file "c:Temptestfolder@{Name=hosts; Destination=etc}.Name" to "/etc" in the virtual machine.
我的json基本上是这样的:
[
{
"Name":"hosts",
"Destination":"/etc/"
},
{
"Name":"resolv.conf",
"Destination":"/etc/"
}
]
我不确定为什么它会"畸形"字符串 - 这个"c:Temptestfolder@{Name=hosts; Destination=etc}.Name"
显然应该C:Temptestfolderhosts
......为什么要这样做?
帮助! J
我认为SourcePath
中的反斜杠引起了问题,可能需要转义:
Copy-VMFile -verbose -Name $VMName -SourcePath c:Temp$VMName$file.Name
我已经修复了我的代码,如下所示:
Invoke-Command -ComputerName $myHV -ArgumentList $VMName,$finalState,$fileconfig -ScriptBlock{
$VMName = $args[0]
$finalState = $args[1]
$fileconfig = $args[2]
$json_object = (Get-Content -Path $fileconfig) -join "`n" | ConvertFrom-Json
ForEach ($object in $json_object.PsObject.Properties.value) {
$filename = $object.Name
Copy-VMFile -verbose -Name $VMName -SourcePath C:Temp$VMName$filename -DestinationPath $object.Destination -FileSource Host -Force
}
我希望有人帮助评论我如何成功摆脱反斜杠,因为上述方法有效,我想知道是否有更好的方法。
J