Permissions error trying to download folder from GoDaddy Website via Powershell - powershell

Has to have something to do with GoDaddy and permissions. I can access files in that folder but get 403 when trying to access the folder itself (download):
$outputdir = 'C:\Windows10Upgrade'
$url = 'httx://www.mydomain.com/Windows10Upgrade/'
# enable TLS 1.2 and TLS 1.1 protocols
#[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'MYPASSWORD' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'MYACCOUNTNUMBER', $password
$WebResponse = Invoke-WebRequest -Uri $url -Credential $credential
# get the list of links, skip the first one ("../") and download the files
$WebResponse.Links | Select-Object -ExpandProperty href -Skip 1 | ForEach-Object {
Write-Host "Downloading file '$_'"
$filePath = Join-Path -Path $outputdir -ChildPath $_
$fileUrl = '{0}/{1}' -f $url.TrimEnd('/'), $_
Invoke-WebRequest -Uri $fileUrl -OutFile $filePath
}

If you have a GoDaddy UserID and Password add a PSCredential object to your request:
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'myuserid', $password
# Download a file
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential
Substitute your UserID with myuserid and your Password with mypassword in the code above which creates the PSCredential object (called $credential) you then pass into the Invoke-WebRequest cmdlet as seen in the last line.

Related

Remove File on SFTP using Powershell

I'm struggling with the below code. Want to delete a file that is on SFTP. Unable to understand how to accomplish this -
$UserName = 'test'
$SecurePassword = ConvertTo-SecureString -String '3ea5e#9dkdadfsfwC' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
$Session = New-SFTPSession -ComputerName 'sftp.test.com' -Credential $Cred
$result = Remove-Item -LiteralPath "\\?sftp://test#sftp.test.com/export/home/dmsmaster/stms/PF/Working_Titles_Primary.csv" -Force
Used the following code to make it work -
$result = Remove-SFTPItem -path "/export/home/dmsmaster/stms/PF/Working_Titles_Primary.csv" -SFTPSession $Session -Force

Powershell: Using send-mailmessage after PSFTP in script

I have written a small script that are using PSFTP to connect to a FTP server, download some files and conclude by sending an email with a summary of downloaded files.
I get a problem with the send-mailmessage part, which fails with this error:
Send-MailMessage : The remote certificate is invalid according to the validation procedure.
When running the send-mailmessage alone, it works flawlessly, it is only when using it combined with PSFTP, it fails. I am guessing, that it is the due to having made a session with the ftpserver, that somehow interferes, but that session should be ended when we come to the send mail. I can't figure this out, can anybody help?
My script:
#--------- FTP server variables here ------
$User = "XXX"
$Pass = "XXX"
$EncryptedPass = ConvertTo-SecureString -String $Pass -asPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User,$EncryptedPass)
$Server = "XXX"
#-------- Mail credentials here -----------
$User_ = "XXX"
$Pass_ = "XXX"
$EncryptedPass_ = ConvertTo-SecureString -String $Pass_ -asPlainText -Force
$Mailcredentials = New-Object System.Management.Automation.PSCredential($User_,$EncryptedPass_)
#$mailcredentials =
$Subject ="'bowkerdownload'"
$To = "XXX"
$From = "XXX"
$body = (get-content -path g:\resultout.txt) -join "`n"
$SMTP = "smtp.office365.com"
#---------File variables here --------------
$month = (Get-Date).AddMonths(-8).ToString('MMM')
$year = (Get-date).addyears(-1).ToString('yyyy')
$filesequential="_*_"
$filesize = "lc"
$filetype = ".txt"
$samlevar=($month + ''+$year + ''+$filesequential + ''+$filesize + ''+$filetype)
$filename = $samlevar.tostring()
#------ The script---------
Set-FTPConnection -Credentials $Credentials -Server $server -Session defaultftpsession -UsePassive
$Session = Get-FTPConnection -Session defaultftpsession
Get-FTPChildItem -Path /Download -filter "$filename" |
Get-FTPItem -session $Session -LocalPath g:\ -Overwrite |
Convertfrom-string -PropertyNames Kode, Status, Action, fil |
Select-Object -Property Status, action, Fil |
Out-file g:\resultout.txt;
Send-MailMessage -To $To -Subject $Subject -Body $Body -SmtpServer $SMTP -From $From -Credential $Mailcredentials -port 587 -UseSsl``

Getting below error on running PowerShell script

