Accesing sharepoint excel using powershell/python - powershell

I am trying to copy excel sharepoint data and manipulate it using powershell or python.
I tried the below code for powershell
$fromfile = "https://company.sharepoint.com/:x:/r/personal/username_domain_company_com/.................
Changes.xlsx"
$tofile = "C:\ExcelTest\NewExcel.xlsx"
$webclient = New-Object System.Net.WebClient
$webclient.UseDefaultCredentials = $true
$webclient.DownloadFile($fromfile, $tofile)
$Excel = New-Object -ComObject Excel.Application
$Workbook = $Excel.Workbooks.Open($tofile)
$Worksheet = $Workbook.Sheets.Item($WorksheetName)
$Excel.Visible = $false
$Workbook.Close($false)
$Excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel) | Out-Null
Remove-Variable Excel
The output is
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At C:\Users\username\Documents\Untitled1.ps1:8 char:1
+ $webclient.DownloadFile($fromfile, $tofile)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
At C:\Users\username\Documents\Untitled1.ps1:12 char:1
+ $Worksheet = $Workbook.Sheets.Item($WorksheetName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Related

Powershell LDAP FindAll() error

I'm trying to connect to new LDAP server which gives me following error. Old site was working without any problems. Can you help?
$dn = "LDAP://ldap.site.cz:389/ou=People,dc=site,dc=com"
$auth = [System.DirectoryServices.AuthenticationTypes]::Anonymous
$de = New-Object System.DirectoryServices.DirectoryEntry($dn,$null,$null,$auth)
$ds = New-Object System.DirectoryServices.DirectorySearcher($de)
[void]$ds.PropertiesToLoad.Add("uid")
$colResults = $ds.FindAll()
Which gives me...
Exception calling "FindAll" with "0" argument(s): "Unknown error (0x80005000)"
At line:9 char:1
+ $colResults = $ds.FindAll()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException

Signing password and get value back

We migrated one Windows Server 2008 to Server 2016.
Now I'm getting an error at this script:
cls
$key = (2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43,6,6,6,6,6,6,31,33,60,23)
$pass = Read-Host -AsSecureString
$securepass = $pass | ConvertFrom-SecureString -Key $key
$bytes = [byte[]][char[]]$securepass
$csp = New-Object System.Security.Cryptography.CspParameters
$csp.KeyContainerName = "SuperSecretProcessOnMachine"
$csp.Flags = $csp.Flags -bor [System.Security.Cryptography.CspProviderFlags]::UseMachineKeyStore
$rsa = New-Object System.Security.Cryptography.RSACryptoServiceProvider -ArgumentList 5120,$csp
$rsa.PersistKeyInCsp = $true
$encrypted = $rsa.Encrypt($bytes,$true)
$encrypted | Export-Clixml 'C:\Temp\encrypted_ysastaginpro_PRE.txt' -Force
Error Code:
New-Object : Exception calling ".ctor" with "2" argument(s): "Object already
exists."
At C:\Program Files\Staging\MESDI\Create_PSW_File_Poly.ps1:13 char:10
+ ... $rsa = New-Object System.Security.Cryptography.RSACryptoServiceP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "Encrypt" with "2" argument(s): "Bad Length."
At C:\Program Files\Staging\MESDI\Create_PSW_File_Poly.ps1:18 char:3
+ $encrypted = $rsa.Encrypt($bytes,$true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CryptographicException
I found the the solution.
Run the PS Script as adminstrator.

FTPS Powershell script

I was wondering is it possible to make an FTPS powershell script to upload and download all files with the same file extension? I have looked and i always see ftp scripts.
I been using this script.
$sourceuri = ""
$targetpath = ""
$username = ""
$password = ""
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)
$ftprequest.Credentials =
New-Object System.Net.NetworkCredential($username,$password)
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $false
$ftprequest.KeepAlive = $false
$ftprequest.EnableSsl = $true
$ftpresponse = $ftprequest.GetResponse()
$responsestream = $ftpresponse.GetResponseStream()
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024
do{
$readlength = $responsestream.Read($readbuffer,0,1024)
$targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)
$targetfile.close()
Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (550) File unavailable (e.g., file not found, no access)."
At H:\-----.ps1:21 char:1
+ $ftpresponse = $ftprequest.GetResponse()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
You cannot call a method on a null-valued expression.
At H:\-------.ps1:24 char:1
+ $responsestream = $ftpresponse.GetResponseStream()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
These are some of the errors I got.

connecting to sharepoint oniline using Powershell : Cannot find an appropriate constructor for type Microsoft.SharePoint.Client.ClientContext

Hi I am trying to connect to sharepoint online and publish calender using the data from a SQL Table and I am getting the following exception , please advise.The same code works fine with slight modification on a on prem sharepoint server I have added sharepointonline for the authentication but it is failing with the error.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
$username = "XXXXXX"
$url = "XXXXXX"
$pass= cat C:\text.txt | ConvertTo-SecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$Pass)
$Context.Credentials = $Creds
$web = $Context.Web
$Context.Load($web)
$Context.Load($splist)
$splist = $Context.web.Lists.GetByTitle("XXXX")
$ItemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
####Some Data coming from SQL Server DB into $table########
$table = $result.Tables[0];
foreach ($row in $table)
{
Write-Host $row.Item("changetitle") $row.Item("status");
$Item1 = $splist.AddItem($ItemCreateInfo)
$Item1["Title"] = "test"
Write-host $date
$Item1.Update()
$Context.ExecuteQuery()
}
Exception
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type Microsoft.SharePoint.Client.ClientContext. At
C:\MOSSLibrary\testingpublish.ps1:15 char:12 + $Context = New-Object
Microsoft.SharePoint.Client.ClientContext($site ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Credentials' cannot be found on this object. Verify
that the property exists and can be set. At
C:\MOSSLibrary\testingpublish.ps1:17 char:1 + $Context.Credentials =
$Creds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:20 char:1 + $Context.Load($web) +
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:21 char:1 + $Context.Load($splist)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:22 char:1 + $splist =
$Context.web.Lists.GetByTitle("XXXXXXX") +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It seems Assemblies are not loading correctly.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
Instead of above, try following
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll"
PS: Make sure that C:\MOSSLibrary\ contains following two .dll's
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll

properties wrong in Powershell

i have a problem with my PS code, i have to start my tests on browsers every tuesday in teamcity! and i wrote the function which goes on my server with credentials and try to make my tests on it
function HTTP-GetRequest($url, $username, $password)
{
$properties = Resolve-Path "C:\Users\Uladzimir_Vaitsiakho\Documents\CI\Build\CI_2.0\vsphere\properties.ps1"
Write-Host $properties
. $properties
$webRequest = [System.Net.WebRequest]::Create($url)
$webRequest.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
$webRequest.PreAuthenticate = $true
$webRequest.Headers.Add("AUTHORIZATION", "Basic");
[System.Net.WebResponse] $resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
[string] $results = $sr.ReadToEnd();
return $results
}
if (($today.DayOfWeek) -eq "Tuesday")
{
if ($env:Browser -eq "Firefox"){
$url = "http://1111111/httpAuth/action.html?add2Queue=bt6&&env.name=Browser&env.value=Chrome"
HTTP-GetRequest $url, $teamcity_username, $teamcity_password
Write-Host $teamcity_password
Write-Host $teamcity_username
}
if ($env:Browser -eq "Chrome"){
$url = "http://11111/httpAuth/action.html?add2Queue=bt6&&env.name=Browser&env.Value=InternetExplorer"
HTTP-GetRequest $url, $teamcity_username, $teamcity_password
}
}
And have got the next output with troubles, but file with properties and credentials i gave to my function, what's can be wrong?!
Cannot convert argument "0", with value: "System.Object[]", for "Create" to type "System.Uri": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Uri"."
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:6 char:47
+ $webRequest = [System.Net.WebRequest]::Create <<<< ($url)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Property 'Credentials' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:7 char:14
+ $webRequest. <<<< Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
+ CategoryInfo : InvalidOperation: (Credentials:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Property 'PreAuthenticate' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:10 char:14
+ $webRequest. <<<< PreAuthenticate = $true
+ CategoryInfo : InvalidOperation: (PreAuthenticate:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:11 char:25
+ $webRequest.Headers.Add <<<< ("AUTHORIZATION", "Basic");
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:13 char:58
+ [System.Net.WebResponse] $resp = $webRequest.GetResponse <<<< ();
+ CategoryInfo : InvalidOperation: (GetResponse:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:14 char:31
+ $rs = $resp.GetResponseStream <<<< ();
+ CategoryInfo : InvalidOperation: (GetResponseStream:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.IO.StreamReader.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:15 char:43
+ [System.IO.StreamReader] $sr = New-Object <<<< System.IO.StreamReader -argumentList $rs;
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:16 char:35
+ [string] $results = $sr.ReadToEnd <<<< ();
+ CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Currently the call to HTTP-GetRequest is passing an array of objects ($url, $teamcity_username , $teamcity_password) to the function. Remove the commas from your function call:
HTTP-GetRequest $url $teamcity_username $teamcity_password