PowerShell Usage - File Upload Directory - powershell

I am hoping to get some assistance on PowerShell usage for HTTPS file upload. My current task to automate the copying of a directory of PDF file from a local network path to a HTTPS:// website. Whilst I have a local account on the web server, I have an issue with file upload and recursing the list all PDF's.
I tried Invoke-RestMethod -URI
$sourceFilePath = Get-ChildItem "\\DFS-Netwrok\PDF" -Recurse -Include *.pdf
$siteAddress = "https://contoso.com/PDF";
$urlDest = "{0}/{1}" -f ($siteAddress, "*.pdf");
$UserName = "UserName"
$Password = "Password"
function uploadFile() {
Param ([string] $sourceFilePath,
[string] $siteAddress ,
[string] $urlDest,
[string] $UserName,
[string] $Password)
$webClient = New-Object System.Net.WebClient;
$webClient.Credentials = New-Object System.Net.NetworkCredential($UserName,$Password);
("*** Uploading {0} file to {1} ***" -f ($sourceFilePath, $siteAddress) ) | write-host -ForegroundColor Green
$webClient.UploadFile($urlDest, "PUT", $sourceFilePath);
$httpresponse = $httprequest.GetResponse()
}
Upload-File -File $SourceFilePath -URI $SiteAddress -Dest $URLDest -Username $MyUsername -Password $MyPassword
Currently I get error on Upload-File.
I am happy to convert to any code which can provide the above task, list PDF from internal path connect to website with User/Pass and upload all PDF from local Directory. I can confirm the account can connect and has correct permissions on the destination website URL.
I am also looking at this example with error "Forbidden":
$Dir="\\Netwrok\Path"
$Url = "https://Website/PDF"
$user = "User"
$pass = "Password"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
foreach($item in (dir $Dir "*.pdf"))
{
"Uploading $item..."
$uri = New-Object System.Uri($Url+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
Returns error:
Exception calling "UploadFile" with "2" argument(s): "The remote server
returned an error: (403) Forbidden."
At line:16 char:22
+ $webclient.UploadFile($uri, $item.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException

Related

Powershell Import-Clixml from a shared network folder using full UNC - The system cannot find the file specified

I am trying to run a powershell script inside a SQL Agent job. I keep getting the error: Import-Clixml : The system cannot find the file specified. At \Data\Powershell\Collibra\Dev\test.ps1:95 char:21 + ... redential = Import-Clixml -Path Filesystem::\Data\Powershell... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Import-Clixml], Cryptographic Exception + FullyQualifiedErrorId : System.Security.Cryptography.CryptographicExcept ion,Microsoft.PowerShell.Commands.ImportClixmlCommand
$Credential = Import-Clixml -Path
Filesystem::\\energy\data\apps\BISharedServices\Powershell\Collibra\Dev\credentials.xml
$username = $Credential.GetNetworkCredential().UserName
$password = $Credential.GetNetworkCredential().Password
$credPair = "$($username):$($password)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
$H = #{ Authorization = "Basic $encodedCredentials" }
I have tried mapping a new drive and doing a set-location. Same results. This is driving me nuts!
Thanks for the help.
In basic Powershell without SSIS at least, it's only one slash at the beginning:
Import-Clixml -Path FileSystem::\path\to\file.txt

Sharepoint Timezone Change Powershell

I need to change the timezone for all sites within sharepoint. I run this code that i found online.
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 to change Timezone regional settings of a SharePoint Online site
Function Set-SPOnlineTimeZone([String]$SiteURL,[String]$TimezoneName,[PSCredential]$Cred)
{
Try
{
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $credentials
#Get the Root web from given URL
$Web = $Ctx.web
$Ctx.Load($Web)
#Get the Time zone to update
$Timezones = $Web.RegionalSettings.TimeZones
$Ctx.Load($Timezones)
$Ctx.ExecuteQuery()
$NewTimezone = $Timezones | Where {$_.Description -eq $TimezoneName}
#Update the timezone of the site
$Web.RegionalSettings.TimeZone = $NewTimezone
$Web.Update()
$Ctx.ExecuteQuery()
Write-host -f Green "Timezone has been updated for "$Web.Url
#Get all subsites of the web
$Ctx.Load($Web.Webs)
$Ctx.executeQuery()
#Iterate through each subsites and call the function recursively
Foreach ($Subweb in $Web.Webs)
{
#Call the function to set Timezone for the web
Set-SPOnlineTimeZone -SiteURL $Subweb.URL -TimezoneName $TimezoneName -Cred $AdminCredentials
}
}
Catch [System.Exception]
{
Write-Host -f Red $_.Exception.Message
}
}
#Config parameters for SharePoint Online Admin Center and Timezone description
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$TimezoneName ="(UTC+04:00) Abu Dhabi, Muscat"
#Get credentials to connect to SharePoint Online Admin Center
$AdminCredentials = Get-Credential
#Connect to SharePoint Online Tenant Admin
Connect-SPOService -URL $AdminSiteURL -Credential $AdminCredentials
#Get all Site Collections
$SitesCollection = Get-SPOSite -Limit ALL
#Iterate through each site collection
ForEach($Site in $SitesCollection)
{
Write-host -f Yellow "Setting Timezone for Site Collection:"$Site.URL
#Call the function to set Timezone for the site
Set-SPOnlineTimeZone -SiteURL $Site.URL -TimezoneName $TimezoneName -cred $AdminCredentials
}
#Read more: https://www.sharepointdiary.com/2017/06/sharepoint-online-change-time-zone-using-powershell.html#ixzz68Mt3Xrom
I gett the following error
At line:10 char:16
+ ... edentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "ExecuteQuery" with "0" argument(s): "The sign-in name or password does not match one in the Microsoft account system."
At line:19 char:1
+ $Ctx.ExecuteQuery()
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdcrlException
An error occurred while enumerating through a collection: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested..
At line:22 char:1
+ $Timezones | Select ID, Description
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Share...lient.TimeZone]:<GetEnumerator>d__0) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
The account that i'm using is admin account for office365 (globle admin)however it has 2fa. I'm assumuing there needs to be some other method for this but no idea. Any help will be appreciated
According the Microsofts documentation on the Connect-SP* command, if your account is using 2FA you'll want to omit the credentials from your connect statement and let it prompt you for credentials manually.
https://learn.microsoft.com/en-us/powershell/module/sharepoint-online/connect-sposervice?view=sharepoint-ps
See example 3
If you are using MFA in your environment, I would suggest you use sharepoint pnp powesrhsell.
You could refer to the below articles for more:
https://techcommunity.microsoft.com/t5/SharePoint/Using-SharePoint-Client-Side-Object-Model-with-PowerShell-and/m-p/92734
https://www.c-sharpcorner.com/blogs/using-csom-to-connect-to-a-sharepoint-site-with-multi-factor-authentication-enabled

