Script execution problem with PowerShell

Hello everyone, I need help to understand the APIs, indeed I created a nice little code but it doesn't want to launch. Here is the error message:

Here is the script:

$function Get-SWFileProperties {
param(
[string]$directoryPath
)

if (-not (Get-Module -ListAvailable -Name ImportExcel)) {
    Install-Module -Name ImportExcel -Scope CurrentUser -AllowClobber -Force
}

$excelFile = Join-Path -Path $directoryPath -ChildPath "SolidWorks_Properties.xlsx"
$SolidWorks = New-Object -ComObject SldWorks.Application
$SolidWorks.Visible = $false
$swDocumentTypes = New-Object -ComObject SolidWorks.Interop.swconst.swDocumentTypes_e
$swOpenDocOptions = New-Object -ComObject SolidWorks.Interop.swconst.swOpenDocOptions_e
$swOpenDocOptions_Silent = $swOpenDocOptions.swOpenDocOptions_Silent
$data = @()

$files = Get-ChildItem -Path $directoryPath -Include *.sldprt, *.slddrw, *.sldasm -Recurse
$totalFiles = $files.Count
$processedFiles = 0

foreach ($file in $files) {
    $filePath = $file.FullName
    $fileType = $null
    switch ($file.Extension.ToLower()) {
        ".sldprt" { $fileType = $swDocumentTypes.swDocPART }
        ".sldasm" { $fileType = $swDocumentTypes.swDocASSEMBLY }
        ".slddrw" { $fileType = $swDocumentTypes.swDocDRAWING }
    }
    $doc = $SolidWorks.OpenDoc6($filePath, $fileType, $swOpenDocOptions_Silent, "", [ref] 0, [ref] 0)
    if ($doc -ne $null) {
        $customPropMgr = $doc.Extension.CustomPropertyManager("")
        $properties = @{}
        $names = @()
        $customPropMgr.GetNames([ref]$names)
        foreach ($name in $names) {
            $value = $null
            $customPropMgr.Get4($name, $false, [ref]$value, [ref]$null)
            $properties[$name] = $value
        }
        $properties['FilePath'] = $filePath
        $data += New-Object PSObject -Property $properties
        $SolidWorks.CloseDoc($doc.GetTitle())
    }
    $processedFiles++
    Write-Progress -Activity "Processing SolidWorks Files" -Status "$processedFiles out of $totalFiles processed" -PercentComplete (($processedFiles / $totalFiles) * 100)
}

$data | Export-Excel -Path $excelFile -WorksheetName "Properties" -AutoSize -TableName "SWProperties"
$SolidWorks.ExitApp()
Write-Progress -Activity "Processing SolidWorks Files" -Completed
Write-Host "Processing complete. $processedFiles files processed."

}

Example of use

Get-SWFileProperties -directoryPath " F:\Machine_3D\BDD "

Here's what he does in detail:

  1. ImportExcel module check: The script starts by checking if the ImportExcel PowerShell module is available. This module is required to create and manipulate Excel files without the need for Excel installed on the machine. If the module is not found, it attempts to install it. This module is used to export the collected data to an Excel file.
  2. Preparing the output Excel file: An Excel file path (SolidWorks_Properties.xlsx) is constructed using the folder path provided as a parameter. This file will be used to store the properties extracted from the SolidWorks files.
  3. SolidWorks Application Initialization: The script creates an instance of the SolidWorks application using COM Automation (Component Object Model). This instance is used to open SolidWorks files and extract their properties. The SolidWorks instance is configured to be non-visible ($SolidWorks.Visible = $false), which allows the script to run in the background without opening the SolidWorks user interface.
  4. SolidWorks File Browsing: The script searches the specified folder for all files with extensions. sldprt (parts), .slddrw (drawings), and .sldasm (assemblies), including all subfolders (-Recurse option).
  5. Extract and store properties: For each file found, the script determines its type (part, drawing, or assembly) and uses SolidWorks to open it silently. It then extracts the custom properties from the open file using the CustomPropertyManager. Property names and values are stored in a $data object.
  6. Exporting the data to Excel: After processing all the files, the collected data is exported to the Excel file prepared in step 2, using the ImportExcel module. Each entry will contain the file's path and its custom properties.
  7. Cleanup: At the end of the run, the SolidWorks application is closed ($SolidWorks.ExitApp()), and the script displays a message indicating the number of files processed.

Do you have any idea where the problem could come from?

You have to look in debug mode where the problem comes from exactly.
What are you coding on, Visual Studio Code?

Hello

Maybe see this topic: Error when running a powershell script - Microsoft Q&A
SW being in 64 bits you may have a problem at this level (if the Excel add-in is in 32bits).
Moreover I have a hard time understanding the fact of having SW without Excel, SW relies on Excel for some functions so in theory you need the software on the workstation.

1 Like

Hello

The code I provided for the function Get-SWFileProperties uses the PowerShell ImportExcel module to export data to an Excel file. This module works regardless of the version of Excel installed on my machine (32-bit or 64-bit) because it doesn't directly use Excel itself. Instead, it directly manipulates Excel files by using .NET libraries to read and write files in Excel format.

I don't need Excel to be installed on my machine for the module ImportExcel to work. It is based on EPPlus, a .NET library that allows me to create and manipulate Excel (.xlsx) files without requiring Excel. This means that my script will work regardless of the version of Excel installed, and whether Excel is in 32-bit or 64-bit does not influence the execution of my script.

If you feel like it, you just have to change the repertoire Get-SWFileProperties -directoryPath "F:\Machine_3D\BDD" to try it out. See if it works on your end.

This script attempts to create an instance of the SolidWorks COM component using New-Object -ComObject. If it succeeds, it displays a message indicating that the SolidWorks COM components are available. Otherwise, it displays a message that they are not:

Checking the Availability of SolidWorks COM Components

Setting the SolidWorks COM Component Name

$componentName = " SldWorks.Application "

Attempting to create an instance of the SolidWorks COM component

try {
# Creating an Instance of the COM Component of SolidWorks
$solidWorks = New-Object -ComObject $componentName -ErrorAction Stop
Write-Host " SolidWorks COM components are available on this system." 
} catch {
Write-Host " SolidWorks COM components are not available on this system." 
}

Here's what it returns:

SolidWorks COM components are accessible.
An error occurred while attempting to create a SolidWorks instance:
Item not found. (HRESULT exception: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))

So it's a communication pb