I am using one PowerShell script to download content (a zip file) from a website which requires credentials to get authenticated for the website. Also, have used proxy and proxy credentials since it is an authenticated proxy. I am getting an error which I have pasted below.
I have tried giving the proxy and proxy credentials but no luck.
I have bypassed the execution policy using Powershell -ExecutionPolicy Bypass.
When I try accessing the website from my browser then I am able to access the zip file.
Please find the code snippet below:
#Path to Save data
$tipath = "C:\Somepath"
$localpath = "\somefile.zip"
$timepath = "\Zip_file.txt"
$unzippath = "\Someotherpath"
$storepath = $tipath + $localpath
$remotefilepath = $tipath + $timepath
$unzipfolder = $tipath + $unzippath
# Create Folder If Not Exists #
$FolderToCreate = $tipath
if (!(Test-Path $FolderToCreate -PathType Container)) {
New-Item -ItemType Directory -Force -Path $FolderToCreate
}
#Downloading File #
$username = "username"
$password = "Password" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $password)
$secPasswd = "password123" | ConvertTo-SecureString -AsPlainText -Force
$wc = New-Object System.Net.WebClient
$wc.Credentials = New-Object System.Net.NetworkCredential("domain\user", $secPasswd)
# get remote file info
Invoke-WebRequest -Proxy "http://x.x.x.x:8080" -ProxyCredential $myCreds -Uri "https://somewebsite/checksum.txt" -OutFile $remotefilepath -Credential $cred
$remotefile = Get-Content -Path $remotefilepath
Write-Host Remote File Hash : $remotefile
# if the file exists already
if (Test-Path $storepath) {
# get local file info
$localfile = (Get-FileHash $storepath -Algorithm SHA256).Hash
Write-Host Local File Hash : $localfile
# if the remote file is newer than the local file
if ($remotefile -ne $localfile) {
Invoke-WebRequest -Proxy "http://x.x.x.x:8080" -ProxyCredential $myCreds -Uri "https://somewebsite/checksum.txt" -OutFile $remotefilepath -Credential $cred
Invoke-WebRequest -Proxy "http://x.x.x.x:8080" -ProxyCredential $myCreds -Uri "https://somewebsite/somezipfile.zip" -OutFile $storepath -Credential $cred
This code should check the hash and download directly download the zip file from the website and unzip it.
If it can download in the zip file then the later part I can troubleshoot.
PS C:\Users\Administrator\Desktop> powershell -ExecutionPolicy ByPass -File C:\Users\Administrator\Desktop\mypowershell.ps1
powershell : Invoke-WebRequest : .?? ??? ?????? ???????? ??? ????? ?????
At line:1 char:1
+ powershell -ExecutionPolicy ByPass -File C:\Users\Administrator\Desktop\mypowershell.p ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Invoke-WebReque...??? ????? ?????:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
The site you are trying to access contains content that is prohibited.
If you believe the website you are trying to access does not contain any such
content, please click here.
Above is the error I am getting.

Find the exact matched string from the variable

In the below code, $Result variable has the following information. I need to iterate below each line in $Result variable and get the <APPPOOL NAME> that is, "DefaultAppPool","Classic .NET AppPool" & ".NET v2.0 Classic" as an input to the second Invoke-Command saved in $Result2. Please advise how this can be accomplished.
$Result output:
APPPOOL "DefaultAppPool" (MgdVersion:v4.0,MgdMode:Integrated,state:Started)
APPPOOL "Classic .NET AppPool" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
APPPOOL ".NET v2.0 Classic" (MgdVersion:v2.0,MgdMode:Classic,state:Started)
$Username = '<username>'
$Password = '<Password>'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
$input_file_path = "servers.txt"
$output_path = "result.txt"
foreach ($server in Get-Content $input_file_path) {
$Result = Invoke-Command -ComputerName $server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools
}
$Result | Add-Content $output_path
$Result2 = Invoke-Command -ComputerName #server -Credential $Cred -ScriptBlock {
C:\Windows\system32\inetsrv\appcmd.exe list apppools <APPPOOL NAME> /text:processmodel.username
}
}

Issues passing credentials to a function Azure Powershell

Hi all I'm trying to pass server login credentials to my 'createSQLServer function but keep hitting the error 'Cannot process argument transformation on parameter 'creds'.userName'' I've tried a lot of different, even tried with a 'param block' but stull stuck. A push in the right direction would be appreciated, cheers.
###### SQL SERVER LOGIN CREDENTIALS
$userName = "aaron"
$password = "Password_1234"
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
### SQL server names with resource group name appeneded
$server1 = "sqlserver1" + $resGroup
$serVerion = "12.0"
function createSQLserver ([string]$server1,[string]$server2, [string]$server3, [System.Management.Automation.PSCredential]$creds,[string]$server1Location, [string]$server2Location, [string]$server3Location, [string]$resGroup, [string]$serVerion, [string]$userName, [string]$password, [SecureString]$securePassword)
{
#Create server 1(Server A)
<#check to see if server exists - It exists, $continue is created and passed to
if statement to append two random characters to name#>
Write-Host "Creating First SQL Server"
$sqlServer = New-AzureRmSqlServer -ServerName $server1 -SqlAdministratorCredentials $creds -Location $server1Location -ResourceGroupName $resGroup -ServerVersion $serVerion -ErrorVariable continue -ErrorAction SilentlyContinue
if ($continue)
{
do {
$server1 = $server1 + (rand)
$sqlServer = New-AzureRmSqlServer -ServerName $server1 `
-SqlAdministratorCredentials $creds -Location $server1Location `
-ResourceGroupName $resGroup -ServerVersion "12.0" -ErrorVariable continue -ErrorAction SilentlyContinue
}
until(!$continue)
Write-Host 'exists creating new' $server1 'Created'
}else{
Write-Host $server1 ' Created'
}
Start-Sleep -s 2
}
createSQLserver $server1 $username $password $securePassword $creds $server1Location $resGroup $serVerion
You need to use your named parameters!
Here's a snippet of your first few parameters:
...
[string]$server1
,
[string]$server2
,
[string]$server3
,
[System.Management.Automation.PSCredential]$creds
...
And then the ones you're passing in to the function call
createSQLserver $server1 $username $password $securePassword ...
So because you're not using the names of your parameters, they are using their relative ordinal position i.e.
param | value
---------+----------------
$server1 | $server1
$server2 | $username
$server3 | $password
$creds | $securePassword
So what have we learned?
Always use named parameters!
createSQLserver -server1 $server1 -username $username -password $password -securePassword $securePassword
That should sort you out :-)