9

我正在尝试使用 Windows Azure PowerShell 将 zip 文件复制到 VM 中。我已经设法按照文档连接到 VM。

但是,我找不到任何教程将 zip 文件上传/复制/传输到 VM 磁盘,比如 C 驱动器。

任何人都可以帮我提供教程的任何链接或任何想法如何复制它吗?

4

6 回答 6

6

这是我在此处记录的另一种方法。它涉及

  1. 创建并装载一个空的本地 VHD。
  2. 将文件复制到新的 VHD 并卸载它。
  3. 将 VHD 复制到 Azure Blob 存储
  4. 将该 VHD 附加到您的 VM。

这是一个例子:

#Create and mount a new local VHD
$volume = new-vhd -Path test.vhd -SizeBytes 50MB | `
  Mount-VHD -PassThru | `
  Initialize-Disk -PartitionStyle mbr -Confirm:$false -PassThru | `
  New-Partition -UseMaximumSize -AssignDriveLetter -MbrType IFS | `
  Format-Volume -NewFileSystemLabel "VHD" -Confirm:$false

#Copy my files  
Copy-Item C:\dev\boxstarter "$($volume.DriveLetter):\" -Recurse
Dismount-VHD test.vhd

#upload the Vhd to azure
Add-AzureVhd -Destination http://mystorageacct.blob.core.windows.net/vhdstore/test.vhd `
  -LocalFilePath test.vhd

#mount the VHD to my VM
Get-AzureVM MyCloudService MyVMName | `
  Add-AzureDataDisk -ImportFrom `
  -MediaLocation "http://mystorageacct.blob.core.windows.net/vhdstore/test.vhd" `
  -DiskLabel "boxstarter" -LUN 0 | `
  Update-AzureVM
于 2013-09-12T10:09:24.233 回答
4

这是我从一些 powershell 示例中获得并修改的一些代码。它适用于使用创建的会话New-PSSession。下面还包括一​​个很酷的包装器。最后,我需要发送一个完整的文件夹,所以也在这里..

将它们捆绑在一起的一些示例用法

# open remote session
$session = Get-Session -uri $uri -credentials $credential 
# copy installer to VM
Write-Verbose "Checking if file $installerDest needs to be uploaded"
Send-File -Source $installerSrc -Destination $installerDest -Session $session -onlyCopyNew $true



<#
.SYNOPSIS
  Returns a session given the URL 
.DESCRIPTION
  http://michaelcollier.wordpress.com/2013/06/23/using-remote-powershell-with-windows-azure-vms/
#>
function Get-Session($uri, $credentials)
{
    for($retry = 0; $retry -le 5; $retry++)
    {
      try
      {
        $session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credentials -Port $uri[0].Port -UseSSL
        if ($session -ne $null)
        {
            return $session
        }

        Write-Output "Unable to create a PowerShell session . . . sleeping and trying again in 30 seconds."
        Start-Sleep -Seconds 30
      }
      catch
      {
        Write-Output "Unable to create a PowerShell session . . . sleeping and trying again in 30 seconds."
        Start-Sleep -Seconds 30
      }
    }
}

<#
.SYNOPSIS
  Sends a file to a remote session.
  NOTE: will delete the destination before uploading
.EXAMPLE
  $remoteSession = New-PSSession -ConnectionUri $remoteWinRmUri.AbsoluteUri -Credential $credential
  Send-File -Source "c:\temp\myappdata.xml" -Destination "c:\temp\myappdata.xml" $remoteSession

  Copy the required files to the remote server 

    $remoteSession = New-PSSession -ConnectionUri $frontEndwinRmUri.AbsoluteUri -Credential $credential
    $sourcePath = "$PSScriptRoot\$remoteScriptFileName"
    $remoteScriptFilePath = "$remoteScriptsDirectory\$remoteScriptFileName"
    Send-File $sourcePath $remoteScriptFilePath $remoteSession

    $answerFileName = Split-Path -Leaf $WebPIApplicationAnswerFile
    $answerFilePath = "$remoteScriptsDirectory\$answerFileName"
    Send-File $WebPIApplicationAnswerFile $answerFilePath $remoteSession
    Remove-PSSession -InstanceId $remoteSession.InstanceId
