You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell在Azure虚拟机之间复制文件?

用PowerShell实现Azure虚拟机间的文件复制

先解决你遇到的脚本错误

你的错误是因为PowerShell解析双引号内的字符串时,把$destinationVMName:当成了变量引用,但冒号不是合法的变量名字符。同时注意PowerShell变量定义需要加$前缀,修正后的脚本如下:

# Source VM details
$sourceResourceGroup = "<source_resource_group_name>"
$sourceVMName = "<source_vm_name>"
$sourceFilePath = "<source_file_path>"

# Destination VM details
$destinationResourceGroup = "<destination_resource_group_name>"
$destinationVMName = "<destination_vm_name>"
$destinationFilePath = "<destination_file_path>"
$subscriptionId = "<subscription_id>"

# 修正后的scp复制命令
az vm run-command invoke -g $sourceResourceGroup -n $sourceVMName --command-id RunShellScript --scripts 'scp $sourceFilePath '$destinationVMName':$destinationFilePath' --subscription $subscriptionId

注意:使用该方法的前提是源VM已配置免密SSH登录目标VM(比如将源VM的公钥添加到目标VM的~/.ssh/authorized_keys文件),且两台VM网络互通(同VNet或开放SSH端口),否则scp会因需要交互输入密码而失败。

更简便可靠的中转方案(无需SSH信任)

如果不想配置SSH信任,用Azure存储账户作为中转是更稳妥的方式,无需两台VM直接连通:

  1. 从源VM上传文件到Azure Blob存储
# 存储账户信息
$storageAccountName = "<your_storage_account_name>"
$containerName = "<your_container_name>"
$sasToken = "<your_container_sas_token>"

# 在源VM执行上传命令
az vm run-command invoke -g $sourceResourceGroup -n $sourceVMName --command-id RunShellScript --scripts "az storage blob upload --file $sourceFilePath --container-name $containerName --name $(basename $sourceFilePath) --account-name $storageAccountName --sas-token '$sasToken'" --subscription $subscriptionId
  1. 在目标VM下载文件
# 获取上传后的Blob文件名
$blobName = (Split-Path $sourceFilePath -Leaf)

# 在目标VM执行下载命令
az vm run-command invoke -g $destinationResourceGroup -n $destinationVMName --command-id RunShellScript --scripts "az storage blob download --file $destinationFilePath --container-name $containerName --name $blobName --account-name $storageAccountName --sas-token '$sasToken'" --subscription $subscriptionId

该方案仅要求VM能访问Azure存储(默认允许),无需额外配置VM间的SSH信任,适配更多网络场景。

内容的提问来源于stack exchange,提问作者Sally

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 02:33:22