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.
Related
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
I would like to create a program in PowerShell to upload files to Sharepoint on schedule (using Task Scheduler)
I was looking for solution and I found this interesting article.
Based on this I wrote this script below:
Import-Module Microsoft.Online.Sharepoint.Powershell -DisableNameChecking;
(System.Reflection.Assembly)::LoadWithPartialName("System.IO.MemoryStream")
Clear-Host
$cred = Get-Credential "emailaddress#domain.com"
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.Username, $cred.Password)
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext("https://")
$clientCOntext.Credentials = $credentials
if (!$clientContext.ServerObjectIsNull.Value) {Write-host "Connected to site" -ForegroundColor Green}
Function UploadFileToLibrary(){
$docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
$clientContext.Load($docLib);
$clientContext.ExecuteQuery();
$rootFolder = $docLib.RootFolder
$Folder = "\\10.x.x.x\xpbuild$\IT\Level0\scresult\Upload";
$FilesInRoot = Get-ChildItem - Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
$startDTM = (Get-Date)
}Write-Host "Uploading File" $File.Name "to" $docLib.Title -ForegroundColor Blue
UploadFile $rootFolder $File $false
$endDTM = (Get-Date)
Write-Host "Total Elapsed Time : $(($endDTM-$startDTM).totalseconds) seconds"
}
Function UploadFile ($SPListFolder, $File, $CheckInRequired){
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $True
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.Url = $File
$UploadedFile = $SPListFolder.Files.Add($FileCreationInfo)
If($CheckInRequired){
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
If($uploadedFile.CheckOutType -ne "none"){
$UploadedFile.CheckIn("Checked in by Administrator", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
}
}
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
}
UploadFileToLibrary
When I tried to execute this I see that connection is active but I got an error:
Method invocation failed because [Microsoft.SharePoint.Client.List] does not contain a method named 'op_Subtraction'.
At C:\PowerShell\UploadSharepoint.ps1:11 char:1
+ $docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Cannot find an overload for "Load" and the argument count: "1".
At C:\PowerShell\UploadSharepoint.ps1:12 char:1
+ $clientContext.Load($docLib);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception calling "ExecuteQuery" with "0" argument(s): "List 'IT Documents' does not exist at site with URL 'https://'."
At C:\PowerShell\UploadSharepoint.ps1:13 char:1
+ $clientContext.ExecuteQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServerException
I cannot tell if any new problem occur once you fix that one, but given that the 2nd and 3rd error is caused by incorrect assignment of $docLib variable, changing - to =should resolve these three:
HERE |
$docLib = $clientContext.Web.Lists.GetByTitle("IT Documents");
# Below uses $docLib so it cannot be executed properly unless $docLib is assigned correct value
$clientContext.Load($docLib);
# And below fails as the above is not executed successfully
$clientContext.ExecuteQuery();
This is my PowerShell script where I am loading the assembly and invoking a function from one of the assemblies.
$dllpath1 = "D:\Adhoc_Testing\AdhocDataServices\AdhocDataServices\bin\AdhocDataServices.dll"
$dllpath2 = "D:\Adhoc_Testing\QueryExpressDataServices\QueryExpressDataServices\bin\Microsoft.IdentityModel.Tokens.dll"
$dllpath3 = "D:\Adhoc_Testing\QueryExpressDataServices\QueryExpressDataServices\bin\System.IdentityModel.Tokens.Jwt.dll"
$lib3 = [Reflection.Assembly]::LoadFile("$dllpath3")
$lib2 = [Reflection.Assembly]::LoadFile("$dllpath2")
$lib1 = [Reflection.Assembly]::LoadFile("$dllpath1")
$obj = New-Object "AdhocDataServices.Controllers.TokenController"
$result = $obj.Fact()
Write-Host $result
Read-Host -Prompt “Press Enter to exit”
I'm getting below error.
New-Object : Cannot find type
[AdhocDataServices.Controllers.TokenController]: verify that the
assembly containing this type is loaded. At line:1 char:8 + $obj =
New-Object AdhocDataServices.Controllers.TokenController +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +
CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException +
FullyQualifiedErrorId :
TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
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.
This script was working just fine today while testing. I made a few changes and started getting an error. I then went back to the very original script I got from the internet and now even it does not work. The errors are:
Exception calling "SetInfo" with "0" argument(s): "A constraint violation
occurred."
At C:\Scripts\CreateTest2.ps1:51 char:2
+ $LABUser.SetInfo()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
Exception calling "Invoke" with "2" argument(s): "There is no such object on the
server."
At C:\Scripts\CreateTest2.ps1:55 char:2
+ $LABUser.psbase.invoke("setPassword", $Pwrd)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
Exception calling "InvokeSet" with "2" argument(s): "The directory property
cannot be found in the cache"
At C:\Scripts\CreateTest2.ps1:56 char:2
+ $LABUser.psbase.invokeSet("AccountDisabled", $false)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
Exception calling "CommitChanges" with "0" argument(s): "A constraint violation
occurred."
At C:\Scripts\CreateTest2.ps1:57 char:2
+ $LABUser.psbase.CommitChanges()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Here is the script. What am I doing wrong?
function Select-FileDialog {
param(
[string]$Title,
[string]$Directory,
[string]$Filter = "CSV Files(*.csv)|*.csv"
)
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$objForm = New-Object System.Windows.Forms.OpenFileDialog
$objForm.InitialDirectory = $Directory
$objForm.Filter = $Filter
$objForm.Title = $Title
$objForm.ShowHelp = $true
$Show = $objForm.ShowDialog()
if ($Show -eq "OK") {
return $objForm.FileName
} else {
exit
}
}
$FileName = Select-FileDialog -Title "Import an CSV file" -Directory "c:\"
$SelectOU = "OU=Test2,OU=Users,OU=Domain Controllers"
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
$DomainDN = (([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).Domains | ? {$_.Name -eq $domain}).GetDirectoryEntry().distinguishedName
$final = "LDAP://$DomainDN"
$DomainPath = [ADSI]"$final"
$UserInformation = Import-Csv $FileName
$OUPath = "LDAP://$SelectOU,$DomainDN"
$UserPath = [ADSI]"$OUPath"
foreach ($User in $UserInformation) {
$CN = $User.samAccountName
$SN = $User.Surname
$Given = $User.givenName
$samAccountName = $User.samAccountName
$Display = $User.DisplayName
$LABUser = $UserPath.Create("User", "CN=$CN")
Write-Host "Please Wait..."
$LABUser.Put("samAccountName", $samAccountName)
$LABUser.Put("sn", $SN)
$LABUser.Put("givenName", $Given)
$LABUser.Put("displayName", $Display)
$LABUser.Put("userPrincipalName", "$samAccountName#$domain")
$LABUser.SetInfo()
$Pwrd = $User.Password
$LABUser.psbase.invoke("setPassword", $Pwrd)
$LABUser.psbase.invokeSet("AccountDisabled", $false)
$LABUser.psbase.CommitChanges()
}
Write-Host "Script Completed"
Can you please try Removing the Quotes from
1) LABUser assignment i.e. CN = $CN.
2) Remove the CN = from that line.
Try it one by one i hope you get your answer.