1

仮想サーバーの 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 コマンドレットは知っていますが、それを使用してこれらすべてを新しい仮想サーバーに移動する方法を知りません。

編集:

[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" として表示され、フル パスが取得されません。

4

1 に答える 1

2

実際、あなたは本当にもうすぐそこにいます。

$Files = Get-ChildItem...$Filesアイテムの配列になり、Powershell はオブジェクトを操作するように設計されているため$Files、引数としてCopy-Item. これに関する注意点は、何らかの理由で、でCopy-Item取得したオブジェクトからのフル パス プロパティを使用しないことですGet-ChildItem(代わりに、ファイル名を取得するだけなので、動作させるにはそのディレクトリにいる必要があります)。最も簡単な方法は次のとおりです。

foreach($dll in $Files){cp $dll.fullname $destinationName}

ディレクトリ構造を維持しながらコピーするには、最初のフル パスを取得し、新しいルート ディレクトリ/サーバーを反映​​するように変更します。これは上記と同様に 1 行で実行できますが、わかりやすく読みやすくするために、次の複数行の設定に拡張しています。

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$destinationNameTest-Path

于 2012-08-03T15:18:32.887 に答える