Add-File.ps1

Function Add-File
{
  <#
      .SYNOPSIS
      Adds Files to a VHD
      .DESCRIPTION
      This Cmdlet Copies one or more files to a Path on a VHD-File
      .EXAMPLE
      Add-File -FilePath C:\Temp\unattend.txt -OSDrive E: -targetPath \
      Copies an unattend.txt to the root of a mounted VHD
      .NOTES
      Version: 1.0
      Author: Holger Voges
      Date: 2018-08-17
      www.netz-weise-it.training/weisheiten/
  #>


   param(     
    [ValidateScript({ If ( Test-Path -Path $_ -PathType Leaf )
                        { $true }
                    Else { Throw "$_ is not a valid File." } 
    })]
    [Parameter(Mandatory=$true)]
    [string]$FilePath,
    
    [String]$NewFileName,

    [ValidatePattern('[c-z,C-Z]:')]
    [String]$OsDrive,
    
    [String]$TargetPath
  )

  If ( test-Path $OsDrive )
  {
    $TargetFolder = Join-Path -Path $OsDrive -ChildPath "$TargetPath" 
    
    if ( -not ( Test-Path $TargetFolder -PathType Container ))
    {
      Try {
        mkdir $TargetPath
      }
      Catch
      {
        Write-Error "Der Pfad $Targetpath existiert nicht und konnte nicht angelegt werden"
        Break
      }
    }
    
    If ( $NewFileName  )
    {
      Copy-Item -Path $FilePath -Destination ( join-path -path $TargetFolder -childpath $NewFileName )
    }
    Else
    {
      Copy-Item -Path $FilePath -Destination $TargetFolder 
    }           
  }
  Else
  {
    Write-Error -Exception "Target $OSDrive could not be found"
  }
}