Powershell outofmemory when creating a folder

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"


Welcome to the forum. :wave:t4:

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.

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

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

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

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.

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.

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.

$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
#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"

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
    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'"

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

Sorry, the paste didn’t take.

Here is the error.

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

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.

$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:

$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
1 Like