#>
function Send-File
{
    param (

        ## The path on the local computer
        [Parameter(Mandatory = $true)]
        [string]
        $Source,

        ## The target path on the remote computer
        [Parameter(Mandatory = $true)]
        [string]
        $Destination,

        ## The session that represents the remote computer
        [Parameter(Mandatory = $true)]
        [System.Management.Automation.Runspaces.PSSession] 
        $Session,

        ## should we quit if file already exists?
        [bool]
        $onlyCopyNew = $false

        )

    $remoteScript =
    {
        param ($destination, $bytes)

        # Convert the destination path to a full filesystem path (to supportrelative paths)
        $Destination = $ExecutionContext.SessionState.`
        Path.GetUnresolvedProviderPathFromPSPath($Destination)

        # Write the content to the new file
        $file = [IO.File]::Open($Destination, "OpenOrCreate")
        $null = $file.Seek(0, "End")
        $null = $file.Write($bytes, 0, $bytes.Length)
        $file.Close()
    }

    # Get the source file, and then start reading its content
    $sourceFile = Get-Item $Source

    # Delete the previously-existing file if it exists
    $abort = Invoke-Command -Session $Session {
        param ([String] $dest, [bool]$onlyCopyNew)

        if (Test-Path $dest) 
        { 
            if ($onlyCopyNew -eq $true)
            {
                return $true
            }

            Remove-Item $dest
        }

        $destinationDirectory = Split-Path -Path $dest -Parent
         if (!(Test-Path $destinationDirectory))
        {
            New-Item -ItemType Directory -Force -Path $destinationDirectory 
        }

        return $false
    } -ArgumentList $Destination, $onlyCopyNew

    if ($abort -eq $true)
    {
        Write-Host 'Ignored file transfer - already exists'
        return
    }

    # Now break it into chunks to stream
    Write-Progress -Activity "Sending $Source" -Status "Preparing file"
    $streamSize = 1MB
    $position = 0
    $rawBytes = New-Object byte[] $streamSize
    $file = [IO.File]::OpenRead($sourceFile.FullName)
    while (($read = $file.Read($rawBytes, 0, $streamSize)) -gt 0)
    {
        Write-Progress -Activity "Writing $Destination" -Status "Sending file" `
            -PercentComplete ($position / $sourceFile.Length * 100)

        # Ensure that our array is the same size as what we read from disk
        if ($read -ne $rawBytes.Length)
        {
            [Array]::Resize( [ref] $rawBytes, $read)
        }

        # And send that array to the remote system
        Invoke-Command -Session $session $remoteScript -ArgumentList $destination, $rawBytes

        # Ensure that our array is the same size as what we read from disk
        if ($rawBytes.Length -ne $streamSize)
        {
            [Array]::Resize( [ref] $rawBytes, $streamSize)
        }
        [GC]::Collect()
        $position += $read
    }

    $file.Close()

    # Show the result
    Invoke-Command -Session $session { Get-Item $args[0] } -ArgumentList $Destination
}

<#
.SYNOPSIS
  Sends all files in a folder to a remote session.
  NOTE: will delete any destination files before uploading
.EXAMPLE
  $remoteSession = New-PSSession -ConnectionUri $remoteWinRmUri.AbsoluteUri -Credential $credential
  Send-Folder -Source 'c:\temp\' -Destination 'c:\temp\' $remoteSession
#>
function Send-Folder 
{
    param (
        ## The path on the local computer
        [Parameter(Mandatory = $true)]
        [string]
        $Source,

        ## The target path on the remote computer
        [Parameter(Mandatory = $true)]
        [string]
        $Destination,

        ## The session that represents the remote computer
     #   [Parameter(Mandatory = $true)]
        [System.Management.Automation.Runspaces.PSSession] 
        $Session,

        ## should we quit if files already exist?
        [bool]
        $onlyCopyNew = $false
    )

    foreach ($item in Get-ChildItem $Source)
    {
        if (Test-Path $item.FullName -PathType Container) {
            Send-Folder $item.FullName "$Destination\$item" $Session $onlyCopyNew
        } else {
            Send-File -Source $item.FullName -Destination "$destination\$item" -Session $Session -onlyCopyNew $onlyCopyNew
        }
    }
}
于 2013-11-26T20:38:29.930 回答
2