Upload files to an FTP Server using powershell

I have the following code to upload a file to an FTP Server via powershell but it's giving me this error:
Code:
$Directory=”C:\test”
#FTP server configuration
$ftpserver = “ftp://ftpserver/”
$username = “user”
$password = “pw”
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
#Copy each file which type is *.tx*
foreach($file in (dir $Directory “*.txt*”)){
“Uploading $file…”
$uri = New-Object System.Uri($ftpserver+$file.Name)
$webclient.UploadFile($uri, $file.FullName)
}
Error:
Exception calling "UploadFile" with "2" argument(s): "Excepção durante um pedido WebClient."
At C:\Users\home\Desktop\test6.ps1:16 char:1
+ $webclient.UploadFile($uri, $file.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
Try it like so:
$Directory = "C:\test"
#FTP server configuration
$ftpserver = "ftp://ftpserver/"
$username = "user"
$password = "pw"
$ftpserverURI = New-Object -TypeName System.Uri -ArgumentList $ftpserver, [System.UriKind]::Absolute
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $username, $password
#Copy each file which type is *.tx*
Get-ChildItem $Directory -Filter *.txt* | ForEach-Object {
Write-Host "Uploading $($_.FullName)..."
$uri = New-Object -TypeName System.Uri -ArgumentList $ftpserverURI, $_.Name
$webclient.UploadFile($uri, [System.Net.WebRequestMethods+Ftp]::UploadFile, $_.FullName)
}
The differences are that I'm making System.Uri combine the path instead of relying on string concatenation, and I'm telling WebClient.UploadFile() the method to use when uploading the file.
If this doesn't work, then I agree with the comments that you should examine the server logs. If you can't, then try it against a server that you can see the logs for. Alternately, you may want to try to use WinSCP, which is also scriptable with PowerShell or with a custom script file. WinSCP has the advantage of supporting FTP, FTPS, and SFTP, as well. The .Net WebClient only natively supports plain FTP, as far as I'm aware.
As far as smart quotes, they work just fine on Windows PowerShell (<= v5.x), but they don't work at all on PowerShell Core (v6+). I would avoid using them to make your code more portable and more future proof.

upload a file to SFTP Filezilla

I will like upload a file to SFTP Filezilla but I have an error message and I can not solve my problem
$ftp = "Address"
$Username = "username"
$Password = "password"
$Localdir = "address\test.docx"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
foreach ($item in (dir $Localdir "*.docx")) {
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
Write-Output $uri,$item.FullName
$webclient.UploadFile($uri, $item.FullName)
}
When I execute my script, I have an error message :
Exception when calling "UploadFile" with "2" argument (s): "An exception occurred during a WebClient request. To the character C: \ Users \ PCA \ Downloads \ powershell \ test4 - to see.ps1: 15: 5 + $ webclient.UploadFile ($ ftp, $ item)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
How resolve this problem ? (I execute this script with on windows 10 and the version powershell is 5.1)

Using special characters (slash) in FTP credentials with WebClient

EDIT: I have discovered it's definitely the password that is causing issues. I have a forward slash in my password and cannot figure out how to get this to accept it. I've already tried replacing it with %5B. Changing the password is not a possibility.
cd v:
$username = "*********"
$password = "*********"
$usrpass = $username + ":" + $password
$webclient = New-Object -TypeName System.Net.WebClient
function ftp-test
{
if (Test-Path v:\*.204)
{
$files = Get-ChildItem v:\ -name -Include *.204 | where { ! $_.PSIsContainer } #gets list of only the .204 files
foreach ($file in $files)
{
$ftp = "ftp://$usrpass#ftp.example.com/IN/$file"
Write-Host $ftp
$uri = New-Object -TypeName System.Uri -ArgumentList $ftp
$webclient.UploadFile($uri, $file)
}
}
}
ftp-test
When I run the above code I get
Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
At line:13 char:34
+ $webclient.UploadFile <<<< ($uri, $file)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
I'm not sure what the issue is. Searching has brought issue with proxies, but I have no proxy that I need to get through.
I can manually upload the file with ftp.exe, but I'd rather do all this in PowerShell if possible instead of generating a script to use ftp.exe with.
You have to URL-encode the special characters. Note that encoded slash (/) is %2F, not %5B (that's [).
Instead of hard-coding encoded characters, use Uri.EscapeDataString:
$usrpass = $username + ":" + [System.Uri]::EscapeDataString($password)
Or use the WebClient.Credentials property, and you do not need to escape anything:
$webclient.Credentials =
New-Object System.Net.NetworkCredential($username, $password)
...
$ftp = "ftp://ftp.example.com/IN/$file"
Similarly for (Ftp)WebRequest: Escape the # character in my PowerShell FTP script