Add specific printer to multiple servers - powershell

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

Related

Powershell scripting1

I am running this Script to get the directory listing
It was working few days ago but I keep having this error
New-PSSession : 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 C:\DEV\Powershell3\directory-listing.ps1:11 char:38
+ $session=New-PSSession -ComputerName $servers
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.NewPSSessionCommand
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At C:\DEV\Powershell3\directory-listing.ps1:31 char:25
+ Invoke-Command -Session $session -ScriptBlock $scb
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
$servers=get-content C:\temp\servers.txt
$session=New-PSSession -ComputerName $servers
$scb = {
Write-host "working on $env:COMPUTERNAME" -ForegroundColor Red
$volumes=Get-WmiObject win32_volume -Filter "drivetype=3"
foreach($volume in $volumes) {
$driveletter=$volume.driveletter
if($driveLetter -ne $null) {
$drivename=$volume.name
(Get-ChildItem -path $drivename -Directory) |Select-Object Name,FullName
}
}
}
Invoke-Command -Session $session -ScriptBlock $scb

Why do I receive an "RPC error" when using Get-WmiObject on a Netapp SVM

How can i get this to show me who's using the shares on our NETAPP.
$computer = "gozer"
$namespace = "root\CIMV2" # note to self find out if this is correct
$userSessions = Get-WmiObject -class Win32_ServerConnection -computername $computer -namespace $namespace
if($userSessions -ne $null)
{
Write-Host "The following users are connected to your PC: "
foreach ($userSession in $userSessions)
{
$userDetails = [string]::Format("User {0} from machine {1} on share: {2}",
$userSession.UserName, $userSession.ComputerName, $userSession.ShareName)
Write-Host $userDetails
}
Read-Host
}
exit
the error i receive when i run this pointing at a NETAPP SVM is:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\test\whos-using-the-share.ps1:3 char:17
+ $userSessions = Get-WmiObject -class Win32_ServerConnection -computername $compu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Powershell Script - AD Discovery - Get-CimInstance : Access is denied. - SCCM 2012

