我正在尝试将虚拟服务器中C:\ windows中的所有.dll文件复制到新的虚拟服务器。我已经设法获得所有.dll文件,但是我找不到将它们复制到新虚拟服务器的方法,并且想知道是否有人可能知道如何使用Powershell执行此操作。
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$server = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the server name with files you want to copy", "Server")
$server2 = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the server name you want files copied to", "Server")
$destinationName = ("\\" + $server2 + '\C$\windows')
$Files = Get-ChildItem -Path ("\\" + $server + '\C$\windows') -recurse | Where {$_.extension -eq ".dll"}
我将如何使用我的$ Files变量将其复制到新VM?我知道copy-item cmdlet,但不知道如何使用它将所有这些移动到新的虚拟服务器。
编辑:
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$server = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the server name with files you want to copy", "Server")
$server2 = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the server name you want files copied to", "Server")
$destinationName = ("\\" + $server2 + '\C$\windows')
$Files = Get-ChildItem -Path ("\\" + $server + '\C$\windows') -recurse | Where {$_.extension -eq ".dll"}
foreach($dll in $Files){
$destinationName +=
cp $dll.fullname $destinationName}
我想为每个特定文件获取“\ $ server2 \ C $ \ windows \ .. \ ..”的路径字符串。
如果代码运行,它将使每个文件/目录显示为“\ $ server2 \ C $ \ windows”,而不是获取完整路径。
答案 0 :(得分:2)
$Files = Get-ChildItem...
使$Files
成为一个项目数组,因为Powershell旨在使用对象,所以您只需使用$Files
作为Copy-Item
的参数。需要注意的是,无论出于何种原因,Copy-Item
都不使用Get-ChildItem
获取的对象的完整路径属性(而只是获取文件名,所以你必须在那个目录让它工作),所以最简单的方法就是:
foreach($dll in $Files){cp $dll.fullname $destinationName}
要在保留目录结构的同时进行复制,您需要采用起始完整路径并只修改它以反映新的根目录/服务器。这可以在与上述类似的一行中完成,但为了清晰和可读性,我将其扩展为以下多行设置:
foreach($dll in $Files){
$target = $dll.fullname -replace "\\\\$server","\\$server2"
$targetDir = $($dll.directory.fullname -replace "\\\\$server","\\$server2")
if(!(Test-Path $targetDir){
mkdir $targetDir
}
cp $dll.fullname $target
}
要解释一下,$target...
行采用当前$dll
的完整路径,比如\\SourceServer\C$\windows\some\rather\deep\file.dll
,正则表达式替换了\\SourceServer
所示路径的部分并替换它与\\DestinationServer
一起使路径的其余部分保持不变。也就是说,它现在是\\TargetServer\C$\windows\some\rather\deep\file.dll
。此方法无需使用$destinationName
变量。
Test-Path
位确保在复制之前远程存在文件的父文件夹,否则将失败。