# Powershell outofmemory when creating a folder

**URL:** <https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938>\
**Category:** PowerShell Help\
**Created:** [November 12, 2021, 4:06pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938 "2021-11-12T16:06:21Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![JRDumont](https://avatars.discourse-cdn.com/v4/letter/j/71c47a/32.png) [@JRDumont](https://forums.powershell.org/u/JRDumont)\
**Post date:** [November 12, 2021, 4:06pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/1 "2021-11-12T16:06:21Z")

</div>

I have a simple script that creates a folder and then copies a file into it.  
The first time I run the script it creates the folder without issue but I get an “outofmemory” message when the file is copied. If I run the script again, the file copies without issue. I assume this is the case because the folder already exists.

I tested the script on another system and I can’t duplicate the issue.  
The biggest difference is the system that gets the error is on a domain and my test system is not.

Here is a section of code the creates the folder and then moves the file.

Write-Host “Looking for a folder that starts with ‘$($fileNameFirst4Char)’ …”  
foreach ($folder in $folders) {

$storeNumber = $folder.Name #.Substring(2,3)  
if ($fileNameFirst4Char -eq $storeNumber.substring(0,4)){  
#$PDFFolderName=$ExternalFolderPath + "" + $storeNumber + ""  
$PDFFolderName=$ExternalFolderPath + "" + $storeNumber + “" + “PDFs - distributed” + “"  
write-host “Yes, match… ‘$($PDFFolderName)’…”  
If ($PDFFolderName) {  
New-Item -ItemType Directory -Force -Path (”$($PDFFolderName)” + “Previous Version”)  
}

```
$PreviousPDFName=($PDFFolderName) + ([System.IO.Path]::GetFileNameWithoutExtension($file._name)) + "*"
Move-Item -Path $PreviousPDFName -Destination ("$($PDFFolderName)" + "Previous Version") -Force
Write-host $($PreviousPDFName)
} #else {
#write-host "No match"

```

#}  
}

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 12, 2021, 6:01pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/2 "2021-11-12T18:01:20Z")

</div>

James,  
Welcome to the forum. 👋🏽

Your code seems quite convoluted for me. So at least next time you post code fomat it as code using the _preformatted text_ button ( **\</\>** ). Simply place your cursor on an empty line, click the button and paste your code. And it would make you code easier to read if you removed unnecessary lines you commented out anyway.

Thanks in advance.

> [@JRDumont](#):
>
> I get an “outofmemory” message

I know it sounds trivial and silly but did you try to restart the system you get the error meesage on? 😉

> [@JRDumont](#):
>
> I assume this is the case because the folder already exists.

This usually throws another error message. But anyway - when you get error messages and you don’t know what to do wiht it you should post these error messages here completely as well (formatted as code as well).

If you want to check if a folder exists before you create it new you can use

> **[Test-Path (Microsoft.PowerShell.Management) - PowerShell](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/test-path?view=powershell-7.2)**
>
> The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or...

Please read the help completely including the examples to learn how to use it.

---

<div class="post-metadata">

**Author:** ![JRDumont](https://avatars.discourse-cdn.com/v4/letter/j/71c47a/32.png) [@JRDumont](https://forums.powershell.org/u/JRDumont)\
**Post date:** [November 12, 2021, 6:26pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/3 "2021-11-12T18:26:22Z")

</div>

Thank you for your response and I apologize for the format of the code.  
I modified my code to use the Test-Path and if the folder doesn’t exist, the script will create it.  
This section works fine. The next line copies a file to the newly created folder and that’s when I get the error.

If I run the script again, the Test-Path is true and the copy works fine.

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 12, 2021, 6:50pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/4 "2021-11-12T18:50:10Z")

</div>

> [@JRDumont](#):
>
> This section works fine. The next line copies a file to the newly created folder and that’s when I get the error.
> 
> If I run the script again, the Test-Path is true and the copy works fine.

The statement is ambiguous. Do you always get the error message on the first run of the script?

Please post the complete error message (formatted as code please) and please post ALL of the relevant code. In the code you posted you have variables where we do not see where or how you defined them.

---

<div class="post-metadata">

**Author:** ![JRDumont](https://avatars.discourse-cdn.com/v4/letter/j/71c47a/32.png) [@JRDumont](https://forums.powershell.org/u/JRDumont)\
**Post date:** [November 12, 2021, 7:32pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/5 "2021-11-12T19:32:39Z")

</div>

The error occurs each time the script is run if the target folder doesn’t exist. However, if the job is resubmitted, it runs properly. The folder creation is bypassed due to the use of Test-path.  
I am fairly certain the system was restarted but I will double-check that as well.

Basically, the script checks for a certain folder, and if it doesn’t exist, creates it and then moves files into it. The error seems to happen when trying to move the files into the newly created folder. The job runs properly if resubmitted.

Below is the complete script.

```auto
$ExternalFolderPath = "\\hall-az-file\Hall-Data\Local Workspace\HP-Vault\Contracts"
#$ExternalFolderPath = "C:\PDF Publish"

$hidePDF = $false
$workingDirectory = "C:\Temp\$($file._Name)"
$localPDFfileLocation = "$workingDirectory\$($file._Name).pdf"
$vaultPDFfileLocation = $file._EntityPath +"/"+ (Split-Path -Leaf $localPDFfileLocation)
$CopyPDFfileLocation = $file._EntityPath -replace "/", "\"
$CopyLocalPDFLocation= ($ExternalFolderPath) + $CopyPDFfileLocation.trim("$") + "\"
$CopyRenamePDFLocation= ($workingDirectory) + "\" + ([System.IO.Path]::GetFileNameWithoutExtension($file._name) + "_" + ($file.Revision) + ".pdf")
$fastOpen = $file._Extension -eq "idw" -or $file._Extension -eq "dwg" -and $file._ReleasedRevision
$fileRev=$file.Revision
$fileNameFirst4Char=$file._name.substring(0,4)
#write-host "Filename first 4 char... '$($fileNameFirst4Char)'..."
$folders = Get-Childitem $ExternalFolderPath

Write-Host "Starting job 'Create PDF as attachment' for file '$($file._Name)' ..."

if( @("idw","dwg") -notcontains $file._Extension ) {
    Write-Host "Files with extension: $($file._Extension)' are not supported"
    return
}

Write-Host "Looking for a folder that starts with '$($fileNameFirst4Char)' ..."
foreach ($folder in $folders) {

  $storeNumber = $folder.Name #.Substring(2,3)
  if ($fileNameFirst4Char -eq $storeNumber.substring(0,4)){
    $PDFFolderName=$ExternalFolderPath + "\" + $storeNumber + "\" + "PDFs - distributed" + "\"
    If (!(test-path $PDFFolderName)) {
      New-Item -ItemType Directory -Force -Path ("$($PDFFolderName)" + "Previous Version")
    }
    $PreviousPDFName=($PDFFolderName) + ([System.IO.Path]::GetFileNameWithoutExtension($file._name)) + "*"
    Move-Item -Path $PreviousPDFName -Destination ("$($PDFFolderName)" + "Previous Version") -Force
    Write-host $($PreviousPDFName)
  }
}

$downloadedFiles = Save-VaultFile -File $file._FullPath -DownloadDirectory $workingDirectory -ExcludeChildren:$fastOpen -ExcludeLibraryContents:$fastOpen
$file = $downloadedFiles | select -First 1
$openResult = Open-Document -LocalFile $file.LocalPath -Options @{ FastOpen = $fastOpen } -Application InventorServer

if($openResult) {
    if($openResult.Application.Name -like 'Inventor*') {
        $configFile = "$($env:POWERJOBS_MODULESDIR)Export\PDF_2D.ini"
    } else {
        $configFile = "$($env:POWERJOBS_MODULESDIR)Export\PDF.dwg" 
    }                  
    $exportResult = Export-Document -Format 'PDF' -To $localPDFfileLocation -Options $configFile
    
    if($exportResult) {       
        $PDFfile = Add-VaultFile -From $localPDFfileLocation -To $vaultPDFfileLocation -FileClassification DesignVisualization -Hidden $hidePDF
        $PDFfile = Update-VaultFile -File $PDFfile._FullPath -Category "Design Representation" -Revision $fileRev
        $file = Update-VaultFile -File $file._FullPath -AddAttachments @($PDFfile._FullPath)
    }
    $closeResult = Close-Document
}

Write-host "Renaming PDF file to have Revision" 
#After PDFfile is vaulted, rename PDF file to append "REV" and Revision
Rename-Item $localPDFfileLocation -NewName $CopyRenamePDFLocation

Write-host "Copy Renamed PDF file to Publish folder if found.."
if ($PDFFolderName){
    Write-host "Copy next" 
    Copy-Item $CopyRenamePDFLocation -Destination $PDFFolderName -Force
    }else{
    Write-Host "No Folder exists to copy to...."
}

Clean-Up -folder $workingDirectory

if(-not $openResult) {
    throw("Failed to open document $($file.LocalPath)! Reason: $($openResult.Error.Message)")
}
if(-not $exportResult) {
    throw("Failed to export document $($file.LocalPath) to $localPDFfileLocation! Reason: $($exportResult.Error.Message)")
}
if(-not $closeResult) {
    throw("Failed to close document $($file.LocalPath)! Reason: $($closeResult.Error.Message))")
}
Write-Host "Completed job 'Create PDF as attachment'"

```

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 12, 2021, 7:52pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/6 "2021-11-12T19:52:11Z")

</div>

This is the last time I ask you to post the error message you get.

---

<div class="post-metadata">

**Author:** ![JRDumont](https://avatars.discourse-cdn.com/v4/letter/j/71c47a/32.png) [@JRDumont](https://forums.powershell.org/u/JRDumont)\
**Post date:** [November 12, 2021, 8:03pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/7 "2021-11-12T20:03:27Z")

</div>

Sorry, the paste didn’t take.

Here is the error.  
 ![image](https://us1.discourse-cdn.com/flex019/uploads/powershell/original/2X/9/9f7266b3dc91f48f33e74f9355429bdf2b0a2ee4.png)

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [November 12, 2021, 8:54pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/8 "2021-11-12T20:54:42Z")

</div>

That’s not a PowerShell error message. You use variables in your code you did not show where they come from and you use cmdlets that probably come from third party modules. How should we help you with that?

Regardless of that - you test for a specific path but you create a different one

```auto
If (!(test-path $PDFFolderName)) {
    New-Item -ItemType Directory -Force -Path ("$($PDFFolderName)" + "Previous Version")
}

```

Then - if I get it right - you use the desination folder name to create circumstantially an path with a wildcard at the end to use this as the source for a copy job to the destination folder with an extended name.

```auto
$PreviousPDFName = ($PDFFolderName) + ([System.IO.Path]::GetFileNameWithoutExtension($file._name)) + "*"
Move-Item -Path $PreviousPDFName -Destination ("$($PDFFolderName)" + "Previous Version") -Force

```

Here is an example how it could/should look to be eassy to understand and easy to maintain:

```auto
$SourceFolder = 'D:\Sample\Source'
$DestinationFolder = 'D:\sample\Destination'

if (-not (Test-Path -Path $DestinationFolder)) {
    New-Item -Path $DestinationFolder -ItemType Directory
}
Get-ChildItem -Path $SourceFolder -Filter '*.pdf' | 
    Copy-Item -Destination $DestinationFolder

```

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:20pm UTC](https://forums.powershell.org/t/powershell-outofmemory-when-creating-a-folder/17938/9 "2024-05-16T20:20:26Z")

</div>

Closed on May 16, 2024, 8:20pm UTC


