Erroraaction in uploading file by FTP - powershell

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"
}
}

Related

Create folder on remote computer using PowerShell

The intention is to create a folder on a remote computer C drive.
I'm trying to run this:
$stageSvrs | %{
Invoke-Command -ComputerName $_ -ScriptBlock {
$setupFolder = "c:\Support\test1"
Write-Host "Creating Support Folder"
New-Item -Path $setupFolder -type directory -Force
Write-Host "Folder creation complete"
}
}
but I get the following error:
Invoke-Command : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At \\company.local\share\share\userdata\username\Documents\WindowsPowerShell\CreateFolder.ps1:2 char:39
+ Invoke-Command -ComputerName $_ -ScriptBlock {
+ ~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand

Add specific printer to multiple servers

I am new to powershell and would like to create a tool to add a single printer to multiple servers.
Here is my code so far:
$printer = read-host "Please enter the printer name"
$ip = read-host "Please enter the printer IP"
foreach ($server in #("NPARTS20SVR",
"NPARTS21SVR",
"NPARTS22SVR",
"NPARTS23SVR",
"NPARTS24SVR")) {
Add-PrinterPort -ComputerName $server -Name $ip -PrinterHostAddress $ip
Add-Printer -ComputerName $server -ConnectionName $printer -PortName $ip -Comment $ip
}
Here is the error I am getting:
Add-PrinterPort : An error occurred while performing the specified operation. See the error details for more
information.
At \\gogo\Software\HELP\NewBuild\PreDomain\Sham scripts\AddPrinterSVR.ps1:14 char:7
+ Add-PrinterPort -ComputerName $server -Name $ip -PrinterHostAdd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (MSFT_PrinterPortTasks:ROOT/StandardCimv2/MSFT_PrinterPortTasks) [Add-Prin
terPort], CimException
+ FullyQualifiedErrorId : HRESULT 0x8007011b,Add-PrinterPort
Add-Printer : Parameter set cannot be resolved using the specified named parameters.
At \\gogo\Software\HELP\NewBuild\PreDomain\Sham scripts\AddPrinterSVR.ps1:15 char:7
+ Add-Printer -ComputerName $server -ConnectionName $printer -Por ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Add-Printer], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Add-Printer

Powershell v5.1 : Copy from share server to local folder on a remote PC

I have to manage around 10 PC running window 10.
I need to copy some software to those PC from share folder ( \company\folder or \MyPC\SharedFolder)
Manual remote is okay, however, doing copy item from share folder to 10 PC is take time and boring.
I found use Invoke-command and copy-item can help me to do it faster. However, I get error Access is denied
$usr = "UserName"
$pw = convertto-securestring -AsPlainText -Force -String Password
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "$usr",$pw
For ($i=1; $i -lt 11; $i++)
{
$computerName=""
if($i -lt 10) {
$computerName="PC000$i"
} else {
$computerName="PC00$i"
}
Write-host "Copy on $computerName"
$session = New-PSSession -ComputerName "ServerA" -Credential $creds -Authentication Kerberos
Invoke-Command -Session $session -ScriptBlock { Copy-Item \\CompanyFolder\Shared\Sample.zip D:\Shared }
}
And below is error
Access is denied
+ CategoryInfo : PermissionDenied: (\\CompanyFolder\Shared\Sample.zip:String) [Copy-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
+ PSComputerName : PC0007
Cannot find path '\\CompanyFolder\Shared\Sample.zip' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\CompanyFolder\Shared\Sample.zip:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
+ PSComputerName : PC0007
I search around and find similar issues at here but it can not fix my issue. Do you have any idea?
At the end, I find the Solution, and it is workaround solutions for this problem.
Copy-Item -ToSession $session -Path \\CompanyFolder\Shared\Samples.zip -Destination D:\ -Recurse
More information can be found here

PowerShell - Error in path while Set-FsrmQuota

I'm trying to make a script that changes the quota of a specific directory on a remote server. For that I'm using the following code ($Quota and $chosen_username enter as parameters):
$prefix_path = "C:\Shares\Users\";
$path = $prefix_path + $chosen_username;
if($Quota){
invoke-command -computername $servername {Set-FsrmQuota -path $path -Size $Quota+"GB"}
}
if((invoke-command -computername $servername {Get-FsrmQuota -path $path} | select #{n='QuotaSize'; e={$_.Size / 1gb -as [int]}}).QuotaSize -eq $Quota){
return "Success."
} else {
return "Failed."
}
And it is giving me this error:
Cannot bind argument to parameter 'Path' because it is an empty string.
+ CategoryInfo : InvalidData: (:) [Set-FsrmQuota], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Set-FsrmQuota
+ PSComputerName : ServerName
I've done debug and the value of $path is correct.
When using invoke-command on a remote computer, the local variables are unknown for the remote host, so you have to use either:
the using prefix for PS >= 3
invoke-command -computername $servername {Set-FsrmQuota -path $using:path -Size $using:Quota+"GB"}
the argumentlist parameter for PS < 3
invoke-command -computername $servername {Set-FsrmQuota -path $args[0] -Size $args[1]+"GB"} -argumentlist $path,$quota

PowerShell Path Parameter Invoke-Command (UnauthorizedAccessException)

When running this simple script I am receiving the error message:
+ CategoryInfo : OpenError: (:) [Import-Csv], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
Param(
[string]$Path,
[string]$Credential
)
Invoke-Command –cn DC –Credential $Credential -ArgumentList $Path –ScriptBlock `
{import-csv -Path $args[0] | select-object –property `
#{name='Identity';expression={$_.username}},#{name='Fax';expression={$_.'fax number'}} `
| foreach{Set-ADUser -Identity $_.identity -Fax $_.fax -Confirm:$false}}
Any idea why this may be happening? I have correct permissions the the path that I am using.
I found the issue and it was because I was not including the CSV file in my path. I was pointing to C:\Files\CSV instead of C:\Files\CSV\fax-users.csv.