Search code examples
powershellsharepointexecutionpolicy

ExecutionPolicy is being asked everytime for running powershell script


Facing small yet hectic issue because of execution policy.

A Powershell script was written to download SharePoint files using "sharepointclientcomponents".

But everytime we are executing it, an error is being thrown saying "Not Digitally Signed". For this, it is becoming mandatory to run "Set -ExecutionPolicy RemoteSigned" first everytime.

Is there any way to set this execution policy permanently so that we can schedule the code?

Your ideas would be a great help for us!

Thanks a ton in Advance!!!!

This is what we tried

    Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass 
    
    #Load SharePoint CSOM Assemblies
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
     
    Function Download-FilesFromLibrary()
    {
        param
        (
            [Parameter(Mandatory=$true)] [string] $SiteURL,
            [Parameter(Mandatory=$true)] [string] $LibraryName,
            [Parameter(Mandatory=$true)] [string] $TargetFolder
        )
     
        Try {
            #Setup Credentials to connect
            $Username="[email protected]"  
            $Password="X1234y"
            $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force          
            #$Cred= Get-Credential
            $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $securePassword)
     
            #Setup the context
            $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
            $Ctx.Credentials = $Credentials
          
            #Get all files from the Library
            $List = $Ctx.Web.Lists.GetByTitle($LibraryName)
            $Ctx.Load($List)
            $Ctx.ExecuteQuery()
             
            #Get Files from the Folder
            $Folder = $List.RootFolder
            $FilesColl = $Folder.Files
            $Ctx.Load($FilesColl)
            $Ctx.ExecuteQuery()
            
            
            Write-host -f Green "All Files from Library '$LibraryName' Downloaded to Folder '$TargetFolder' Successfully!" $_.Exception.Message
            Write-host -f Green "Creating parameters file..." $_.Exception.Message
            $FileNameArray=@()
            $count=0
            $CountArray=@()
            $YearsArray=@()
            $PeriodArray=@()
            
            Foreach($File in $FilesColl)
            { 
                $FileName=$File.Name
                $FileNameYear=$FileName.SubString(4,4)
                $FileNamePeriod=$FileName.SubString(0,3)
                $TargetFile = $TargetFolder+$File.Name
                #Download the file
                $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$File.ServerRelativeURL)
                $WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)
                $FileInfo.Stream.CopyTo($WriteStream)
                $WriteStream.Close()
                $count+=1
                #"'$FileName'" Prints the File Names
                $FileNameArray+=@($FileName)
                $CountArray+=@($count)
                $YearsArray+=@($FileNameYear)
                $PeriodArray+=@($FileNamePeriod)
            }
             "File names stored in an array:"
             $FileNameArray
             "Count stored in an array:"
             $CountArray
             "Years stored in an array:"
             $YearsArray
             "Periods stored in an array:"
             $PeriodArray
             "Total no. of Files extracted:"
             $count
             If ($FileNameArray.Count -gt $CountArray.Count) {
              $limit = $FileNameArray.Count
             } Else {
              $limit = $CountArray.Count
             }
    
            $csv = For ($i = 0; $i -lt $limit; $i++) {
              New-Object -TypeName psobject -Property @{
              'Serial' = $(If ($CountArray[$i]) { $CountArray[$i] })
              'File_Names' = $(If ($FileNameArray[$i]) { $FileNameArray[$i] })
              'Years' = $(If ($YearsArray[$i]) { $YearsArray[$i] })
              'Period' = $(If ($PeriodArray[$i]) { $PeriodArray[$i] })
              'Count' = $(If ($count) { $count })
              }
            }
            $csv | Export-CSV "D:\info.csv" -NoTypeInformation
            Write-host -f Green "Parameters File Created Successfully!" $_.Exception.Message
      }
        Catch {
            write-host -f Red "Error Downloading Files from Library!" $_.Exception.Message
        }
    }
     
    #Set parameter values
    $SiteURL="https://yyyy.sharepoint.com/sites/XXXX/"
    $LibraryName="test_library"
    $TargetFolder="D:\"
     
    #Call the function to download file
    Download-FilesFromLibrary -SiteURL $SiteURL -LibraryName $LibraryName -TargetFolder $TargetFolder

