1

I´m struggling since hours to create content types via script and csv.

The first problem is, that I want to compare existings content types within a sitecollection and the one in the csv.

But it doesn´t work. Could you please help me?

This is the script, just to read and compare the content types:

function new-SPOnlineContentType {
#variables that needs to be set before starting the script
$siteURL = "xxx"
$userName = "xxx"
$CSVLocation = "C:\Users\xxx\Documents\Scripts\ContentTypes.csv"


# Let the user fill in their password in the PowerShell window
$password = Read-Host "Please enter the password for $($userName)" -AsSecureString

# set SharePoint Online credentials
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)

# Creating client context object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$context.credentials = $SPOCredentials
$contentTypes = $context.web.contenttypes
$context.load($contentTypes)

#load CSV file
$contentTypesCSV = import-csv $CSVLocation

# send the request containing all operations to the server
try{
    $context.executeQuery()
    write-host "info: Loaded Fields and Content Types" -foregroundcolor green
}
catch{
    write-host "info: $($_.Exception.Message)" -foregroundcolor red
}

# Loop through all content types to verify it doesn't exist
foreach ($contentType in $contentTypes){
    if ($contentType.Name -eq $contentTypesCSV.NameContentType ){
        write-host "Info: The content type  already exists." -foregroundcolor red
        $contentTypeExists = $true
    }
    else{
    write-host "Info: The content type  does not exists." -foregroundcolor green
        $contentTypeExists = $false
    }
}

}

  • Where exactly are you facing issue? I tried your code and I am able to retrieve all the content types – Deepmala Feb 2 at 1:26
  • Hi Deepmala, the script always says, the "content type already exists", even if the ct does not exists. At debugging the "if" within the foreach will never reached. – spnewbie Feb 2 at 7:51
1

Your if statement seems incorrect:

if ($contentType.Name -eq $contentTypesCSV.NameContentType )

You test if the current selected contentType from $contentTypes array is equal to the whole csv-column that is returned as an array as well.

But I don't know why it evaluates always to true... I tested it and it evaluated to false.

You can change your if statement to this:

if ($contentTypesCSV.NameContentType.Contains($contentType.Name))

You could even improve if you would compare the objects and go further from there:

Compare-Object -ReferenceObject $contentTypesCSV.NameContentType -DifferenceObject $contentType.Name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.