Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows Azure Powershell正在将文件复制到VM_Powershell_Azure_Azure Virtual Machine - Fatal编程技术网

Windows Azure Powershell正在将文件复制到VM

Windows Azure Powershell正在将文件复制到VM,powershell,azure,azure-virtual-machine,Powershell,Azure,Azure Virtual Machine,我正在尝试使用Windows Azure PowerShell将zip文件复制到VM中。 我已经按照文档连接到VM 但是,我找不到任何教程来上传/复制/传输zip文件到虚拟机磁盘,比如说到C驱动器 有人能帮我提供教程的链接吗?有人能告诉我如何复制此教程吗?您不能使用PowerShell将文件直接复制到虚拟机的操作系统磁盘(甚至是其连接的磁盘之一)。没有用于直接与虚拟机内部通信的API(您需要为此创建自己的自定义服务) 您可以使用PowerShell将文件上载到Blob,并使用设置AzureSto

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

但是,我找不到任何教程来上传/复制/传输zip文件到虚拟机磁盘,比如说到C驱动器


有人能帮我提供教程的链接吗?有人能告诉我如何复制此教程吗?

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

您可以使用PowerShell将文件上载到Blob,并使用
设置AzureStorageBlobContent

此时,您可以通知虚拟机上正在运行的应用程序(可能带有队列消息?)有一个文件正在等待处理。处理过程可以很简单,只需将文件复制到虚拟机的本地磁盘即可。

以下是我介绍的另一种方法。它包括

  • 创建和装载空的本地VHD
  • 将文件复制到新的VHD并卸载它
  • 将VHD复制到azure blob存储
  • 将该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
    

    下面是我从一些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
            }
        }
    }
    
    #打开远程会话
    $session=Get session-uri$uri-credentials$credential
    #将安装程序复制到虚拟机
    详细编写“检查是否需要上载文件$InstallerTest”
    发送文件-源$installerSrc-目标$installerTest-会话$Session-onlyCopyNew$true
    函数获取会话($uri,$credentials)
    {
    对于($retry=0;$retry-le 5;$retry++)
    {
    尝试
    {
    $session=New-PSSession-ComputerName$uri[0]。DnsSafeHost-Credential$credentials-Port$uri[0]。端口-UseSSL
    如果($session-ne$null)
    {
    返回$session
    }
    写入输出“无法创建PowerShell会话…正在休眠并在30秒内重试。”
    开始睡眠-30秒
    }
    抓住
    {
    写入输出“无法创建PowerShell会话…正在休眠并在30秒内重试。”
    开始睡眠-30秒
    }
    }
    }
    函数发送文件
    {
    param(
    ##本地计算机上的路径
    [参数(必需=$true)]
    [字符串]
    $Source,
    ##远程计算机上的目标路径
    [参数(必需=$true)]
    [字符串]
    $Destination,
    ##表示远程计算机的会话
    [参数(必需=$true)]
    [系统、管理、自动化、运行空间、PSSession]
    $Session,
    ##如果文件已经存在,我们应该退出吗?
    [布尔]
    $onlyCopyNew=$false
    )
    $remoteScript=
    {
    param($destination,$bytes)
    #将目标路径转换为完整的文件系统路径(以支持相对路径)
    $Destination=$ExecutionContext.SessionState`
    Path.getUnsolvedProviderPathFrompPath($Destination)
    #将内容写入新文件
    $file=[IO.file]::打开($Destination,“OpenOrCreate”)
    $null=$file.Seek(0,“结束”)
    $null=$file.Write($bytes,0,$bytes.Length)
    $file.Close()
    }
    #获取源文件,然后开始读取其内容
    $sourceFile=Get Item$Source
    #删除以前存在的文件(如果存在)
    $abort=调用命令-会话$Session{
    参数([String]$dest[bool]$onlyCopyNew)
    if(测试路径$dest)
    { 
    如果($onlyCopyNew-eq$true)
    {
    返回$true
    }
    删除项目$dest
    }
    $destinationDirectory=Split Path-Path$dest-Parent
    if(!(测试路径$destinationDirectory))
    {
    新建项-ItemType目录-Force-Path$destinationDirectory
    }
    返回$false
    }-ArgumentList$Destination,$onlyCopyNew
    如果($abort-eq$true)
    {
    写入主机“忽略文件传输-已存在”
    返回
    }
    #现在把它分成几块流
    写入进度-活动“发送$Source”-状态“正在准备文件”
    $streamSize=1MB
    $position=0
    $rawBytes=新对象字节[]$streamSize
    $file=[IO.file]::OpenRead($sourceFile.FullName)
    而(($read=$file.read($rawBytes,0,$streamSize))-gt 0)
    {
    写入进度-活动“写入$Destination”-状态“发送文件”`
    -完成百分比($position/$sourceFile.Length*100)
    #确保我们的阵列与从磁盘读取的阵列大小相同
    if($read-ne$rawBytes.Length)
    {
    [数组]::调整大小([ref]$rawBytes,$read)
    }
    #并将该阵列发送到远程系统
    Invoke命令-Session$Session$remoteScript-ArgumentList$destination$rawBytes
    #确保我们的阵列与从磁盘读取的阵列大小相同
    if($rawBytes.Length-ne$streamSize)
    {
    [数组]::调整大小([ref]$rawBytes,$streamSize)
    }
    [GC]::Collect()
    $position+=$read
    }
    $file.Close()
    #显示结果
    调用命令-Session$Session{Get Item$args[0]}-ArgumentList$Destination
    }
    函数发送文件夹
    {
    param(
    ##本地计算机上的路径
    [参数(必需=$true)]
    [字符串]
    $Source,
    ##远程计算机上的目标路径
    [参数(必需=$true)]
    [字符串]
    $Destination,
    ##表示远程计算机的会话
    #[参数(必需=$true)]
    [System.Management.Automation.Runspaces]。
    
        .\AzCopy /Source:C:\myfolder /Dest:https://myaccount.blob.core.windows.net/mycontainer/myfolder/ /DestKey:key /Pattern:abc.txt
    
        .\AzCopy /Source:https://myaccount.file.core.windows.net/myfileshare/myfolder/ /Dest:C:\myfolder /SourceKey:key /Pattern:abc.txt
    
    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
    
    powershell.exe Start-Process -Wait  -PassThru msiexec -ArgumentList '/qn /i "c:\MyTempFolder\ddagent.msi" APIKEY="8532473174"'