Hello. I created the script below that checks to see if a sub-folder exists in the SCCM console folder structure and if not, create it. It is using a “for each” loop to check the sub-folders of the main specified folder and after that, if it doesn’t exist, then create it.
The problem is, while this creates the sub-folder and exits out of the loop, the…
new-item -Name $APPLICATION_FOLDER_NAME -Path $SCCM_SITE_CODE\Application$APPLICATION_CATEGORY_FOLDER
…command runs more than once so even though the sub-folder gets created, I then get the following error after it exits the loop:
new-item : Path already exists.
At line:16 char:9
+ new-item -Name $APPLICATION_FOLDER_NAME -Path $SCCM_SITE_CODE …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (NP2SCCM701V.sta…n\PSL\NewFolder:String) [New-Item], InvalidOperationException
+ FullyQualifiedErrorId : Path,Microsoft.PowerShell.Commands.NewItemCommand
And that occurs because while the folder didn’t exist until the script was ran, it then did get created from the script, but is running an additional time so I am either using the wrong kind of loop or it is failing on when to exit the loop after the sub-folder is created.
Any ideas? Code below:
# GET SCCM SITE CODE $SMS = gwmi -Namespace 'root\sms' -query "SELECT SiteCode FROM SMS_ProviderLocation" $SCCM_SITE_CODE = $SMS.SiteCode + ":" # SET VARIABLES $APPLICATION_CATEGORY_FOLDER = "PSL" $APPLICATION_FOLDER_NAME = "NewFolder" # GET LIST OF SCCM CONSOLE SUB-FOLDERS OF THE "PSL" FOLDER $GET_SUBFOLDERS_OF_APPLICATION_CATEGORY = get-item -Path "LCS:\Application\$APPLICATION_CATEGORY_FOLDER\*" | select -ExpandProperty Name # IF SUB-FOLDER ALREADY EXISTS, DO NOTHING, OTHERWISE CREATE THE FOLDER SPECIFIED IN $APPLICATION_FOLDER_NAME foreach($SUB_FOLDER in $GET_SUBFOLDERS_OF_APPLICATION_CATEGORY) { if($SUB_FOLDER -eq $APPLICATION_FOLDER_NAME) { Write-Output ("Sub-folder already exists.") } Else { new-item -Name $APPLICATION_FOLDER_NAME -Path $SCCM_SITE_CODE\Application\$APPLICATION_CATEGORY_FOLDER } }