您不能使用 PowerShell 将文件直接复制到虚拟机的操作系统磁盘(甚至是其附加磁盘之一)。没有用于直接与虚拟机内部通信的 API(您需要为此创建自己的自定义服务。

可以使用 PowerShell 将文件上传到 Blob,使用Set-AzureStorageBlobContent. 此时,您可以通知您的虚拟机上正在运行的应用程序(可能带有队列消息?)有一个文件等待它处理。处理过程可以像将文件复制到虚拟机的本地磁盘一样简单。

于 2013-08-05T04:18:01.947 回答
1
  1. 从http://aka.ms/downloadazcopy安装 AzCopy
  2. 从以下位置阅读文档:https ://docs.microsoft.com/en-us/azure/storage/storage-use-azcopy
  3. cd "C:\Program Files (x86)\Microsoft SDKs\Azure\AzCopy"
  4. 获取 Blob 存储(辅助)密钥
  5. Powershell:Blob 上传单个文件

    .\AzCopy /Source:C:\myfolder /Dest:https://myaccount.blob.core.windows.net/mycontainer/myfolder/ /DestKey:key /Pattern:abc.txt

  1. 登录远程虚拟机

  2. Powershell:Blob 下载单个文件

    .\AzCopy /Source:https://myaccount.file.core.windows.net/myfileshare/myfolder/ /Dest:C:\myfolder /SourceKey:key /Pattern:abc.txt

于 2017-03-20T03:40:00.473 回答
0

另一种解决方案是使用自定义扩展脚本
即使 VM 没有公共 ip(专用网络),使用自定义扩展脚本也可以将文件复制到 VM。所以你不需要配置 winRm 什么的。

我过去曾使用自定义扩展脚本进行后期部署,例如在 VM 或规模集上安装应用程序。基本上,您将文件上传到 blob 存储,自定义扩展脚本将在 VM 上下载这些文件。

test-container在我的 blob 存储帐户上创建了一个并上传了两个文件:

  • deploy.ps1:在虚拟机上执行的脚本。
  • test.txt:带有“来自VM的Hello world”的文本文件

这是deploy.ps1文件的代码:

Param(
    [string] [Parameter(Mandatory=$true)] $filename,
    [string] [Parameter(Mandatory=$true)] $destinationPath
)

# Getting the full path of the downloaded file
$filePath = $PSScriptRoot + "\" + $filename

Write-Host "Checking the destination folder..." -Verbose
if(!(Test-Path $destinationPath -Verbose)){
    Write-Host "Creating the destination folder..." -Verbose
    New-Item -ItemType directory -Path $destinationPath -Force -Verbose
}

Copy-Item $filePath -Destination $destinationPath -Force -Verbose

这是向虚拟机添加自定义脚本扩展的代码。

Login-AzureRMAccount

$resourceGroupName = "resourcegroupname"
$storageAccountName = "storageaccountname"
$containerName = "test-container"
$location = "Australia East"
$vmName = "TestVM"
$extensionName = "copy-file-to-vm"
$filename = "test.txt"
$deploymentScript = "deploy.ps1"
$destintionPath = "C:\MyTempFolder\"

$storageAccountKeys = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value
$storageAccountKey = $storageAccountKeys[0]

Set-AzureRmVMCustomScriptExtension -ResourceGroupName $resourceGroupName -VMName $vmName -Name $extensionName -Location $location -TypeHandlerVersion "1.9" -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey -ContainerName $containerName -FileName $deploymentScript, $filename -Run $deploymentScript -Argument "$filename $destintionPath" -ForceRerun "1"

复制文件后,您可以删除扩展名:

Remove-AzureRmVMCustomScriptExtension -ResourceGroupName $resourceGroupName -VMName $vmName -Name $extensionName -Force

在我的场景中,我有一个逻辑应用程序,每次将新文件添加到容器时都会触发该应用程序。逻辑应用调用添加自定义脚本扩展然后将其删除的 Runbook(需要azure 自动化帐户)。

于 2018-02-01T23:15:40.513 回答
0

我能够在目标服务器上复制二进制文件但无法安装,我deploy.ps1在底部使用以下语法

powershell.exe Start-Process -Wait  -PassThru msiexec -ArgumentList '/qn /i "c:\MyTempFolder\ddagent.msi" APIKEY="8532473174"'
于 2020-04-07T15:37:48.587 回答