I'm trying to create a powershell script to make AD Discovery possible, whenever i start te script i always get Get-CimInstance : Access is denied.
i also try to fill in the values of a Active Directory Container but the script always says that the property .Values cannot be found on this object.
what am i doing wrong ?
this is the full script:
Import-Module 'C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager'
Set-Location PS1:
# variable
$CMSiteCode = 'PS1'
$CMSiteServer = 'CM01.local.cursusdom.tm'
$CMNameSpace = "root\SMS\site_$CMSiteCode"
# create a schedule
$CMGroupDiscoverySchedule = New-CMSchedule -RecurInterval Days -RecurCount 7
# Forest Discovery
Set-CMDiscoveryMethod -ActiveDirectoryForestDiscovery ` -SiteCode $CMSiteCode ` -EnableActiveDirectorySiteBoundaryCreation $true ` -EnableSubnetBoundaryCreation $true ` -Enabled $true
# Configure Group Discovery
# Create the base discovery method using the schedule
Set-CMDiscoveryMethod -ActiveDirectoryGroupDiscovery ` -SiteCode $CMSiteCode ` -EnableDeltaDiscovery $true ` -DeltaDiscoveryIntervalMinutes 5 ` -EnableFilteringExpiredLogon $true ` -TimeSinceLastLogonDays 30 ` -EnableFilteringExpiredPassword $true ` -TimeSinceLastPasswordUpdateDays 90 ` -PollingSchedule $CMGroupDiscoverySchedule ` -Enabled $true
# AD containers
$ADGroupDiscovery = Get-CimInstance -ComputerName $CMSiteServer `
-Namespace $CMNameSpace `
-ClassName SMS_SCI_Component `
-Filter 'ComponentName ="SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT"'
$ADContainerProp = $GroupDiscovery.PropLists | where {$_.PropertyListName -eq "AD Containers" }
$ADContainerProp.Values = "Acme - Software groups",0,0,1
$ADGroupDiscovery = Get-CimInstance -ComputerName $CMSiteServer ` -Namespace $CMNameSpace ` -ClassName SMS_SCI_Component ` -Filter 'ComponentName ="SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT"'
$NewGroupProp = New-CimInstance -ClientOnly -Namespace $CMNameSpace -ClassName SMS_EmbeddedPropertyList -Property #{PropertyListName='Search Bases:PS1';Values=[string[]]'LDAP://OU=Software groups,OU=Acme,DC=Local,DC=cursusdom,DC=tm'}
$ADGroupDiscovery.PropLists += $NewGroupProp
# change back to the CIM instance
Get-CimInstance -ComputerName $CMSiteServer ` -Namespace $CMNameSpace ` -ClassName SMS_SCI_Component ` -Filter 'ComponentName ="SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT"' | Set-CimInstance -Property #{PropLists=$ADGroupDiscovery.PropLists}
# Configure System Discovery
# polling schedule
$CMSystemDiscoverySchedule = New-CMSchedule -RecurInterval Days -RecurCount 1
# Create the base discovery method using the schedule
Set-CMDiscoveryMethod -ActiveDirectorySystemDiscovery ` -SiteCode $CMSiteCode ` -EnableDeltaDiscovery $true ` -DeltaDiscoveryIntervalMinutes 5 ` -EnableFilteringExpiredLogon $true ` -TimeSinceLastLogonDays 30 ` -EnableFilteringExpiredPassword $true ` -TimeSinceLastPasswordUpdateDays 90 ` -PollingSchedule $CMSystemDiscoverySchedule ` -Enabled $true
# AD containers
$ADSysDiscovery = Get-CimInstance -ComputerName $CMSiteServer `-Namespace $CMNameSpace ` -ClassName SMS_SCI_Component ` -Filter 'ComponentName ="SMS_AD_SYSTEM_DISCOVERY_AGENT"'
$ADContainerProp =$Sysdiscovery.PropLists | where {$_.PropertyListName -eq "AD Containers" }
$ADContainerProp.Values = "LDAP://OU=Domain Controllers,DC=local,DC=cursusdom,DC=tm",1,1 # Ldap path of the Container, Recursive search, Discover objects within groups
$ADContainerProp =$Sysdiscovery.PropLists | where {$_.PropertyListName -eq "AD Containers" }
$ADContainerProp.Values = "LDAP://OU=Computers,OU=Acme,DC=local,DC=cursusdom,DC=tm",1,1 # Ldap path of the Container, Recursive search, Discover objects within groups
# change back to the CIM instance
Get-CimInstance -ComputerName $CMSiteServer `
-Namespace $CMNameSpace `
-ClassName SMS_SCI_Component `
-Filter 'ComponentName ="SMS_AD_SYSTEM_DISCOVERY_AGENT"' | Set-CimInstance -Property #{PropLists=$ADSysDiscovery.PropLists}
# User Discovery
# polling schedule
$CMUserDiscoverySchedule = New-CMSchedule -RecurInterval Days -RecurCount 1
# Create the base discovery method
Set-CMDiscoveryMethod -ActiveDirectoryUserDiscovery `
-SiteCode $CMSiteCode `
-EnableDeltaDiscovery $true `
-DeltaDiscoveryIntervalMinutes 5 `
-PollingSchedule $CMUserDiscoverySchedule `
-enabled $true
# AD containers
$ADUserDiscovery = Get-CimInstance -ComputerName $CMSiteServer `
-Namespace $CMNameSpace `
-ClassName SMS_SCI_Component `
-Filter 'ComponentName ="SMS_AD_USER_DISCOVERY_AGENT"'
$ADUserContainers = $ADUserDiscovery.PropLists | Where-Object {$_.PropertyListName -eq 'AD Containers'}
$ADContainerProp.Values = "LDAP://OU=Users,OU=Acme,DC=local,DC=cursusdom,DC=tm",0,0
$ADContainerProp.Values = "LDAP://OU=Admins,OU=Acme,DC=local,DC=cursusdom,DC=tm",0,0
# change back to the CIM instance
Get-CimInstance -ComputerName $CMSiteServer `
-Namespace $CMNameSpace `
-ClassName SMS_SCI_Component `
-Filter 'ComponentName ="SMS_AD_USER_DISCOVERY_AGENT"' | Set-CimInstance -Property #{PropLists=$ADUserDiscovery.PropLists}
# 5.0 - Restart SMS_SITE_COMPONENT_MANAGER Service to apply changes
Get-Service -ComputerName $CMSiteServer -Name SMS_SITE_COMPONENT_MANAGER | Restart-Service
these are the errors i'm getting:
PS C:\Users\Admin> C:\Users\Admin\Downloads\AD discovery.ps1
Get-CimInstance : Access is denied.
At C:\Users\Admin\Downloads\AD discovery.ps1:34 char:21
+ $ADGroupDiscovery = Get-CimInstance -ComputerName $CMSiteServer `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : CM01.local.cursusdom.tm
The property 'Values' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Admin\Downloads\AD discovery.ps1:40 char:1
+ $ADContainerProp.Values = "Acme - Software groups",0,0,1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Get-CimInstance : Access is denied.
At C:\Users\Admin\Downloads\AD discovery.ps1:43 char:21
+ ... Discovery = Get-CimInstance -ComputerName $CMSiteServer ` -Namespa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : CM01.local.cursusdom.tm
The property 'PropLists' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Admin\Downloads\AD discovery.ps1:47 char:1
+ $ADGroupDiscovery.PropLists += $NewGroupProp
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Get-CimInstance : Access is denied.
At C:\Users\Admin\Downloads\AD discovery.ps1:51 char:1
+ Get-CimInstance -ComputerName $CMSiteServer ` -Namespace $CMNameSp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : CM01.local.cursusdom.tm
Get-CimInstance : A positional parameter cannot be found that accepts argument '-Namespace'.
At C:\Users\Admin\Downloads\AD discovery.ps1:74 char:19
+ ... Discovery = Get-CimInstance -ComputerName $CMSiteServer `-Namespace $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-CimInstance], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstan
ceCommand
The property 'Values' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Admin\Downloads\AD discovery.ps1:77 char:1
+ $ADContainerProp.Values = "LDAP://OU=Domain Controllers,DC=local,DC=c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
The property 'Values' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Admin\Downloads\AD discovery.ps1:80 char:1
+ $ADContainerProp.Values = "LDAP://OU=Computers,OU=Acme,DC=local,DC=cu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Get-CimInstance : Access is denied.
At C:\Users\Admin\Downloads\AD discovery.ps1:84 char:1
+ Get-CimInstance -ComputerName $CMSiteServer `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : CM01.local.cursusdom.tm
Get-CimInstance : Access is denied.
At C:\Users\Admin\Downloads\AD discovery.ps1:110 char:20
+ $ADUserDiscovery = Get-CimInstance -ComputerName $CMSiteServer `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : CM01.local.cursusdom.tm
The property 'Values' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Admin\Downloads\AD discovery.ps1:117 char:1
+ $ADContainerProp.Values = "LDAP://OU=Users,OU=Acme,DC=local,DC=cursus ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
The property 'Values' cannot be found on this object. Verify that the property exists and can be set.
At C:\Users\Admin\Downloads\AD discovery.ps1:119 char:1
+ $ADContainerProp.Values = "LDAP://OU=Admins,OU=Acme,DC=local,DC=cursu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Get-CimInstance : Access is denied.
At C:\Users\Admin\Downloads\AD discovery.ps1:124 char:1
+ Get-CimInstance -ComputerName $CMSiteServer `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070005,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
+ PSComputerName : CM01.local.cursusdom.tm
Restart-Service : Service 'SMS_SITE_COMPONENT_MANAGER (SMS_SITE_COMPONENT_MANAGER)' cannot be stopped due to the follo
wing error: Cannot open SMS_SITE_COMPONENT_MANAGER service on computer 'CM01.local.cursusdom.tm'.
At C:\Users\Admin\Downloads\AD discovery.ps1:131 char:76
+ ... Name $CMSiteServer -Name SMS_SITE_COMPONENT_MANAGER | Restart-Service
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (System.ServiceProcess.ServiceController:ServiceController) [Restart-Servic
e], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Commands.RestartServiceCommand
PS PS1:\>
Could anyone help me ? :) i'm still trying to learn powershell.
thanks

New-CIMInstance dosent trigger try catch

why did the catch block
$ComputerName = "server"
try {
#Hostname Abfragen der fürs CMI Query passt
$OptDCOM = New-CimSessionOption -Protocol Dcom
$CimSessionDCOM = New-CimSession -ComputerName $ComputerName -SessionOption $OptDCOM
}
catch{
Write-Host "Fehler beim CIM-Instance mit DCOM: $ComputerName"
$array += $_.Exception.Message
$BS = "PSR"
}
$BS
doesnt trigger ?
got the following error:
New-CimSession : Der RPC-Server ist nicht verfügbar.
In Zeile:6 Zeichen:23
+ ... ssionDCOM = New-CimSession -ComputerName $ComputerName -SessionOption ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-CimSession], CimException
+ FullyQualifiedErrorId : HRESULT 0x800706ba,Microsoft.Management.Infrastructure.CimCmdlets.NewCimSessionCommand
+ PSComputerName :
But nothing in the catch-Block happen, i need to change to PS-Remoting when this above failed.
Thanks
Add -ErrorAction Stop
$CimSessionDCOM = New-CimSession -ComputerName $ComputerName -SessionOption $OptDCOM -ErrorAction Stop

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