Dispose and Flush method in MsftFileSystemImage (Powershell script)

125 views Asked by At

I found a Powershell Script that burn the Zip File from one location $Path = "C:\temp\test.zip" to CD ROM. The script program work fine. I try to enchance the program by delete the zip file in the $Path after the script complete but run into error.

Remove-Item : Cannot remove item "C:\temp\test.zip": The process cannot access the file "C:\temp\test.zip" because it is being used by another proces

This is my code:

Function Out-CD
{
    [CmdletBinding()]
 
    param (
        $Path = 'C:\temp\test.zip',
        $CdTitle = 'data'
    )
    
    BEGIN
    {
        try
        {
            Write-Verbose 'Creating COM Objects.' -Verbose
 
            $DiskMaster      = New-Object -com IMAPI2.MsftDiscMaster2
            $DiscRecorder    = New-Object -com IMAPI2.MsftDiscRecorder2
            $FileSystemImage = New-Object -com IMAPI2FS.MsftFileSystemImage
            $DiscFormatData  = New-Object -com IMAPI2.MsftDiscFormat2Data
        }
        catch
        {
            $err = $Error[0]
            Write-Error $err
            return
        }
    }
 
    PROCESS
    {
        Write-Verbose 'Initializing Disc Recorder.' -Verbose
        $id = $DiskMaster.Item(0)
        $DiscRecorder.InitializeDiscRecorder($id)
 
        Write-Verbose 'Assigning recorder.' -Verbose
        $dir = $FileSystemImage.Root
        $DiscFormatData.Recorder = $DiscRecorder
        $DiscFormatData.ClientName = 'PowerShell Burner'
 
        Write-Verbose 'Multisession?' -Verbose
        if (-not $DiscFormatData.MediaHeuristicallyBlank)
        {
        Write-Verbose 'inside if condition' -Verbose
            try
            {
                $FileSystemImage.MultisessionInterfaces = $DiscFormatData.MultisessionInterfaces
                Write-Verbose 'Importing existing session.' -Verbose
 
                $FileSystemImage.ImportFileSystem() | Out-Null
            }
            catch
            {
                $err = $Error[0]
                Write-Error $err
                return
            }
        }
        else
        {
            Write-Verbose 'Empty medium.' -Verbose
            $FileSystemImage.ChooseImageDefaults($DiscRecorder)
            $FileSystemImage.VolumeName = $CdTitle
        }
 
        Write-Verbose "Adding directory tree ($Path)." -Verbose
        $dir.AddTree($Path, $true)
 
        Write-Verbose 'Creating image.' -Verbose
        $result = $FileSystemImage.CreateResultImage()
        $stream = $result.ImageStream
 
        Write-Verbose 'Burning.' -Verbose
        $DiscFormatData.Write($stream)
 
        Write-Verbose 'Done.' -Verbose
    }
 
    END { 
         //My Code
       Remove-Item -Path $Path -Force -Recurse
    }
}

I am wondering is that because MsftFileSystemImage is still running and it needed to be flush() or close() or delete()? I looked at the Microsoft Website but cannot find any method that I mentioned above

0

There are 0 answers