Solution

  • Please try replacing the "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass " in the first line of the code with "Set-ExecutionPolicy Bypass -Scope Process -Force ",it will help you set this execution policy permanently.

    The following is the changed code:

    Set-ExecutionPolicy Bypass  -Scope Process -Force 
        
        #Load SharePoint CSOM Assemblies
        Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
        Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
         
        Function Download-FilesFromLibrary()
        {
            param
            (
                [Parameter(Mandatory=$true)] [string] $SiteURL,
                [Parameter(Mandatory=$true)] [string] $LibraryName,
                [Parameter(Mandatory=$true)] [string] $TargetFolder
            )
         
            Try {
                #Setup Credentials to connect
                $Username="[email protected]"  
                $Password="X1234y"
                $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force          
                #$Cred= Get-Credential
                $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $securePassword)
         
                #Setup the context
                $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
                $Ctx.Credentials = $Credentials
              
                #Get all files from the Library
                $List = $Ctx.Web.Lists.GetByTitle($LibraryName)
                $Ctx.Load($List)
                $Ctx.ExecuteQuery()
                 
                #Get Files from the Folder
                $Folder = $List.RootFolder
                $FilesColl = $Folder.Files
                $Ctx.Load($FilesColl)
                $Ctx.ExecuteQuery()
                
                
                Write-host -f Green "All Files from Library '$LibraryName' Downloaded to Folder '$TargetFolder' Successfully!" $_.Exception.Message
                Write-host -f Green "Creating parameters file..." $_.Exception.Message
                $FileNameArray=@()
                $count=0
                $CountArray=@()
                $YearsArray=@()
                $PeriodArray=@()
                
                Foreach($File in $FilesColl)
                { 
                    $FileName=$File.Name
                    $FileNameYear=$FileName.SubString(4,4)
                    $FileNamePeriod=$FileName.SubString(0,3)
                    $TargetFile = $TargetFolder+$File.Name
                    #Download the file
                    $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$File.ServerRelativeURL)
                    $WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)
                    $FileInfo.Stream.CopyTo($WriteStream)
                    $WriteStream.Close()
                    $count+=1
                    #"'$FileName'" Prints the File Names
                    $FileNameArray+=@($FileName)
                    $CountArray+=@($count)
                    $YearsArray+=@($FileNameYear)
                    $PeriodArray+=@($FileNamePeriod)
                }
                 "File names stored in an array:"
                 $FileNameArray
                 "Count stored in an array:"
                 $CountArray
                 "Years stored in an array:"
                 $YearsArray
                 "Periods stored in an array:"
                 $PeriodArray
                 "Total no. of Files extracted:"
                 $count
                 If ($FileNameArray.Count -gt $CountArray.Count) {
                  $limit = $FileNameArray.Count
                 } Else {
                  $limit = $CountArray.Count
                 }
        
                $csv = For ($i = 0; $i -lt $limit; $i++) {
                  New-Object -TypeName psobject -Property @{
                  'Serial' = $(If ($CountArray[$i]) { $CountArray[$i] })
                  'File_Names' = $(If ($FileNameArray[$i]) { $FileNameArray[$i] })
                  'Years' = $(If ($YearsArray[$i]) { $YearsArray[$i] })
                  'Period' = $(If ($PeriodArray[$i]) { $PeriodArray[$i] })
                  'Count' = $(If ($count) { $count })
                  }
                }
                $csv | Export-CSV "D:\info.csv" -NoTypeInformation
                Write-host -f Green "Parameters File Created Successfully!" $_.Exception.Message
          }
            Catch {
                write-host -f Red "Error Downloading Files from Library!" $_.Exception.Message
            }
        }
         
        #Set parameter values
        $SiteURL="https://yyyy.sharepoint.com/sites/XXXX/"
        $LibraryName="test_library"
        $TargetFolder="D:\"
         
        #Call the function to download file
        Download-FilesFromLibrary -SiteURL $SiteURL -LibraryName $LibraryName -TargetFolder $TargetFolder