powershellsharepoint

sharepoint powershell - Exception calling "ExecuteQuery" with "0" argument(s): "The underlying connection was closed:"


something is wrong and i don't know what's it ,the same script is working in my local machine but when i tried it in VM it just will not work and throw me exception

-the PowerShell is the same version -the same PowerShell SDK -i added rule to allowing PowerShell -my user is admin -all the parameters are correct and i can enter the SharePoint in browser

Import-Module 'C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll'
Import-Module 'C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll'
Clear-Host
# getting all argument before starting the process #
$SiteURL = "user"
$ListName = "list"
$Username ="email"
$Password ="pass"

if ($SiteURL -eq $null -or $ListName -eq $null -or $Username -eq $null -or $Password -eq $null)
    {
        Write-Output "Somthing went wrong!"
        Write-Output "Some of the variables are not correct"
    }
else
    {
        $outfile = $PSCommandPath | Split-Path -Parent
        $outfile += '\items.txt'
        Clear-Host
        Write-Output "Getting Items"
        $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $securePassword=ConvertTo-SecureString $Password -AsPlainText -Force
        $Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $securePassword)
        $Web = $Context.Web
        $List = $Web.get_lists().getByTitle($ListName)
        $itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
        $ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
        $Context.Load($ListItems)
        $Context.ExecuteQuery()
        $ListItems | ForEach-Object {
            $output=$_["Title"] + "~~"
            $output | Out-File -FilePath $outfile -Append
        }
        Write-Output "Done!"
    }

Solution

  • it's seems the security for the local machine has a SSL Certificate for my account by default but in the VM it was missing that Certificate, so i just invoked by using TLS 1.2

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    

    to the first line of my power-shell code and everything worked nice