How to download multiple files via PowerShell script? - powershell

I have multiple files to download, as many as 7 at a time, it downloads the first file then peters out.
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At line:17 char:5
$IE.Navigate2("https://mdf.mydomain.com/SeaNet//DownloadFile ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], COMException
FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
$BinaryID = 7458,7457,7446,7317
# open IE
$IE = New-Object -COMObject "InternetExplorer.Application"
$IE.Visible = $True
$MyUser = ""
$MyCreds = Get-Credential -Credential $MyUser
$MyPass = $Creds.GetNetworkCredential().Password
$IE.Navigate2("https://mdf.mydomain.com/SeaNet/CustomReport.aspx?reportId=692")
While($IE.Busy -eq $true) {Start-Sleep -Seconds 30}
$IE.document.getElementById('UserNameTB').value = "$MyUser"
$IE.document.getElementById('PasswordTB').value = "$MyPass"
$Link = $IE.Document.getElementByID('LoginIBtn')[0].Item().Click()
ForEach ($ID in $BinaryID) {
$IE.Navigate2("https://mdf.mydomain.com/SeaNet/DownloadFile.aspx?binaryid=$ID")
Pause
}

Related

Excute Shell Script remotely to Azure Linux VM

i'am trying to excute a shell script to an azure linux virtual machine using powershell
Why I'm i using powershell? :
The virtual machine has a Copied VHD from storage account which means it doesn't have Azure VM agent
so i can't use :
azure vm extentions
azure vm Runs
i tried also using an automation runbook with the ssh module and got those errors :
Exception calling "Connect" with "0" argument(s): "Server HMAC algorithm not found" At C:\Modules\User\SSH\SSH.psm1:68 char:5 + $SSHConnection.Connect() + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
and
Exception calling "RunCommand" with "1" argument(s): "Client not connected." At C:\Modules\User\SSH\SSH.psm1:69 char:5 + $ResultObject = $SSHConnection.RunCommand($ScriptBlock.ToString() ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
which is based on my understanding caused by the vm that is missing KexAlgorithms to describe which methods are supported by the SSH daemon
What i'm trying to do now is to ssh into the vm and excute the command using powershell
here is what i got now (a Powershell scripot to ssh into the vm and excute a command):
$Password = "pwd"
$User = "pwd"
$ComputerName = "ip adress"
$Command = "touch tst.txt"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
echo 'Executing...'
$output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Output
Remove-SSHSession -Name $SessionID | Out-Null
im getting this error :
Invoke-SshCommand : A parameter cannot be found that matches parameter name 'Index'.
At C:\Users\octoadmin\Desktop\sign in.ps1:11 char:30
+ $output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Out ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-SshCommand], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Invoke-SshCommand
i looked in the internet but couldn't find anything.
apparently the ssh invoke command can't find a session with the index $SessionID
but i don't know where exactly is the problem
hope someone can guide me to the right direction.
Updating Posh-SSH worked for me with this code :
to install Posh-SSH :
Install-Module -Name Posh-SSH -RequiredVersion 2.1
The Script:
$Command = "fetch $scripturl; sh script.sh"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$ComputerName = Get-AzPublicIpAddress -ResourceGroupName $RG -Name $IPName | Select-Object -ExpandProperty ipAddress
echo 'ip is : '
echo $ComputerName
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -AcceptKey -Credential $Credentials
echo 'Exucuting...'
$Query = (Invoke-SshCommand -SSHSession $SessionID -Command $Command).Output
echo $Query
Remove-SSHSession -Name $SessionID | Out-Null

Get-Credentials error in PowerShell 'Cannot find an Overload for "PSCredential"'

I'm new to PowerShell. I am trying to make it so I can setup a new computer connecting to the network to allow me to do certain tasks. When I run this:
$domain = "mydomain.com"
$mycred = get-credential
$credential = New-Object System.Management.Automation.PSCredential("$($domain)\$($mycred.Username)","$($mycred.Password)")
$compName = Read-Host -Prompt "Enter new computer name"
Add-Computer -DomainName $domain -newname $compName -Credential $credential -Restart
Pause
I get the error:
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At C:\Users\entername\Downloads\1-JoinDomainCred.ps1:7 char:15
... redential = New-Object System.Management.Automation.PSCredential("$($ ...
CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Where am I going wrong?
Get-Credential aready returns a proper credentials object. Just use that:
$mycred = Get-Credential; Add-Computer ... -Credential $mycred
PowerShell is not C#, pass the arguments as an array without the ():
$credential = New-Object System.Management.Automation.PSCredential "$($domain)\$($mycred.Username)",$mycred.Password

You cannot call a method on a null-valued expression. + $submitButton.click()

I'm running a script that I've used for some time successfully, but I am now getting the following error message:
You cannot call a method on a null-valued expression. At
G:\Backup\2021\DownloadASX300 v1.ps1:14 char:1
$submitButton.click()
CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
The script I'm running is as follows:
$OutputFilePath = "c:\_Temp\ASX300html.htm
$url = 'https://www.marketindex.com.au/asx300'
$IE = New-Object -ComObject InternetExplorer.Application
$IE.Navigate($url)
$IE.Visible = $true
while ($IE.Busy -eq $true){Start-Sleep -seconds 5;}
$submitButton=$IE.Document.IHTMLDocument3_getelementsbytagname("a") | Where-Object {$_.innerhtml -like '*SHOW ALL COMPANIES*'}
$submitButton -eq $null
$submitButton.click()
Start-Sleep -s 5
$IE.Document.body.innerHTML | Out-File -FilePath $OutputFilePath
$IE.Quit()
This script basically downloads share prices from a website after opening the full list on that site.
Any help you can offer will be greatly apprreciated.

Erroraaction in uploading file by FTP

I have a file with IP address of servers. And script reads adress ($line) by adress, but sometimes can occur address of server that will be down. It is necessary to script steel run till end of IP address. So I used -Erroraction Continue to Set_FTPConnection But script break anyway. How to solve this problem?
foreach ($line in $FTPServer)
{
Start-Transcript -Path $results
Write-Host -Object "ftp url: $line"
Set-FTPConnection -Credentials $FTPCredential -Server $line -Session MySession -UsePassive -ErrorAction Continue
$Session = Get-FTPConnection -Session MySession
$Session>>.\sessions.txt
#Write-Host $Error[0]
if($session.UsePassive -eq "True"){$connect="OK"}
else{$connect="FAIL"}
foreach ($item in (Get-ChildItem .\Upload))
{
#Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse
Write-Host -Object "Uploading $item..."
$Send= Add-FTPItem -Session $Session -Path $FTPPlace -LocalPath .\Upload\$item -Overwrite -ErrorAction Continue #>> .\up.txt #.\Upload\test.txt
$item|gm >>.\up.txt
if($Send.Name -eq $item.Name){$Rec="OK"}
else{$Rec="!!!-FAIL-!!!"}
$array = $line, $item, $connect, $Rec
$FailTable=New-Object -TypeName PSObject -Property ([ordered]#{"FTP Server"=$array[0]; "File"=$array[1];"Connected"=$array[2];"Uploaded"=$array[3]})
Add-Content .\stats.txt $FailTable
}
Stop-Transcript
}
Errors:
From my code
Transcript started, output file is .\logs.txt
ftp url: 10.80.59.173
Set-FTPConnection : Exception calling "GetResponse" with "0" argument(s): "Unable to connect to the remote server"
At F:\DPI FTP\FTPUpload_v2.ps1:25 char:13
+ Set-FTPConnection -Credentials $FTPCredential -Server $li ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Set-FTPConnection
With Test-NetConnection
Start-Transcript : Transcription cannot be started.
At F:\DPI FTP\FTPUpload_v2.ps1:21 char:9
+ Start-Transcript -Path $results #if $session.usepa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
ftp url: 10.80.59.173
Test-NetConnection : The term 'Test-NetConnection' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At F:\DPI FTP\FTPUpload_v2.ps1:23 char:13
+ If (Test-NetConnection $line -Port '21')
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Transcript started, output file is .\logs.txt
ftp url: 10.80.59.170
Test-NetConnection : The term 'Test-NetConnection' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At F:\DPI FTP\FTPUpload_v2.ps1:23 char:13
+ If (Test-NetConnection $line -Port '21')
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test-NetConnection:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
With If:
WARNING: Could not connect to 10.80.59.173
Start-Transcript : Transcription cannot be started.
At F:\DPI FTP\FTPUpload_v2.ps1:20 char:9
+ Start-Transcript -Path $results #if $session.usepa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : CannotStartTranscription,Microsoft.PowerShell.Commands.StartTranscriptCommand
Stop-Transcript : An error occurred stopping transcription: The host is not currently transcribing.
At F:\DPI FTP\FTPUpload_v2.ps1:47 char:9
+ Stop-Transcript
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Stop-Transcript], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StopTranscriptCommand
Continue is actually the default setting. It means that if a non-terminating error occurs, it will show the error and then should be continuing with the command and rest of the script. You could try SilentlyContinue to see if that helps.
Alternatively you could test if the IP Address is connectable first. If you're using Windows 8/Server 2012 or newer and PowerShell v4+ you could use Test-NetConnection -Port 21 to do this specifically for the FTP port, if not you could use Test-Connection instead (which is a PS equivalent of Ping):
foreach ($line in $FTPServer)
{
Start-Transcript -Path $results
Write-Host -Object "ftp url: $line"
If (Test-Connection $line) {
Set-FTPConnection -Credentials $FTPCredential -Server $line -Session MySession -UsePassive -ErrorAction Continue
$Session = Get-FTPConnection -Session MySession
$Session>>.\sessions.txt
#Write-Host $Error[0]
if($session.UsePassive -eq "True"){$connect="OK"}
else{$connect="FAIL"}
foreach ($item in (Get-ChildItem .\Upload))
{
#Get-FTPChildItem -Session $Session -Path /htdocs #-Recurse
Write-Host -Object "Uploading $item..."
$Send= Add-FTPItem -Session $Session -Path $FTPPlace -LocalPath .\Upload\$item -Overwrite -ErrorAction Continue #>> .\up.txt #.\Upload\test.txt
$item|gm >>.\up.txt
if($Send.Name -eq $item.Name){$Rec="OK"}
else{$Rec="!!!-FAIL-!!!"}
$array = $line, $item, $connect, $Rec
$FailTable=New-Object -TypeName PSObject -Property ([ordered]#{"FTP Server"=$array[0]; "File"=$array[1];"Connected"=$array[2];"Uploaded"=$array[3]})
Add-Content .\stats.txt $FailTable
}
Stop-Transcript
} Else {
Write-Warning "Could not connect to $line"
}
}

ProcessStartInfo and Process in PowerShell - Authentication Error

I have code that uses ProcessStartInfo and Process to invoke another script, and to return the output of that script.
Unfortunately, I am getting errors, and I am unsure how to troubleshoot them.
#script1.ps1
$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL
<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = "powershell.exe"
$startInfo.Arguments = "C:\script\script2.ps1", $abc
$startInfo.RedirectStandardOutput = $true
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $false
$startInfo.Username = "DOMAIN\Username"
$startInfo.Password = $password
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$standardOut = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
# $standardOut should contain the results of "C:\script\script2.ps1"
$standardOut
The errors I get are:
Exception calling "Start" with "0" argument(s): "Logon failure: unknown user name or bad password"
At C:\script\script1.ps1:46 char:15
+ $process.Start <<<< () | Out-Null
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
You cannot call a method on a null-valued expression.
At C:\script\script1.ps1:47 char:49
+ $standardOut = $process.StandardOutput.ReadToEnd <<<< ()
+ CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\script\script1.ps1:48 char:21
+ $process.WaitForExit <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How can I fix this problem?
It's pretty much spelled out to you, isn't it?:
"Logon failure: unknown user name or bad password"
(first error line).
Note that DOMAIN should be provided in separate property:
$startInfo.Username = "Username"
$startInfo.Domain = "DOMAIN"